Instruction:
Explain what the following Python 3 code does
def curve_reduce(curve, reduced):
    if NO_IMAGES:
        return

    figure, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
    curve.plot(256, ax=ax1)
    color = ax1.lines[-1].get_color()
    add_patch(ax1, curve._nodes, color)
    reduced.plot(256, ax=ax2)
    color = ax2.lines[-1].get_color()
    add_patch(ax2, reduced._nodes, color)
    ax1.axis("scaled")
    ax2.axis("scaled")
    _plot_helpers.add_plot_boundary(ax2)
    save_image(figure, "curve_reduce.png")

Response: Image for : meth :. curve. Curve. reduce docstring.


Instruction:
Create a Python 3 function for
imaging for : meth :. curve. Curve. reduce docstring.

Response:
def curve_reduce_approx(curve, reduced):
    """Image for :meth:`.curve.Curve.reduce` docstring."""
    if NO_IMAGES:
        return

    ax = curve.plot(256)
    color = ax.lines[-1].get_color()
    add_patch(ax, curve._nodes, color, alpha=0.25, node_color=color)
    reduced.plot(256, ax=ax)
    color = ax.lines[-1].get_color()
    add_patch(ax, reduced._nodes, color, alpha=0.25, node_color=color)
    ax.axis("scaled")
    _plot_helpers.add_plot_boundary(ax)
    save_image(ax.figure, "curve_reduce_approx.png")


Instruction:
How would you explain what the following Python 3 function does
def update_locate_candidates(candidate, next_candidates, x_val, y_val, degree):
    centroid_x, centroid_y, width, candidate_nodes = candidate
    point = np.asfortranarray([x_val, y_val])
    if not _helpers.contains_nd(candidate_nodes, point):
        return

    nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes(
        candidate_nodes, degree
    )
    half_width = 0.5 * width
    next_candidates.extend(
        (
            (
                centroid_x - half_width,
                centroid_y - half_width,
                half_width,
                nodes_a,
            ),
            (centroid_x, centroid_y, -half_width, nodes_b),
            (centroid_x + width, centroid_y - half_width, half_width, nodes_c),
            (centroid_x - half_width, centroid_y + width, half_width, nodes_d),
        )
    )

Response: This function updates the list of candidates during geometric search for a point.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def mean_centroid(candidates):
    sum_x = 0.0
    sum_y = 0.0
    for centroid_x, centroid_y, _, _ in candidates:
        sum_x += centroid_x
        sum_y += centroid_y
    denom = 3.0 * len(candidates)
    return sum_x / denom, sum_y / denom

Response: Take the mean of all centroids in set of reference triangles.


Instruction:
Make a summary of the following Python 3 code
def _locate_point(nodes, degree, x_val, y_val):
    # We track the centroid rather than base_x/base_y/width (by storing triple
    # the centroid -- to avoid division by three until needed). We also need
    # to track the width (or rather, just the sign of the width).
    candidates = [(1.0, 1.0, 1.0, nodes)]
    for _ in six.moves.xrange(MAX_LOCATE_SUBDIVISIONS + 1):
        next_candidates = []
        for candidate in candidates:
            update_locate_candidates(
                candidate, next_candidates, x_val, y_val, degree
            )
        candidates = next_candidates
    if not candidates:
        return None

    # We take the average of all centroids from the candidates
    # that may contain the point.
    s_approx, t_approx = mean_centroid(candidates)
    s, t = newton_refine(nodes, degree, x_val, y_val, s_approx, t_approx)
    actual = _surface_helpers.evaluate_barycentric(
        nodes, degree, 1.0 - s - t, s, t
    )
    expected = np.asfortranarray([x_val, y_val])
    if not _helpers.vector_close(
        actual.ravel(order="F"), expected, eps=LOCATE_EPS
    ):
        s, t = newton_refine(nodes, degree, x_val, y_val, s, t)
    return s, t

Response: r Finds a point on a base - image of a given degree on a given set of nodes.


Instruction:
Given the following Python 3 function, write the documentation
def same_intersection(intersection1, intersection2, wiggle=0.5 ** 40):
    if intersection1.index_first != intersection2.index_first:
        return False

    if intersection1.index_second != intersection2.index_second:
        return False

    return np.allclose(
        [intersection1.s, intersection1.t],
        [intersection2.s, intersection2.t],
        atol=0.0,
        rtol=wiggle,
    )

Response: Check if two intersections are close to machine precision.


Instruction:
Can you implement a function in Python 3 that
verifies that a set of intersections had expected duplicates.

Response:
def verify_duplicates(duplicates, uniques):
    """Verify that a set of intersections had expected duplicates.

    .. note::

       This is a helper used only by :func:`generic_intersect`.

    Args:
        duplicates (List[.Intersection]): List of intersections
            corresponding to duplicates that were filtered out.
        uniques (List[.Intersection]): List of "final" intersections
            with duplicates filtered out.

    Raises:
        ValueError: If the ``uniques`` are not actually all unique.
        ValueError: If one of the ``duplicates`` does not correspond to
            an intersection in ``uniques``.
        ValueError: If a duplicate occurs only once but does not have
            exactly one of ``s`` and ``t`` equal to ``0.0``.
        ValueError: If a duplicate occurs three times but does not have
            exactly both ``s == t == 0.0``.
        ValueError: If a duplicate occurs a number other than one or three
            times.
    """
    for uniq1, uniq2 in itertools.combinations(uniques, 2):
        if same_intersection(uniq1, uniq2):
            raise ValueError("Non-unique intersection")

    counter = collections.Counter()
    for dupe in duplicates:
        matches = []
        for index, uniq in enumerate(uniques):
            if same_intersection(dupe, uniq):
                matches.append(index)
        if len(matches) != 1:
            raise ValueError("Duplicate not among uniques", dupe)

        matched = matches[0]
        counter[matched] += 1
    for index, count in six.iteritems(counter):
        uniq = uniques[index]
        if count == 1:
            if (uniq.s, uniq.t).count(0.0) != 1:
                raise ValueError("Count == 1 should be a single corner", uniq)

        elif count == 3:
            if (uniq.s, uniq.t) != (0.0, 0.0):
                raise ValueError("Count == 3 should be a double corner", uniq)

        else:
            raise ValueError("Unexpected duplicate count", count)


Instruction:
How would you explain what the following Python 3 function does
def verify_edge_segments(edge_infos):
    if edge_infos is None:
        return

    for edge_info in edge_infos:
        num_segments = len(edge_info)
        for index in six.moves.xrange(-1, num_segments - 1):
            index1, start1, end1 = edge_info[index]
            # First, verify the start and end parameters for the current
            # segment.
            if not 0.0 <= start1 < end1 <= 1.0:
                raise ValueError(BAD_SEGMENT_PARAMS, edge_info[index])

            # Then, verify that the indices are not the same.
            index2, _, _ = edge_info[index + 1]
            if index1 == index2:
                raise ValueError(
                    SEGMENTS_SAME_EDGE, edge_info[index], edge_info[index + 1]
                )

Response: Verify that the edge segments in an intersection are valid.


Instruction:
Write a Python 3 script for
adding an intersection that is COINCIDENT_UNUSED but on an edge end.

Response:
def add_edge_end_unused(intersection, duplicates, intersections):
    """Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end.

    This is a helper for :func:`~._surface_intersection.add_intersection`.
    It assumes that

    * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0``
    * A "misclassified" intersection in ``intersections`` that matches
      ``intersection`` will be the "same" if it matches both ``index_first``
      and ``index_second`` and if it matches the start index exactly

    Args:
        intersection (.Intersection): An intersection to be added.
        duplicates (List[.Intersection]): List of duplicate intersections.
        intersections (List[.Intersection]): List of "accepted" (i.e.
            non-duplicate) intersections.
    """
    found = None
    for other in intersections:
        if (
            intersection.index_first == other.index_first
            and intersection.index_second == other.index_second
        ):
            if intersection.s == 0.0 and other.s == 0.0:
                found = other
                break

            if intersection.t == 0.0 and other.t == 0.0:
                found = other
                break

    if found is not None:
        intersections.remove(found)
        duplicates.append(found)
    intersections.append(intersection)


Instruction:
Explain what the following Python 3 code does
def check_unused(intersection, duplicates, intersections):
    for other in intersections:
        if (
            other.interior_curve == UNUSED_T
            and intersection.index_first == other.index_first
            and intersection.index_second == other.index_second
        ):
            if intersection.s == 0.0 and other.s == 0.0:
                duplicates.append(intersection)
                return True

            if intersection.t == 0.0 and other.t == 0.0:
                duplicates.append(intersection)
                return True

    return False

Response: Checks if a valid intersection is already in intersections.


Instruction:
How would you implement a function in Python 3 that
adds an intersection to the current node list.

Response:
def add_intersection(  # pylint: disable=too-many-arguments
    index1,
    s,
    index2,
    t,
    interior_curve,
    edge_nodes1,
    edge_nodes2,
    duplicates,
    intersections,
):
    """Create an :class:`Intersection` and append.

    The intersection will be classified as either a duplicate or a valid
    intersection and appended to one of ``duplicates`` or ``intersections``
    depending on that classification.

    Args:
        index1 (int): The index (among 0, 1, 2) of the first edge in the
            intersection.
        s (float): The parameter along the first curve of the intersection.
        index2 (int): The index (among 0, 1, 2) of the second edge in the
            intersection.
        t (float): The parameter along the second curve of the intersection.
        interior_curve (Optional[.IntersectionClassification]): The
            classification of the intersection, if known. If :data:`None`,
            the classification will be computed below.
        edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The
            nodes of the three edges of the first surface being intersected.
        edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The
            nodes of the three edges of the second surface being intersected.
        duplicates (List[.Intersection]): List of duplicate intersections.
        intersections (List[.Intersection]): List of "accepted" (i.e.
            non-duplicate) intersections.
    """
    # NOTE: There is no corresponding "enable", but the disable only applies
    #       in this lexical scope.
    # pylint: disable=too-many-locals
    edge_end, is_corner, intersection_args = _surface_helpers.handle_ends(
        index1, s, index2, t
    )
    if edge_end:
        intersection = _intersection_helpers.Intersection(*intersection_args)
        intersection.interior_curve = interior_curve
        if interior_curve == UNUSED_T:
            add_edge_end_unused(intersection, duplicates, intersections)
        else:
            duplicates.append(intersection)
    else:
        intersection = _intersection_helpers.Intersection(index1, s, index2, t)
        if is_corner:
            is_duplicate = check_unused(
                intersection, duplicates, intersections
            )
            if is_duplicate:
                return

        # Classify the intersection.
        if interior_curve is None:
            interior_curve = _surface_helpers.classify_intersection(
                intersection, edge_nodes1, edge_nodes2
            )
        intersection.interior_curve = interior_curve
        intersections.append(intersection)


Instruction:
Here you have a function in Python 3, explain what it does
def classify_coincident(st_vals, coincident):
    if not coincident:
        return None

    if st_vals[0, 0] >= st_vals[0, 1] or st_vals[1, 0] >= st_vals[1, 1]:
        return UNUSED_T

    else:
        return CLASSIFICATION_T.COINCIDENT

Response: r Determine if the intersection parameters of two curves are used.


Instruction:
How would you implement a function in Python 3 that
checks if an intersection can be used as part of a curved polygon.

Response:
def should_use(intersection):
    """Check if an intersection can be used as part of a curved polygon.

    Will return :data:`True` if the intersection is classified as
    :attr:`~.IntersectionClassification.FIRST`,
    :attr:`~.IntersectionClassification.SECOND` or
    :attr:`~.IntersectionClassification.COINCIDENT` or if the intersection
    is classified is a corner / edge end which is classified as
    :attr:`~.IntersectionClassification.TANGENT_FIRST` or
    :attr:`~.IntersectionClassification.TANGENT_SECOND`.

    Args:
        intersection (.Intersection): An intersection to be added.

    Returns:
        bool: Indicating if the intersection will be used.
    """
    if intersection.interior_curve in ACCEPTABLE_CLASSIFICATIONS:
        return True

    if intersection.interior_curve in TANGENT_CLASSIFICATIONS:
        return intersection.s == 0.0 or intersection.t == 0.0

    return False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def surface_intersections(edge_nodes1, edge_nodes2, all_intersections):
    # NOTE: There is no corresponding "enable", but the disable only applies
    #       in this lexical scope.
    # pylint: disable=too-many-locals
    intersections = []
    duplicates = []
    for index1, nodes1 in enumerate(edge_nodes1):
        for index2, nodes2 in enumerate(edge_nodes2):
            st_vals, coincident = all_intersections(nodes1, nodes2)
            interior_curve = classify_coincident(st_vals, coincident)
            for s, t in st_vals.T:
                add_intersection(
                    index1,
                    s,
                    index2,
                    t,
                    interior_curve,
                    edge_nodes1,
                    edge_nodes2,
                    duplicates,
                    intersections,
                )
    all_types = set()
    to_keep = []
    unused = []
    for intersection in intersections:
        all_types.add(intersection.interior_curve)
        # Only keep the intersections which are "acceptable".
        if should_use(intersection):
            to_keep.append(intersection)
        else:
            unused.append(intersection)
    return to_keep, duplicates, unused, all_types

Response: Find all intersections among edges of two surfaces.


Instruction:
Explain what the following Python 3 code does
def generic_intersect(
    nodes1, degree1, nodes2, degree2, verify, all_intersections
):
    r"""Find all intersections among edges of two surfaces.

    This treats intersections which have ``s == 1.0`` or ``t == 1.0``
    as duplicates. The duplicates will be checked by :func:`verify_duplicates`
    if ``verify`` is :data:`True`.

    Args:
        nodes1 (numpy.ndarray): The nodes defining the first surface in
            the intersection (assumed in :math:\mathbf{R}^2`).
        degree1 (int): The degree of the surface given by ``nodes1``.
        nodes2 (numpy.ndarray): The nodes defining the second surface in
            the intersection (assumed in :math:\mathbf{R}^2`).
        degree2 (int): The degree of the surface given by ``nodes2``.
        verify (Optional[bool]): Indicates if duplicate intersections
            should be checked.
        all_intersections (Callable): A helper that intersects B |eacute| zier
            curves. Takes the nodes of each curve as input and returns an
            array (``2 x N``) of intersections.

    Returns:
        Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of

        * List of "edge info" lists. Each list represents a curved polygon
          and contains 3-tuples of edge index, start and end (see the
          output of :func:`ends_to_curve`).
        * "Contained" boolean. If not :data:`None`, indicates
          that one of the surfaces is contained in the other.
        * The nodes of three edges of the first surface being intersected
          followed by the nodes of the three edges of the second.
    """
    bbox_int = _geometric_intersection.bbox_intersect(nodes1, nodes2)
    if bbox_int != INTERSECTION_T:
        return [], None, ()

    # We need **all** edges (as nodes).
    edge_nodes1 = _surface_helpers.compute_edge_nodes(nodes1, degree1)
    edge_nodes2 = _surface_helpers.compute_edge_nodes(nodes2, degree2)
    # Run through **all** pairs of edges.
    intersections, duplicates, unused, all_types = surface_intersections(
        edge_nodes1, edge_nodes2, all_intersections
    )
    edge_infos, contained = _surface_helpers.combine_intersections(
        intersections, nodes1, degree1, nodes2, degree2, all_types
    )
    # Verify the duplicates and intersection if need be.
    if verify:
        verify_duplicates(duplicates, intersections + unused)
        verify_edge_segments(edge_infos)
    if edge_infos is None or edge_infos == []:
        return edge_infos, contained, ()

    return edge_infos, contained, edge_nodes1 + edge_nodes2

Response: r Returns a list of lists of edges that intersect the two surfaces.


Instruction:
How would you explain what the following Python 3 function does
def _geometric_intersect(nodes1, degree1, nodes2, degree2, verify):
    all_intersections = _geometric_intersection.all_intersections
    return generic_intersect(
        nodes1, degree1, nodes2, degree2, verify, all_intersections
    )

Response: r Returns a tuple of lists containing intersections between two surfaces.


Instruction:
Explain what the following Python 3 code does
def algebraic_intersect(nodes1, degree1, nodes2, degree2, verify):
    all_intersections = _algebraic_intersection.all_intersections
    return generic_intersect(
        nodes1, degree1, nodes2, degree2, verify, all_intersections
    )

Response: r Returns a tuple of lists containing all intersections among the two surfaces.


Instruction:
Implement a function in Python 3 to
modify the module search path.

Response:
def modify_path():
    """Modify the module search path."""
    # Only modify path on Windows.
    if os.name != "nt":
        return

    path = os.environ.get("PATH")
    if path is None:
        return

    try:
        extra_dll_dir = pkg_resources.resource_filename("bezier", "extra-dll")
        if os.path.isdir(extra_dll_dir):
            os.environ["PATH"] = path + os.pathsep + extra_dll_dir
    except ImportError:
        pass


Instruction:
Can you generate a brief explanation for the following Python 3 code
def handle_import_error(caught_exc, name):
    for template in TEMPLATES:
        expected_msg = template.format(name)
        if caught_exc.args == (expected_msg,):
            return

    raise caught_exc

Response: Allow or re - raise an import error.


Instruction:
Create a Python 3 function for
checking if the current build is gfortran on macOS.

Response:
def is_macos_gfortran(f90_compiler):
    """Checks if the current build is ``gfortran`` on macOS.

    Args:
        f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler
            instance.

    Returns:
        bool: Only :data:`True` if

        * Current OS is macOS (checked via ``sys.platform``).
        * ``f90_compiler`` corresponds to ``gfortran``.
    """
    # NOTE: NumPy may not be installed, but we don't want **this** module to
    #       cause an import failure.
    from numpy.distutils.fcompiler import gnu

    # Only macOS.
    if sys.platform != MAC_OS:
        return False

    # Only ``gfortran``.
    if not isinstance(f90_compiler, gnu.Gnu95FCompiler):
        return False

    return True


Instruction:
Implement a function in Python 3 to
patch up the Fortran Gnu95FCompiler s library_dirs.

Response:
def patch_f90_compiler(f90_compiler):
    """Patch up ``f90_compiler.library_dirs``.

    On macOS, a Homebrew installed ``gfortran`` needs some help. The
    ``numpy.distutils`` "default" constructor for ``Gnu95FCompiler`` only has
    a single library search path, but there are many library paths included in
    the full ``gcc`` install.

    Args:
        f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler
            instance.
    """
    if not is_macos_gfortran(f90_compiler):
        return

    library_dirs = f90_compiler.library_dirs
    # ``library_dirs`` is a list (i.e. mutable), so we can update in place.
    library_dirs[:] = setup_helpers.gfortran_search_path(library_dirs)


Instruction:
Create a Python 3 function for
converting a description of edges into a curved polygon.

Response:
def _make_intersection(edge_info, all_edge_nodes):
    """Convert a description of edges into a curved polygon.

    .. note::

       This is a helper used only by :meth:`.Surface.intersect`.

    Args:
        edge_info (Tuple[Tuple[int, float, float], ...]): Information
            describing each edge in the curved polygon by indicating which
            surface / edge on the surface and then start and end parameters
            along that edge. (See :func:`.ends_to_curve`.)
        all_edge_nodes (Tuple[numpy.ndarray, ...]): The nodes of three edges
            of the first surface being intersected followed by the nodes of
            the three edges of the second.

    Returns:
        .CurvedPolygon: The intersection corresponding to ``edge_info``.
    """
    edges = []
    for index, start, end in edge_info:
        nodes = all_edge_nodes[index]
        new_nodes = _curve_helpers.specialize_curve(nodes, start, end)
        degree = new_nodes.shape[1] - 1
        edge = _curve_mod.Curve(new_nodes, degree, _copy=False)
        edges.append(edge)
    return curved_polygon.CurvedPolygon(
        *edges, metadata=edge_info, _verify=False
    )


Instruction:
Given the following Python 3 function, write the documentation
def from_nodes(cls, nodes, _copy=True):
        _, num_nodes = nodes.shape
        degree = cls._get_degree(num_nodes)
        return cls(nodes, degree, _copy=_copy)

Response: Create a : class :. Surface from a numpy array of nodes.


Instruction:
Given the following Python 3 function, write the documentation
def _get_degree(num_nodes):
        # 8 * num_nodes = 4(d + 1)(d + 2)
        #               = 4d^2 + 12d + 8
        #               = (2d + 3)^2 - 1
        d_float = 0.5 * (np.sqrt(8.0 * num_nodes + 1.0) - 3.0)
        d_int = int(np.round(d_float))
        if (d_int + 1) * (d_int + 2) == 2 * num_nodes:
            return d_int

        else:
            raise ValueError(num_nodes, "not a triangular number")

Response: Get the degree of the current surface.


Instruction:
Here you have a function in Python 3, explain what it does
def area(self):
        if self._dimension != 2:
            raise NotImplementedError(
                "2D is the only supported dimension",
                "Current dimension",
                self._dimension,
            )

        edge1, edge2, edge3 = self._get_edges()
        return _surface_helpers.compute_area(
            (edge1._nodes, edge2._nodes, edge3._nodes)
        )

Response: Calculates the area of the current surface.


Instruction:
Can you tell what is the following Python 3 function doing
def _compute_edges(self):
        nodes1, nodes2, nodes3 = _surface_helpers.compute_edge_nodes(
            self._nodes, self._degree
        )
        edge1 = _curve_mod.Curve(nodes1, self._degree, _copy=False)
        edge2 = _curve_mod.Curve(nodes2, self._degree, _copy=False)
        edge3 = _curve_mod.Curve(nodes3, self._degree, _copy=False)
        return edge1, edge2, edge3

Response: Compute the edges of the current node and edge of the current node.


Instruction:
Implement a function in Python 3 to
get the edges for the current surface.

Response:
def _get_edges(self):
        """Get the edges for the current surface.

        If they haven't been computed yet, first compute and store them.

        This is provided as a means for internal calls to get the edges
        without copying (since :attr:`.edges` copies before giving to
        a user to keep the stored data immutable).

        Returns:
            Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \
                  ~bezier.curve.Curve]: The edges of
            the surface.
        """
        if self._edges is None:
            self._edges = self._compute_edges()
        return self._edges


Instruction:
Make a summary of the following Python 3 code
def _verify_barycentric(lambda1, lambda2, lambda3):
        weights_total = lambda1 + lambda2 + lambda3
        if not np.allclose(weights_total, 1.0, atol=0.0):
            raise ValueError(
                "Weights do not sum to 1", lambda1, lambda2, lambda3
            )

        if lambda1 < 0.0 or lambda2 < 0.0 or lambda3 < 0.0:
            raise ValueError(
                "Weights must be positive", lambda1, lambda2, lambda3
            )

Response: Verifies that the weights are barycentric and on the reference triangle.


Instruction:
Explain what the following Python 3 code does
def evaluate_barycentric_multi(self, param_vals, _verify=True):
        if _verify:
            if param_vals.ndim != 2:
                raise ValueError("Parameter values must be 2D array")

            for lambda1, lambda2, lambda3 in param_vals:
                self._verify_barycentric(lambda1, lambda2, lambda3)
        return _surface_helpers.evaluate_barycentric_multi(
            self._nodes, self._degree, param_vals, self._dimension
        )

Response: r This method evaluates multiple points on the surface.


Instruction:
Given the following Python 3 function, write the documentation
def _verify_cartesian(s, t):
        if s < 0.0 or t < 0.0 or s + t > 1.0:
            raise ValueError("Point lies outside reference triangle", s, t)

Response: Verifies that a point is in the reference triangle.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def evaluate_cartesian(self, s, t, _verify=True):
        if _verify:
            self._verify_cartesian(s, t)
        return _surface_helpers.evaluate_barycentric(
            self._nodes, self._degree, 1.0 - s - t, s, t
        )

Response: r Returns a point on the surface.


Instruction:
Can you tell what is the following Python 3 function doing
def plot(self, pts_per_edge, color=None, ax=None, with_nodes=False):
        if self._dimension != 2:
            raise NotImplementedError(
                "2D is the only supported dimension",
                "Current dimension",
                self._dimension,
            )

        if ax is None:
            ax = _plot_helpers.new_axis()
        _plot_helpers.add_patch(ax, color, pts_per_edge, *self._get_edges())
        if with_nodes:
            ax.plot(
                self._nodes[0, :],
                self._nodes[1, :],
                color="black",
                marker="o",
                linestyle="None",
            )
        return ax

Response: Plots the current control points of the current object.


Instruction:
Can you tell what is the following Python 3 function doing
def subdivide(self):
        nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes(
            self._nodes, self._degree
        )
        return (
            Surface(nodes_a, self._degree, _copy=False),
            Surface(nodes_b, self._degree, _copy=False),
            Surface(nodes_c, self._degree, _copy=False),
            Surface(nodes_d, self._degree, _copy=False),
        )

Response: Split the surface into four sub - surfaces.


Instruction:
Explain what the following Python 3 code does
def locate(self, point, _verify=True):
        if _verify:
            if self._dimension != 2:
                raise NotImplementedError("Only 2D surfaces supported.")

            if point.shape != (self._dimension, 1):
                point_dimensions = " x ".join(
                    str(dimension) for dimension in point.shape
                )
                msg = _LOCATE_ERROR_TEMPLATE.format(
                    self._dimension, self._dimension, point, point_dimensions
                )
                raise ValueError(msg)

        return _surface_intersection.locate_point(
            self._nodes, self._degree, point[0, 0], point[1, 0]
        )

Response: r Returns the s t and t values corresponding to the point on the current surface.


Instruction:
How would you explain what the following Python 3 function does
def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True):
        if _verify:
            if not isinstance(other, Surface):
                raise TypeError(
                    "Can only intersect with another surface",
                    "Received",
                    other,
                )

            if self._dimension != 2 or other._dimension != 2:
                raise NotImplementedError(
                    "Intersection only implemented in 2D"
                )

        if strategy == _STRATEGY.GEOMETRIC:
            do_intersect = _surface_intersection.geometric_intersect
        elif strategy == _STRATEGY.ALGEBRAIC:
            do_intersect = _surface_intersection.algebraic_intersect
        else:
            raise ValueError("Unexpected strategy.", strategy)

        edge_infos, contained, all_edge_nodes = do_intersect(
            self._nodes, self._degree, other._nodes, other._degree, _verify
        )
        if edge_infos is None:
            if contained:
                return [self]

            else:
                return [other]

        else:
            return [
                _make_intersection(edge_info, all_edge_nodes)
                for edge_info in edge_infos
            ]

Response: Find the common intersection with another surface.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def elevate(self):
        _, num_nodes = self._nodes.shape
        # (d + 1)(d + 2)/2 --> (d + 2)(d + 3)/2
        num_new = num_nodes + self._degree + 2
        new_nodes = np.zeros((self._dimension, num_new), order="F")
        # NOTE: We start from the index triples (i, j, k) for the current
        #       nodes and map them onto (i + 1, j, k), etc. This index
        #       tracking is also done in :func:`.de_casteljau_one_round`.
        index = 0
        # parent_i1 = index + k
        # parent_i2 = index + k + 1
        # parent_i3 = index + degree + 2
        parent_i1 = 0
        parent_i2 = 1
        parent_i3 = self._degree + 2
        for k in six.moves.xrange(self._degree + 1):
            for j in six.moves.xrange(self._degree + 1 - k):
                i = self._degree - j - k
                new_nodes[:, parent_i1] += (i + 1) * self._nodes[:, index]
                new_nodes[:, parent_i2] += (j + 1) * self._nodes[:, index]
                new_nodes[:, parent_i3] += (k + 1) * self._nodes[:, index]
                # Update all the indices.
                parent_i1 += 1
                parent_i2 += 1
                parent_i3 += 1
                index += 1
            # Update the indices that depend on k.
            parent_i1 += 1
            parent_i2 += 1
        # Hold off on division until the end, to (attempt to) avoid round-off.
        denominator = self._degree + 1.0
        new_nodes /= denominator
        return Surface(new_nodes, self._degree + 1, _copy=False)

Response: r Return a degree - elevated version of the current surface.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _newton_refine(s, nodes1, t, nodes2):
    # NOTE: We form -F(s, t) since we want to solve -DF^{-1} F(s, t).
    func_val = _curve_helpers.evaluate_multi(
        nodes2, np.asfortranarray([t])
    ) - _curve_helpers.evaluate_multi(nodes1, np.asfortranarray([s]))
    if np.all(func_val == 0.0):
        # No refinement is needed.
        return s, t

    # NOTE: This assumes the curves are 2D.
    jac_mat = np.empty((2, 2), order="F")
    jac_mat[:, :1] = _curve_helpers.evaluate_hodograph(s, nodes1)
    jac_mat[:, 1:] = -_curve_helpers.evaluate_hodograph(t, nodes2)
    # Solve the system.
    singular, delta_s, delta_t = _helpers.solve2x2(jac_mat, func_val[:, 0])
    if singular:
        raise ValueError("Jacobian is singular.")

    else:
        return s + delta_s, t + delta_t

Response: r Apply one step of 2D Newton s method.


Instruction:
Implement a Python 3 function for
getting the library directory paths for ``gfortran``. Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs`` and then parses the paths. If this fails for any reason, this method will print an error and return ``library_dirs``. Args: library_dirs (List[str]): Existing library directories. Returns: List[str]: The library directories for ``gfortran``.

Response:
def gfortran_search_path(library_dirs):
    """Get the library directory paths for ``gfortran``.

    Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs``
    and then parses the paths. If this fails for any reason, this method will
    print an error and return ``library_dirs``.

    Args:
        library_dirs (List[str]): Existing library directories.

    Returns:
        List[str]: The library directories for ``gfortran``.
    """
    cmd = ("gfortran", "-print-search-dirs")
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    return_code = process.wait()
    # Bail out if the command failed.
    if return_code != 0:
        return library_dirs

    cmd_output = process.stdout.read().decode("utf-8")
    # Find single line starting with ``libraries: ``.
    search_lines = cmd_output.strip().split("\n")
    library_lines = [
        line[len(FORTRAN_LIBRARY_PREFIX) :]
        for line in search_lines
        if line.startswith(FORTRAN_LIBRARY_PREFIX)
    ]
    if len(library_lines) != 1:
        msg = GFORTRAN_MISSING_LIBS.format(cmd_output)
        print(msg, file=sys.stderr)
        return library_dirs

    # Go through each library in the ``libraries: = ...`` line.
    library_line = library_lines[0]
    accepted = set(library_dirs)
    for part in library_line.split(os.pathsep):
        full_path = os.path.abspath(part.strip())
        if os.path.isdir(full_path):
            accepted.add(full_path)
        else:
            # Ignore anything that isn't a directory.
            msg = GFORTRAN_BAD_PATH.format(full_path)
            print(msg, file=sys.stderr)
    return sorted(accepted)


Instruction:
Write a Python 3 function that can
update a given set of compiler flags.

Response:
def _update_flags(compiler_flags, remove_flags=()):
    """Update a given set of compiler flags.

    Args:
        compiler_flags (List[str]): Existing flags associated with a compiler.
        remove_flags (Optional[Container[str]]): A container of flags to remove
            that will override any of the defaults.

    Returns:
        List[str]: The modified list (i.e. some flags added and some removed).
    """
    for flag in GFORTRAN_SHARED_FLAGS:
        if flag not in compiler_flags:
            compiler_flags.append(flag)
    if DEBUG_ENV in os.environ:
        to_add = GFORTRAN_DEBUG_FLAGS
        to_remove = GFORTRAN_OPTIMIZE_FLAGS
    else:
        to_add = GFORTRAN_OPTIMIZE_FLAGS
        if os.environ.get(WHEEL_ENV) is None:
            to_add += (GFORTRAN_NATIVE_FLAG,)
        to_remove = GFORTRAN_DEBUG_FLAGS
    for flag in to_add:
        if flag not in compiler_flags:
            compiler_flags.append(flag)
    return [
        flag
        for flag in compiler_flags
        if not (flag in to_remove or flag in remove_flags)
    ]


Instruction:
Can you write a function in Python 3 where it
patches up f90_compiler. gfortran. f90. gfortran. f90. f90.

Response:
def patch_f90_compiler(f90_compiler):
    """Patch up ``f90_compiler``.

    For now, only updates the flags for ``gfortran``. In this case, it add
    any of ``GFORTRAN_SHARED_FLAGS`` that are missing. In debug mode, it also
    adds any flags in ``GFORTRAN_DEBUG_FLAGS`` and makes sure none of the flags
    in ``GFORTRAN_OPTIMIZE_FLAGS`` are present. In standard mode ("OPTIMIZE"),
    makes sure flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present and flags in
    ``GFORTRAN_DEBUG_FLAGS`` are not.

    Args:
        f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler
            instance.
    """
    # NOTE: NumPy may not be installed, but we don't want **this** module to
    #       cause an import failure in ``setup.py``.
    from numpy.distutils.fcompiler import gnu

    # Only ``gfortran``.
    if not isinstance(f90_compiler, gnu.Gnu95FCompiler):
        return False

    f90_compiler.compiler_f77[:] = _update_flags(
        f90_compiler.compiler_f77, remove_flags=("-Werror",)
    )
    f90_compiler.compiler_f90[:] = _update_flags(f90_compiler.compiler_f90)


Instruction:
Can you create a Python 3 function that
starts the journaling of the current entry point.

Response:
def start_journaling(self):
        """Capture calls to the system by compilers.

        See: https://github.com/numpy/numpy/blob/v1.15.2/\
        numpy/distutils/ccompiler.py#L154

        Intercepts all calls to ``CCompiler.spawn`` and keeps the
        arguments around to be stored in the local ``commands``
        instance attribute.
        """
        import numpy.distutils.ccompiler

        if self.journal_file is None:
            return

        def journaled_spawn(patched_self, cmd, display=None):
            self.commands.append(cmd)
            return numpy.distutils.ccompiler.CCompiler_spawn(
                patched_self, cmd, display=None
            )

        numpy.distutils.ccompiler.replace_method(
            distutils.ccompiler.CCompiler, "spawn", journaled_spawn
        )


Instruction:
How would you explain what the following Python 3 function does
def save_journal(self):
        if self.journal_file is None:
            return

        try:
            as_text = self._commands_to_text()
            with open(self.journal_file, "w") as file_obj:
                file_obj.write(as_text)
        except Exception as exc:
            msg = BAD_JOURNAL.format(exc)
            print(msg, file=sys.stderr)

Response: Save the commands to a file.


Instruction:
How would you implement a function in Python 3 that
creates a static library for the current locale.

Response:
def _default_static_lib(self, obj_files):
        """Create a static library (i.e. a ``.a`` / ``.lib`` file).

        Args:
            obj_files (List[str]): List of paths of compiled object files.
        """
        c_compiler = self.F90_COMPILER.c_compiler
        static_lib_dir = os.path.join(self.build_lib, "bezier", "lib")
        if not os.path.exists(static_lib_dir):
            os.makedirs(static_lib_dir)
        c_compiler.create_static_lib(
            obj_files, "bezier", output_dir=static_lib_dir
        )
        # NOTE: We must "modify" the paths for the ``extra_objects`` in
        #       each extension since they were compiled with
        #       ``output_dir=self.build_temp``.
        for extension in self.extensions:
            extension.extra_objects[:] = [
                os.path.join(self.build_temp, rel_path)
                for rel_path in extension.extra_objects
            ]


Instruction:
Given the following Python 3 function, write the documentation
def _default_cleanup(self):
        if not self.inplace:
            return

        shutil.move(
            os.path.join(self.build_lib, "bezier", "lib"),
            os.path.join("src", "bezier"),
        )

Response: Default cleanup after run.


Instruction:
Write a Python 3 script to
verify that two consecutive edge endpoints share an endpoint.

Response:
def _verify_pair(prev, curr):
        """Verify a pair of sides share an endpoint.

        .. note::

           This currently checks that edge endpoints match **exactly**
           but allowing some roundoff may be desired.

        Args:
            prev (.Curve): "Previous" curve at piecewise junction.
            curr (.Curve): "Next" curve at piecewise junction.

        Raises:
            ValueError: If the previous side is not in 2D.
            ValueError: If consecutive sides don't share an endpoint.
        """
        if prev._dimension != 2:
            raise ValueError("Curve not in R^2", prev)

        end = prev._nodes[:, -1]
        start = curr._nodes[:, 0]
        if not _helpers.vector_close(end, start):
            raise ValueError(
                "Not sufficiently close",
                "Consecutive sides do not have common endpoint",
                prev,
                curr,
            )


Instruction:
How would you implement a function in Python 3 that
verifies that the edges define a curved polygon.

Response:
def _verify(self):
        """Verify that the edges define a curved polygon.

        This may not be entirely comprehensive, e.g. won't check
        self-intersection of the defined polygon.

        .. note::

           This currently checks that edge endpoints match **exactly**
           but allowing some roundoff may be desired.

        Raises:
            ValueError: If there are fewer than two sides.
            ValueError: If one of the sides is not in 2D.
            ValueError: If consecutive sides don't share an endpoint.
        """
        if self._num_sides < 2:
            raise ValueError("At least two sides required.")

        for prev, curr in six.moves.zip(self._edges, self._edges[1:]):
            self._verify_pair(prev, curr)
        # Now we check that the final edge wraps around.
        prev = self._edges[-1]
        curr = self._edges[0]
        self._verify_pair(prev, curr)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def area(self):
        edges = tuple(edge._nodes for edge in self._edges)
        return _surface_helpers.compute_area(edges)

Response: r A method to compute the area of the current curved polygon.


Instruction:
Given the following Python 3 function, write the documentation
def plot(self, pts_per_edge, color=None, ax=None):
        if ax is None:
            ax = _plot_helpers.new_axis()
        _plot_helpers.add_patch(ax, color, pts_per_edge, *self._edges)
        return ax

Response: Plot the current curved polygon.


Instruction:
Make a summary of the following Python 3 code
def compute_implicit_line(nodes):
    delta = nodes[:, -1] - nodes[:, 0]
    length = np.linalg.norm(delta, ord=2)
    # Normalize and rotate 90 degrees to the "left".
    coeff_a = -delta[1] / length
    coeff_b = delta[0] / length
    # c = - ax - by = (delta[1] x - delta[0] y) / L
    # NOTE: We divide by ``length`` at the end to "put off" rounding.
    coeff_c = (delta[1] * nodes[0, 0] - delta[0] * nodes[1, 0]) / length
    return coeff_a, coeff_b, coeff_c

Response: Compute the implicit form of the line connecting curve endpoints.


Instruction:
Given the following Python 3 function, write the documentation
def compute_fat_line(nodes):
    coeff_a, coeff_b, coeff_c = compute_implicit_line(nodes)
    # NOTE: This assumes, but does not check, that there are two rows.
    _, num_nodes = nodes.shape
    d_min = 0.0
    d_max = 0.0
    for index in six.moves.xrange(1, num_nodes - 1):  # Only interior nodes.
        curr_dist = (
            coeff_a * nodes[0, index] + coeff_b * nodes[1, index] + coeff_c
        )
        if curr_dist < d_min:
            d_min = curr_dist
        elif curr_dist > d_max:
            d_max = curr_dist
    return coeff_a, coeff_b, coeff_c, d_min, d_max

Response: Compute the fat line around a B |eacute| zier curve.


Instruction:
Implement a function in Python 3 to
update the start and end of the clipped parameter range.

Response:
def _update_parameters(s_min, s_max, start0, end0, start1, end1):
    """Update clipped parameter range.

    .. note::

       This is a helper for :func:`clip_range`.

    Does so by intersecting one of the two fat lines with an edge
    of the convex hull of the distance polynomial of the curve being
    clipped.

    If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s`
    value that is valid for ``s_min`` would also be valid for ``s_max``.
    Rather than adding a special case to handle this scenario, **only**
    ``s_min`` will be updated.

    In cases where a given parameter :math:`s` would be a valid update
    for both ``s_min`` and ``s_max``
    This function **only** updates ``s_min``

    Args:
        s_min (float): Current start of clipped interval. If "unset", this
            value will be ``DEFAULT_S_MIN``.
        s_max (float): Current end of clipped interval. If "unset", this
            value will be ``DEFAULT_S_MAX``.
        start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start
            vector of one of the two fat lines.
        end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end
            vector of one of the two fat lines.
        start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start
            vector of an edge of the convex hull of the distance
            polynomial :math:`d(t)` as an explicit B |eacute| zier curve.
        end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end
            vector of an edge of the convex hull of the distance
            polynomial :math:`d(t)` as an explicit B |eacute| zier curve.

    Returns:
        Tuple[float, float]: The (possibly updated) start and end
        of the clipped parameter range.

    Raises:
        NotImplementedError: If the two line segments are parallel. (This
            case will be supported at some point, just not now.)
    """
    s, t, success = _geometric_intersection.segment_intersection(
        start0, end0, start1, end1
    )
    if not success:
        raise NotImplementedError(NO_PARALLEL)

    if _helpers.in_interval(t, 0.0, 1.0):
        if _helpers.in_interval(s, 0.0, s_min):
            return s, s_max

        elif _helpers.in_interval(s, s_max, 1.0):
            return s_min, s

    return s_min, s_max


Instruction:
Can you generate the documentation for the following Python 3 function
def _check_parameter_range(s_min, s_max):
    if s_min == DEFAULT_S_MIN:
        # Based on the way ``_update_parameters`` works, we know
        # both parameters must be unset if ``s_min``.
        return 0.0, 1.0

    if s_max == DEFAULT_S_MAX:
        return s_min, s_min

    return s_min, s_max

Response: r This function checks the range of the current time range.


Instruction:
How would you explain what the following Python 3 function does
def clip_range(nodes1, nodes2):
    # NOTE: There is no corresponding "enable", but the disable only applies
    #       in this lexical scope.
    # pylint: disable=too-many-locals
    coeff_a, coeff_b, coeff_c, d_min, d_max = compute_fat_line(nodes1)
    # NOTE: This assumes, but does not check, that there are two rows.
    _, num_nodes2 = nodes2.shape
    polynomial = np.empty((2, num_nodes2), order="F")
    denominator = float(num_nodes2 - 1)
    for index in six.moves.xrange(num_nodes2):
        polynomial[0, index] = index / denominator
        polynomial[1, index] = (
            coeff_a * nodes2[0, index] + coeff_b * nodes2[1, index] + coeff_c
        )
    # Define segments for the top and the bottom of the region
    # bounded by the fat line.
    start_bottom = np.asfortranarray([0.0, d_min])
    end_bottom = np.asfortranarray([1.0, d_min])
    start_top = np.asfortranarray([0.0, d_max])
    end_top = np.asfortranarray([1.0, d_max])
    s_min = DEFAULT_S_MIN
    s_max = DEFAULT_S_MAX
    # NOTE: We avoid computing the convex hull and just compute where
    #       all segments connecting two control points intersect the
    #       fat lines.
    for start_index in six.moves.xrange(num_nodes2 - 1):
        for end_index in six.moves.xrange(start_index + 1, num_nodes2):
            s_min, s_max = _update_parameters(
                s_min,
                s_max,
                start_bottom,
                end_bottom,
                polynomial[:, start_index],
                polynomial[:, end_index],
            )
            s_min, s_max = _update_parameters(
                s_min,
                s_max,
                start_top,
                end_top,
                polynomial[:, start_index],
                polynomial[:, end_index],
            )
    return _check_parameter_range(s_min, s_max)

Response: r Reduce the parameter range where two curves can intersect.


Instruction:
Write a Python 3 function for
posting - process a generated journal file on Travis macOS.

Response:
def post_process_travis_macos(journal_filename):
    """Post-process a generated journal file on Travis macOS.

    Args:
        journal_filename (str): The name of the journal file.
    """
    travis_build_dir = os.environ.get("TRAVIS_BUILD_DIR", "")
    with open(journal_filename, "r") as file_obj:
        content = file_obj.read()
    processed = content.replace(travis_build_dir, "${TRAVIS_BUILD_DIR}")
    with open(journal_filename, "w") as file_obj:
        file_obj.write(processed)


Instruction:
Can you tell what is the following Python 3 function doing
def mod_replace(match, sphinx_modules):
    sphinx_modules.append(match.group("module"))
    return "`{}`_".format(match.group("value"))

Response: Convert Sphinx mod name to plain reST link name.


Instruction:
How would you implement a function in Python 3 that
converts Sphinx doc to plain reST link.

Response:
def doc_replace(match, sphinx_docs):
    """Convert Sphinx ``:doc:`` to plain reST link.

    Args:
        match (_sre.SRE_Match): A match (from ``re``) to be used
            in substitution.
        sphinx_docs (list): List to be track the documents that have been
            encountered.

    Returns:
        str: The ``match`` converted to a link.
    """
    sphinx_docs.append(match.group("path"))
    return "`{}`_".format(match.group("value"))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_diff(value1, value2, name1, name2):
    lines1 = [line + "\n" for line in value1.splitlines()]
    lines2 = [line + "\n" for line in value2.splitlines()]
    diff_lines = difflib.context_diff(
        lines1, lines2, fromfile=name1, tofile=name2
    )
    return "".join(diff_lines)

Response: Get a diff between two strings.


Instruction:
Here you have a function in Python 3, explain what it does
def populate_readme(revision, rtd_version, **extra_kwargs):
    with open(TEMPLATE_FILE, "r") as file_obj:
        template = file_obj.read()
    img_prefix = IMG_PREFIX.format(revision=revision)
    extra_links = EXTRA_LINKS.format(
        rtd_version=rtd_version, revision=revision
    )
    docs_img = DOCS_IMG.format(rtd_version=rtd_version)
    bernstein_basis = BERNSTEIN_BASIS_PLAIN.format(img_prefix=img_prefix)
    bezier_defn = BEZIER_DEFN_PLAIN.format(img_prefix=img_prefix)
    sum_to_unity = SUM_TO_UNITY_PLAIN.format(img_prefix=img_prefix)
    template_kwargs = {
        "code_block1": PLAIN_CODE_BLOCK,
        "code_block2": PLAIN_CODE_BLOCK,
        "code_block3": PLAIN_CODE_BLOCK,
        "testcleanup": "",
        "toctree": "",
        "bernstein_basis": bernstein_basis,
        "bezier_defn": bezier_defn,
        "sum_to_unity": sum_to_unity,
        "img_prefix": img_prefix,
        "extra_links": extra_links,
        "docs": "|docs| ",
        "docs_img": docs_img,
        "pypi": "\n\n|pypi| ",
        "pypi_img": PYPI_IMG,
        "versions": "|versions|\n\n",
        "versions_img": VERSIONS_IMG,
        "rtd_version": rtd_version,
        "revision": revision,
        "circleci_badge": CIRCLECI_BADGE,
        "circleci_path": "",
        "travis_badge": TRAVIS_BADGE,
        "travis_path": "",
        "appveyor_badge": APPVEYOR_BADGE,
        "appveyor_path": "",
        "coveralls_badge": COVERALLS_BADGE,
        "coveralls_path": COVERALLS_PATH,
        "zenodo": "|zenodo|",
        "zenodo_img": ZENODO_IMG,
        "joss": " |JOSS|",
        "joss_img": JOSS_IMG,
    }
    template_kwargs.update(**extra_kwargs)
    readme_contents = template.format(**template_kwargs)
    # Apply regular expressions to convert Sphinx "roles" to plain reST.
    readme_contents = INLINE_MATH_EXPR.sub(inline_math, readme_contents)
    sphinx_modules = []
    to_replace = functools.partial(mod_replace, sphinx_modules=sphinx_modules)
    readme_contents = MOD_EXPR.sub(to_replace, readme_contents)
    if sphinx_modules != ["bezier.curve", "bezier.surface"]:
        raise ValueError("Unexpected sphinx_modules", sphinx_modules)

    sphinx_docs = []
    to_replace = functools.partial(doc_replace, sphinx_docs=sphinx_docs)
    readme_contents = DOC_EXPR.sub(to_replace, readme_contents)
    if sphinx_docs != ["python/reference/bezier", "development"]:
        raise ValueError("Unexpected sphinx_docs", sphinx_docs)

    return readme_contents

Response: Populate the README template with values.


Instruction:
Create a Python 3 function to
populate the template and compare to the expected README.

Response:
def readme_verify():
    """Populate the template and compare to ``README``.

    Raises:
        ValueError: If the current README doesn't agree with the expected
            value computed from the template.
    """
    expected = populate_readme(REVISION, RTD_VERSION)
    # Actually get the stored contents.
    with open(README_FILE, "r") as file_obj:
        contents = file_obj.read()
    if contents != expected:
        err_msg = "\n" + get_diff(
            contents, expected, "README.rst.actual", "README.rst.expected"
        )
        raise ValueError(err_msg)

    else:
        print("README contents are as expected.")


Instruction:
How would you explain what the following Python 3 function does
def release_readme_verify():
    version = "{version}"
    expected = populate_readme(
        version,
        version,
        pypi="",
        pypi_img="",
        versions="\n\n",
        versions_img="",
        circleci_badge=CIRCLECI_BADGE_RELEASE,
        circleci_path="/{circleci_build}",
        travis_badge=TRAVIS_BADGE_RELEASE,
        travis_path="/builds/{travis_build}",
        appveyor_badge=APPVEYOR_BADGE_RELEASE,
        appveyor_path="/build/{appveyor_build}",
        coveralls_badge=COVERALLS_BADGE_RELEASE,
        coveralls_path="builds/{coveralls_build}",
    )
    with open(RELEASE_README_FILE, "r") as file_obj:
        contents = file_obj.read()
    if contents != expected:
        err_msg = "\n" + get_diff(
            contents,
            expected,
            "README.rst.release.actual",
            "README.rst.release.expected",
        )
        raise ValueError(err_msg)

    else:
        print("README.rst.release.template contents are as expected.")

Response: Specialize the template to a PyPI release template.


Instruction:
Make a summary of the following Python 3 code
def _index_verify(index_file, **extra_kwargs):
    side_effect = extra_kwargs.pop("side_effect", None)
    with open(TEMPLATE_FILE, "r") as file_obj:
        template = file_obj.read()
    template_kwargs = {
        "code_block1": SPHINX_CODE_BLOCK1,
        "code_block2": SPHINX_CODE_BLOCK2,
        "code_block3": SPHINX_CODE_BLOCK3,
        "testcleanup": TEST_CLEANUP,
        "toctree": TOCTREE,
        "bernstein_basis": BERNSTEIN_BASIS_SPHINX,
        "bezier_defn": BEZIER_DEFN_SPHINX,
        "sum_to_unity": SUM_TO_UNITY_SPHINX,
        "img_prefix": "",
        "extra_links": "",
        "docs": "",
        "docs_img": "",
        "pypi": "\n\n|pypi| ",
        "pypi_img": PYPI_IMG,
        "versions": "|versions|\n\n",
        "versions_img": VERSIONS_IMG,
        "rtd_version": RTD_VERSION,
        "revision": REVISION,
        "circleci_badge": CIRCLECI_BADGE,
        "circleci_path": "",
        "travis_badge": TRAVIS_BADGE,
        "travis_path": "",
        "appveyor_badge": APPVEYOR_BADGE,
        "appveyor_path": "",
        "coveralls_badge": COVERALLS_BADGE,
        "coveralls_path": COVERALLS_PATH,
        "zenodo": "|zenodo|",
        "zenodo_img": ZENODO_IMG,
        "joss": " |JOSS|",
        "joss_img": JOSS_IMG,
    }
    template_kwargs.update(**extra_kwargs)
    expected = template.format(**template_kwargs)
    if side_effect is not None:
        expected = side_effect(expected)
    with open(index_file, "r") as file_obj:
        contents = file_obj.read()
    if contents != expected:
        err_msg = "\n" + get_diff(
            contents,
            expected,
            index_file + ".actual",
            index_file + ".expected",
        )
        raise ValueError(err_msg)

    else:
        rel_name = os.path.relpath(index_file, _ROOT_DIR)
        msg = "{} contents are as expected.".format(rel_name)
        print(msg)

Response: Populate the template and compare to the index file.


Instruction:
Make a summary of the following Python 3 code
def release_docs_side_effect(content):
    # First replace **all** curly braces.
    result = content.replace("{", "{{").replace("}", "}}")
    # Then reset the actual template arguments.
    result = result.replace("{{version}}", "{version}")
    result = result.replace("{{circleci_build}}", "{circleci_build}")
    result = result.replace("{{travis_build}}", "{travis_build}")
    result = result.replace("{{appveyor_build}}", "{appveyor_build}")
    result = result.replace("{{coveralls_build}}", "{coveralls_build}")
    return result

Response: Updates the template so that curly braces are escaped correctly.


Instruction:
Can you write a function in Python 3 where it
populates template and compare to index. rst. release. template.

Response:
def release_docs_index_verify():
    """Populate template and compare to ``docs/index.rst.release.template``.

    Raises:
        ValueError: If the current ``index.rst.release.template`` doesn't
            agree with the expected value computed from the template.
    """
    version = "{version}"
    _index_verify(
        RELEASE_INDEX_FILE,
        side_effect=release_docs_side_effect,
        pypi="",
        pypi_img="",
        versions="\n\n",
        versions_img="",
        rtd_version=version,
        revision=version,
        circleci_badge=CIRCLECI_BADGE_RELEASE,
        circleci_path="/{circleci_build}",
        travis_badge=TRAVIS_BADGE_RELEASE,
        travis_path="/builds/{travis_build}",
        appveyor_badge=APPVEYOR_BADGE_RELEASE,
        appveyor_path="/build/{appveyor_build}",
        coveralls_badge=COVERALLS_BADGE_RELEASE,
        coveralls_path="builds/{coveralls_build}",
    )


Instruction:
Here you have a function in Python 3, explain what it does
def development_verify():
    with open(DEVELOPMENT_TEMPLATE, "r") as file_obj:
        template = file_obj.read()
    expected = template.format(revision=REVISION, rtd_version=RTD_VERSION)
    with open(DEVELOPMENT_FILE, "r") as file_obj:
        contents = file_obj.read()
    if contents != expected:
        err_msg = "\n" + get_diff(
            contents,
            expected,
            "DEVELOPMENT.rst.actual",
            "DEVELOPMENT.rst.expected",
        )
        raise ValueError(err_msg)

    else:
        print("DEVELOPMENT.rst contents are as expected.")

Response: Populate template and compare to the current development file.


Instruction:
Given the following Python 3 function, write the documentation
def native_libraries_verify():
    with open(BINARY_EXT_TEMPLATE, "r") as file_obj:
        template = file_obj.read()
    expected = template.format(revision=REVISION)
    with open(BINARY_EXT_FILE, "r") as file_obj:
        contents = file_obj.read()
    if contents != expected:
        err_msg = "\n" + get_diff(
            contents,
            expected,
            "docs/python/binary-extension.rst.actual",
            "docs/python/binary-extension.rst.expected",
        )
        raise ValueError(err_msg)

    else:
        print("docs/python/binary-extension.rst contents are as expected.")

Response: Populate the template and compare to the binary - extension. rst file.


Instruction:
Make a summary of the following Python 3 code
def _evaluate3(nodes, x_val, y_val):
    # NOTE: This may be (a) slower and (b) less precise than
    #       hard-coding the determinant.
    sylvester_mat = np.zeros((6, 6), order="F")
    delta = nodes - np.asfortranarray([[x_val], [y_val]])
    delta[:, 1:3] *= 3.0
    # Swap rows/columns so that x-y are right next to each other.
    # This will only change the determinant up to a sign.
    sylvester_mat[:2, :4] = delta
    sylvester_mat[2:4, 1:5] = delta
    sylvester_mat[4:, 2:] = delta
    return np.linalg.det(sylvester_mat)

Response: Helper function for evaluating degree 3.


Instruction:
Can you generate the documentation for the following Python 3 function
def evaluate(nodes, x_val, y_val):
    _, num_nodes = nodes.shape
    if num_nodes == 1:
        raise ValueError("A point cannot be implicitized")

    elif num_nodes == 2:
        # x(s) - x = (x0 - x) (1 - s) + (x1 - x) s
        # y(s) - y = (y0 - y) (1 - s) + (y1 - y) s
        # Modified Sylvester: [x0 - x, x1 - x]
        #                     [y0 - y, y1 - y]
        return (nodes[0, 0] - x_val) * (nodes[1, 1] - y_val) - (
            nodes[0, 1] - x_val
        ) * (nodes[1, 0] - y_val)

    elif num_nodes == 3:
        # x(s) - x = (x0 - x) (1 - s)^2 + 2 (x1 - x) s(1 - s) + (x2 - x) s^2
        # y(s) - y = (y0 - y) (1 - s)^2 + 2 (y1 - y) s(1 - s) + (y2 - y) s^2
        # Modified Sylvester: [x0 - x, 2(x1 - x),    x2 - x,      0] = A|B|C|0
        #                     [     0,    x0 - x, 2(x1 - x), x2 - x]   0|A|B|C
        #                     [y0 - y, 2(y1 - y),    y2 - y,      0]   D|E|F|0
        #                     [     0,    y0 - y, 2(y1 - y), y2 - y]   0|D|E|F
        val_a, val_b, val_c = nodes[0, :] - x_val
        val_b *= 2
        val_d, val_e, val_f = nodes[1, :] - y_val
        val_e *= 2
        #     [A, B, C]         [E, F, 0]
        # det [E, F, 0] = - det [A, B, C] = -E (BF - CE) + F(AF - CD)
        #     [D, E, F]         [D, E, F]
        sub1 = val_b * val_f - val_c * val_e
        sub2 = val_a * val_f - val_c * val_d
        sub_det_a = -val_e * sub1 + val_f * sub2
        #     [B, C, 0]
        # det [A, B, C] = B (BF - CE) - C (AF - CD)
        #     [D, E, F]
        sub_det_d = val_b * sub1 - val_c * sub2
        return val_a * sub_det_a + val_d * sub_det_d

    elif num_nodes == 4:
        return _evaluate3(nodes, x_val, y_val)

    else:
        raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3))

Response: r Evaluates the implicitized bivariate polynomial containing the curve.


Instruction:
Given the following Python 3 function, write the documentation
def _to_power_basis11(nodes1, nodes2):
    # We manually invert the Vandermonde matrix:
    # [1 0][c0] = [n0]
    # [1 1][c1]   [n1]
    val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0)
    val1 = eval_intersection_polynomial(nodes1, nodes2, 1.0)
    # [c0] = [ 1 0][n0]
    # [c1] = [-1 1][n1]
    return np.asfortranarray([val0, -val0 + val1])

Response: r Converts the nodes in nodes1 and nodes2 into a power basis matrix.


Instruction:
Here you have a function in Python 3, explain what it does
def _to_power_basis13(nodes1, nodes2):
    # We manually invert the Vandermonde matrix:
    # Use exact f.p. numbers to avoid round-off wherever possible.
    # [1 0   0    0    ][c0] = [n0]
    # [1 1/4 1/16 1/64 ][c1]   [n1]
    # [1 3/4 9/16 27/64][c2]   [n2]
    # [1 1   1    1    ][c3]   [n3]
    val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0)
    val1 = eval_intersection_polynomial(nodes1, nodes2, 0.25)
    val2 = eval_intersection_polynomial(nodes1, nodes2, 0.75)
    val3 = eval_intersection_polynomial(nodes1, nodes2, 1.0)
    # [c0] =       [  3   0   0   0][n0]
    # [c1] = 1 / 3 [-19  24  -8   3][n1]
    # [c2] =       [ 32 -56  40 -16][n2]
    # [c3] =       [-16  32 -32  16][n3]
    # Since polynomial coefficients, we don't need to divide by 3
    # to get the same polynomial. Avoid the division to avoid round-off.
    return np.asfortranarray(
        [
            3.0 * val0,
            -19.0 * val0 + 24.0 * val1 - 8.0 * val2 + 3.0 * val3,
            32.0 * val0 - 56.0 * val1 + 40.0 * val2 - 16.0 * val3,
            -16.0 * val0 + 32.0 * val1 - 32.0 * val2 + 16.0 * val3,
        ]
    )

Response: r Returns the coefficients of an intersection polynomial.


Instruction:
Make a summary of the following Python 3 code
def _to_power_basis_degree4(nodes1, nodes2):
    # We manually invert the Vandermonde matrix:
    # [1 0   0    0     0     ][c0] = [n0]
    # [1 1/4 1/16 1/64  1/256 ][c1]   [n1]
    # [1 1/2 1/4  1/8   1/16  ][c2]   [n2]
    # [1 3/4 9/16 27/64 81/256][c3]   [n3]
    # [1 1   1    1     1     ][c4]   [n4]
    val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0)
    val1 = eval_intersection_polynomial(nodes1, nodes2, 0.25)
    val2 = eval_intersection_polynomial(nodes1, nodes2, 0.5)
    val3 = eval_intersection_polynomial(nodes1, nodes2, 0.75)
    val4 = eval_intersection_polynomial(nodes1, nodes2, 1.0)
    # [c0] =       [ 3   0    0    0    0 ][n0]
    # [c1] = 1 / 3 [-25  48  -36   16  -3 ][n1]
    # [c2] =       [ 70 -208  228 -112  22][n2]
    # [c3] =       [-80  288 -384  224 -48][n3]
    # [c4] =       [ 32 -128  192 -128  32][n4]
    # Since polynomial coefficients, we don't need to divide by 3
    # to get the same polynomial. Avoid the division to avoid round-off.
    return np.asfortranarray(
        [
            3.0 * val0,
            -25.0 * val0
            + 48.0 * val1
            - 36.0 * val2
            + 16.0 * val3
            - 3.0 * val4,
            70.0 * val0
            - 208.0 * val1
            + 228.0 * val2
            - 112.0 * val3
            + 22.0 * val4,
            (
                -80.0 * val0
                + 288.0 * val1
                - 384.0 * val2
                + 224.0 * val3
                - 48.0 * val4
            ),
            32.0 * val0
            - 128.0 * val1
            + 192.0 * val2
            - 128.0 * val3
            + 32.0 * val4,
        ]
    )

Response: r Returns the coefficients of an intersection polynomial in a power basis.


Instruction:
Make a summary of the following Python 3 code
def _to_power_basis_degree8(nodes1, nodes2):
    evaluated = [
        eval_intersection_polynomial(nodes1, nodes2, t_val) for t_val in _CHEB9
    ]
    return polynomial.polyfit(_CHEB9, evaluated, 8)

Response: r Helper function for to_power_basis.


Instruction:
Make a summary of the following Python 3 code
def _to_power_basis33(nodes1, nodes2):
    evaluated = [
        eval_intersection_polynomial(nodes1, nodes2, t_val)
        for t_val in _CHEB10
    ]
    return polynomial.polyfit(_CHEB10, evaluated, 9)

Response: r Helper function for to_power_basis.


Instruction:
Here you have a function in Python 3, explain what it does
def to_power_basis(nodes1, nodes2):
    # NOTE: There is no corresponding "enable", but the disable only applies
    #       in this lexical scope.
    # pylint: disable=too-many-return-statements
    _, num_nodes1 = nodes1.shape
    _, num_nodes2 = nodes2.shape
    if num_nodes1 == 2:
        if num_nodes2 == 2:
            return _to_power_basis11(nodes1, nodes2)

        elif num_nodes2 == 3:
            return _to_power_basis12(nodes1, nodes2)

        elif num_nodes2 == 4:
            return _to_power_basis13(nodes1, nodes2)

        elif num_nodes2 == 5:
            return _to_power_basis_degree4(nodes1, nodes2)

    elif num_nodes1 == 3:
        if num_nodes2 == 3:
            return _to_power_basis_degree4(nodes1, nodes2)

        elif num_nodes2 == 4:
            return _to_power_basis23(nodes1, nodes2)

        elif num_nodes2 == 5:
            return _to_power_basis_degree8(nodes1, nodes2)

    elif num_nodes1 == 4:
        if num_nodes2 == 4:
            return _to_power_basis33(nodes1, nodes2)

    raise NotImplementedError(
        "Degree 1",
        num_nodes1 - 1,
        "Degree 2",
        num_nodes2 - 1,
        _POWER_BASIS_ERR,
    )

Response: Compute the coefficients of an intersection polynomial.


Instruction:
Explain what the following Python 3 code does
def normalize_polynomial(coeffs, threshold=_L2_THRESHOLD):
    l2_norm = polynomial_norm(coeffs)
    if l2_norm < threshold:
        return np.zeros(coeffs.shape, order="F")

    else:
        coeffs /= l2_norm
        return coeffs

Response: r Normalizes a polynomial in the L_2 sense.


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_sigma_coeffs(coeffs):
    num_nodes, = coeffs.shape
    degree = num_nodes - 1
    effective_degree = None
    for index in six.moves.range(degree, -1, -1):
        if coeffs[index] != 0.0:
            effective_degree = index
            break

    if effective_degree is None:
        # NOTE: This means ``np.all(coeffs == 0.0)``.
        return None, 0, 0

    if effective_degree == 0:
        return None, degree, 0

    sigma_coeffs = coeffs[:effective_degree] / coeffs[effective_degree]
    # Now we need to add the binomial coefficients, but we avoid
    # computing actual binomial coefficients. Starting from the largest
    # exponent, the first ratio of binomial coefficients is
    #       (d C (e - 1)) / (d C e)
    #     = e / (d - e + 1)
    binom_numerator = effective_degree
    binom_denominator = degree - effective_degree + 1
    for exponent in six.moves.xrange(effective_degree - 1, -1, -1):
        sigma_coeffs[exponent] *= binom_numerator
        sigma_coeffs[exponent] /= binom_denominator
        # We swap (d C j) with (d C (j - 1)), so `p / q` becomes
        #       (p / q) (d C (j - 1)) / (d C j)
        #     = (p j) / (q (d - j + 1))
        binom_numerator *= exponent
        binom_denominator *= degree - exponent + 1
    return sigma_coeffs, degree, effective_degree

Response: Compute the sigma coefficients of the non - lead terms in the Bernstein basis.


Instruction:
Explain what the following Python 3 code does
def bernstein_companion(coeffs):
    sigma_coeffs, degree, effective_degree = _get_sigma_coeffs(coeffs)
    if effective_degree == 0:
        return np.empty((0, 0), order="F"), degree, 0

    companion = np.zeros((effective_degree, effective_degree), order="F")
    companion.flat[
        effective_degree :: effective_degree + 1  # noqa: E203
    ] = 1.0
    companion[0, :] = -sigma_coeffs[::-1]
    return companion, degree, effective_degree

Response: r Compute a companion matrix for a polynomial in Bernstein basis.


Instruction:
Make a summary of the following Python 3 code
def bezier_roots(coeffs):
    companion, degree, effective_degree = bernstein_companion(coeffs)
    if effective_degree:
        sigma_roots = np.linalg.eigvals(companion)
        # Filter out `sigma = -1`, i.e. "points at infinity".
        # We want the error ||(sigma - (-1))|| ~= 2^{-52}
        to_keep = np.abs(sigma_roots + 1.0) > _SIGMA_THRESHOLD
        sigma_roots = sigma_roots[to_keep]
        s_vals = sigma_roots / (1.0 + sigma_roots)
    else:
        s_vals = np.empty((0,), order="F")
    if effective_degree != degree:
        delta = degree - effective_degree
        s_vals = np.hstack([s_vals, [1] * delta])
    return s_vals

Response: r Compute polynomial roots of a Bernstein basis.


Instruction:
Given the following Python 3 function, write the documentation
def roots_in_unit_interval(coeffs):
    all_roots = polynomial.polyroots(coeffs)
    # Only keep roots inside or very near to the unit interval.
    all_roots = all_roots[
        (_UNIT_INTERVAL_WIGGLE_START < all_roots.real)
        & (all_roots.real < _UNIT_INTERVAL_WIGGLE_END)
    ]
    # Only keep roots with very small imaginary part. (Really only
    # keep the real parts.)
    real_inds = np.abs(all_roots.imag) < _IMAGINARY_WIGGLE
    return all_roots[real_inds].real

Response: r Compute roots of a polynomial in the unit interval.


Instruction:
Explain what the following Python 3 code does
def _strip_leading_zeros(coeffs, threshold=_COEFFICIENT_THRESHOLD):
    while np.abs(coeffs[-1]) < threshold:
        coeffs = coeffs[:-1]
    return coeffs

Response: r Strip leading zeros from a polynomial.


Instruction:
Create a Python 3 function to
resolve a computed intersection and adds to lists.

Response:
def _resolve_and_add(nodes1, s_val, final_s, nodes2, t_val, final_t):
    """Resolve a computed intersection and add to lists.

    We perform one Newton step to deal with any residual issues of
    high-degree polynomial solves (one of which depends on the already
    approximate ``x_val, y_val``).

    Args:
        nodes1 (numpy.ndarray): The nodes in the first curve.
        s_val (float): The approximate intersection parameter
            along ``nodes1``.
        final_s (List[float]): The list of accepted intersection
            parameters ``s``.
        nodes2 (numpy.ndarray): The nodes in the second curve.
        t_val (float): The approximate intersection parameter
            along ``nodes2``.
        final_t (List[float]): The list of accepted intersection
            parameters ``t``.
    """
    s_val, t_val = _intersection_helpers.newton_refine(
        s_val, nodes1, t_val, nodes2
    )
    s_val, success_s = _helpers.wiggle_interval(s_val)
    t_val, success_t = _helpers.wiggle_interval(t_val)
    if not (success_s and success_t):
        return

    final_s.append(s_val)
    final_t.append(t_val)


Instruction:
Given the following Python 3 function, write the documentation
def intersect_curves(nodes1, nodes2):
    nodes1 = _curve_helpers.full_reduce(nodes1)
    nodes2 = _curve_helpers.full_reduce(nodes2)
    _, num_nodes1 = nodes1.shape
    _, num_nodes2 = nodes2.shape
    swapped = False
    if num_nodes1 > num_nodes2:
        nodes1, nodes2 = nodes2, nodes1
        swapped = True
    coeffs = normalize_polynomial(to_power_basis(nodes1, nodes2))
    if np.all(coeffs == 0.0):
        raise NotImplementedError(_COINCIDENT_ERR)

    _check_non_simple(coeffs)
    t_vals = roots_in_unit_interval(coeffs)
    final_s = []
    final_t = []
    for t_val in t_vals:
        (x_val,), (y_val,) = _curve_helpers.evaluate_multi(
            nodes2, np.asfortranarray([t_val])
        )
        s_val = locate_point(nodes1, x_val, y_val)
        if s_val is not None:
            _resolve_and_add(nodes1, s_val, final_s, nodes2, t_val, final_t)
    result = np.zeros((2, len(final_s)), order="F")
    if swapped:
        final_s, final_t = final_t, final_s
    result[0, :] = final_s
    result[1, :] = final_t
    return result

Response: r Intersects two parametric B |eacute| zier curves.


Instruction:
How would you implement a function in Python 3 that
converts a B |eacute| zier curve to a polynomial in power basis.

Response:
def poly_to_power_basis(bezier_coeffs):
    """Convert a B |eacute| zier curve to polynomial in power basis.

    .. note::

       This assumes, but does not verify, that the "B |eacute| zier
       degree" matches the true degree of the curve. Callers can
       guarantee this by calling :func:`.full_reduce`.

    Args:
        bezier_coeffs (numpy.ndarray): A 1D array of coefficients in
            the Bernstein basis.

    Returns:
        numpy.ndarray: 1D array of coefficients in monomial basis.

    Raises:
        .UnsupportedDegree: If the degree of the curve is not among
            0, 1, 2 or 3.
    """
    num_coeffs, = bezier_coeffs.shape
    if num_coeffs == 1:
        return bezier_coeffs

    elif num_coeffs == 2:
        # C0 (1 - s) + C1 s = C0 + (C1 - C0) s
        coeff0, coeff1 = bezier_coeffs
        return np.asfortranarray([coeff0, coeff1 - coeff0])

    elif num_coeffs == 3:
        #   C0 (1 - s)^2 + C1 2 (1 - s) s + C2 s^2
        # = C0 + 2(C1 - C0) s + (C2 - 2 C1 + C0) s^2
        coeff0, coeff1, coeff2 = bezier_coeffs
        return np.asfortranarray(
            [coeff0, 2.0 * (coeff1 - coeff0), coeff2 - 2.0 * coeff1 + coeff0]
        )

    elif num_coeffs == 4:
        #   C0 (1 - s)^3 + C1 3 (1 - s)^2 + C2 3 (1 - s) s^2 + C3 s^3
        # = C0 + 3(C1 - C0) s + 3(C2 - 2 C1 + C0) s^2 +
        #   (C3 - 3 C2 + 3 C1 - C0) s^3
        coeff0, coeff1, coeff2, coeff3 = bezier_coeffs
        return np.asfortranarray(
            [
                coeff0,
                3.0 * (coeff1 - coeff0),
                3.0 * (coeff2 - 2.0 * coeff1 + coeff0),
                coeff3 - 3.0 * coeff2 + 3.0 * coeff1 - coeff0,
            ]
        )

    else:
        raise _helpers.UnsupportedDegree(
            num_coeffs - 1, supported=(0, 1, 2, 3)
        )


Instruction:
Can you generate a brief explanation for the following Python 3 code
def all_intersections(nodes_first, nodes_second):
    # Only attempt this if the bounding boxes intersect.
    bbox_int = _geometric_intersection.bbox_intersect(
        nodes_first, nodes_second
    )
    if bbox_int == _DISJOINT:
        return np.empty((2, 0), order="F"), False

    return intersect_curves(nodes_first, nodes_second), False

Response: r Returns a 2x2 array of all intersections between two sets of nodes.


Instruction:
How would you explain what the following Python 3 function does
def _vector_close(vec1, vec2, eps=_EPS):
    # NOTE: This relies on ``vec1`` and ``vec2`` being one-dimensional
    #       vectors so NumPy doesn't try to use a matrix norm.
    size1 = np.linalg.norm(vec1, ord=2)
    size2 = np.linalg.norm(vec2, ord=2)
    if size1 == 0:
        return size2 <= eps

    elif size2 == 0:
        return size1 <= eps

    else:
        upper_bound = eps * min(size1, size2)
        return np.linalg.norm(vec1 - vec2, ord=2) <= upper_bound

Response: r Check that two vectors are close to some threshold.


Instruction:
How would you explain what the following Python 3 function does
def _bbox(nodes):
    left, bottom = np.min(nodes, axis=1)
    right, top = np.max(nodes, axis=1)
    return left, right, bottom, top

Response: Returns the bounding box for a set of points.


Instruction:
Implement a Python 3 function for
computing the product of two Fortran contiguous matrices.

Response:
def matrix_product(mat1, mat2):
    """Compute the product of two Fortran contiguous matrices.

    This is to avoid the overhead of NumPy converting to C-contiguous
    before computing a matrix product.

    Does so via ``A B = (B^T A^T)^T`` since ``B^T`` and ``A^T`` will be
    C-contiguous without a copy, then the product ``P = B^T A^T`` will
    be C-contiguous and we can return the view ``P^T`` without a copy.

    Args:
        mat1 (numpy.ndarray): The left-hand side matrix.
        mat2 (numpy.ndarray): The right-hand side matrix.

    Returns:
        numpy.ndarray: The product of the two matrices.
    """
    return np.dot(mat2.T, mat1.T).T


Instruction:
How would you explain what the following Python 3 function does
def cross_product_compare(start, candidate1, candidate2):
    delta1 = candidate1 - start
    delta2 = candidate2 - start
    return cross_product(delta1, delta2)

Response: Compare two relative changes by their cross - product.


Instruction:
Write a Python 3 script to
check if a value is contained in a sorted list.

Response:
def in_sorted(values, value):
    """Checks if a value is in a sorted list.

    Uses the :mod:`bisect` builtin to find the insertion point for
    ``value``.

    Args:
        values (List[int]): Integers sorted in ascending order.
        value (int): Value to check if contained in ``values``.

    Returns:
        bool: Indicating if the value is contained.
    """
    index = bisect.bisect_left(values, value)
    if index >= len(values):
        return False

    return values[index] == value


Instruction:
Can you generate the documentation for the following Python 3 function
def _simple_convex_hull(points):
    # NOTE: There is no corresponding "enable", but the disable only applies
    #       in this lexical scope.
    # pylint: disable=too-many-branches
    if points.size == 0:
        return points

    # First, drop duplicates.
    unique_points = np.unique(points, axis=1)
    _, num_points = unique_points.shape
    if num_points < 2:
        return unique_points

    # Then sort the data in left-to-right order (and break ties by y-value).
    points = np.empty((2, num_points), order="F")
    for index, xy_val in enumerate(
        sorted(tuple(column) for column in unique_points.T)
    ):
        points[:, index] = xy_val
    # After sorting, if there are only 2 points, return.
    if num_points < 3:
        return points

    # Build lower hull
    lower = [0, 1]
    for index in six.moves.xrange(2, num_points):
        point2 = points[:, index]
        while len(lower) >= 2:
            point0 = points[:, lower[-2]]
            point1 = points[:, lower[-1]]
            if cross_product_compare(point0, point1, point2) > 0:
                break

            else:
                lower.pop()
        lower.append(index)
    # Build upper hull
    upper = [num_points - 1]
    for index in six.moves.xrange(num_points - 2, -1, -1):
        # Don't consider indices from the lower hull (other than the ends).
        if index > 0 and in_sorted(lower, index):
            continue

        point2 = points[:, index]
        while len(upper) >= 2:
            point0 = points[:, upper[-2]]
            point1 = points[:, upper[-1]]
            if cross_product_compare(point0, point1, point2) > 0:
                break

            else:
                upper.pop()
        upper.append(index)
    # **Both** corners are double counted.
    size_polygon = len(lower) + len(upper) - 2
    polygon = np.empty((2, size_polygon), order="F")
    for index, column in enumerate(lower[:-1]):
        polygon[:, index] = points[:, column]
    index_start = len(lower) - 1
    for index, column in enumerate(upper[:-1]):
        polygon[:, index + index_start] = points[:, column]
    return polygon

Response: r Compute the convex hull for a set of points.


Instruction:
Can you generate the documentation for the following Python 3 function
def is_separating(direction, polygon1, polygon2):
    # NOTE: We assume throughout that ``norm_squared != 0``. If it **were**
    #       zero that would mean the ``direction`` corresponds to an
    #       invalid edge.
    norm_squared = direction[0] * direction[0] + direction[1] * direction[1]
    params = []
    vertex = np.empty((2,), order="F")
    for polygon in (polygon1, polygon2):
        _, polygon_size = polygon.shape
        min_param = np.inf
        max_param = -np.inf
        for index in six.moves.xrange(polygon_size):
            vertex[:] = polygon[:, index]
            param = cross_product(direction, vertex) / norm_squared
            min_param = min(min_param, param)
            max_param = max(max_param, param)
        params.append((min_param, max_param))
    # NOTE: The indexing is based on:
    #       params[0] = (min_param1, max_param1)
    #       params[1] = (min_param2, max_param2)
    return params[0][0] > params[1][1] or params[0][1] < params[1][0]

Response: Checks if a given direction is a separating line for two polygons.


Instruction:
Can you implement a function in Python 3 that
determines if two convex polygons collide.

Response:
def _polygon_collide(polygon1, polygon2):
    """Determines if two **convex** polygons collide.

    .. _SAT: https://en.wikipedia.org/wiki/Hyperplane_separation_theorem
    .. _see also: https://hackmd.io/s/ryFmIZrsl

    This code uses the Separating axis theorem (`SAT`_) to quickly
    determine if the polygons intersect. `See also`_.

    .. note::

       There is also a Fortran implementation of this function, which
       will be used if it can be built.

    Args:
        polygon1 (numpy.ndarray): A ``2 x N`` array (``float64``) of ordered
            points in a polygon.
        polygon2 (numpy.ndarray): A ``2 x N`` array (``float64``) of ordered
            points in a polygon.

    Returns:
        bool: Flag indicating if the two polygons collide.
    """
    direction = np.empty((2,), order="F")
    for polygon in (polygon1, polygon2):
        _, polygon_size = polygon.shape
        for index in six.moves.xrange(polygon_size):
            # NOTE: When ``index == 0`` this will "wrap around" and refer
            #       to index ``-1``.
            direction[:] = polygon[:, index] - polygon[:, index - 1]
            if is_separating(direction, polygon1, polygon2):
                return False

    return True


Instruction:
Can you generate a brief explanation for the following Python 3 code
def solve2x2(lhs, rhs):
    # A <--> lhs[0, 0]
    # B <--> lhs[0, 1]
    # C <--> lhs[1, 0]
    # D <--> lhs[1, 1]
    # E <--> rhs[0]
    # F <--> rhs[1]
    if np.abs(lhs[1, 0]) > np.abs(lhs[0, 0]):
        # NOTE: We know there is no division by zero here since ``C``
        #       is **strictly** bigger than **some** value (in magnitude).
        # [A | B][x] = [E]
        # [C | D][y]   [F]
        ratio = lhs[0, 0] / lhs[1, 0]
        # r = A / C
        # [A - rC | B - rD][x]   [E - rF]
        # [C      | D     ][y] = [F     ]
        # ==> 0x + (B - rD) y = E - rF
        denominator = lhs[0, 1] - ratio * lhs[1, 1]
        if denominator == 0.0:
            return True, None, None

        y_val = (rhs[0] - ratio * rhs[1]) / denominator
        # Cx + Dy = F ==> x = (F - Dy) / C
        x_val = (rhs[1] - lhs[1, 1] * y_val) / lhs[1, 0]
        return False, x_val, y_val

    else:
        if lhs[0, 0] == 0.0:
            return True, None, None

        # [A | B][x] = [E]
        # [C | D][y]   [F]
        ratio = lhs[1, 0] / lhs[0, 0]
        # r = C / A
        # [A      | B     ][x] = [E     ]
        # [C - rA | D - rB][y]   [F - rE]
        # ==> 0x + (D - rB) y = F - rE
        denominator = lhs[1, 1] - ratio * lhs[0, 1]
        if denominator == 0.0:
            return True, None, None

        y_val = (rhs[1] - ratio * rhs[0]) / denominator
        # Ax + By = E ==> x = (E - B y) / A
        x_val = (rhs[0] - lhs[0, 1] * y_val) / lhs[0, 0]
        return False, x_val, y_val

Response: Solve a square 2 x 2 system via LU factorization.


Instruction:
How would you explain what the following Python 3 function does
def add_plot_boundary(ax, padding=0.125):
    nodes = np.asfortranarray(
        np.vstack([line.get_xydata() for line in ax.lines]).T
    )
    left, right, bottom, top = _helpers.bbox(nodes)
    center_x = 0.5 * (right + left)
    delta_x = right - left
    center_y = 0.5 * (top + bottom)
    delta_y = top - bottom
    multiplier = (1.0 + padding) * 0.5
    ax.set_xlim(
        center_x - multiplier * delta_x, center_x + multiplier * delta_x
    )
    ax.set_ylim(
        center_y - multiplier * delta_y, center_y + multiplier * delta_y
    )

Response: Add a buffer of empty space around a plot boundary.


Instruction:
Given the following Python 3 function, write the documentation
def add_patch(ax, color, pts_per_edge, *edges):
    from matplotlib import patches
    from matplotlib import path as _path_mod

    s_vals = np.linspace(0.0, 1.0, pts_per_edge)
    # Evaluate points on each edge.
    all_points = []
    for edge in edges:
        points = edge.evaluate_multi(s_vals)
        # We assume the edges overlap and leave out the first point
        # in each.
        all_points.append(points[:, 1:])
    # Add first point as last point (polygon is closed).
    first_edge = all_points[0]
    all_points.append(first_edge[:, [0]])
    # Add boundary first.
    polygon = np.asfortranarray(np.hstack(all_points))
    line, = ax.plot(polygon[0, :], polygon[1, :], color=color)
    # Reset ``color`` in case it was ``None`` and set from color wheel.
    color = line.get_color()
    # ``polygon`` is stored Fortran-contiguous with ``x-y`` points in each
    # column but ``Path()`` wants ``x-y`` points in each row.
    path = _path_mod.Path(polygon.T)
    patch = patches.PathPatch(path, facecolor=color, alpha=0.625)
    ax.add_patch(patch)

Response: Adds a polygonal surface patch to a matplotlib axis.


Instruction:
Write a Python 3 function that can
visit a literal_block node. This verifies the state of each literal block.

Response:
def visit_literal_block(self, node):
        """Visit a ``literal_block`` node.

        This verifies the state of each literal / code block.
        """
        language = node.attributes.get("language", "")
        test_type = node.attributes.get("testnodetype", "")
        if test_type != "doctest":
            if language.lower() in ("", "python"):
                msg = _LITERAL_ERR_TEMPLATE.format(
                    node.rawsource, language, test_type
                )
                raise errors.ExtensionError(msg)

        # The base classes are not new-style, so we can't use super().
        return html.HTMLTranslator.visit_literal_block(self, node)


Instruction:
Here you have a function in Python 3, explain what it does
def linearization_error(nodes):
    _, num_nodes = nodes.shape
    degree = num_nodes - 1
    if degree == 1:
        return 0.0

    second_deriv = nodes[:, :-2] - 2.0 * nodes[:, 1:-1] + nodes[:, 2:]
    worst_case = np.max(np.abs(second_deriv), axis=1)
    # max_{0 <= s <= 1} s(1 - s)/2 = 1/8 = 0.125
    multiplier = 0.125 * degree * (degree - 1)
    # NOTE: worst_case is 1D due to np.max(), so this is the vector norm.
    return multiplier * np.linalg.norm(worst_case, ord=2)

Response: r Compute the maximum error of a linear approximation.


Instruction:
Here you have a function in Python 3, explain what it does
def line_line_collide(line1, line2):
    s, t, success = segment_intersection(
        line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1]
    )
    if success:
        return _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval(
            t, 0.0, 1.0
        )

    else:
        disjoint, _ = parallel_lines_parameters(
            line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1]
        )
        return not disjoint

Response: Determines if two line segments meet.


Instruction:
Implement a function in Python 3 to
determine if the convex hulls of two curves collide.

Response:
def convex_hull_collide(nodes1, nodes2):
    """Determine if the convex hulls of two curves collide.

    .. note::

       This is a helper for :func:`from_linearized`.

    Args:
        nodes1 (numpy.ndarray): Control points of a first curve.
        nodes2 (numpy.ndarray): Control points of a second curve.

    Returns:
        bool: Indicating if the convex hulls collide.
    """
    polygon1 = _helpers.simple_convex_hull(nodes1)
    _, polygon_size1 = polygon1.shape
    polygon2 = _helpers.simple_convex_hull(nodes2)
    _, polygon_size2 = polygon2.shape
    if polygon_size1 == 2 and polygon_size2 == 2:
        return line_line_collide(polygon1, polygon2)

    else:
        return _helpers.polygon_collide(polygon1, polygon2)


Instruction:
Write a Python 3 script to
determine curve - curve intersection from two linearizations.

Response:
def from_linearized(first, second, intersections):
    """Determine curve-curve intersection from pair of linearizations.

    .. note::

       This assumes that at least one of ``first`` and ``second`` is
       not a line. The line-line case should be handled "early"
       by :func:`check_lines`.

    .. note::

       This assumes the caller has verified that the bounding boxes
       for ``first`` and ``second`` actually intersect.

    If there is an intersection along the segments, adds that intersection
    to ``intersections``. Otherwise, returns without doing anything.

    Args:
        first (Linearization): First curve being intersected.
        second (Linearization): Second curve being intersected.
        intersections (list): A list of existing intersections.

    Raises:
        ValueError: If ``first`` and ``second`` both have linearization error
            of ``0.0`` (i.e. they are both lines). This is because this
            function expects the caller to have used :func:`check_lines`
            already.
    """
    # NOTE: There is no corresponding "enable", but the disable only applies
    #       in this lexical scope.
    # pylint: disable=too-many-return-statements
    s, t, success = segment_intersection(
        first.start_node, first.end_node, second.start_node, second.end_node
    )
    bad_parameters = False
    if success:
        if not (
            _helpers.in_interval(s, 0.0, 1.0)
            and _helpers.in_interval(t, 0.0, 1.0)
        ):
            bad_parameters = True
    else:
        if first.error == 0.0 and second.error == 0.0:
            raise ValueError(_UNHANDLED_LINES)

        # Just fall back to a Newton iteration starting in the middle of
        # the given intervals.
        bad_parameters = True
        s = 0.5
        t = 0.5
    if bad_parameters:
        # In the unlikely case that we have parallel segments or segments
        # that intersect outside of [0, 1] x [0, 1], we can still exit
        # if the convex hulls don't intersect.
        if not convex_hull_collide(first.curve.nodes, second.curve.nodes):
            return

    # Now, promote ``s`` and ``t`` onto the original curves.
    orig_s = (1 - s) * first.curve.start + s * first.curve.end
    orig_t = (1 - t) * second.curve.start + t * second.curve.end
    refined_s, refined_t = _intersection_helpers.full_newton(
        orig_s, first.curve.original_nodes, orig_t, second.curve.original_nodes
    )
    refined_s, success = _helpers.wiggle_interval(refined_s)
    if not success:
        return

    refined_t, success = _helpers.wiggle_interval(refined_t)
    if not success:
        return

    add_intersection(refined_s, refined_t, intersections)


Instruction:
Here you have a function in Python 3, explain what it does
def tangent_bbox_intersection(first, second, intersections):
    node_first1 = first.nodes[:, 0]
    node_first2 = first.nodes[:, -1]
    node_second1 = second.nodes[:, 0]
    node_second2 = second.nodes[:, -1]
    endpoint_check(
        first, node_first1, 0.0, second, node_second1, 0.0, intersections
    )
    endpoint_check(
        first, node_first1, 0.0, second, node_second2, 1.0, intersections
    )
    endpoint_check(
        first, node_first2, 1.0, second, node_second1, 0.0, intersections
    )
    endpoint_check(
        first, node_first2, 1.0, second, node_second2, 1.0, intersections
    )

Response: r Check if two curves with tangent bounding boxes intersect.


Instruction:
How would you explain what the following Python 3 function does
def bbox_line_intersect(nodes, line_start, line_end):
    left, right, bottom, top = _helpers.bbox(nodes)
    if _helpers.in_interval(
        line_start[0], left, right
    ) and _helpers.in_interval(line_start[1], bottom, top):
        return BoxIntersectionType.INTERSECTION

    if _helpers.in_interval(line_end[0], left, right) and _helpers.in_interval(
        line_end[1], bottom, top
    ):
        return BoxIntersectionType.INTERSECTION

    # NOTE: We allow ``segment_intersection`` to fail below (i.e.
    #       ``success=False``). At first, this may appear to "ignore"
    #       some potential intersections of parallel lines. However,
    #       no intersections will be missed. If parallel lines don't
    #       overlap, then there is nothing to miss. If they do overlap,
    #       then either the segment will have endpoints on the box (already
    #       covered by the checks above) or the segment will contain an
    #       entire side of the box, which will force it to intersect the 3
    #       edges that meet at the two ends of those sides. The parallel
    #       edge will be skipped, but the other two will be covered.
    # Bottom Edge
    s_bottom, t_bottom, success = segment_intersection(
        np.asfortranarray([left, bottom]),
        np.asfortranarray([right, bottom]),
        line_start,
        line_end,
    )
    if (
        success
        and _helpers.in_interval(s_bottom, 0.0, 1.0)
        and _helpers.in_interval(t_bottom, 0.0, 1.0)
    ):
        return BoxIntersectionType.INTERSECTION

    # Right Edge
    s_right, t_right, success = segment_intersection(
        np.asfortranarray([right, bottom]),
        np.asfortranarray([right, top]),
        line_start,
        line_end,
    )
    if (
        success
        and _helpers.in_interval(s_right, 0.0, 1.0)
        and _helpers.in_interval(t_right, 0.0, 1.0)
    ):
        return BoxIntersectionType.INTERSECTION

    # Top Edge
    s_top, t_top, success = segment_intersection(
        np.asfortranarray([right, top]),
        np.asfortranarray([left, top]),
        line_start,
        line_end,
    )
    if (
        success
        and _helpers.in_interval(s_top, 0.0, 1.0)
        and _helpers.in_interval(t_top, 0.0, 1.0)
    ):
        return BoxIntersectionType.INTERSECTION

    # NOTE: We skip the "last" edge. This is because any curve
    #       that doesn't have an endpoint on a curve must cross
    #       at least two, so we will have already covered such curves
    #       in one of the branches above.
    return BoxIntersectionType.DISJOINT

Response: r Determine intersection of a bounding box and a line segment.