code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def elXpath(self, xpath, dom=None): """check if element is present by css""" if dom is None: dom = self.browser return expect(dom.is_element_present_by_xpath, args=[xpath])
check if element is present by css
Below is the the instruction that describes the task: ### Input: check if element is present by css ### Response: def elXpath(self, xpath, dom=None): """check if element is present by css""" if dom is None: dom = self.browser return expect(dom.is_element_present_by_xpath, args=[...
def _check_function(self): ''' make some basic checks on the function to make sure it is valid''' # note, callable is valid for Python 2 and Python 3.2 onwards but # not inbetween if not callable(self._function): raise RuntimeError( "provided function '{0}' is...
make some basic checks on the function to make sure it is valid
Below is the the instruction that describes the task: ### Input: make some basic checks on the function to make sure it is valid ### Response: def _check_function(self): ''' make some basic checks on the function to make sure it is valid''' # note, callable is valid for Python 2 and Python 3.2 onwa...
def _reverse(self): """ reverse patch direction (this doesn't touch filenames) """ for p in self.items: for h in p.hunks: h.startsrc, h.starttgt = h.starttgt, h.startsrc h.linessrc, h.linestgt = h.linestgt, h.linessrc for i,line in enumerate(h.text): # need to use line[0:...
reverse patch direction (this doesn't touch filenames)
Below is the the instruction that describes the task: ### Input: reverse patch direction (this doesn't touch filenames) ### Response: def _reverse(self): """ reverse patch direction (this doesn't touch filenames) """ for p in self.items: for h in p.hunks: h.startsrc, h.starttgt = h.starttgt, ...
def export_keys(output_path, stash, passphrase, backend): """Export all keys to a file """ stash = _get_stash(backend, stash, passphrase) try: click.echo('Exporting stash to {0}...'.format(output_path)) stash.export(output_path=output_path) click.echo('Export complete!') exc...
Export all keys to a file
Below is the the instruction that describes the task: ### Input: Export all keys to a file ### Response: def export_keys(output_path, stash, passphrase, backend): """Export all keys to a file """ stash = _get_stash(backend, stash, passphrase) try: click.echo('Exporting stash to {0}...'.for...
def _add_missing_schema_attributes(self): ''' Adds any missed schema attributes to the _attributes list The attributes can be class attributes and they won't be included in the _attributes list automatically ''' for attr in [attr for attr in dir(self) if not attr.startsw...
Adds any missed schema attributes to the _attributes list The attributes can be class attributes and they won't be included in the _attributes list automatically
Below is the the instruction that describes the task: ### Input: Adds any missed schema attributes to the _attributes list The attributes can be class attributes and they won't be included in the _attributes list automatically ### Response: def _add_missing_schema_attributes(self): ''' ...
def clear(self): """ Clears the registry """ with self.__svc_lock: self.__svc_registry.clear() self.__svc_factories.clear() self.__svc_specs.clear() self.__bundle_svc.clear() self.__bundle_imports.clear() self.__fact...
Clears the registry
Below is the the instruction that describes the task: ### Input: Clears the registry ### Response: def clear(self): """ Clears the registry """ with self.__svc_lock: self.__svc_registry.clear() self.__svc_factories.clear() self.__svc_specs.clear()...
def _ftp_nlst(self, dir_name): """Variant of `self.ftp.nlst()` that supports encoding-fallback.""" assert compat.is_native(dir_name) lines = [] def _add_line(status, line): lines.append(line) cmd = "NLST " + dir_name self._ftp_retrlines_native(cmd, ...
Variant of `self.ftp.nlst()` that supports encoding-fallback.
Below is the the instruction that describes the task: ### Input: Variant of `self.ftp.nlst()` that supports encoding-fallback. ### Response: def _ftp_nlst(self, dir_name): """Variant of `self.ftp.nlst()` that supports encoding-fallback.""" assert compat.is_native(dir_name) lines = [] ...
def extract_source_params(src): """ Extract params from source object. """ tags = get_taglist(src) data = [] for key, param, vtype in BASE_PARAMS: if key in src.attrib: if vtype == "c": data.append((param, src.attrib[key])) elif vtype == "f": ...
Extract params from source object.
Below is the the instruction that describes the task: ### Input: Extract params from source object. ### Response: def extract_source_params(src): """ Extract params from source object. """ tags = get_taglist(src) data = [] for key, param, vtype in BASE_PARAMS: if key in src.attrib: ...
def _choice_getter(self): """ Return a function object suitable for the "get" side of the property descriptor. """ def get_group_member_element(obj): return obj.first_child_found_in(*self._member_nsptagnames) get_group_member_element.__doc__ = ( 'R...
Return a function object suitable for the "get" side of the property descriptor.
Below is the the instruction that describes the task: ### Input: Return a function object suitable for the "get" side of the property descriptor. ### Response: def _choice_getter(self): """ Return a function object suitable for the "get" side of the property descriptor. """ ...
def save_figure(self, event=None, panel='top'): """ save figure image to file""" panel = self.get_panel(panel) panel.save_figure(event=event)
save figure image to file
Below is the the instruction that describes the task: ### Input: save figure image to file ### Response: def save_figure(self, event=None, panel='top'): """ save figure image to file""" panel = self.get_panel(panel) panel.save_figure(event=event)
def find_project_directory(start_path) -> str: """ Locate top-level project directory """ start_path = os.path.realpath(start_path) possible_name = os.path.join(start_path, ModelConfig.PROJECT_FILE_NAME) if os.path.exists(possible_name): return start_path else: ...
Locate top-level project directory
Below is the the instruction that describes the task: ### Input: Locate top-level project directory ### Response: def find_project_directory(start_path) -> str: """ Locate top-level project directory """ start_path = os.path.realpath(start_path) possible_name = os.path.join(start_path, Mod...
def compute_two_dimensional_near_isotropic_downsampling_scales( size, voxel_size, max_scales=float('inf'), max_downsampling=DEFAULT_MAX_DOWNSAMPLING, max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE): """Compute a list of successive downsampling factors for 2-d tiles.""" ...
Compute a list of successive downsampling factors for 2-d tiles.
Below is the the instruction that describes the task: ### Input: Compute a list of successive downsampling factors for 2-d tiles. ### Response: def compute_two_dimensional_near_isotropic_downsampling_scales( size, voxel_size, max_scales=float('inf'), max_downsampling=DEFAULT_MAX_DOW...
def revnet(inputs, hparams, reuse=None): """Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() o...
Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() object in the common_hparams module: ...
Below is the the instruction that describes the task: ### Input: Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained i...
def set_led(self, led, action=None, cabinet=Required, frame=Required, board=Required): """Set or toggle the state of an LED. .. note:: At the time of writing, LED 7 is only set by the BMP on start-up to indicate that the watchdog timer reset the board. After this...
Set or toggle the state of an LED. .. note:: At the time of writing, LED 7 is only set by the BMP on start-up to indicate that the watchdog timer reset the board. After this point, the LED is available for use by applications. Parameters ---------- l...
Below is the the instruction that describes the task: ### Input: Set or toggle the state of an LED. .. note:: At the time of writing, LED 7 is only set by the BMP on start-up to indicate that the watchdog timer reset the board. After this point, the LED is available for ...
def unzip(self, directory): """ Write contents of zipfile to directory """ if not os.path.exists(directory): os.makedirs(directory) shutil.copytree(self.src_dir, directory)
Write contents of zipfile to directory
Below is the the instruction that describes the task: ### Input: Write contents of zipfile to directory ### Response: def unzip(self, directory): """ Write contents of zipfile to directory """ if not os.path.exists(directory): os.makedirs(directory) shutil.copytr...
def load_model(itos_filename, classifier_filename, num_classes): """Load the classifier and int to string mapping Args: itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl) classifier_filename (str): The filename of the trained classifier Returns: ...
Load the classifier and int to string mapping Args: itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl) classifier_filename (str): The filename of the trained classifier Returns: string to int mapping, trained classifer model
Below is the the instruction that describes the task: ### Input: Load the classifier and int to string mapping Args: itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl) classifier_filename (str): The filename of the trained classifier Returns: ...
def get_default_preds(): """dynamically build autocomplete options based on an external file""" g = ontospy.Ontospy(rdfsschema, text=True, verbose=False, hide_base_schemas=False) classes = [(x.qname, x.bestDescription()) for x in g.all_classes] properties = [(x.qname, x.bestDescription()) for x in g.all...
dynamically build autocomplete options based on an external file
Below is the the instruction that describes the task: ### Input: dynamically build autocomplete options based on an external file ### Response: def get_default_preds(): """dynamically build autocomplete options based on an external file""" g = ontospy.Ontospy(rdfsschema, text=True, verbose=False, hide_base...
def columnSchema(self): """ Returns the schema for the image column. :return: a :class:`StructType` for image column, ``struct<origin:string, height:int, width:int, nChannels:int, mode:int, data:binary>``. .. versionadded:: 2.4.0 """ if self._columnSchema i...
Returns the schema for the image column. :return: a :class:`StructType` for image column, ``struct<origin:string, height:int, width:int, nChannels:int, mode:int, data:binary>``. .. versionadded:: 2.4.0
Below is the the instruction that describes the task: ### Input: Returns the schema for the image column. :return: a :class:`StructType` for image column, ``struct<origin:string, height:int, width:int, nChannels:int, mode:int, data:binary>``. .. versionadded:: 2.4.0 ### Response: def ...
def add_cookies_to_web_driver(driver, cookies): """ Sets cookies in an existing WebDriver session. """ for cookie in cookies: driver.add_cookie(convert_cookie_to_dict(cookie)) return driver
Sets cookies in an existing WebDriver session.
Below is the the instruction that describes the task: ### Input: Sets cookies in an existing WebDriver session. ### Response: def add_cookies_to_web_driver(driver, cookies): """ Sets cookies in an existing WebDriver session. """ for cookie in cookies: driver.add_cookie(convert_cookie_to_dic...
def send(self, request_body): ''' Sends request body. ''' if not request_body: self._httprequest.send() else: self._httprequest.send(request_body)
Sends request body.
Below is the the instruction that describes the task: ### Input: Sends request body. ### Response: def send(self, request_body): ''' Sends request body. ''' if not request_body: self._httprequest.send() else: self._httprequest.send(request_body)
def parse_problem_name(name): """Determines if problem_name specifies a copy and/or reversal. Args: name: str, problem name, possibly with suffixes. Returns: ProblemSpec: namedtuple with ["base_name", "was_reversed", "was_copy"] Raises: ValueError if name contains multiple suffixes of the same ty...
Determines if problem_name specifies a copy and/or reversal. Args: name: str, problem name, possibly with suffixes. Returns: ProblemSpec: namedtuple with ["base_name", "was_reversed", "was_copy"] Raises: ValueError if name contains multiple suffixes of the same type ('_rev' or '_copy'). One o...
Below is the the instruction that describes the task: ### Input: Determines if problem_name specifies a copy and/or reversal. Args: name: str, problem name, possibly with suffixes. Returns: ProblemSpec: namedtuple with ["base_name", "was_reversed", "was_copy"] Raises: ValueError if name contain...
def system(command, answer=''): """commands.getoutput() replacement that also works on windows""" p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ...
commands.getoutput() replacement that also works on windows
Below is the the instruction that describes the task: ### Input: commands.getoutput() replacement that also works on windows ### Response: def system(command, answer=''): """commands.getoutput() replacement that also works on windows""" p = subprocess.Popen(command, shell=True, ...
def anonymous_required(func=None, url=None): """Required that the user is not logged in.""" url = url or "/" def _dec(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): ...
Required that the user is not logged in.
Below is the the instruction that describes the task: ### Input: Required that the user is not logged in. ### Response: def anonymous_required(func=None, url=None): """Required that the user is not logged in.""" url = url or "/" def _dec(view_func): @wraps(view_func, assigned=available_attrs(...
def smart_email_list(self, status="all", client_id=None): """Gets the smart email list.""" if client_id is None: response = self._get( "/transactional/smartEmail?status=%s" % status) else: response = self._get( "/transactional/smartEmail?st...
Gets the smart email list.
Below is the the instruction that describes the task: ### Input: Gets the smart email list. ### Response: def smart_email_list(self, status="all", client_id=None): """Gets the smart email list.""" if client_id is None: response = self._get( "/transactional/smartEmail?sta...
def update(version=None): ''' Update the salt minion from the URL defined in opts['update_url'] SaltStack, Inc provides the latest builds here: update_url: https://repo.saltstack.com/windows/ Be aware that as of 2014-8-11 there's a bug in esky such that only the latest version available in the ...
Update the salt minion from the URL defined in opts['update_url'] SaltStack, Inc provides the latest builds here: update_url: https://repo.saltstack.com/windows/ Be aware that as of 2014-8-11 there's a bug in esky such that only the latest version available in the update_url can be downloaded and insta...
Below is the the instruction that describes the task: ### Input: Update the salt minion from the URL defined in opts['update_url'] SaltStack, Inc provides the latest builds here: update_url: https://repo.saltstack.com/windows/ Be aware that as of 2014-8-11 there's a bug in esky such that only the l...
def load_alerts(self): """ NOTE: use refresh() instead of this, if you are just needing to refresh the alerts list Gets raw xml (cap) from the Alerts feed, throws it into the parser and ends up with a list of alerts object, which it stores to self._alerts """ self._feed =...
NOTE: use refresh() instead of this, if you are just needing to refresh the alerts list Gets raw xml (cap) from the Alerts feed, throws it into the parser and ends up with a list of alerts object, which it stores to self._alerts
Below is the the instruction that describes the task: ### Input: NOTE: use refresh() instead of this, if you are just needing to refresh the alerts list Gets raw xml (cap) from the Alerts feed, throws it into the parser and ends up with a list of alerts object, which it stores to self._alerts ### Re...
def _parse_merged_entities(self): """set self._merged_entities to the longest possible(wrapping) tokens """ self._merged_entities = list(filterfalse( lambda token: self._is_wrapped(token, self.entities), self.entities))
set self._merged_entities to the longest possible(wrapping) tokens
Below is the the instruction that describes the task: ### Input: set self._merged_entities to the longest possible(wrapping) tokens ### Response: def _parse_merged_entities(self): """set self._merged_entities to the longest possible(wrapping) tokens """ self._merged_entities = list(filterfa...
def revoke_auth(preserve_minion_cache=False): ''' The minion sends a request to the master to revoke its own key. Note that the minion session will be revoked and the minion may not be able to return the result of this command back to the master. If the 'preserve_minion_cache' flag is set to True, ...
The minion sends a request to the master to revoke its own key. Note that the minion session will be revoked and the minion may not be able to return the result of this command back to the master. If the 'preserve_minion_cache' flag is set to True, the master cache for this minion will not be removed. ...
Below is the the instruction that describes the task: ### Input: The minion sends a request to the master to revoke its own key. Note that the minion session will be revoked and the minion may not be able to return the result of this command back to the master. If the 'preserve_minion_cache' flag is se...
def read_client_secrets(): '''for private or protected registries, a client secrets file is required to be located at .sregistry. If no secrets are found, we use default of Singularity Hub, and return a dummy secrets. ''' client_secrets = _default_client_secrets() # If token file not prov...
for private or protected registries, a client secrets file is required to be located at .sregistry. If no secrets are found, we use default of Singularity Hub, and return a dummy secrets.
Below is the the instruction that describes the task: ### Input: for private or protected registries, a client secrets file is required to be located at .sregistry. If no secrets are found, we use default of Singularity Hub, and return a dummy secrets. ### Response: def read_client_secrets(): '''...
def checksum(digits): """ Calculate and return control digit for given list of digits based on ISO7064, MOD 11,10 standard. """ remainder = 10 for digit in digits: remainder = (remainder + digit) % 10 if remainder == 0: remainder = 10 remainder = (remainder * ...
Calculate and return control digit for given list of digits based on ISO7064, MOD 11,10 standard.
Below is the the instruction that describes the task: ### Input: Calculate and return control digit for given list of digits based on ISO7064, MOD 11,10 standard. ### Response: def checksum(digits): """ Calculate and return control digit for given list of digits based on ISO7064, MOD 11,10 standard...
def describe_group(record, region): """Attempts to describe group ids.""" account_id = record['account'] group_name = cloudwatch.filter_request_parameters('groupName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) group_id = cloudwatch.filter_request_parameters('groupId', r...
Attempts to describe group ids.
Below is the the instruction that describes the task: ### Input: Attempts to describe group ids. ### Response: def describe_group(record, region): """Attempts to describe group ids.""" account_id = record['account'] group_name = cloudwatch.filter_request_parameters('groupName', record) vpc_id = c...
def _mangle_prefix(res): """ Mangle prefix result """ # fugly cast from large numbers to string to deal with XML-RPC res['total_addresses'] = unicode(res['total_addresses']) res['used_addresses'] = unicode(res['used_addresses']) res['free_addresses'] = unicode(res['free_addresses']) # postg...
Mangle prefix result
Below is the the instruction that describes the task: ### Input: Mangle prefix result ### Response: def _mangle_prefix(res): """ Mangle prefix result """ # fugly cast from large numbers to string to deal with XML-RPC res['total_addresses'] = unicode(res['total_addresses']) res['used_addresses']...
def extract_variables(href): """Return a list of variable names used in a URI template.""" patterns = [re.sub(r'\*|:\d+', '', pattern) for pattern in re.findall(r'{[\+#\./;\?&]?([^}]+)*}', href)] variables = [] for pattern in patterns: for part in pattern.split(","): ...
Return a list of variable names used in a URI template.
Below is the the instruction that describes the task: ### Input: Return a list of variable names used in a URI template. ### Response: def extract_variables(href): """Return a list of variable names used in a URI template.""" patterns = [re.sub(r'\*|:\d+', '', pattern) for pattern in re.fi...
def _addProtein(self, proteinId, proteinName, sequence, fastaHeader, headerInfo, isDecoy=False, isContaminant=False): """#TODO""" proteinEntry = ProteinEntry( proteinId, proteinName, sequence, fastaHeader, headerInfo, isDecoy=isDecoy, isContaminant=isContamina...
#TODO
Below is the the instruction that describes the task: ### Input: #TODO ### Response: def _addProtein(self, proteinId, proteinName, sequence, fastaHeader, headerInfo, isDecoy=False, isContaminant=False): """#TODO""" proteinEntry = ProteinEntry( proteinId, proteinName,...
def render(self, file_path, **kwargs): """ Save the content of the .text file in the PDF. Parameters ---------- file_path: str Path to the output file. """ temp = get_tempfile(suffix='.tex') self.save_content(temp.name) try: self....
Save the content of the .text file in the PDF. Parameters ---------- file_path: str Path to the output file.
Below is the the instruction that describes the task: ### Input: Save the content of the .text file in the PDF. Parameters ---------- file_path: str Path to the output file. ### Response: def render(self, file_path, **kwargs): """ Save the content of the .text file in t...
def lu_solve(LU, b): r"""Solve for LU decomposition. Solve the linear equations :math:`\mathrm A \mathbf x = \mathbf b`, given the LU factorization of :math:`\mathrm A`. Args: LU (array_like): LU decomposition. b (array_like): Right-hand side. Returns: :class:`numpy.ndarra...
r"""Solve for LU decomposition. Solve the linear equations :math:`\mathrm A \mathbf x = \mathbf b`, given the LU factorization of :math:`\mathrm A`. Args: LU (array_like): LU decomposition. b (array_like): Right-hand side. Returns: :class:`numpy.ndarray`: The solution to the s...
Below is the the instruction that describes the task: ### Input: r"""Solve for LU decomposition. Solve the linear equations :math:`\mathrm A \mathbf x = \mathbf b`, given the LU factorization of :math:`\mathrm A`. Args: LU (array_like): LU decomposition. b (array_like): Right-hand side...
def set_file(self, filename): """ Analyse the file with the captured content """ # Use the file name as prefix if none is given if self.output_prefix is None: _, self.output_prefix = os.path.split(filename) # Check if the file is present, since rdpcap will not do that ...
Analyse the file with the captured content
Below is the the instruction that describes the task: ### Input: Analyse the file with the captured content ### Response: def set_file(self, filename): """ Analyse the file with the captured content """ # Use the file name as prefix if none is given if self.output_prefix is None: ...
def ec_geometric_series(p0, T, n): r"""Compute expected transition counts for Markov chain after n steps. Expected counts are computed according to ..math:: E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^t T^{k})_{i} p_{ij} The sum is computed using the eigenvalue decomposition of T and applying the e...
r"""Compute expected transition counts for Markov chain after n steps. Expected counts are computed according to ..math:: E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^t T^{k})_{i} p_{ij} The sum is computed using the eigenvalue decomposition of T and applying the expression for a finite geometric series...
Below is the the instruction that describes the task: ### Input: r"""Compute expected transition counts for Markov chain after n steps. Expected counts are computed according to ..math:: E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^t T^{k})_{i} p_{ij} The sum is computed using the eigenvalue decompositi...
def csch(x, context=None): """ Return the hyperbolic cosecant of x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_csch, (BigFloat._implicit_convert(x),), context, )
Return the hyperbolic cosecant of x.
Below is the the instruction that describes the task: ### Input: Return the hyperbolic cosecant of x. ### Response: def csch(x, context=None): """ Return the hyperbolic cosecant of x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_csch, (BigFloat._implic...
def create(embedding_name, **kwargs): """Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :fun...
Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :func:`gluonnlp.embedding.list_sources`. Pa...
Below is the the instruction that describes the task: ### Input: Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name...
def has_bounds(self): """return True, if any variable is bounded""" bounds = self.bounds if bounds in (None, [None, None]): return False for ib, bound in enumerate(bounds): if bound is not None: sign_ = 2 * ib - 1 for bound_i in bou...
return True, if any variable is bounded
Below is the the instruction that describes the task: ### Input: return True, if any variable is bounded ### Response: def has_bounds(self): """return True, if any variable is bounded""" bounds = self.bounds if bounds in (None, [None, None]): return False for ib, bound i...
def read(self, n=1): """Return n bytes :param n: number of bytes to return :type n: :class:`int` :return: bytes :rtype: :class:`bytes` """ self.offset += n return self.data[self.offset - n:self.offset]
Return n bytes :param n: number of bytes to return :type n: :class:`int` :return: bytes :rtype: :class:`bytes`
Below is the the instruction that describes the task: ### Input: Return n bytes :param n: number of bytes to return :type n: :class:`int` :return: bytes :rtype: :class:`bytes` ### Response: def read(self, n=1): """Return n bytes :param n: number of bytes to return...
def debug(ftn, txt): """Used for debugging.""" if debug_p: sys.stdout.write("{0}.{1}:{2}\n".format(modname, ftn, txt)) sys.stdout.flush()
Used for debugging.
Below is the the instruction that describes the task: ### Input: Used for debugging. ### Response: def debug(ftn, txt): """Used for debugging.""" if debug_p: sys.stdout.write("{0}.{1}:{2}\n".format(modname, ftn, txt)) sys.stdout.flush()
def _notify_mutated(self, obj, old, hint=None): ''' A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : ...
A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : The "old" value of the container ...
Below is the the instruction that describes the task: ### Input: A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (o...
def _from_arrays(self, x, y, z): """ Create VTK rectilinear grid directly from numpy arrays. Each array gives the uniques coordinates of the mesh along each axial direction. To help ensure you are using this correctly, we take the unique values of each argument. Paramete...
Create VTK rectilinear grid directly from numpy arrays. Each array gives the uniques coordinates of the mesh along each axial direction. To help ensure you are using this correctly, we take the unique values of each argument. Parameters ---------- x : np.ndarray ...
Below is the the instruction that describes the task: ### Input: Create VTK rectilinear grid directly from numpy arrays. Each array gives the uniques coordinates of the mesh along each axial direction. To help ensure you are using this correctly, we take the unique values of each argument. ...
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any er...
Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Below is the the instruction that describes the task: ### Input: Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call wit...
def ctype_class(self): """Summary Returns: TYPE: Description """ def vec_factory(elemType): """Summary Args: elemType (TYPE): Description Returns: TYPE: Description """ class Vec(St...
Summary Returns: TYPE: Description
Below is the the instruction that describes the task: ### Input: Summary Returns: TYPE: Description ### Response: def ctype_class(self): """Summary Returns: TYPE: Description """ def vec_factory(elemType): """Summary Args: ...
def process_corpus(self): """Q.process_corpus() -- processes the queries defined by us, by tokenizing, stemming, and removing stop words. """ for doc in self.corpus_list: doc = wt(doc) sentence = [] for word in doc: if word not in self.stop_words and word not in self.punctuation: word = self....
Q.process_corpus() -- processes the queries defined by us, by tokenizing, stemming, and removing stop words.
Below is the the instruction that describes the task: ### Input: Q.process_corpus() -- processes the queries defined by us, by tokenizing, stemming, and removing stop words. ### Response: def process_corpus(self): """Q.process_corpus() -- processes the queries defined by us, by tokenizing, stemming, and re...
def getTopologyInfo(self, topologyName, cluster, role, environ): """ Returns the JSON representation of a topology by its name, cluster, environ, and an optional role parameter. Raises exception if no such topology is found. """ # Iterate over the values to filter the desired topology. for (...
Returns the JSON representation of a topology by its name, cluster, environ, and an optional role parameter. Raises exception if no such topology is found.
Below is the the instruction that describes the task: ### Input: Returns the JSON representation of a topology by its name, cluster, environ, and an optional role parameter. Raises exception if no such topology is found. ### Response: def getTopologyInfo(self, topologyName, cluster, role, environ): """...
def update_fixed(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo, lens_add_fixed=[], source_add_fixed=[], lens_light_add_fixed=[], ps_add_fixed=[], cosmo_add_fixed=[], lens_remove_fixed=[], source_remove_fixed=[], lens_light_remove_fixed=[], ps_remo...
adds the values of the keyword arguments that are stated in the _add_fixed to the existing fixed arguments. :param kwargs_lens: :param kwargs_source: :param kwargs_lens_light: :param kwargs_ps: :param kwargs_cosmo: :param lens_add_fixed: :param source_add_fixed: ...
Below is the the instruction that describes the task: ### Input: adds the values of the keyword arguments that are stated in the _add_fixed to the existing fixed arguments. :param kwargs_lens: :param kwargs_source: :param kwargs_lens_light: :param kwargs_ps: :param kwargs_co...
def Call(func_name, args=None, prefix=None): """A function call""" node = Node(syms.power, [func_name, ArgList(args)]) if prefix is not None: node.prefix = prefix return node
A function call
Below is the the instruction that describes the task: ### Input: A function call ### Response: def Call(func_name, args=None, prefix=None): """A function call""" node = Node(syms.power, [func_name, ArgList(args)]) if prefix is not None: node.prefix = prefix return node
def _set_peer(self, v, load=False): """ Setter method for peer, mapped from YANG variable /ntp/peer (list) If this variable is read-only (config: false) in the source YANG file, then _set_peer is considered as a private method. Backends looking to populate this variable should do so via calling ...
Setter method for peer, mapped from YANG variable /ntp/peer (list) If this variable is read-only (config: false) in the source YANG file, then _set_peer is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_peer() directly.
Below is the the instruction that describes the task: ### Input: Setter method for peer, mapped from YANG variable /ntp/peer (list) If this variable is read-only (config: false) in the source YANG file, then _set_peer is considered as a private method. Backends looking to populate this variable should ...
def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the REST interface ''' return query(key, value, service, profile)
Set a key/value pair in the REST interface
Below is the the instruction that describes the task: ### Input: Set a key/value pair in the REST interface ### Response: def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the REST interface ''' return query(key, value, service, profile)
def start(logger, full_id, fetch=True, env=None, volumes=None, cpus=None, memory=None, gpu_devices=None, offline=False): """ Starts the job with all logging of a job_id """ owner, name, id = unpack_full_job_id(full_id) if isinstance(sys.stdout, GeneralLogger): # we don't want to have stuff...
Starts the job with all logging of a job_id
Below is the the instruction that describes the task: ### Input: Starts the job with all logging of a job_id ### Response: def start(logger, full_id, fetch=True, env=None, volumes=None, cpus=None, memory=None, gpu_devices=None, offline=False): """ Starts the job with all logging of a job_id """ ow...
def unflatten(d, splitter='tuple', inverse=False): """Unflatten dict-like object. Parameters ---------- d: dict-like object The dict that will be unflattened. splitter: {'tuple', 'path', function} (default: 'tuple') The key splitting method. If a function is given, the function will...
Unflatten dict-like object. Parameters ---------- d: dict-like object The dict that will be unflattened. splitter: {'tuple', 'path', function} (default: 'tuple') The key splitting method. If a function is given, the function will be used to split. 'tuple': Use each eleme...
Below is the the instruction that describes the task: ### Input: Unflatten dict-like object. Parameters ---------- d: dict-like object The dict that will be unflattened. splitter: {'tuple', 'path', function} (default: 'tuple') The key splitting method. If a function is given, the fu...
def type_str(tp, assumed_globals=None, update_assumed_globals=None, implicit_globals=None, bound_Generic=None, bound_typevars=None): """Generates a nicely readable string representation of the given type. The returned representation is workable as a source code string and would reconstruct the g...
Generates a nicely readable string representation of the given type. The returned representation is workable as a source code string and would reconstruct the given type if handed to eval, provided that globals/locals are configured appropriately (e.g. assumes that various types from typing have been im...
Below is the the instruction that describes the task: ### Input: Generates a nicely readable string representation of the given type. The returned representation is workable as a source code string and would reconstruct the given type if handed to eval, provided that globals/locals are configured approp...
def bed_to_interval(orig_bed, bam_file): """Add header and format BED bait and target files for Picard if necessary. """ with open(orig_bed) as in_handle: line = in_handle.readline() if line.startswith("@"): yield orig_bed else: with pysam.Samfile(bam_file, "rb") as bam_handl...
Add header and format BED bait and target files for Picard if necessary.
Below is the the instruction that describes the task: ### Input: Add header and format BED bait and target files for Picard if necessary. ### Response: def bed_to_interval(orig_bed, bam_file): """Add header and format BED bait and target files for Picard if necessary. """ with open(orig_bed) as in_hand...
def edf_greenhall(alpha, d, m, N, overlapping=False, modified=False, verbose=False): """ returns Equivalent degrees of freedom Parameters ---------- alpha: int noise type, +2...-4 d: int 1 first-difference variance 2 Allan variance ...
returns Equivalent degrees of freedom Parameters ---------- alpha: int noise type, +2...-4 d: int 1 first-difference variance 2 Allan variance 3 Hadamard variance require alpha+2*d>1 m: int averaging...
Below is the the instruction that describes the task: ### Input: returns Equivalent degrees of freedom Parameters ---------- alpha: int noise type, +2...-4 d: int 1 first-difference variance 2 Allan variance 3 Hadamard variance...
def ndmeshgrid(*arrs): """Return a mesh grid for N dimensions. The input are N arrays, each of which contains the values along one axis of the coordinate system. The arrays do not have to have the same number of entries. The function returns arrays that can be fed into numpy functions so that they ...
Return a mesh grid for N dimensions. The input are N arrays, each of which contains the values along one axis of the coordinate system. The arrays do not have to have the same number of entries. The function returns arrays that can be fed into numpy functions so that they produce values for *all* point...
Below is the the instruction that describes the task: ### Input: Return a mesh grid for N dimensions. The input are N arrays, each of which contains the values along one axis of the coordinate system. The arrays do not have to have the same number of entries. The function returns arrays that can be fed...
def to_local_name(acs, attr): """ :param acs: List of AttributeConverter instances :param attr: an Attribute instance :return: The local attribute name """ for aconv in acs: lattr = aconv.from_format(attr) if lattr: return lattr return attr.friendly_name
:param acs: List of AttributeConverter instances :param attr: an Attribute instance :return: The local attribute name
Below is the the instruction that describes the task: ### Input: :param acs: List of AttributeConverter instances :param attr: an Attribute instance :return: The local attribute name ### Response: def to_local_name(acs, attr): """ :param acs: List of AttributeConverter instances :param attr: an...
def vswitch_query(self, vswitch_name): """Check the virtual switch status :param str vswitch_name: the name of the virtual switch :returns: Dictionary describing virtual switch info :rtype: dict """ action = "get virtual switch information" with zvmutils.log_and_...
Check the virtual switch status :param str vswitch_name: the name of the virtual switch :returns: Dictionary describing virtual switch info :rtype: dict
Below is the the instruction that describes the task: ### Input: Check the virtual switch status :param str vswitch_name: the name of the virtual switch :returns: Dictionary describing virtual switch info :rtype: dict ### Response: def vswitch_query(self, vswitch_name): """Check th...
def sync(self): """Retrieve zones from ElkM1""" self.elk.send(az_encode()) self.elk.send(zd_encode()) self.elk.send(zp_encode()) self.elk.send(zs_encode()) self.get_descriptions(TextDescriptions.ZONE.value)
Retrieve zones from ElkM1
Below is the the instruction that describes the task: ### Input: Retrieve zones from ElkM1 ### Response: def sync(self): """Retrieve zones from ElkM1""" self.elk.send(az_encode()) self.elk.send(zd_encode()) self.elk.send(zp_encode()) self.elk.send(zs_encode()) self.g...
def elem_wrap(self, tree, debug=False, root_id=None): """takes a DGParentedTree and puts a nucleus or satellite on top, depending on the nuclearity of the root element of the tree. """ if root_id is None: root_id = tree.root_id elem = self.elem_dict[root_id] ...
takes a DGParentedTree and puts a nucleus or satellite on top, depending on the nuclearity of the root element of the tree.
Below is the the instruction that describes the task: ### Input: takes a DGParentedTree and puts a nucleus or satellite on top, depending on the nuclearity of the root element of the tree. ### Response: def elem_wrap(self, tree, debug=False, root_id=None): """takes a DGParentedTree and puts a nucle...
def create_jail(name, arch, version="9.0-RELEASE"): ''' Creates a new poudriere jail if one does not exist *NOTE* creating a new jail will take some time the master is not hanging CLI Example: .. code-block:: bash salt '*' poudriere.create_jail 90amd64 amd64 ''' # Config file mus...
Creates a new poudriere jail if one does not exist *NOTE* creating a new jail will take some time the master is not hanging CLI Example: .. code-block:: bash salt '*' poudriere.create_jail 90amd64 amd64
Below is the the instruction that describes the task: ### Input: Creates a new poudriere jail if one does not exist *NOTE* creating a new jail will take some time the master is not hanging CLI Example: .. code-block:: bash salt '*' poudriere.create_jail 90amd64 amd64 ### Response: def creat...
def _split_what(what): """ Returns a tuple of `frozenset`s of classes and attributes. """ return ( frozenset(cls for cls in what if isclass(cls)), frozenset(cls for cls in what if isinstance(cls, Attribute)), )
Returns a tuple of `frozenset`s of classes and attributes.
Below is the the instruction that describes the task: ### Input: Returns a tuple of `frozenset`s of classes and attributes. ### Response: def _split_what(what): """ Returns a tuple of `frozenset`s of classes and attributes. """ return ( frozenset(cls for cls in what if isclass(cls)), ...
def patch_resource(self, session, json_data, api_type, obj_id): """ Replacement of resource values. :param session: SQLAlchemy session :param json_data: Request JSON Data :param api_type: Type of the resource :param obj_id: ID of the resource """ model = ...
Replacement of resource values. :param session: SQLAlchemy session :param json_data: Request JSON Data :param api_type: Type of the resource :param obj_id: ID of the resource
Below is the the instruction that describes the task: ### Input: Replacement of resource values. :param session: SQLAlchemy session :param json_data: Request JSON Data :param api_type: Type of the resource :param obj_id: ID of the resource ### Response: def patch_resource(self, ses...
def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default _default = _default or translation(DEFAULT_L...
Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object.
Below is the the instruction that describes the task: ### Input: Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. ### Response: def gettext(message): ...
def upload_pgp_keys(): """ upload and/or update the PGP keys for editors, import them into PGP""" get_vars() upload_target = '/tmp/pgp_pubkeys.tmp' with fab.settings(fab.hide('running')): fab.run('rm -rf %s' % upload_target) fab.run('mkdir %s' % upload_target) local_key_path = pa...
upload and/or update the PGP keys for editors, import them into PGP
Below is the the instruction that describes the task: ### Input: upload and/or update the PGP keys for editors, import them into PGP ### Response: def upload_pgp_keys(): """ upload and/or update the PGP keys for editors, import them into PGP""" get_vars() upload_target = '/tmp/pgp_pubkeys.tmp' with...
def top_corr(self, df): """Give aggregation counts and correlations""" tag_freq = df.sum() tag_freq.sort(ascending=False) corr = df.corr().fillna(1) corr_dict = corr.to_dict() for tag, count in tag_freq.iteritems(): print ' %s%s: %s%s%s (' % (color.Green, t...
Give aggregation counts and correlations
Below is the the instruction that describes the task: ### Input: Give aggregation counts and correlations ### Response: def top_corr(self, df): """Give aggregation counts and correlations""" tag_freq = df.sum() tag_freq.sort(ascending=False) corr = df.corr().fillna(1) corr_...
def CoarsePepper(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False, random_state=None): """ Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels. dtype support:: See ``imgaug.augmenters.arithmet...
Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels. dtype support:: See ``imgaug.augmenters.arithmetic.ReplaceElementwise``. Parameters ---------- p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional Pro...
Below is the the instruction that describes the task: ### Input: Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels. dtype support:: See ``imgaug.augmenters.arithmetic.ReplaceElementwise``. Parameters ---------- p : float or tuple of float or list of...
def cli(env): """List all active quotes on an account""" table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id' ]) table.align['Name'] = 'l' table.align['Package Name'] = 'r' table.align['Package Id'] = 'l' manager = ordering.Orderin...
List all active quotes on an account
Below is the the instruction that describes the task: ### Input: List all active quotes on an account ### Response: def cli(env): """List all active quotes on an account""" table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id' ]) table.alig...
def HasColumn(self, table_name, column_name): """Determines if a specific column exists. Args: table_name (str): name of the table. column_name (str): name of the column. Returns: bool: True if the column exists. Raises: IOError: if the database file is not opened. OSErr...
Determines if a specific column exists. Args: table_name (str): name of the table. column_name (str): name of the column. Returns: bool: True if the column exists. Raises: IOError: if the database file is not opened. OSError: if the database file is not opened.
Below is the the instruction that describes the task: ### Input: Determines if a specific column exists. Args: table_name (str): name of the table. column_name (str): name of the column. Returns: bool: True if the column exists. Raises: IOError: if the database file is not ope...
def _parse_sequence_tag(self): '''Parses the sequence and atomic mass.''' #main_tags = self._dom.getElementsByTagName("uniprot") #assert(len(main_tags) == 1) #entry_tags = main_tags[0].getElementsByTagName("entry") #assert(len(entry_tags) == 1) #entry_tags[0] ent...
Parses the sequence and atomic mass.
Below is the the instruction that describes the task: ### Input: Parses the sequence and atomic mass. ### Response: def _parse_sequence_tag(self): '''Parses the sequence and atomic mass.''' #main_tags = self._dom.getElementsByTagName("uniprot") #assert(len(main_tags) == 1) #entry_ta...
def gen_lines_from_textfiles( files: Iterable[TextIO]) -> Generator[str, None, None]: """ Generates lines from file-like objects. Args: files: iterable of :class:`TextIO` objects Yields: each line of all the files """ for file in files: for line in file: ...
Generates lines from file-like objects. Args: files: iterable of :class:`TextIO` objects Yields: each line of all the files
Below is the the instruction that describes the task: ### Input: Generates lines from file-like objects. Args: files: iterable of :class:`TextIO` objects Yields: each line of all the files ### Response: def gen_lines_from_textfiles( files: Iterable[TextIO]) -> Generator[str, None,...
def total_seconds(td): """For those with older versions of Python, a pure-Python implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`. Args: td (datetime.timedelta): The timedelta to convert to seconds. Returns: float: total number of seconds >>> td = timedelta(...
For those with older versions of Python, a pure-Python implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`. Args: td (datetime.timedelta): The timedelta to convert to seconds. Returns: float: total number of seconds >>> td = timedelta(days=4, seconds=33) >>> to...
Below is the the instruction that describes the task: ### Input: For those with older versions of Python, a pure-Python implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`. Args: td (datetime.timedelta): The timedelta to convert to seconds. Returns: float: total num...
def calc_log_size(request, calc_id): """ Get the current number of lines in the log """ try: response_data = logs.dbcmd('get_log_size', calc_id) except dbapi.NotFound: return HttpResponseNotFound() return HttpResponse(content=json.dumps(response_data), content_type=JSON)
Get the current number of lines in the log
Below is the the instruction that describes the task: ### Input: Get the current number of lines in the log ### Response: def calc_log_size(request, calc_id): """ Get the current number of lines in the log """ try: response_data = logs.dbcmd('get_log_size', calc_id) except dbapi.NotFoun...
def _handle_status(self, key, value): """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. """ if key in ( "USERID_HINT", "NEED_PASSPHRASE", "BAD_PASSPHRASE", ...
Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown.
Below is the the instruction that describes the task: ### Input: Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. ### Response: def _handle_status(self, key, value): """Parse a status code from the attached GnuPG process....
def poll_parser(poll): """ Parses a poll object """ if __is_deleted(poll): return deleted_parser(poll) if poll['type'] not in poll_types: raise Exception('Not a poll type') return Poll( poll['id'], poll['by'], __check_key('kids', poll), # poll and pollopt...
Parses a poll object
Below is the the instruction that describes the task: ### Input: Parses a poll object ### Response: def poll_parser(poll): """ Parses a poll object """ if __is_deleted(poll): return deleted_parser(poll) if poll['type'] not in poll_types: raise Exception('Not a poll type') re...
def get_items_of_credit_note_per_page(self, credit_note_id, per_page=1000, page=1): """ Get items of credit note per page :param credit_note_id: the credit note id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list...
Get items of credit note per page :param credit_note_id: the credit note id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
Below is the the instruction that describes the task: ### Input: Get items of credit note per page :param credit_note_id: the credit note id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list ### Response: def get_items_of_cr...
def get_input_files(dirname, *ext): """Returns files in passed directory, filtered by extension. - dirname - path to input directory - *ext - list of arguments describing permitted file extensions """ filelist = [f for f in os.listdir(dirname) if os.path.splitext(f)[-1] in ext] ...
Returns files in passed directory, filtered by extension. - dirname - path to input directory - *ext - list of arguments describing permitted file extensions
Below is the the instruction that describes the task: ### Input: Returns files in passed directory, filtered by extension. - dirname - path to input directory - *ext - list of arguments describing permitted file extensions ### Response: def get_input_files(dirname, *ext): """Returns files in passed di...
def _init_datastore_v3_stub(self, **stub_kwargs): """Initializes the datastore stub using nosegae config magic""" task_args = dict(datastore_file=self._data_path) task_args.update(stub_kwargs) self.testbed.init_datastore_v3_stub(**task_args)
Initializes the datastore stub using nosegae config magic
Below is the the instruction that describes the task: ### Input: Initializes the datastore stub using nosegae config magic ### Response: def _init_datastore_v3_stub(self, **stub_kwargs): """Initializes the datastore stub using nosegae config magic""" task_args = dict(datastore_file=self._data_path)...
def get_pretty_format(self, include_id=True, max_name_length=0, abbreviate=True): """Returns a nicely formatted string with the GO term information. Parameters ---------- include_id: bool, optional Include the GO term ID. max_name_length: in...
Returns a nicely formatted string with the GO term information. Parameters ---------- include_id: bool, optional Include the GO term ID. max_name_length: int, optional Truncate the formatted string so that its total length does not exceed this value. ...
Below is the the instruction that describes the task: ### Input: Returns a nicely formatted string with the GO term information. Parameters ---------- include_id: bool, optional Include the GO term ID. max_name_length: int, optional Truncate the formatted str...
def UpdateInfo(self): '''Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If you are concerned about performance, ...
Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If you are concerned about performance, minimize the number of...
Below is the the instruction that describes the task: ### Input: Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If y...
def get_padding_lengths(self) -> Dict[str, Dict[str, int]]: """ Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a mapping from padding keys to actual lengths, and we just key that dictionary by field name. """ lengths = {} for field_n...
Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a mapping from padding keys to actual lengths, and we just key that dictionary by field name.
Below is the the instruction that describes the task: ### Input: Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a mapping from padding keys to actual lengths, and we just key that dictionary by field name. ### Response: def get_padding_lengths(self) -> Dict[str, Dict[...
def _apply_changes(self): """Serialize our changes back to the PDF in memory Depending how we are initialized, leave our metadata mark and producer. """ if self.mark: self[QName(XMP_NS_XMP, 'MetadataDate')] = datetime.now().isoformat() self[QName(XMP_NS_PDF, 'Pro...
Serialize our changes back to the PDF in memory Depending how we are initialized, leave our metadata mark and producer.
Below is the the instruction that describes the task: ### Input: Serialize our changes back to the PDF in memory Depending how we are initialized, leave our metadata mark and producer. ### Response: def _apply_changes(self): """Serialize our changes back to the PDF in memory Depending how...
def DNN(input_shape, dense_layers, output_layer=[1, 'sigmoid'], optimizer='adam', loss='binary_crossentropy'): """Summary Args: input_shape (list): The shape of the input layer targets (int): Number of targets dense_layers (list): Dense la...
Summary Args: input_shape (list): The shape of the input layer targets (int): Number of targets dense_layers (list): Dense layer descriptor [fully_connected] optimizer (str or object optional): Keras optimizer as string or keras optimizer Returns: TYPE: model, b...
Below is the the instruction that describes the task: ### Input: Summary Args: input_shape (list): The shape of the input layer targets (int): Number of targets dense_layers (list): Dense layer descriptor [fully_connected] optimizer (str or object optional): Keras optimizer ...
def __add_min_max_value( parser, basename, default_min, default_max, initial, help_template): """ Generates parser entries for options with a min, max, and default value. Args: parser: the parser to use. basename: the base option name. Gen...
Generates parser entries for options with a min, max, and default value. Args: parser: the parser to use. basename: the base option name. Generated options will have flags --basename-min, --basename-max, and --basename. default_min: the default min value default_max:...
Below is the the instruction that describes the task: ### Input: Generates parser entries for options with a min, max, and default value. Args: parser: the parser to use. basename: the base option name. Generated options will have flags --basename-min, --basename-max, and --base...
def validate_uuid(value): """ UUID 128-bit validator """ if value and not isinstance(value, UUID): try: return UUID(str(value), version=4) except (AttributeError, ValueError): raise ValidationError('not a valid UUID') return value
UUID 128-bit validator
Below is the the instruction that describes the task: ### Input: UUID 128-bit validator ### Response: def validate_uuid(value): """ UUID 128-bit validator """ if value and not isinstance(value, UUID): try: return UUID(str(value), version=4) except (AttributeError, ValueError): ...
def update_shot_browser(self, project, releasetype): """Update the shot browser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.mode...
Update the shot browser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: None :rtype: None ...
Below is the the instruction that describes the task: ### Input: Update the shot browser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter...
def get_all(self): """Returns all the timings, sorted in decreasing order. Each value is a dict: { path: <path>, timing: <timing in seconds> } """ return [{'label': x[0], 'timing': x[1], 'is_tool': x[0] in self._tool_labels} for x in sorted(self._timings_by_path.items(), key=lambda x: x[1],...
Returns all the timings, sorted in decreasing order. Each value is a dict: { path: <path>, timing: <timing in seconds> }
Below is the the instruction that describes the task: ### Input: Returns all the timings, sorted in decreasing order. Each value is a dict: { path: <path>, timing: <timing in seconds> } ### Response: def get_all(self): """Returns all the timings, sorted in decreasing order. Each value is a dict: { pa...
def _mark_image_file_deleted(cls, mapper, connection, target): """When the session flushes, marks images as deleted. The files of this marked images will be actually deleted in the image storage when the ongoing transaction succeeds. If it fails the :attr:`_deleted_images` queue will be ...
When the session flushes, marks images as deleted. The files of this marked images will be actually deleted in the image storage when the ongoing transaction succeeds. If it fails the :attr:`_deleted_images` queue will be just empty.
Below is the the instruction that describes the task: ### Input: When the session flushes, marks images as deleted. The files of this marked images will be actually deleted in the image storage when the ongoing transaction succeeds. If it fails the :attr:`_deleted_images` queue will be just ...
def get_result_as_array(self): """ Returns the float values converted into strings using the parameters given at initialisation, as a numpy array """ if self.formatter is not None: return np.array([self.formatter(x) for x in self.values]) if self.fixed_width...
Returns the float values converted into strings using the parameters given at initialisation, as a numpy array
Below is the the instruction that describes the task: ### Input: Returns the float values converted into strings using the parameters given at initialisation, as a numpy array ### Response: def get_result_as_array(self): """ Returns the float values converted into strings using the ...
def read_prov(self, document_id=None): """ Load the provenance of this document .. note:: This method is called automatically if needed when the :py:meth:`prov` property is accessed. Manual use of this method is unusual. :param document_id: (optional) set the docu...
Load the provenance of this document .. note:: This method is called automatically if needed when the :py:meth:`prov` property is accessed. Manual use of this method is unusual. :param document_id: (optional) set the document id if this is an :py:meth:`abstract` document ...
Below is the the instruction that describes the task: ### Input: Load the provenance of this document .. note:: This method is called automatically if needed when the :py:meth:`prov` property is accessed. Manual use of this method is unusual. :param document_id: (optional) se...
def earwax(self): '''Makes audio easier to listen to on headphones. Adds ‘cues’ to 44.1kHz stereo audio so that when listened to on headphones the stereo image is moved from inside your head (standard for headphones) to outside and in front of the listener (standard for speakers). ...
Makes audio easier to listen to on headphones. Adds ‘cues’ to 44.1kHz stereo audio so that when listened to on headphones the stereo image is moved from inside your head (standard for headphones) to outside and in front of the listener (standard for speakers). Warning: Will only work pr...
Below is the the instruction that describes the task: ### Input: Makes audio easier to listen to on headphones. Adds ‘cues’ to 44.1kHz stereo audio so that when listened to on headphones the stereo image is moved from inside your head (standard for headphones) to outside and in front of the ...
def binned_entropy(x, max_bins): """ First bins the values of x into max_bins equidistant bins. Then calculates the value of .. math:: - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)} where :math:`p_k` is the percentage of samples in bin :math:`k`. ...
First bins the values of x into max_bins equidistant bins. Then calculates the value of .. math:: - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)} where :math:`p_k` is the percentage of samples in bin :math:`k`. :param x: the time series to calculate the fe...
Below is the the instruction that describes the task: ### Input: First bins the values of x into max_bins equidistant bins. Then calculates the value of .. math:: - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)} where :math:`p_k` is the percentage of samples...
def delete_device_subscriptions(self, device_id): """Removes a device's subscriptions :param device_id: ID of the device (Required) :returns: None """ api = self._get_api(mds.SubscriptionsApi) return api.delete_endpoint_subscriptions(device_id)
Removes a device's subscriptions :param device_id: ID of the device (Required) :returns: None
Below is the the instruction that describes the task: ### Input: Removes a device's subscriptions :param device_id: ID of the device (Required) :returns: None ### Response: def delete_device_subscriptions(self, device_id): """Removes a device's subscriptions :param device_id: ID o...
def status(self): """ Poll YubiKey for status. """ data = self._read() self._status = YubiKeyUSBHIDStatus(data) return self._status
Poll YubiKey for status.
Below is the the instruction that describes the task: ### Input: Poll YubiKey for status. ### Response: def status(self): """ Poll YubiKey for status. """ data = self._read() self._status = YubiKeyUSBHIDStatus(data) return self._status
def segment_radial_dist(seg, pos): '''Return the radial distance of a tree segment to a given point The radial distance is the euclidian distance between the mid-point of the segment and the point in question. Parameters: seg: tree segment pos: origin to which distances are measured. ...
Return the radial distance of a tree segment to a given point The radial distance is the euclidian distance between the mid-point of the segment and the point in question. Parameters: seg: tree segment pos: origin to which distances are measured. It must have at lease 3 components...
Below is the the instruction that describes the task: ### Input: Return the radial distance of a tree segment to a given point The radial distance is the euclidian distance between the mid-point of the segment and the point in question. Parameters: seg: tree segment pos: origin to whi...
def get_calling_namespaces(): """Return the locals and globals for the function that called into this module in the current call stack.""" try: 1//0 except ZeroDivisionError: # Don't start iterating with the current stack-frame to # prevent creating reference cycles (f_back is safe). ...
Return the locals and globals for the function that called into this module in the current call stack.
Below is the the instruction that describes the task: ### Input: Return the locals and globals for the function that called into this module in the current call stack. ### Response: def get_calling_namespaces(): """Return the locals and globals for the function that called into this module in the curre...
def list(gandi, domain, zone_id, output, format, limit): """List DNS zone records for a domain.""" options = { 'items_per_page': limit, } output_keys = ['name', 'type', 'value', 'ttl'] if not zone_id: result = gandi.domain.info(domain) zone_id = result['zone_id'] if not...
List DNS zone records for a domain.
Below is the the instruction that describes the task: ### Input: List DNS zone records for a domain. ### Response: def list(gandi, domain, zone_id, output, format, limit): """List DNS zone records for a domain.""" options = { 'items_per_page': limit, } output_keys = ['name', 'type', 'value'...