output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Compute the fat line around a B |eacute| zier curve.
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...
You are a Python code generator, capable of creating scripts from specifications.
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. ...
Implement a function in Python 3 to update the start and end of the clipped parameter range.
As a Python code translator, you convert algorithms and pseudocode into Python.
r This function checks the range of the current time range.
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: ...
You are a Python code architect, reviewing and designing scalable and efficient code
r Reduce the parameter range where two curves can intersect.
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) ...
As a Python code composer, you craft elegant and concise scripts.
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 ...
Write a Python 3 function for posting - process a generated journal file on Travis macOS.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert Sphinx mod name to plain reST link name.
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"))
You are a Python code architect, reviewing and designing scalable and efficient code
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: ...
How would you implement a function in Python 3 that converts Sphinx doc to plain reST link.
You are a Python code architect, reviewing and designing scalable and efficient code
Get a diff between two strings.
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=nam...
As a python code expert, you are capable of creating scripts from specifications.
Populate the README template with values.
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_ver...
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Create a Python 3 function to populate the template and compare to the expected README.
You are a Python code analyst, evaluating scripts for potential improvements.
Specialize the template to a PyPI release template.
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, ...
As a python code expert, you are capable of creating scripts from specifications.
Populate the template and compare to the index file.
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":...
You are a Python code analyst, evaluating scripts for potential improvements.
Updates the template so that curly braces are escaped correctly.
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("{...
You are a Python code generator, capable of creating scripts from specifications.
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( ...
Can you write a function in Python 3 where it populates template and compare to index. rst. release. template.
You are a Python code architect, reviewing and designing scalable and efficient code
Populate template and compare to the current development file.
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 = fi...
As a Python code composer, you craft elegant and concise scripts.
Populate the template and compare to the binary - extension. rst file.
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() ...
As a python code expert, you are capable of creating scripts from specifications.
Helper function for evaluating degree 3.
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 ...
As a Python code translator, you convert algorithms and pseudocode into Python.
r Evaluates the implicitized bivariate polynomial containing the curve.
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...
As a python code expert, you are capable of creating scripts from specifications.
r Converts the nodes in nodes1 and nodes2 into a power basis matrix.
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) ...
As a python code expert, you are capable of creating scripts from specifications.
r Returns the coefficients of an intersection polynomial.
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...
You are a Python code generator, capable of creating scripts from specifications.
r Returns the coefficients of an intersection polynomial in a power basis.
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...
You are a Python code analyst, evaluating scripts for potential improvements.
r Helper function for to_power_basis.
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)
As a Python code analyst, you investigate and solve complex coding mysteries
r Helper function for to_power_basis.
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)
As a python code expert, you are capable of creating scripts from specifications.
Compute the coefficients of an intersection polynomial.
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.shap...
As a Python code composer, you craft elegant and concise scripts.
r Normalizes a polynomial in the L_2 sense.
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
You are a Python code analyst, evaluating scripts for potential improvements.
Compute the sigma coefficients of the non - lead terms in the Bernstein basis.
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 b...
You are a Python code analyst, evaluating scripts for potential improvements.
r Compute a companion matrix for a polynomial in Bernstein basis.
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") compani...
As a Python code translator, you convert algorithms and pseudocode into Python.
r Compute polynomial roots of a Bernstein basis.
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 - (...
As a Python code composer, you craft elegant and concise scripts.
r Compute roots of a polynomial in the unit interval.
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 < _U...
You are a Python code generator, capable of creating scripts from specifications.
r Strip leading zeros from a polynomial.
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
As a python code expert, you are capable of creating scripts from specifications.
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: ...
Create a Python 3 function to resolve a computed intersection and adds to lists.
As a Python code composer, you craft elegant and concise scripts.
r Intersects two parametric B |eacute| zier curves.
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: ...
You are a Python code architect, reviewing and designing scalable and efficient code
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`. Ar...
How would you implement a function in Python 3 that converts a B |eacute| zier curve to a polynomial in power basis.
You are a Python code generator, capable of creating scripts from specifications.
r Returns a 2x2 array of all intersections between two sets of nodes.
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.e...
You are a Python code generator, capable of creating scripts from specifications.
r Check that two vectors are close to some threshold.
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) ...
As a Python code composer, you craft elegant and concise scripts.
Returns the bounding box for a set of points.
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
As a Python code composer, you craft elegant and concise scripts.
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 ...
Implement a Python 3 function for computing the product of two Fortran contiguous matrices.
You are a Python code architect, reviewing and designing scalable and efficient code
Compare two relative changes by their cross - product.
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)
As a Python code composer, you craft elegant and concise scripts.
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: ...
Write a Python 3 script to check if a value is contained in a sorted list.
You are a Python code analyst, evaluating scripts for potential improvements.
r Compute the convex hull for a set of points.
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, dro...
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks if a given direction is a separating line for two polygons.
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...
You are a Python code architect, reviewing and designing scalable and efficient code
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 inte...
Can you implement a function in Python 3 that determines if two convex polygons collide.
As a Python code analyst, you investigate and solve complex coding mysteries
Solve a square 2 x 2 system via LU factorization.
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 z...
You are a Python code architect, reviewing and designing scalable and efficient code
Add a buffer of empty space around a plot boundary.
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 ...
As a Python code composer, you craft elegant and concise scripts.
Adds a polygonal surface patch to a matplotlib axis.
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: ...
You are a Python code architect, reviewing and designing scalable and efficient code
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 ...
Write a Python 3 function that can visit a literal_block node. This verifies the state of each literal block.
You are a Python code analyst, evaluating scripts for potential improvements.
r Compute the maximum error of a linear approximation.
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) # ...
As a Python code composer, you craft elegant and concise scripts.
Determines if two line segments meet.
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 ...
As a Python code analyst, you investigate and solve complex coding mysteries
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. Ret...
Implement a function in Python 3 to determine if the convex hulls of two curves collide.
As a Python code analyst, you investigate and solve complex coding mysteries
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:: ...
Write a Python 3 script to determine curve - curve intersection from two linearizations.
You are a Python code generator, capable of creating scripts from specifications.
r Check if two curves with tangent bounding boxes intersect.
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....
You are a Python code architect, reviewing and designing scalable and efficient code
r Determine intersection of a bounding box and a line segment.
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 BoxIntersec...
As a Python code composer, you craft elegant and concise scripts.
def intersect_one_round(candidates, intersections): """Perform one step of the intersection process. .. note:: This is a helper for :func:`_all_intersections` and that function has a Fortran equivalent. Checks if the bounding boxes of each pair in ``candidates`` intersect. If the boundi...
Write a Python 3 function that can perform one step of the intersection process.
As a Python code composer, you craft elegant and concise scripts.
Reduce number of candidate intersection pairs.
Given the following Python 3 function, write the documentation def prune_candidates(candidates): pruned = [] # NOTE: In the below we replace ``isinstance(a, B)`` with # ``a.__class__ is B``, which is a 3-3.5x speedup. for first, second in candidates: if first.__class__ is Linearization: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def make_same_degree(nodes1, nodes2): """Degree-elevate a curve so two curves have matching degree. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier curve. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier curve. Returns: ...
Implement a function in Python 3 to make a new set of control points that are in the same degree.
You are a Python code generator, capable of creating scripts from specifications.
Checks if two curves are lines and returns a pair of two sets of intersection boolean arrays.
Here you have a function in Python 3, explain what it does def check_lines(first, second): # NOTE: In the below we replace ``isinstance(a, B)`` with # ``a.__class__ is B``, which is a 3-3.5x speedup. if not ( first.__class__ is Linearization and second.__class__ is Linearization ...
As a python code expert, you are capable of creating scripts from specifications.
def subdivide(self): """Split the curve into a left and right half. See :meth:`.Curve.subdivide` for more information. Returns: Tuple[SubdividedCurve, SubdividedCurve]: The left and right sub-curves. """ left_nodes, right_nodes = _curve_helpers.subdivide...
Write a Python 3 function that can split the curve into a left and right half.
You are a Python code analyst, evaluating scripts for potential improvements.
Try to linearize a curve or an already linearized curve.
Here you have a function in Python 3, explain what it does def from_shape(cls, shape): # NOTE: In the below we replace ``isinstance(a, B)`` with # ``a.__class__ is B``, which is a 3-3.5x speedup. if shape.__class__ is cls: return shape else: error = lineari...
As a Python code composer, you craft elegant and concise scripts.
Evaluate the curve along the curve.
Given the following Python 3 function, write the documentation def evaluate(self, s): return _curve_helpers.evaluate_multi( self._nodes, np.asfortranarray([s]) )
As a Python code composer, you craft elegant and concise scripts.
def plot(self, num_pts, color=None, alpha=None, ax=None): """Plot the current curve. Args: num_pts (int): Number of points to plot. color (Optional[Tuple[float, float, float]]): Color as RGB profile. alpha (Optional[float]): The alpha channel for the color. ...
Can you implement a function in Python 3 that plots the current curve.
As a python code expert, you are capable of creating scripts from specifications.
def intersect( self, other, strategy=IntersectionStrategy.GEOMETRIC, _verify=True ): """Find the points of intersection with another curve. See :doc:`../../algorithms/curve-curve-intersection` for more details. .. image:: ../../images/curve_intersect.png :align: center ...
How would you code a function in Python 3 to find the points of intersection with another curve.
You are a Python code analyst, evaluating scripts for potential improvements.
Return a degree - elevated version of the current curve.
Given the following Python 3 function, write the documentation def elevate(self): new_nodes = _curve_helpers.elevate_nodes(self._nodes) return Curve(new_nodes, self._degree + 1, _copy=False)
As a Python code composer, you craft elegant and concise scripts.
r Returns a degree - reduced version of the current curve.
Here you have a function in Python 3, explain what it does def reduce_(self): new_nodes = _curve_helpers.reduce_pseudo_inverse(self._nodes) return Curve(new_nodes, self._degree - 1, _copy=False)
As a Python code translator, you convert algorithms and pseudocode into Python.
Specialize the curve to a given start and end point.
Make a summary of the following Python 3 code def specialize(self, start, end): new_nodes = _curve_helpers.specialize_curve(self._nodes, start, end) return Curve(new_nodes, self._degree, _copy=False)
As a Python code analyst, you investigate and solve complex coding mysteries
r Finds a point on the current curve.
Given the following Python 3 function, write the documentation def locate(self, point): if point.shape != (self._dimension, 1): point_dimensions = " x ".join( str(dimension) for dimension in point.shape ) msg = _LOCATE_ERROR_TEMPLATE.format( se...
As a Python code analyst, you investigate and solve complex coding mysteries
Cleans up local names in a C source file.
Make a summary of the following Python 3 code def clean_file(c_source, virtualenv_dirname): with open(c_source, "r") as file_obj: contents = file_obj.read().rstrip() # Replace the path to the Cython include files. py_version = "python{}.{}".format(*sys.version_info[:2]) lib_path = os.path.join( ...
You are a Python code architect, reviewing and designing scalable and efficient code
Get the current version from setup. py.
Explain what the following Python 3 code does def get_version(): # "Spoof" the ``setup.py`` helper modules. sys.modules["setup_helpers"] = object() sys.modules["setup_helpers_macos"] = object() sys.modules["setup_helpers_windows"] = object() filename = os.path.join(_ROOT_DIR, "setup.py") loader ...
You are a Python code generator, capable of creating scripts from specifications.
Populates the README. rst file with release - specific data.
Make a summary of the following Python 3 code def populate_readme( version, circleci_build, appveyor_build, coveralls_build, travis_build ): """Populates ``README.rst`` with release-specific data. This is because ``README.rst`` is used on PyPI. Args: version (str): The current version. ...
You are a Python code analyst, evaluating scripts for potential improvements.
Populates the index. rst file with the release - specific data.
Here you have a function in Python 3, explain what it does def populate_index( version, circleci_build, appveyor_build, coveralls_build, travis_build ): """Populates ``docs/index.rst`` with release-specific data. Args: version (str): The current version. circleci_build (Union[str, int]): Th...
As a Python code composer, you craft elegant and concise scripts.
def populate_native_libraries(version): """Populates ``binary-extension.rst`` with release-specific data. Args: version (str): The current version. """ with open(BINARY_EXT_TEMPLATE, "r") as file_obj: template = file_obj.read() contents = template.format(revision=version) with o...
Write a Python 3 function that can populate binary - extension. rst with release - specific data.
As a Python code analyst, you investigate and solve complex coding mysteries
def populate_development(version): """Populates ``DEVELOPMENT.rst`` with release-specific data. This is because ``DEVELOPMENT.rst`` is used in the Sphinx documentation. Args: version (str): The current version. """ with open(DEVELOPMENT_TEMPLATE, "r") as file_obj: template = file_o...
Implement a Python 3 function for populating the DEVELOPMENT. rst file with release - specific data.
As a python code expert, you are capable of creating scripts from specifications.
Populate the templates with release - specific fields.
Can you generate a brief explanation for the following Python 3 code def main(): version = get_version() circleci_build = six.moves.input("CircleCI Build ID: ") appveyor_build = six.moves.input("AppVeyor Build ID: ") coveralls_build = six.moves.input("Coveralls Build ID: ") travis_build = six.moves....
As a Python code analyst, you investigate and solve complex coding mysteries
This function creates the matrix used to subdivide a node into left and right nodes respectively.
Explain what the following Python 3 code does def make_subdivision_matrices(degree): left = np.zeros((degree + 1, degree + 1), order="F") right = np.zeros((degree + 1, degree + 1), order="F") left[0, 0] = 1.0 right[-1, -1] = 1.0 for col in six.moves.xrange(1, degree + 1): half_prev = 0.5 * l...
You are a Python code architect, reviewing and designing scalable and efficient code
def _subdivide_nodes(nodes): """Subdivide a curve into two sub-curves. Does so by taking the unit interval (i.e. the domain of the surface) and splitting it into two sub-intervals by splitting down the middle. .. note:: There is also a Fortran implementation of this function, which will...
Create a Python 3 function for subdividing a curve into two sub - curves.
You are a Python code analyst, evaluating scripts for potential improvements.
r Evaluates a B |eacute| zier type - function.
Here you have a function in Python 3, explain what it does def _evaluate_multi_barycentric(nodes, lambda1, lambda2): # NOTE: We assume but don't check that lambda2 has the same shape. num_vals, = lambda1.shape dimension, num_nodes = nodes.shape degree = num_nodes - 1 # Resize as row vectors for broa...
You are a Python code architect, reviewing and designing scalable and efficient code
r Compute the size of a set of nodes.
How would you explain what the following Python 3 function does def vec_size(nodes, s_val): result_vec = evaluate_multi(nodes, np.asfortranarray([s_val])) # NOTE: We convert to 1D to make sure NumPy uses vector norm. return np.linalg.norm(result_vec[:, 0], ord=2)
As a python code expert, you are capable of creating scripts from specifications.
r Degree - elevate a B |eacute| zier curves.
Can you generate the documentation for the following Python 3 function def _elevate_nodes(nodes): dimension, num_nodes = np.shape(nodes) new_nodes = np.empty((dimension, num_nodes + 1), order="F") multipliers = np.arange(1, num_nodes, dtype=_FLOAT64)[np.newaxis, :] denominator = float(num_nodes) new...
You are a Python code analyst, evaluating scripts for potential improvements.
def de_casteljau_one_round(nodes, lambda1, lambda2): """Perform one round of de Casteljau's algorithm. .. note:: This is a helper for :func:`_specialize_curve`. It does not have a Fortran speedup because it is **only** used by a function which has a Fortran speedup. The weights ar...
Write a Python 3 script to perform one round of de Casteljau s algorithm.
You are a Python code analyst, evaluating scripts for potential improvements.
def _specialize_curve(nodes, start, end): """Specialize a curve to a re-parameterization .. note:: This assumes the curve is degree 1 or greater but doesn't check. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: ...
Write a Python 3 script to specialize a specialization of a single internal control point.
You are a Python code architect, reviewing and designing scalable and efficient code
r Evaluates the Hodograph curve at a point s.
Make a summary of the following Python 3 code def _evaluate_hodograph(s, nodes): _, num_nodes = np.shape(nodes) first_deriv = nodes[:, 1:] - nodes[:, :-1] return (num_nodes - 1) * evaluate_multi( first_deriv, np.asfortranarray([s]) )
You are a Python code architect, reviewing and designing scalable and efficient code
r Re - fine a solution to a newton s method.
Can you tell what is the following Python 3 function doing def _newton_refine(nodes, point, s): pt_delta = point - evaluate_multi(nodes, np.asfortranarray([s])) derivative = evaluate_hodograph(s, nodes) # Each array is 2 x 1 (i.e. a column vector), we want the vector # dot product. delta_s = np.vdot...
You are a Python code architect, reviewing and designing scalable and efficient code
r Returns a new node that is located on a curve.
Explain what the following Python 3 code does def _locate_point(nodes, point): candidates = [(0.0, 1.0, nodes)] for _ in six.moves.xrange(_MAX_LOCATE_SUBDIVISIONS + 1): next_candidates = [] for start, end, candidate in candidates: if _helpers.contains_nd(candidate, point.ravel(order=...
As a Python code analyst, you investigate and solve complex coding mysteries
Performs a pseudo - inverse degree reduction for a B |eacute| zier curve.
Can you generate a brief explanation for the following Python 3 code def _reduce_pseudo_inverse(nodes): _, num_nodes = np.shape(nodes) if num_nodes == 2: reduction = _REDUCTION0 denom = _REDUCTION_DENOM0 elif num_nodes == 3: reduction = _REDUCTION1 denom = _REDUCTION_DENOM1 ...
As a Python code composer, you craft elegant and concise scripts.
def projection_error(nodes, projected): """Compute the error between ``nodes`` and the projected nodes. .. note:: This is a helper for :func:`maybe_reduce`, which is in turn a helper for :func:`_full_reduce`. Hence there is no corresponding Fortran speedup. For now, just compute t...
Can you write a function in Python 3 where it computes the error between nodes and projected nodes.
As a python code expert, you are capable of creating scripts from specifications.
Apply degree reduction to nodes until it can no longer be reduced.
Explain what the following Python 3 code does def _full_reduce(nodes): was_reduced, nodes = maybe_reduce(nodes) while was_reduced: was_reduced, nodes = maybe_reduce(nodes) return nodes
As a Python code composer, you craft elegant and concise scripts.
Get all public members in the main package.
Can you generate a brief explanation for the following Python 3 code def get_public_members(): if bezier is None: return [] local_members = [] all_members = set() for name in dir(bezier): # Filter out non-public. if name.startswith("_") and name not in SPECIAL_MEMBERS: ...
You are a Python code generator, capable of creating scripts from specifications.
Populate DESIRED_TEMPLATE with public members.
Explain what the following Python 3 code does def get_desired(): public_members = get_public_members() if public_members: members = "\n :members: {}".format(", ".join(public_members)) else: members = "" return DESIRED_TEMPLATE.format(members=members)
You are a Python code architect, reviewing and designing scalable and efficient code
Main entry point to replace the generated contents.
Can you generate a brief explanation for the following Python 3 code def main(): with open(FILENAME, "r") as file_obj: contents = file_obj.read() desired = get_desired() if contents == EXPECTED: with open(FILENAME, "w") as file_obj: file_obj.write(desired) elif contents != de...
You are a Python code analyst, evaluating scripts for potential improvements.
def patch_f90_compiler(f90_compiler): """Patch up ``f90_compiler.library_dirs``. Updates flags in ``gfortran`` and ignores other compilers. The only modification is the removal of ``-fPIC`` since it is not used on Windows and the build flags turn warnings into errors. Args: f90_compiler (n...
Create a Python 3 function to patch up the Fortran compiler and ignore other compilers.
You are a Python code analyst, evaluating scripts for potential improvements.
def clean(session): """Clean up build files. Cleans up all artifacts that might get created during other ``nox`` sessions. There is no need for the session to create a ``virtualenv`` here (we are just pretending to be ``make``). """ clean_dirs = ( get_path(".cache"), get_pa...
Create a Python 3 function to clean up build files.
You are a Python code generator, capable of creating scripts from specifications.
Get a specific sub module of the app
Can you generate the documentation for the following Python 3 function def get_app_submodules(module_name): for name, module in get_app_modules(): if module_has_submodule(module, module_name): yield name, import_module('{0}.{1}'.format(name, module_name))
You are a Python code generator, capable of creating scripts from specifications.
def register_all_hooks(): """ Register all hooks found in 'auth_hooks' sub modules :return: """ global _all_hooks_registered if not _all_hooks_registered: logger.debug("Searching for hooks") hooks = list(get_app_submodules('auth_hooks')) logger.debug("Got %s hooks" % len(...
Implement a function in Python 3 to register all hooks found in auth_hooks sub modules
You are a Python code generator, capable of creating scripts from specifications.
def exec_request(endpoint, func, raise_for_status=False, **kwargs): """ Send an https api request """ try: endpoint = '{0}/api/v1/{1}'.format(settings.SEAT_URL, endpoint) headers = {'X-Token': settings.SEAT_XTOKEN, 'Accept': 'application/json'} logger.debug(headers) ...
Write a Python 3 script for sending an HTTP request to SeAT API
As a Python code translator, you convert algorithms and pseudocode into Python.
Add user to SeAT service
Given the following Python 3 function, write the documentation def add_user(cls, username, email): sanitized = str(cls.__sanitize_username(username)) logger.debug("Adding user to SeAT with username %s" % sanitized) password = cls.__generate_random_pass() ret = cls.exec_request('user', 'p...
As a Python code translator, you convert algorithms and pseudocode into Python.
def delete_user(cls, username): """ Delete user """ ret = cls.exec_request('user/{}'.format(username), 'delete') logger.debug(ret) if cls._response_ok(ret): logger.info("Deleted SeAT user with username %s" % username) return username return None
Can you implement a function in Python 3 that deletes user with username username
You are a Python code architect, reviewing and designing scalable and efficient code
def enable_user(cls, username): """ Enable user """ ret = cls.exec_request('user/{}'.format(username), 'put', account_status=1) logger.debug(ret) if cls._response_ok(ret): logger.info("Enabled SeAT user with username %s" % username) return username logger....
Write a Python 3 script for enabling user with username username
As a Python code analyst, you investigate and solve complex coding mysteries
def disable_user(cls, username): """ Disable user """ cls.update_roles(username, []) ret = cls.exec_request('user/{}'.format(username), 'put', account_status=0) logger.debug(ret) if cls._response_ok(ret): logger.info("Disabled SeAT user with username %s" % username) ...
Can you write a function in Python 3 where it disables user with username username
You are a Python code generator, capable of creating scripts from specifications.
def _check_email_changed(cls, username, email): """Compares email to one set on SeAT""" ret = cls.exec_request('user/{}'.format(username), 'get', raise_for_status=True) return ret['email'] != email
Create a Python 3 function for comparing email to one set on SeAT
You are a Python code architect, reviewing and designing scalable and efficient code
def format_name(self): """ :return: str Generated name """ format_data = self.get_format_data() return Formatter().vformat(self.string_formatter, args=[], kwargs=format_data)
Can you create a Python 3 function that returns the name of the log entry.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_form_kwargs(self): """ Inject the request user into the kwargs passed to the form """ kwargs = super(AddUpdateMixin, self).get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs
Create a Python 3 function to inject the request user into the kwargs passed to the form
As a Python code analyst, you investigate and solve complex coding mysteries