output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def git_commits_since_last_tag(last_tag: str) -> dict: """ :last_tag: The Git tag that should serve as the starting point for the commit log lookup. Calls ``git log <last_tag>.. --format='%H %s'`` and returns the output as a dict of hash-message pairs. """ try: cmd = ['git', 'log', ...
Write a Python 3 function that can return a dict of hash - message pairs for all commits since the given git tag.
As a python code expert, you are capable of creating scripts from specifications.
Parse Git log and return either maj min or pat.
How would you explain what the following Python 3 function does def parse_commit_log(commit_log: dict) -> str: rv = 'pat' cc_patterns = patterns() for value in commit_log.values(): if re.search(cc_patterns['feat'], value): rv = 'min' if re.search(cc_patterns['BREAKING CHANGE'],...
As a Python code composer, you craft elegant and concise scripts.
Alternative constructor that accepts a string SemVer.
Given the following Python 3 function, write the documentation def from_str(cls, version_str: str): o = cls() o.version = version_str return o
You are a Python code generator, capable of creating scripts from specifications.
Sets the major version number property.
Can you generate the documentation for the following Python 3 function def major(self, major: int) -> None: self.filter_negatives(major) self._major = major
As a python code expert, you are capable of creating scripts from specifications.
def minor(self, minor: int) -> None: """ param minor Minor version number property. Must be a non-negative integer. """ self.filter_negatives(minor) self._minor = minor
How would you code a function in Python 3 to set the minor version number property.
You are a Python code analyst, evaluating scripts for potential improvements.
def patch(self, patch: int) -> None: """ param patch Patch version number property. Must be a non-negative integer. """ self.filter_negatives(patch) self._patch = patch
How would you code a function in Python 3 to set the patch version number property.
As a Python code translator, you convert algorithms and pseudocode into Python.
def version(self) -> str: """ Version version number property. Must be a string consisting of three non-negative integers delimited by periods (eg. '1.0.1'). """ version: str = ( str(self._major) + '.' + str(self._minor) + '.' + str(self._patch...
Implement a Python 3 function for returning the version number property.
You are a Python code analyst, evaluating scripts for potential improvements.
Sets the version number property of the object.
Can you generate a brief explanation for the following Python 3 code def version(self, version_str: str) -> None: ver = [] for i in version_str.split('.'): ver.append(int(i)) self.filter_negatives(int(i)) self._major, self._minor, self._patch = ver[0], ver[1], ver[2]
As a python code expert, you are capable of creating scripts from specifications.
def estimate(data, fit_offset="mean", fit_profile="tilt", border_px=0, from_mask=None, ret_mask=False): """Estimate the background value of an image Parameters ---------- data: np.ndarray Data from which to compute the background value fit_profile: str The type of backg...
Write a Python 3 function that can estimate the background value of an image.
As a Python code composer, you craft elegant and concise scripts.
def offset_gaussian(data): """Fit a gaussian model to `data` and return its center""" nbins = 2 * int(np.ceil(np.sqrt(data.size))) mind, maxd = data.min(), data.max() drange = (mind - (maxd - mind) / 2, maxd + (maxd - mind) / 2) histo = np.histogram(data, nbins, density=True, range=drange) dx = ...
Can you implement a function in Python 3 that fits a gaussian model to data and return its center
You are a Python code architect, reviewing and designing scalable and efficient code
Compute Mode using a histogram with sqrt ( data. size ) bins
How would you explain what the following Python 3 function does def offset_mode(data): nbins = int(np.ceil(np.sqrt(data.size))) mind, maxd = data.min(), data.max() histo = np.histogram(data, nbins, density=True, range=(mind, maxd)) dx = abs(histo[1][1] - histo[1][2]) / 2 hx = histo[1][1:] - dx h...
As a Python code composer, you craft elegant and concise scripts.
Fit a 2D tilt to data [ mask ]
Make a summary of the following Python 3 code def profile_tilt(data, mask): params = lmfit.Parameters() params.add(name="mx", value=0) params.add(name="my", value=0) params.add(name="off", value=np.average(data[mask])) fr = lmfit.minimize(tilt_residual, params, args=(data, mask)) bg = tilt_model...
As a Python code analyst, you investigate and solve complex coding mysteries
def profile_poly2o(data, mask): """Fit a 2D 2nd order polynomial to `data[mask]`""" # lmfit params = lmfit.Parameters() params.add(name="mx", value=0) params.add(name="my", value=0) params.add(name="mxy", value=0) params.add(name="ax", value=0) params.add(name="ay", value=0) params.a...
Can you write a function in Python 3 where it fits a 2D 2nd order polynomial to data [ mask ]
As a Python code analyst, you investigate and solve complex coding mysteries
lmfit 2nd order polynomial residuals
Here you have a function in Python 3, explain what it does def poly2o_residual(params, data, mask): bg = poly2o_model(params, shape=data.shape) res = (data - bg)[mask] return res.flatten()
You are a Python code generator, capable of creating scripts from specifications.
Infer the current version of the current node.
Explain what the following Python 3 code does def infer(args: argparse.Namespace) -> None: try: last_tag = last_git_release_tag(git_tags()) except NoGitTagsException: print(SemVer(0, 1, 0)) exit(0) commit_log = git_commits_since_last_tag(last_tag) action = parse_commit_log(commi...
As a Python code analyst, you investigate and solve complex coding mysteries
Bump the current version of the current node.
Explain what the following Python 3 code does def bump(args: argparse.Namespace) -> None: try: last_tag = last_git_release_tag(git_tags()) except NoGitTagsException: print(SemVer(0, 1, 0)) exit(0) last_ver = git_tag_to_semver(last_tag) if args.type == 'patch': print(las...
You are a Python code architect, reviewing and designing scalable and efficient code
def find_sideband(ft_data, which=+1, copy=True): """Find the side band position of a hologram The hologram is Fourier-transformed and the side band is determined by finding the maximum amplitude in Fourier space. Parameters ---------- ft_data: 2d ndarray Fourier transform of the ho...
How would you implement a function in Python 3 that finds the side band position of a hologram image.
You are a Python code generator, capable of creating scripts from specifications.
Compute the 2D Fourier transform with zero padding
Make a summary of the following Python 3 code def fourier2dpad(data, zero_pad=True): if zero_pad: # zero padding size is next order of 2 (N, M) = data.shape order = np.int(max(64., 2**np.ceil(np.log(2 * max(N, M)) / np.log(2)))) # this is faster than np.pad datapad = np.zero...
As a Python code translator, you convert algorithms and pseudocode into Python.
Compute the complex field from a real - valued 2d array containing the data of the central band and the sideband.
How would you explain what the following Python 3 function does def get_field(hologram, sideband=+1, filter_name="disk", filter_size=1 / 3, subtract_mean=True, zero_pad=True, copy=True): """Compute the complex field from a hologram using Fourier analysis Parameters ---------- hologram: re...
You are a Python code architect, reviewing and designing scalable and efficient code
Recursively copy all hdf5 data from one group to another.
Can you tell what is the following Python 3 function doing def copyh5(inh5, outh5): if not isinstance(inh5, h5py.Group): inh5 = h5py.File(inh5, mode="r") if outh5 is None: # create file in memory h5kwargs = {"name": "qpimage{}.h5".format(QPImage._instances), "driver":...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _conv_which_data(which_data): """Convert which data to string or tuple This function improves user convenience, as `which_data` may be of several types (str, ,str with spaces and commas, list, tuple) which is internally handled by this method. """ if isinstan...
Write a Python 3 script to convert which data to string or tuple
You are a Python code architect, reviewing and designing scalable and efficient code
Convert input data to phase and amplitude.
Can you generate the documentation for the following Python 3 function def _get_amp_pha(self, data, which_data): which_data = QPImage._conv_which_data(which_data) if which_data not in VALID_INPUT_DATA: msg = "`which_data` must be one of {}!".format(VALID_INPUT_DATA) raise ValueEr...
As a python code expert, you are capable of creating scripts from specifications.
def info(self): """list of tuples with QPImage meta data""" info = [] # meta data meta = self.meta for key in meta: info.append((key, self.meta[key])) # background correction for imdat in [self._amp, self._pha]: info += imdat.info r...
Can you write a function in Python 3 where it lists of tuples with QPImage meta data
As a Python code translator, you convert algorithms and pseudocode into Python.
def clear_bg(self, which_data=("amplitude", "phase"), keys="fit"): """Clear background correction Parameters ---------- which_data: str or list of str From which type of data to remove the background information. The list contains either "amplitude", ...
Write a Python 3 script to clear the background correction of the current object.
You are a Python code generator, capable of creating scripts from specifications.
def compute_bg(self, which_data="phase", fit_offset="mean", fit_profile="tilt", border_m=0, border_perc=0, border_px=0, from_mask=None, ret_mask=False): """Compute background correction Parameters ---------- which_data: str or lis...
Can you create a Python 3 function that computes background correction of the base image of the base image.
As a Python code analyst, you investigate and solve complex coding mysteries
Create a copy of the current instance of the QPImage.
Can you generate the documentation for the following Python 3 function def copy(self, h5file=None): h5 = copyh5(self.h5, h5file) return QPImage(h5file=h5, h5dtype=self.h5dtype)
You are a Python code analyst, evaluating scripts for potential improvements.
Compute a numerically refocused QPImage.
Can you tell what is the following Python 3 function doing def refocus(self, distance, method="helmholtz", h5file=None, h5mode="a"): field2 = nrefocus.refocus(field=self.field, d=distance/self["pixel size"], nm=self["medium index"], ...
You are a Python code architect, reviewing and designing scalable and efficient code
def set_bg_data(self, bg_data, which_data=None): """Set background amplitude and phase data Parameters ---------- bg_data: 2d ndarray (float or complex), list, QPImage, or `None` The background data (must be same type as `data`). If set to `None`, the background ...
Can you write a function in Python 3 where it sets the background amplitude and phase data for the current object.
You are a Python code generator, capable of creating scripts from specifications.
def add_qpimage(self, qpi, identifier=None, bg_from_idx=None): """Add a QPImage instance to the QPSeries Parameters ---------- qpi: qpimage.QPImage The QPImage that is added to the series identifier: str Identifier key for `qpi` bg_from_idx: int o...
Can you create a Python 3 function that adds a QPImage instance to the series.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_qpimage(self, index): """Return a single QPImage of the series Parameters ---------- index: int or str Index or identifier of the QPImage Notes ----- Instead of ``qps.get_qpimage(index)``, it is possible to use the short-hand ``qps[in...
Create a Python 3 function to return a single QPImage of the series with the given index.
You are a Python code generator, capable of creating scripts from specifications.
Collect invariants from the bases and merge them with the invariants in the namespace.
How would you explain what the following Python 3 function does def _collapse_invariants(bases: List[type], namespace: MutableMapping[str, Any]) -> None: invariants = [] # type: List[Contract] # Add invariants of the bases for base in bases: if hasattr(base, "__invariants__"): invarian...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _collapse_preconditions(base_preconditions: List[List[Contract]], bases_have_func: bool, preconditions: List[List[Contract]], func: Callable[..., Any]) -> List[List[Contract]]: """ Collapse function preconditions with the preconditions collected from the base classes. :param...
How would you implement a function in Python 3 that collapses function preconditions with the preconditions collected from the base classes.
You are a Python code architect, reviewing and designing scalable and efficient code
def _collapse_snapshots(base_snapshots: List[Snapshot], snapshots: List[Snapshot]) -> List[Snapshot]: """ Collapse snapshots of pre-invocation values with the snapshots collected from the base classes. :param base_snapshots: snapshots collected from the base classes :param snapshots: snapshots of the f...
Implement a Python 3 function for collapsing snapshots of pre - invocation values with the snapshots collected from the base classes.
As a Python code analyst, you investigate and solve complex coding mysteries
Collapse function postconditions with the postconditions collected from the base classes.
Can you generate a brief explanation for the following Python 3 code def _collapse_postconditions(base_postconditions: List[Contract], postconditions: List[Contract]) -> List[Contract]: return base_postconditions + postconditions
As a python code expert, you are capable of creating scripts from specifications.
Decorate the function at the key in the base class and the base class.
Here you have a function in Python 3, explain what it does def _decorate_namespace_function(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None: # pylint: disable=too-many-branches # pylint: disable=too-many-locals value = namespace[key] assert inspect.isfunction(value) or isinsta...
You are a Python code architect, reviewing and designing scalable and efficient code
def _decorate_namespace_property(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None: """Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them.""" # pylint: disable=too-many-locals # pylint: disable=too-many-branches # pylint: disable=too-man...
Can you write a function in Python 3 where it decorates a property in a namespace by iterating over all base classes and checking if they are present.
As a Python code composer, you craft elegant and concise scripts.
Decorate all methods in the namespace.
How would you explain what the following Python 3 function does def _dbc_decorate_namespace(bases: List[type], namespace: MutableMapping[str, Any]) -> None: _collapse_invariants(bases=bases, namespace=namespace) for key, value in namespace.items(): if inspect.isfunction(value) or isinstance(value, (sta...
You are a Python code analyst, evaluating scripts for potential improvements.
def _representable(value: Any) -> bool: """ Check whether we want to represent the value in the error message on contract breach. We do not want to represent classes, methods, modules and functions. :param value: value related to an AST node :return: True if we want to represent it in the violatio...
Write a Python 3 function that can check whether the value is representable in the error message on contract breach.
You are a Python code analyst, evaluating scripts for potential improvements.
Inspects the source code of a decorator call.
Here you have a function in Python 3, explain what it does def inspect_decorator(lines: List[str], lineno: int, filename: str) -> DecoratorInspection: if lineno < 0 or lineno >= len(lines): raise ValueError(("Given line number {} of one of the decorator lines " "is not within the r...
As a Python code composer, you craft elegant and concise scripts.
def find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]: """ Inspect the decorator and extract the condition as lambda. If the condition is not given as a lambda function, return None. """ call_node = decorator_inspection.node lambda_node = N...
Can you implement a function in Python 3 that inspects the decorator and extract the condition as lambda function.
You are a Python code architect, reviewing and designing scalable and efficient code
Return a list of value representations of the given condition function.
Can you tell what is the following Python 3 function doing def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspection], condition_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]: # pylint: disable=too-many-locals """ Represent function...
You are a Python code generator, capable of creating scripts from specifications.
Generate the message upon contract violation.
Can you generate a brief explanation for the following Python 3 code def generate_message(contract: Contract, condition_kwargs: Mapping[str, Any]) -> str: # pylint: disable=protected-access parts = [] # type: List[str] if contract.location is not None: parts.append("{}:\n".format(contract.location...
As a Python code analyst, you investigate and solve complex coding mysteries
Resolve the name from the variable look - up and the built - in lookup.
Explain what the following Python 3 code does def visit_Name(self, node: ast.Name) -> None: if node in self._recomputed_values: value = self._recomputed_values[node] # Check if it is a non-built-in is_builtin = True for lookup in self._variable_lookup: ...
As a python code expert, you are capable of creating scripts from specifications.
Represent the attribute by dumping its source code.
Here you have a function in Python 3, explain what it does def visit_Attribute(self, node: ast.Attribute) -> None: if node in self._recomputed_values: value = self._recomputed_values[node] if _representable(value=value): text = self._atok.get_text(node) s...
As a Python code translator, you convert algorithms and pseudocode into Python.
Represent the call by dumping its source code.
Explain what the following Python 3 code does def visit_Call(self, node: ast.Call) -> None: if node in self._recomputed_values: value = self._recomputed_values[node] text = self._atok.get_text(node) self.reprs[text] = value self.generic_visit(node=node)
As a Python code analyst, you investigate and solve complex coding mysteries
def visit_ListComp(self, node: ast.ListComp) -> None: """Represent the list comprehension by dumping its source code.""" if node in self._recomputed_values: value = self._recomputed_values[node] text = self._atok.get_text(node) self.reprs[text] = value self....
Write a Python 3 function that can represent the list comprehension by dumping its source code.
As a python code expert, you are capable of creating scripts from specifications.
Represent the dictionary comprehension by dumping its source code.
Given the following Python 3 function, write the documentation def visit_DictComp(self, node: ast.DictComp) -> None: if node in self._recomputed_values: value = self._recomputed_values[node] text = self._atok.get_text(node) self.reprs[text] = value self.generic_visi...
You are a Python code architect, reviewing and designing scalable and efficient code
Iterate through the stack of decorated functions until the original function is decorated.
Explain what the following Python 3 code does def _walk_decorator_stack(func: CallableT) -> Iterable['CallableT']: while hasattr(func, "__wrapped__"): yield func func = getattr(func, "__wrapped__") yield func
You are a Python code analyst, evaluating scripts for potential improvements.
Iterate through the decorator stack till we find the contract checker.
Given the following Python 3 function, write the documentation def find_checker(func: CallableT) -> Optional[CallableT]: contract_checker = None # type: Optional[CallableT] for a_wrapper in _walk_decorator_stack(func): if hasattr(a_wrapper, "__preconditions__") or hasattr(a_wrapper, "__postconditions__...
You are a Python code generator, capable of creating scripts from specifications.
def _kwargs_from_call(param_names: List[str], kwdefaults: Dict[str, Any], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> MutableMapping[str, Any]: """ Inspect the input values received at the wrapper for the actual function call. :param param_names: parameter (*i.e.* argument) name...
Implement a Python 3 function for inspecting the input values received at the wrapper for the actual function call.
As a Python code translator, you convert algorithms and pseudocode into Python.
Assert that the contract holds as a precondition.
Given the following Python 3 function, write the documentation def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None: # Check that all arguments to the condition function have been set. missing_args = [arg_name for arg_name in contract.condition_args if arg_name not in resolve...
You are a Python code generator, capable of creating scripts from specifications.
Assert that the contract holds as a class invariant given the instance of the class.
Can you generate a brief explanation for the following Python 3 code def _assert_invariant(contract: Contract, instance: Any) -> None: if 'self' in contract.condition_arg_set: check = contract.condition(self=instance) else: check = contract.condition() if not check: if contract.erro...
You are a Python code generator, capable of creating scripts from specifications.
def _capture_snapshot(a_snapshot: Snapshot, resolved_kwargs: Mapping[str, Any]) -> Any: """ Capture the snapshot from the keyword arguments resolved before the function call (including the default values). :param a_snapshot: snapshot to be captured :param resolved_kwargs: resolved keyword arguments (in...
Can you write a function in Python 3 where it captures the snapshot from the keyword arguments resolved before the function call.
As a Python code composer, you craft elegant and concise scripts.
def decorate_with_checker(func: CallableT) -> CallableT: """Decorate the function with a checker that verifies the preconditions and postconditions.""" assert not hasattr(func, "__preconditions__"), \ "Expected func to have no list of preconditions (there should be only a single contract checker per fun...
Can you implement a function in Python 3 that decorates the function with a checker that verifies the preconditions and postconditions.
You are a Python code generator, capable of creating scripts from specifications.
Find the instance of self in the arguments.
Explain what the following Python 3 code does def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any: instance_i = param_names.index("self") if instance_i < len(args): instance = args[instance_i] else: instance = kwargs["self"] return instance
You are a Python code architect, reviewing and designing scalable and efficient code
def _decorate_with_invariants(func: CallableT, is_init: bool) -> CallableT: """ Decorate the function ``func`` of the class ``cls`` with invariant checks. If the function has been already decorated with invariant checks, the function returns immediately. :param func: function to be wrapped :param ...
Write a Python 3 function that can decorate the function func with invariant checks.
You are a Python code analyst, evaluating scripts for potential improvements.
Check if the function has already been decorated with an invariant check by going through its decorator stack.
Here you have a function in Python 3, explain what it does def _already_decorated_with_invariants(func: CallableT) -> bool: already_decorated = False for a_decorator in _walk_decorator_stack(func=func): if getattr(a_decorator, "__is_invariant_check__", False): already_decorated = True ...
You are a Python code generator, capable of creating scripts from specifications.
def add_invariant_checks(cls: type) -> None: """Decorate each of the class functions with invariant checks if not already decorated.""" # Candidates for the decoration as list of (name, dir() value) init_name_func = None # type: Optional[Tuple[str, Callable[..., None]]] names_funcs = [] # type: List[T...
Write a Python 3 function that can decorate each of the class methods with invariant checks if not already decorated.
As a Python code analyst, you investigate and solve complex coding mysteries
def main() -> None: """"Execute the main routine.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--module", help="name of the module to import", choices=[ "functions_100_with_no_contract", "functi...
How would you code a function in Python 3 to execute the main routine.
As a Python code composer, you craft elegant and concise scripts.
Execute the main routine.
Given the following Python 3 function, write the documentation def main() -> None: modules = [ "functions_100_with_no_contract", "functions_100_with_1_contract", "functions_100_with_5_contracts", "functions_100_with_10_contracts", "functions_100_with_1_disabled_contract", ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def main() -> None: """"Execute the main routine.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--outdir", help="output directory", default=os.path.dirname(__file__)) args = parser.parse_args() outdir = pathlib.Path(args.outdir) if not outdir.exists(): ra...
Write a Python 3 script to execute the main routine.
As a Python code translator, you convert algorithms and pseudocode into Python.
Recompute the value as the bytes at the node.
Can you generate a brief explanation for the following Python 3 code def visit_Bytes(self, node: ast.Bytes) -> bytes: result = node.s self.recomputed_values[node] = result return node.s
You are a Python code architect, reviewing and designing scalable and efficient code
def visit_List(self, node: ast.List) -> List[Any]: """Visit the elements and assemble the results into a list.""" if isinstance(node.ctx, ast.Store): raise NotImplementedError("Can not compute the value of a Store on a list") result = [self.visit(node=elt) for elt in node.elts] ...
Write a Python 3 function that can visit the elements and assemble the results into a list.
As a Python code translator, you convert algorithms and pseudocode into Python.
Visit the elements and assemble the results into a tuple.
Here you have a function in Python 3, explain what it does def visit_Tuple(self, node: ast.Tuple) -> Tuple[Any, ...]: if isinstance(node.ctx, ast.Store): raise NotImplementedError("Can not compute the value of a Store on a tuple") result = tuple(self.visit(node=elt) for elt in node.elts) ...
As a Python code composer, you craft elegant and concise scripts.
Visit the elements and assemble the results into a set.
Given the following Python 3 function, write the documentation def visit_Set(self, node: ast.Set) -> Set[Any]: result = set(self.visit(node=elt) for elt in node.elts) self.recomputed_values[node] = result return result
As a Python code translator, you convert algorithms and pseudocode into Python.
def visit_Dict(self, node: ast.Dict) -> Dict[Any, Any]: """Visit keys and values and assemble a dictionary with the results.""" recomputed_dict = dict() # type: Dict[Any, Any] for key, val in zip(node.keys, node.values): recomputed_dict[self.visit(node=key)] = self.visit(node=val) ...
How would you code a function in Python 3 to visit keys and values and assemble a dictionary with the results.
You are a Python code generator, capable of creating scripts from specifications.
Forward the node value as a result.
How would you explain what the following Python 3 function does def visit_NameConstant(self, node: ast.NameConstant) -> Any: self.recomputed_values[node] = node.value return node.value
As a Python code composer, you craft elegant and concise scripts.
Load the variable by looking it up in the variable look - up and in the built - ins.
Explain what the following Python 3 code does def visit_Name(self, node: ast.Name) -> Any: if not isinstance(node.ctx, ast.Load): raise NotImplementedError("Can only compute a value of Load on a name {}, but got context: {}".format( node.id, node.ctx)) result = None # type:...
As a Python code composer, you craft elegant and concise scripts.
Visit the node s value and return the result.
Make a summary of the following Python 3 code def visit_Expr(self, node: ast.Expr) -> Any: result = self.visit(node=node.value) self.recomputed_values[node] = result return result
You are a Python code architect, reviewing and designing scalable and efficient code
Visit the node operand and apply the operation on the result.
Make a summary of the following Python 3 code def visit_UnaryOp(self, node: ast.UnaryOp) -> Any: if isinstance(node.op, ast.UAdd): result = +self.visit(node=node.operand) elif isinstance(node.op, ast.USub): result = -self.visit(node=node.operand) elif isinstance(node.op, ...
You are a Python code analyst, evaluating scripts for potential improvements.
Recursively visit the comparators and apply the operations on them.
Can you tell what is the following Python 3 function doing def visit_Compare(self, node: ast.Compare) -> Any: # pylint: disable=too-many-branches left = self.visit(node=node.left) comparators = [self.visit(node=comparator) for comparator in node.comparators] result = None # type: Opti...
As a Python code composer, you craft elegant and concise scripts.
def visit_Call(self, node: ast.Call) -> Any: """Visit the function and the arguments and finally make the function call with them.""" func = self.visit(node=node.func) args = [] # type: List[Any] for arg_node in node.args: if isinstance(arg_node, ast.Starred): ...
Implement a function in Python 3 to visit the function and the arguments and then make the function call with them.
You are a Python code architect, reviewing and designing scalable and efficient code
def visit_IfExp(self, node: ast.IfExp) -> Any: """Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``.""" test = self.visit(node=node.test) if test: result = self.visit(node=node.body) else: result = self.visit(node=node.orelse) ...
Can you create a Python 3 function that visits the test and depending on its outcome the body or orelse.
You are a Python code generator, capable of creating scripts from specifications.
Visit the node s value and get the attribute from the result.
Can you tell what is the following Python 3 function doing def visit_Attribute(self, node: ast.Attribute) -> Any: value = self.visit(node=node.value) if not isinstance(node.ctx, ast.Load): raise NotImplementedError( "Can only compute a value of Load on the attribute {}, but g...
As a Python code analyst, you investigate and solve complex coding mysteries
Visit the node s value and store the result in the recomputed_values dict.
Can you tell what is the following Python 3 function doing def visit_Index(self, node: ast.Index) -> Any: result = self.visit(node=node.value) self.recomputed_values[node] = result return result
You are a Python code analyst, evaluating scripts for potential improvements.
def visit_Slice(self, node: ast.Slice) -> slice: """Visit ``lower``, ``upper`` and ``step`` and recompute the node as a ``slice``.""" lower = None # type: Optional[int] if node.lower is not None: lower = self.visit(node=node.lower) upper = None # type: Optional[int] ...
Create a Python 3 function for visiting lower upper and step and recompute the node as a slice.
As a Python code analyst, you investigate and solve complex coding mysteries
def visit_ExtSlice(self, node: ast.ExtSlice) -> Tuple[Any, ...]: """Visit each dimension of the advanced slicing and assemble the dimensions in a tuple.""" result = tuple(self.visit(node=dim) for dim in node.dims) self.recomputed_values[node] = result return result
Create a Python 3 function for visiting each dimension of the advanced slicing and assemble the dimensions in a tuple.
You are a Python code architect, reviewing and designing scalable and efficient code
Visit the slice and a value and get the element.
Here you have a function in Python 3, explain what it does def visit_Subscript(self, node: ast.Subscript) -> Any: value = self.visit(node=node.value) a_slice = self.visit(node=node.slice) result = value[a_slice] self.recomputed_values[node] = result return result
As a Python code translator, you convert algorithms and pseudocode into Python.
def _execute_comprehension(self, node: Union[ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp]) -> Any: """Compile the generator or comprehension from the node and execute the compiled code.""" args = [ast.arg(arg=name) for name in sorted(self._name_to_value.keys())] func_def_node = as...
Create a Python 3 function to compile the generator or comprehension from the node and execute the compiled code.
You are a Python code analyst, evaluating scripts for potential improvements.
def visit_GeneratorExp(self, node: ast.GeneratorExp) -> Any: """Compile the generator expression as a function and call it.""" result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(generator.iter) # Do not set the computed value of the...
Can you implement a function in Python 3 that compiles the generator expression as a function and call it.
You are a Python code generator, capable of creating scripts from specifications.
Compile the list comprehension as a function and call it.
Can you generate a brief explanation for the following Python 3 code def visit_ListComp(self, node: ast.ListComp) -> Any: result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(generator.iter) self.recomputed_values[node] = result retur...
You are a Python code architect, reviewing and designing scalable and efficient code
Compile the set comprehension as a function and call it.
Here you have a function in Python 3, explain what it does def visit_SetComp(self, node: ast.SetComp) -> Any: result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(generator.iter) self.recomputed_values[node] = result return result
As a Python code composer, you craft elegant and concise scripts.
Compile the dictionary comprehension as a function and call it.
Here you have a function in Python 3, explain what it does def visit_DictComp(self, node: ast.DictComp) -> Any: result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(generator.iter) self.recomputed_values[node] = result return result
You are a Python code architect, reviewing and designing scalable and efficient code
Raise an exception that this node is unexpected.
Make a summary of the following Python 3 code def visit_Return(self, node: ast.Return) -> Any: # pylint: disable=no-self-use raise AssertionError("Unexpected return node during the re-computation: {}".format(ast.dump(node)))
You are a Python code analyst, evaluating scripts for potential improvements.
def generic_visit(self, node: ast.AST) -> None: """Raise an exception that this node has not been handled.""" raise NotImplementedError("Unhandled recomputation of the node: {} {}".format(type(node), node))
Implement a Python 3 function for raising an exception that this node has not been handled.
As a Python code composer, you craft elegant and concise scripts.
Tokenize input text to words.
Explain what the following Python 3 code does def tokenize_words(string): string = six.text_type(string) return re.findall(WORD_TOKENIZATION_RULES, string)
You are a Python code generator, capable of creating scripts from specifications.
Aligns the decision tree with the witnesses
Can you tell what is the following Python 3 function doing def align(self): ''' Every step we have 3 choices: 1) Move pointer witness a --> omission 2) Move pointer witness b --> addition 3) Move pointer of both witness a/b --> match Note: a replacement is omission follo...
As a Python code analyst, you investigate and solve complex coding mysteries
def connect_near(self, source, target, weight): # Near edges are added to self.near_graph, not self.graph, to avoid cycles """ :type source: integer :type target: integer """ self.near_graph.add_edge(source, target, weight = weight, type='near')
Implement a function in Python 3 to connect two sets of nodes near to the target set.
As a Python code analyst, you investigate and solve complex coding mysteries
def merge(self, graph, witness_sigil, witness_tokens, alignments={}): """ :type graph: VariantGraph """ # NOTE: token_to_vertex only contains newly generated vertices token_to_vertex = {} last = graph.start for token in witness_tokens: vertex = alignme...
Write a Python 3 script for merging the given graph with the given witness_sigil and returns a dictionary of all the vertices that are connected to the witness_sigil.
You are a Python code generator, capable of creating scripts from specifications.
def collate(self, graph): """ :type graph: VariantGraph """ # prepare the token index self.token_index.prepare() self.vertex_array = [None] * len(self.token_index.token_array) # Build the variant graph for the first witness # this is easy: generate a vert...
How would you code a function in Python 3 to collate the given VariantGraph into a single variant graph for each witness in the sequence
As a Python code translator, you convert algorithms and pseudocode into Python.
def _parse(self, pattern): """Parse string of comma-separated x-y/step -like ranges""" # Comma separated ranges if pattern.find(',') < 0: subranges = [pattern] else: subranges = pattern.split(',') for subrange in subranges: if subrange.find('/...
Write a Python 3 function that can parse a string of comma - separated x - y - step - like ranges and return a tuple of the node range info.
As a Python code analyst, you investigate and solve complex coding mysteries
def fromlist(cls, rnglist, autostep=None): """Class method that returns a new RangeSet with ranges from provided list.""" inst = RangeSet(autostep=autostep) inst.updaten(rnglist) return inst
Implement a function in Python 3 to class method that returns a new RangeSet with ranges from provided list.
You are a Python code analyst, evaluating scripts for potential improvements.
Class method that returns a new RangeSet of one single item or a single range ( from integer or slice object.
Can you generate the documentation for the following Python 3 function def fromone(cls, index, pad=0, autostep=None): inst = RangeSet(autostep=autostep) # support slice object with duck-typing try: inst.add(index, pad) except TypeError: if not index.stop: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def set_autostep(self, val): """Set autostep value (property)""" if val is None: # disabled by default for pdsh compat (+inf is 1E400, but a bug in # python 2.4 makes it impossible to be pickled, so we use less) # NOTE: Later, we could consider sys.maxint here ...
Implement a function in Python 3 to set autostep value ( property
You are a Python code analyst, evaluating scripts for potential improvements.
def striter(self): """Iterate over each (optionally padded) string element in RangeSet.""" pad = self.padding or 0 for i in self._sorted(): yield "%0*d" % (pad, i)
Write a Python 3 function for iterating over each string element in RangeSet.
You are a Python code generator, capable of creating scripts from specifications.
def contiguous(self): """Object-based iterator over contiguous range sets.""" pad = self.padding or 0 for sli in self._contiguous_slices(): yield RangeSet.fromone(slice(sli.start, sli.stop, sli.step), pad)
Write a Python 3 script to object - based iterator over contiguous range sets.
You are a Python code analyst, evaluating scripts for potential improvements.
Stringify the slices list.
Make a summary of the following Python 3 code def _strslices(self): pad = self.padding or 0 for sli in self.slices(): if sli.start + 1 == sli.stop: yield "%0*d" % (pad, sli.start) else: assert sli.step >= 0, "Internal error: sli.step < 0" ...
You are a Python code generator, capable of creating scripts from specifications.
Internal iterator over contiguous slices in RangeSet.
Here you have a function in Python 3, explain what it does def _contiguous_slices(self): k = j = None for i in self._sorted(): if k is None: k = j = i if i - j > 1: yield slice(k, j + 1, 1) k = i j = i if k is no...
As a Python code composer, you craft elegant and concise scripts.
Internal generator that is able to retrieve ranges organized by step.
Given the following Python 3 function, write the documentation def _folded_slices(self): if len(self) == 0: return prng = None # pending range istart = None # processing starting indice m = 0 # processing step for sli in self._contiguous_s...
As a Python code composer, you craft elegant and concise scripts.
def split(self, nbr): """ Split the rangeset into nbr sub-rangesets (at most). Each sub-rangeset will have the same number of elements more or less 1. Current rangeset remains unmodified. Returns an iterator. >>> RangeSet("1-5").split(3) RangeSet("1-2") ...
Write a Python 3 function for splitting the rangeset into nbr sub - nodesets.
You are a Python code architect, reviewing and designing scalable and efficient code