code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def f_df_nc(self,x): ''' Wrapper of the derivative of *f*: takes an input x with size of the not fixed dimensions expands it and evaluates the gradient of the entire function. ''' x = np.atleast_2d(x) xx = self.context_manager._expand_vector(x) f_nocontext_xx , df...
Wrapper of the derivative of *f*: takes an input x with size of the not fixed dimensions expands it and evaluates the gradient of the entire function.
Below is the the instruction that describes the task: ### Input: Wrapper of the derivative of *f*: takes an input x with size of the not fixed dimensions expands it and evaluates the gradient of the entire function. ### Response: def f_df_nc(self,x): ''' Wrapper of the derivative of *f*: ta...
def transmit(self, payload, **kwargs): """ Transmit content metadata items to the integrated channel. """ items_to_create, items_to_update, items_to_delete, transmission_map = self._partition_items(payload) self._prepare_items_for_delete(items_to_delete) prepared_items = ...
Transmit content metadata items to the integrated channel.
Below is the the instruction that describes the task: ### Input: Transmit content metadata items to the integrated channel. ### Response: def transmit(self, payload, **kwargs): """ Transmit content metadata items to the integrated channel. """ items_to_create, items_to_update, items...
def rebuild_auth(self, prepared_request, response): """ When being redirected we should always strip Authorization header, since nonce may not be reused as per OAuth spec. """ if "Authorization" in prepared_request.headers: # If we get redirected to a new host, we sho...
When being redirected we should always strip Authorization header, since nonce may not be reused as per OAuth spec.
Below is the the instruction that describes the task: ### Input: When being redirected we should always strip Authorization header, since nonce may not be reused as per OAuth spec. ### Response: def rebuild_auth(self, prepared_request, response): """ When being redirected we should always s...
def _delete_forever_values(self, forever_key): """ Delete all of the keys that have been stored forever. :type forever_key: str """ forever = self._store.connection().lrange(forever_key, 0, -1) if len(forever) > 0: self._store.connection().delete(*forever)
Delete all of the keys that have been stored forever. :type forever_key: str
Below is the the instruction that describes the task: ### Input: Delete all of the keys that have been stored forever. :type forever_key: str ### Response: def _delete_forever_values(self, forever_key): """ Delete all of the keys that have been stored forever. :type forever_key: s...
def calculate_average_diameter(self, **kwargs): """ Return the average diamension of a molecule. Returns ------- :class:`float` The average dimension of the molecule. """ self.average_diameter = find_average_diameter( self.elements, self....
Return the average diamension of a molecule. Returns ------- :class:`float` The average dimension of the molecule.
Below is the the instruction that describes the task: ### Input: Return the average diamension of a molecule. Returns ------- :class:`float` The average dimension of the molecule. ### Response: def calculate_average_diameter(self, **kwargs): """ Return the avera...
def create_message(payload, key=None): """ Construct a :class:`Message` :param payload: The payload to send to Kafka. :type payload: :class:`bytes` or ``None`` :param key: A key used to route the message when partitioning and to determine message identity on a compacted topic. :type key...
Construct a :class:`Message` :param payload: The payload to send to Kafka. :type payload: :class:`bytes` or ``None`` :param key: A key used to route the message when partitioning and to determine message identity on a compacted topic. :type key: :class:`bytes` or ``None``
Below is the the instruction that describes the task: ### Input: Construct a :class:`Message` :param payload: The payload to send to Kafka. :type payload: :class:`bytes` or ``None`` :param key: A key used to route the message when partitioning and to determine message identity on a compacted to...
def filter_ribo_counts(counts, orf_start=None, orf_stop=None): """Filter read counts and return only upstream of orf_start or downstream of orf_stop. Keyword arguments: counts -- Ribo-Seq read counts obtained from get_ribo_counts. orf_start -- Start position of the longest ORF. orf_stop -- Sto...
Filter read counts and return only upstream of orf_start or downstream of orf_stop. Keyword arguments: counts -- Ribo-Seq read counts obtained from get_ribo_counts. orf_start -- Start position of the longest ORF. orf_stop -- Stop position of the longest ORF.
Below is the the instruction that describes the task: ### Input: Filter read counts and return only upstream of orf_start or downstream of orf_stop. Keyword arguments: counts -- Ribo-Seq read counts obtained from get_ribo_counts. orf_start -- Start position of the longest ORF. orf_stop -- Stop...
def func_args(func)->bool: "Return the arguments of `func`." code = func.__code__ return code.co_varnames[:code.co_argcount]
Return the arguments of `func`.
Below is the the instruction that describes the task: ### Input: Return the arguments of `func`. ### Response: def func_args(func)->bool: "Return the arguments of `func`." code = func.__code__ return code.co_varnames[:code.co_argcount]
async def _load_tuple(self, reader, elem_type, params=None, elem=None): """ Loads tuple of elements from the reader. Supports the tuple ref. Returns loaded tuple. :param reader: :param elem_type: :param params: :param container: :return: """ ...
Loads tuple of elements from the reader. Supports the tuple ref. Returns loaded tuple. :param reader: :param elem_type: :param params: :param container: :return:
Below is the the instruction that describes the task: ### Input: Loads tuple of elements from the reader. Supports the tuple ref. Returns loaded tuple. :param reader: :param elem_type: :param params: :param container: :return: ### Response: async def _load_tuple(sel...
def clean_tarinfo(cls, tar_info): """ Clean metadata from a TarInfo object to make it more reproducible. - Set uid & gid to 0 - Set uname and gname to "" - Normalise permissions to 644 or 755 - Set mtime if not None """ ti = copy(tar_info)...
Clean metadata from a TarInfo object to make it more reproducible. - Set uid & gid to 0 - Set uname and gname to "" - Normalise permissions to 644 or 755 - Set mtime if not None
Below is the the instruction that describes the task: ### Input: Clean metadata from a TarInfo object to make it more reproducible. - Set uid & gid to 0 - Set uname and gname to "" - Normalise permissions to 644 or 755 - Set mtime if not None ### Response: def clean...
def sort_rows(self, rows, section): """Sort the rows, as appropriate for the section. :param rows: List of tuples (all same length, same values in each position) :param section: Name of section, should match const in Differ class :return: None; rows are sorted in-place """ ...
Sort the rows, as appropriate for the section. :param rows: List of tuples (all same length, same values in each position) :param section: Name of section, should match const in Differ class :return: None; rows are sorted in-place
Below is the the instruction that describes the task: ### Input: Sort the rows, as appropriate for the section. :param rows: List of tuples (all same length, same values in each position) :param section: Name of section, should match const in Differ class :return: None; rows are sorted in-p...
def actually_possibly_award(self, **state): """ Does the actual work of possibly awarding a badge. """ user = state["user"] force_timestamp = state.pop("force_timestamp", None) awarded = self.award(**state) if awarded is None: return if awarded...
Does the actual work of possibly awarding a badge.
Below is the the instruction that describes the task: ### Input: Does the actual work of possibly awarding a badge. ### Response: def actually_possibly_award(self, **state): """ Does the actual work of possibly awarding a badge. """ user = state["user"] force_timestamp = sta...
def walk(self): """ Default file path retrieval function. sprinter() - Generates file path list using pool processing and Queues crawler() - Generates file path list using os.walk() in sequence """ if self.parallelize: self.filepaths = Sprinter(self.directory,...
Default file path retrieval function. sprinter() - Generates file path list using pool processing and Queues crawler() - Generates file path list using os.walk() in sequence
Below is the the instruction that describes the task: ### Input: Default file path retrieval function. sprinter() - Generates file path list using pool processing and Queues crawler() - Generates file path list using os.walk() in sequence ### Response: def walk(self): """ Default fi...
def CheckEmptyBlockBody(filename, clean_lines, linenum, error): """Look for empty loop/conditional body with only a single semicolon. 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 functio...
Look for empty loop/conditional body with only a single semicolon. 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: Look for empty loop/conditional body with only a single semicolon. 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 functio...
def add_swagger_api_route(app, target_route, swagger_json_route): """ mount a swagger statics page. app: the flask app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be. """ static_root = get_sw...
mount a swagger statics page. app: the flask app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be.
Below is the the instruction that describes the task: ### Input: mount a swagger statics page. app: the flask app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be. ### Response: def add_swagger_api_route(...
def log(self, message, level=logging.DEBUG): """ Logs the message in the root logger with the log level @param message: Message to be logged @type message: string @param level: Log level, defaul DEBUG @type level: integer @return: 1 on success and 0 on error ...
Logs the message in the root logger with the log level @param message: Message to be logged @type message: string @param level: Log level, defaul DEBUG @type level: integer @return: 1 on success and 0 on error @rtype: integer
Below is the the instruction that describes the task: ### Input: Logs the message in the root logger with the log level @param message: Message to be logged @type message: string @param level: Log level, defaul DEBUG @type level: integer @return: 1 on success and 0 on er...
def set_property_value(self, name, value, dry_run=False): """Set or remove property value. See DAVResource.set_property_value() """ raise DAVError( HTTP_FORBIDDEN, err_condition=PRECONDITION_CODE_ProtectedProperty )
Set or remove property value. See DAVResource.set_property_value()
Below is the the instruction that describes the task: ### Input: Set or remove property value. See DAVResource.set_property_value() ### Response: def set_property_value(self, name, value, dry_run=False): """Set or remove property value. See DAVResource.set_property_value() """ ...
def _get_connection(self): """ Returns our cached LDAPObject, which may or may not be bound. """ if self._connection is None: uri = self.settings.SERVER_URI if callable(uri): if func_supports_parameter(uri, "request"): uri = uri...
Returns our cached LDAPObject, which may or may not be bound.
Below is the the instruction that describes the task: ### Input: Returns our cached LDAPObject, which may or may not be bound. ### Response: def _get_connection(self): """ Returns our cached LDAPObject, which may or may not be bound. """ if self._connection is None: uri ...
def start_tunnel(self, local_port, remote_address, remote_port): """ Start ssh forward tunnel :type local_port: int :param local_port: local port binding for ssh tunnel :type remote_address: str :param remote_address: remote tunnel endpoint bind address :type rem...
Start ssh forward tunnel :type local_port: int :param local_port: local port binding for ssh tunnel :type remote_address: str :param remote_address: remote tunnel endpoint bind address :type remote_port: int :param remote_port: remote tunnel endpoint bind port
Below is the the instruction that describes the task: ### Input: Start ssh forward tunnel :type local_port: int :param local_port: local port binding for ssh tunnel :type remote_address: str :param remote_address: remote tunnel endpoint bind address :type remote_port: int ...
def reset(self): """Expand to the full scale""" import ephem, MOPcoord sun=ephem.Sun() sun.compute(self.date.get()) self.sun=MOPcoord.coord((sun.ra,sun.dec)) doplot(kbos) self.plot_pointings()
Expand to the full scale
Below is the the instruction that describes the task: ### Input: Expand to the full scale ### Response: def reset(self): """Expand to the full scale""" import ephem, MOPcoord sun=ephem.Sun() sun.compute(self.date.get()) self.sun=MOPcoord.coord((sun.ra,sun.dec)) doplot(kbos) ...
def get_schedules(profile='pagerduty', subdomain=None, api_key=None): ''' List schedules belonging to this account CLI Example: salt myminion pagerduty.get_schedules ''' return _list_items( 'schedules', 'id', profile=profile, subdomain=subdomain, ap...
List schedules belonging to this account CLI Example: salt myminion pagerduty.get_schedules
Below is the the instruction that describes the task: ### Input: List schedules belonging to this account CLI Example: salt myminion pagerduty.get_schedules ### Response: def get_schedules(profile='pagerduty', subdomain=None, api_key=None): ''' List schedules belonging to this account CL...
def get_shape(self, ds_id, ds_info): """Return data array shape for item specified. """ var_path = ds_info.get('file_key', '{}'.format(ds_id.name)) if var_path + '/shape' not in self: # loading a scalar value shape = 1 else: shape = self[var_pa...
Return data array shape for item specified.
Below is the the instruction that describes the task: ### Input: Return data array shape for item specified. ### Response: def get_shape(self, ds_id, ds_info): """Return data array shape for item specified. """ var_path = ds_info.get('file_key', '{}'.format(ds_id.name)) if var_path ...
def autoconvert(s): """Convert input to a numerical type if possible. 1. A non-string object is returned as it is 2. Try conversion to int, float, str. """ if type(s) is not str: return s for converter in int, float, str: # try them in increasing order of lenience try: ...
Convert input to a numerical type if possible. 1. A non-string object is returned as it is 2. Try conversion to int, float, str.
Below is the the instruction that describes the task: ### Input: Convert input to a numerical type if possible. 1. A non-string object is returned as it is 2. Try conversion to int, float, str. ### Response: def autoconvert(s): """Convert input to a numerical type if possible. 1. A non-string obj...
def delta(self): """ Returns a delta based on this widget's information. :return <datetime.timedelta> """ number = self._numberSpinner.value() unit = self._unitCombo.currentText() direction = self._directionCombo.currentText() ...
Returns a delta based on this widget's information. :return <datetime.timedelta>
Below is the the instruction that describes the task: ### Input: Returns a delta based on this widget's information. :return <datetime.timedelta> ### Response: def delta(self): """ Returns a delta based on this widget's information. :return <datetime....
def t_text(self, t): r':\s*<text>' t.lexer.text_start = t.lexer.lexpos - len('<text>') t.lexer.begin('text')
r':\s*<text>
Below is the the instruction that describes the task: ### Input: r':\s*<text> ### Response: def t_text(self, t): r':\s*<text>' t.lexer.text_start = t.lexer.lexpos - len('<text>') t.lexer.begin('text')
def create_incidence_matrix(self, weights=None, fmt='coo', drop_zeros=False): r""" Creates a weighted incidence matrix in the desired sparse format Parameters ---------- weights : array_like, optional An array containing the throat val...
r""" Creates a weighted incidence matrix in the desired sparse format Parameters ---------- weights : array_like, optional An array containing the throat values to enter into the matrix (In graph theory these are known as the 'weights'). If omitted, ones ...
Below is the the instruction that describes the task: ### Input: r""" Creates a weighted incidence matrix in the desired sparse format Parameters ---------- weights : array_like, optional An array containing the throat values to enter into the matrix (In grap...
def paintEvent(self, event): """ Overloads the paint event to paint additional \ hint information if no text is set on the \ editor. :param event | <QPaintEvent> """ super(XLineEdit, self).paintEvent(event) # paint the hint text...
Overloads the paint event to paint additional \ hint information if no text is set on the \ editor. :param event | <QPaintEvent>
Below is the the instruction that describes the task: ### Input: Overloads the paint event to paint additional \ hint information if no text is set on the \ editor. :param event | <QPaintEvent> ### Response: def paintEvent(self, event): """ Overloads the p...
def to_dictionary( self, key_selector=None, value_selector=None): """Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item or None. If None, the default key selector produces a si...
Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item or None. If None, the default key selector produces a single dictionary key, which if the key of this Grouping. value_selector: A unary call...
Below is the the instruction that describes the task: ### Input: Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item or None. If None, the default key selector produces a single dictionary key, which i...
def _get_full_block(grouped_dicoms): """ Generate a full datablock containing all timepoints """ # For each slice / mosaic create a data volume block data_blocks = [] for index in range(0, len(grouped_dicoms)): logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms))) ...
Generate a full datablock containing all timepoints
Below is the the instruction that describes the task: ### Input: Generate a full datablock containing all timepoints ### Response: def _get_full_block(grouped_dicoms): """ Generate a full datablock containing all timepoints """ # For each slice / mosaic create a data volume block data_blocks = ...
def reset_secret(self): """ Resets the client secret for this client. """ result = self._client.post("{}/reset_secret".format(OAuthClient.api_endpoint), model=self) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when resetting secret!', jso...
Resets the client secret for this client.
Below is the the instruction that describes the task: ### Input: Resets the client secret for this client. ### Response: def reset_secret(self): """ Resets the client secret for this client. """ result = self._client.post("{}/reset_secret".format(OAuthClient.api_endpoint), model=sel...
def _assert_validators(self, validators): """Asserts if all validators in the list are satisfied. It asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified. Raises: AttributeError: Raised if validators work w...
Asserts if all validators in the list are satisfied. It asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified. Raises: AttributeError: Raised if validators work with a non-existing flag. IllegalFlagValueEr...
Below is the the instruction that describes the task: ### Input: Asserts if all validators in the list are satisfied. It asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified. Raises: AttributeError: Raised ...
def _validate_args(env, args): """Raises an ArgumentError if the given arguments are not valid.""" if all([args['cpu'], args['flavor']]): raise exceptions.ArgumentError( '[-c | --cpu] not allowed with [-f | --flavor]') if all([args['memory'], args['flavor']]): raise exceptions....
Raises an ArgumentError if the given arguments are not valid.
Below is the the instruction that describes the task: ### Input: Raises an ArgumentError if the given arguments are not valid. ### Response: def _validate_args(env, args): """Raises an ArgumentError if the given arguments are not valid.""" if all([args['cpu'], args['flavor']]): raise exceptions.Ar...
def smembers(self, key, *, encoding=_NOTSET): """Get all the members in a set.""" return self.execute(b'SMEMBERS', key, encoding=encoding)
Get all the members in a set.
Below is the the instruction that describes the task: ### Input: Get all the members in a set. ### Response: def smembers(self, key, *, encoding=_NOTSET): """Get all the members in a set.""" return self.execute(b'SMEMBERS', key, encoding=encoding)
def saveToFile(self,imageObjectList): """ Saves the static mask to a file it uses the signatures associated with each mask to contruct the filename for the output mask image. """ virtual = imageObjectList[0].inmemory for key in self.masklist.keys(): #...
Saves the static mask to a file it uses the signatures associated with each mask to contruct the filename for the output mask image.
Below is the the instruction that describes the task: ### Input: Saves the static mask to a file it uses the signatures associated with each mask to contruct the filename for the output mask image. ### Response: def saveToFile(self,imageObjectList): """ Saves the static mask to a fi...
def add_model(self, model): """ Adds a PyFlux model to the aggregating algorithm Parameters ---------- model : pf.[MODEL] A PyFlux univariate model Returns ---------- - Void (changes self.model_list) """ if model.model_type n...
Adds a PyFlux model to the aggregating algorithm Parameters ---------- model : pf.[MODEL] A PyFlux univariate model Returns ---------- - Void (changes self.model_list)
Below is the the instruction that describes the task: ### Input: Adds a PyFlux model to the aggregating algorithm Parameters ---------- model : pf.[MODEL] A PyFlux univariate model Returns ---------- - Void (changes self.model_list) ### Response:...
def shuffle(self, *args): """Shuffles all arguments and returns them. ARG_1,...,ARG_N %{SHUFFLE:A, B ,...,F} -> 'CDA B FE' """ call_args = list(args) self.random.shuffle(call_args) return ''.join(call_args)
Shuffles all arguments and returns them. ARG_1,...,ARG_N %{SHUFFLE:A, B ,...,F} -> 'CDA B FE'
Below is the the instruction that describes the task: ### Input: Shuffles all arguments and returns them. ARG_1,...,ARG_N %{SHUFFLE:A, B ,...,F} -> 'CDA B FE' ### Response: def shuffle(self, *args): """Shuffles all arguments and returns them. ARG_1,...,ARG_N %{SHUF...
def move_to_result(self, lst_idx): """Moves element from lst available at lst_idx.""" self.in_result_idx.add(lst_idx) if lst_idx in self.not_in_result_root_match_idx: self.not_in_result_root_match_idx.remove(lst_idx)
Moves element from lst available at lst_idx.
Below is the the instruction that describes the task: ### Input: Moves element from lst available at lst_idx. ### Response: def move_to_result(self, lst_idx): """Moves element from lst available at lst_idx.""" self.in_result_idx.add(lst_idx) if lst_idx in self.not_in_result_root_match_idx:...
def pretty_print(self, decimal_digits=2): """ Returns a string repr of the wavefunction, ignoring all outcomes with approximately zero amplitude (up to a certain number of decimal digits) and rounding the amplitudes to decimal_digits. :param int decimal_digits: The number of dig...
Returns a string repr of the wavefunction, ignoring all outcomes with approximately zero amplitude (up to a certain number of decimal digits) and rounding the amplitudes to decimal_digits. :param int decimal_digits: The number of digits to truncate to. :return: A dict with outcomes as k...
Below is the the instruction that describes the task: ### Input: Returns a string repr of the wavefunction, ignoring all outcomes with approximately zero amplitude (up to a certain number of decimal digits) and rounding the amplitudes to decimal_digits. :param int decimal_digits: The number...
def save_json(obj, filename, **kwargs): """ Save an object as a JSON file. Args: obj: The object to save. Must be JSON-serializable. filename: Path to the output file. **kwargs: Additional arguments to `json.dump`. """ with open(filename, 'w', encoding='utf-8') as f: ...
Save an object as a JSON file. Args: obj: The object to save. Must be JSON-serializable. filename: Path to the output file. **kwargs: Additional arguments to `json.dump`.
Below is the the instruction that describes the task: ### Input: Save an object as a JSON file. Args: obj: The object to save. Must be JSON-serializable. filename: Path to the output file. **kwargs: Additional arguments to `json.dump`. ### Response: def save_json(obj, filename, **kwarg...
def transform_sparql_construct(rdf, construct_query): """Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph.""" logging.debug("performing SPARQL CONSTRUCT transformation") if construct_query[0] == '@': # actual query should be read from file construct_query = file(construct_q...
Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph.
Below is the the instruction that describes the task: ### Input: Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph. ### Response: def transform_sparql_construct(rdf, construct_query): """Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph.""" logging.debug("perfor...
def _raw_write(self): """ Takes ciphertext from the memory bio and writes it to the socket. :return: A byte string of ciphertext going to the socket. Used for debugging the handshake only. """ data_available = libssl.BIO_ctrl_pending(self._wbio) ...
Takes ciphertext from the memory bio and writes it to the socket. :return: A byte string of ciphertext going to the socket. Used for debugging the handshake only.
Below is the the instruction that describes the task: ### Input: Takes ciphertext from the memory bio and writes it to the socket. :return: A byte string of ciphertext going to the socket. Used for debugging the handshake only. ### Response: def _raw_write(self): ""...
def p_expression_lessthan(self, p): 'expression : expression LT expression' p[0] = LessThan(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
expression : expression LT expression
Below is the the instruction that describes the task: ### Input: expression : expression LT expression ### Response: def p_expression_lessthan(self, p): 'expression : expression LT expression' p[0] = LessThan(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
def data(self, data: numpy.ndarray) -> None: """Set the data. :param data: A numpy ndarray. .. versionadded:: 1.0 Scriptable: Yes """ self.__data_item.set_data(numpy.copy(data))
Set the data. :param data: A numpy ndarray. .. versionadded:: 1.0 Scriptable: Yes
Below is the the instruction that describes the task: ### Input: Set the data. :param data: A numpy ndarray. .. versionadded:: 1.0 Scriptable: Yes ### Response: def data(self, data: numpy.ndarray) -> None: """Set the data. :param data: A numpy ndarray. .. versio...
def validate_response(expected_responses): """ Decorator to validate responses from QTM """ def internal_decorator(function): @wraps(function) async def wrapper(*args, **kwargs): response = await function(*args, **kwargs) for expected_response in expected_responses: ...
Decorator to validate responses from QTM
Below is the the instruction that describes the task: ### Input: Decorator to validate responses from QTM ### Response: def validate_response(expected_responses): """ Decorator to validate responses from QTM """ def internal_decorator(function): @wraps(function) async def wrapper(*args, **...
def get_host_power_status(self): """Request the power state of the server. :returns: Power State of the server, 'ON' or 'OFF' :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) return GET_POWER_STATE_MAP.get(sushy_syste...
Request the power state of the server. :returns: Power State of the server, 'ON' or 'OFF' :raises: IloError, on an error from iLO.
Below is the the instruction that describes the task: ### Input: Request the power state of the server. :returns: Power State of the server, 'ON' or 'OFF' :raises: IloError, on an error from iLO. ### Response: def get_host_power_status(self): """Request the power state of the server. ...
async def seek(self, pos, whence=sync_io.SEEK_SET): """Move to new file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current position, p...
Move to new file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current position, positive or negative), and SEEK_END or 2 (move relative ...
Below is the the instruction that describes the task: ### Input: Move to new file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current posit...
def update_team(self, team_data, project_id, team_id): """UpdateTeam. [Preview API] Update a team's name and/or description. :param :class:`<WebApiTeam> <azure.devops.v5_1.core.models.WebApiTeam>` team_data: :param str project_id: The name or ID (GUID) of the team project containing the ...
UpdateTeam. [Preview API] Update a team's name and/or description. :param :class:`<WebApiTeam> <azure.devops.v5_1.core.models.WebApiTeam>` team_data: :param str project_id: The name or ID (GUID) of the team project containing the team to update. :param str team_id: The name of ID of the ...
Below is the the instruction that describes the task: ### Input: UpdateTeam. [Preview API] Update a team's name and/or description. :param :class:`<WebApiTeam> <azure.devops.v5_1.core.models.WebApiTeam>` team_data: :param str project_id: The name or ID (GUID) of the team project containing t...
def gradient(self, image, label): """Calculates the gradient of the cross-entropy loss w.r.t. the image. The default implementation calls predictions_and_gradient. Subclasses can provide more efficient implementations that only calculate the gradient. Parameters -------...
Calculates the gradient of the cross-entropy loss w.r.t. the image. The default implementation calls predictions_and_gradient. Subclasses can provide more efficient implementations that only calculate the gradient. Parameters ---------- image : `numpy.ndarray` ...
Below is the the instruction that describes the task: ### Input: Calculates the gradient of the cross-entropy loss w.r.t. the image. The default implementation calls predictions_and_gradient. Subclasses can provide more efficient implementations that only calculate the gradient. Pa...
def get_frontend_data_dict_for_placeholders(placeholders, request, editable=False): """ Takes a list of placeholder instances and returns the data that is used by the frontend to render all contents. The returned dict is grouped by placeholder slots. """ data_dict = {} for placeholder in placeho...
Takes a list of placeholder instances and returns the data that is used by the frontend to render all contents. The returned dict is grouped by placeholder slots.
Below is the the instruction that describes the task: ### Input: Takes a list of placeholder instances and returns the data that is used by the frontend to render all contents. The returned dict is grouped by placeholder slots. ### Response: def get_frontend_data_dict_for_placeholders(placeholders, request, ed...
def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs): """Correct off-by-one error in GFDL instantaneous model data. Instantaneous data that is outputted by GFDL models is generally off by one timestep. For example, a netCDF file that is supposed to correspond to 6 hourly data...
Correct off-by-one error in GFDL instantaneous model data. Instantaneous data that is outputted by GFDL models is generally off by one timestep. For example, a netCDF file that is supposed to correspond to 6 hourly data for the month of January, will have its last time value be in Febr...
Below is the the instruction that describes the task: ### Input: Correct off-by-one error in GFDL instantaneous model data. Instantaneous data that is outputted by GFDL models is generally off by one timestep. For example, a netCDF file that is supposed to correspond to 6 hourly data for t...
def plot_histograms(ertobj, keys, **kwargs): """Generate histograms for one or more keys in the given container. Parameters ---------- ertobj : container instance or :class:`pandas.DataFrame` data object which contains the data. keys : str or list of strings which keys (column names...
Generate histograms for one or more keys in the given container. Parameters ---------- ertobj : container instance or :class:`pandas.DataFrame` data object which contains the data. keys : str or list of strings which keys (column names) to plot merge : bool, optional if True...
Below is the the instruction that describes the task: ### Input: Generate histograms for one or more keys in the given container. Parameters ---------- ertobj : container instance or :class:`pandas.DataFrame` data object which contains the data. keys : str or list of strings which k...
def _check(cls, name, val, can_be_zero=False, val_type=float): """Check init arguments. Args: name: name of the argument. For logging purpose. val: value. Value has to be non negative number. can_be_zero: whether value can be zero. val_type: Python type of the value. Returns: ...
Check init arguments. Args: name: name of the argument. For logging purpose. val: value. Value has to be non negative number. can_be_zero: whether value can be zero. val_type: Python type of the value. Returns: The value. Raises: ValueError: when invalid value is passe...
Below is the the instruction that describes the task: ### Input: Check init arguments. Args: name: name of the argument. For logging purpose. val: value. Value has to be non negative number. can_be_zero: whether value can be zero. val_type: Python type of the value. Returns: ...
def is_treshold_reached(self, scraped_request): """Check if similar requests to the given requests have already been crawled X times. Where X is the minimum treshold amount from the options. Args: scraped_request (:class:`nyawc.http.Request`): The request that possibly reached the ...
Check if similar requests to the given requests have already been crawled X times. Where X is the minimum treshold amount from the options. Args: scraped_request (:class:`nyawc.http.Request`): The request that possibly reached the minimum treshold. Returns: bool: True ...
Below is the the instruction that describes the task: ### Input: Check if similar requests to the given requests have already been crawled X times. Where X is the minimum treshold amount from the options. Args: scraped_request (:class:`nyawc.http.Request`): The request that possibly re...
def getMetadataId(self, metadata): """ Returns the id of a metadata """ return str(datamodel.VariantSetMetadataCompoundId( self.getCompoundId(), 'metadata:' + metadata.key))
Returns the id of a metadata
Below is the the instruction that describes the task: ### Input: Returns the id of a metadata ### Response: def getMetadataId(self, metadata): """ Returns the id of a metadata """ return str(datamodel.VariantSetMetadataCompoundId( self.getCompoundId(), 'metadata:' + meta...
def get_connection_id(self, conn_or_int_id): """Get the connection id. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connection or None if ...
Get the connection id. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connection or None if it cannot be found. Raises: ...
Below is the the instruction that describes the task: ### Input: Get the connection id. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connectio...
def cudnnSetFilter4dDescriptor(wDesc, dataType, format, k, c, h, w): """" Initialize a filter descriptor. This function initializes a previously created filter descriptor object into a 4D filter. Filters layout must be contiguous in memory. Parameters ---------- wDesc : cudnnFilterDescript...
Initialize a filter descriptor. This function initializes a previously created filter descriptor object into a 4D filter. Filters layout must be contiguous in memory. Parameters ---------- wDesc : cudnnFilterDescriptor Handle to a previously created filter descriptor. dataType : cudnnD...
Below is the the instruction that describes the task: ### Input: Initialize a filter descriptor. This function initializes a previously created filter descriptor object into a 4D filter. Filters layout must be contiguous in memory. Parameters ---------- wDesc : cudnnFilterDescriptor Ha...
def declare_internal(self, function): """Like declare(), but the registered function will also receive the current namespace as its first argument. Useful for functions that inspect the state of the compilation, like ``variable-exists()``. Probably not so useful for anything else. ...
Like declare(), but the registered function will also receive the current namespace as its first argument. Useful for functions that inspect the state of the compilation, like ``variable-exists()``. Probably not so useful for anything else.
Below is the the instruction that describes the task: ### Input: Like declare(), but the registered function will also receive the current namespace as its first argument. Useful for functions that inspect the state of the compilation, like ``variable-exists()``. Probably not so useful for ...
def _nanmedian(array, axis=None): """Bottleneck nanmedian function that handle tuple axis.""" if isinstance(axis, tuple): array = _move_tuple_axes_first(array, axis=axis) axis = 0 return bottleneck.nanmedian(array, axis=axis)
Bottleneck nanmedian function that handle tuple axis.
Below is the the instruction that describes the task: ### Input: Bottleneck nanmedian function that handle tuple axis. ### Response: def _nanmedian(array, axis=None): """Bottleneck nanmedian function that handle tuple axis.""" if isinstance(axis, tuple): array = _move_tuple_axes_first(array, axis=...
def input_identity(interface = TerminalInterface()): """Get the full name, email address and SMTP information from the user.""" while True: identity = interface.input_fields(""" In order to send your files via email, I need to get your name and email address you will be using to s...
Get the full name, email address and SMTP information from the user.
Below is the the instruction that describes the task: ### Input: Get the full name, email address and SMTP information from the user. ### Response: def input_identity(interface = TerminalInterface()): """Get the full name, email address and SMTP information from the user.""" while True: identity =...
def build_inside(input_method, input_args=None, substitutions=None): """ use requested input plugin to load configuration and then initiate build """ def process_keyvals(keyvals): """ ["key=val", "x=y"] -> {"key": "val", "x": "y"} """ keyvals = keyvals or [] processed_keyvals = {...
use requested input plugin to load configuration and then initiate build
Below is the the instruction that describes the task: ### Input: use requested input plugin to load configuration and then initiate build ### Response: def build_inside(input_method, input_args=None, substitutions=None): """ use requested input plugin to load configuration and then initiate build """ ...
def from_range(cls, range_list, register_flag=True): """ core class method to create visible objects from a range (nested list) """ s = dict_from_range(range_list) obj = cls.from_serializable(s, register_flag) return obj
core class method to create visible objects from a range (nested list)
Below is the the instruction that describes the task: ### Input: core class method to create visible objects from a range (nested list) ### Response: def from_range(cls, range_list, register_flag=True): """ core class method to create visible objects from a range (nested list) """ s = dict_from_ran...
def log_analyzer(path): """This procedure replaces every line which can't be parsed with special object MalformedLogEntry. """ with handle(MalformedLogEntryError, lambda (c): invoke_restart('use_value', MalformedLogEntry(c.text...
This procedure replaces every line which can't be parsed with special object MalformedLogEntry.
Below is the the instruction that describes the task: ### Input: This procedure replaces every line which can't be parsed with special object MalformedLogEntry. ### Response: def log_analyzer(path): """This procedure replaces every line which can't be parsed with special object MalformedLogEntry. "...
def _get_blockade_id_from_cwd(self, cwd=None): '''Generate a new blockade ID based on the CWD''' if not cwd: cwd = os.getcwd() # this follows a similar pattern as docker-compose uses parent_dir = os.path.abspath(cwd) basename = os.path.basename(parent_dir).lower() ...
Generate a new blockade ID based on the CWD
Below is the the instruction that describes the task: ### Input: Generate a new blockade ID based on the CWD ### Response: def _get_blockade_id_from_cwd(self, cwd=None): '''Generate a new blockade ID based on the CWD''' if not cwd: cwd = os.getcwd() # this follows a similar patt...
def feature_distribution(self, featureset_name, feature, mode='counts', **slice_kwargs): """ Calculates the distribution of a feature across slices of the corpus. Examples -------- .. code-block:: python >>> corpus.feature_distribution(fe...
Calculates the distribution of a feature across slices of the corpus. Examples -------- .. code-block:: python >>> corpus.feature_distribution(featureset_name='citations', \ ... feature='DOLE RJ 1965 CELL', \ ... ...
Below is the the instruction that describes the task: ### Input: Calculates the distribution of a feature across slices of the corpus. Examples -------- .. code-block:: python >>> corpus.feature_distribution(featureset_name='citations', \ ... ...
def _get_value_error_message_for_invalid_prarameter(self, parameter, value): """Returns the ValueError message for the given parameter. :param string parameter: Name of the parameter the message has to be created for. :param numeric value: Value outside the parameters interval. :...
Returns the ValueError message for the given parameter. :param string parameter: Name of the parameter the message has to be created for. :param numeric value: Value outside the parameters interval. :return: Returns a string containing hte message. :rtype: string
Below is the the instruction that describes the task: ### Input: Returns the ValueError message for the given parameter. :param string parameter: Name of the parameter the message has to be created for. :param numeric value: Value outside the parameters interval. :return: Returns ...
def load_hvjs(cls, logo=False, bokeh_logo=False, mpl_logo=False, plotly_logo=False, JS=True, message='HoloViewsJS successfully loaded.'): """ Displays javascript and CSS to initialize HoloViews widgets. """ import jinja2 # Evaluate load_notebook.html template wi...
Displays javascript and CSS to initialize HoloViews widgets.
Below is the the instruction that describes the task: ### Input: Displays javascript and CSS to initialize HoloViews widgets. ### Response: def load_hvjs(cls, logo=False, bokeh_logo=False, mpl_logo=False, plotly_logo=False, JS=True, message='HoloViewsJS successfully loaded.'): """ ...
def saveProfile(self, key, settings=None): """ Writes the view settings to the persistent store :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened. """ #logger.debug("Writing view settings f...
Writes the view settings to the persistent store :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened.
Below is the the instruction that describes the task: ### Input: Writes the view settings to the persistent store :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened. ### Response: def saveProfile(self, key, se...
def _loader(app, init_func, entry_points=None, modules=None): """Run generic loader. Used to load and initialize entry points and modules using an custom initialization function. .. versionadded: 1.0.0 """ if entry_points: for entry_point in entry_points: for ep in pkg_reso...
Run generic loader. Used to load and initialize entry points and modules using an custom initialization function. .. versionadded: 1.0.0
Below is the the instruction that describes the task: ### Input: Run generic loader. Used to load and initialize entry points and modules using an custom initialization function. .. versionadded: 1.0.0 ### Response: def _loader(app, init_func, entry_points=None, modules=None): """Run generic load...
def _build_table_options(self, row): """ Setup the mostly-non-schema table options, like caching settings """ return dict((o, row.get(o)) for o in self.recognized_table_options if o in row)
Setup the mostly-non-schema table options, like caching settings
Below is the the instruction that describes the task: ### Input: Setup the mostly-non-schema table options, like caching settings ### Response: def _build_table_options(self, row): """ Setup the mostly-non-schema table options, like caching settings """ return dict((o, row.get(o)) for o in self.rec...
def wt(u, v, dfs_data): """The wt_u[v] function used in the paper.""" # Determine the edge_id edge_id = dfs_data['graph'].get_first_edge_id_by_node_ids(u, v) # Pull the weight of that edge return dfs_data['edge_weights'][edge_id]
The wt_u[v] function used in the paper.
Below is the the instruction that describes the task: ### Input: The wt_u[v] function used in the paper. ### Response: def wt(u, v, dfs_data): """The wt_u[v] function used in the paper.""" # Determine the edge_id edge_id = dfs_data['graph'].get_first_edge_id_by_node_ids(u, v) # Pull the weight of t...
def run(self, repo: str, branch: str, task: Task, git_repo: Repo, repo_path: Path) -> Result: """ Gets or builds an image for the repo, gets or starts a container for the image and runs the script. :param repo: Repository URL :param branch: Branch ane :param task: :class:`Task` to run. ...
Gets or builds an image for the repo, gets or starts a container for the image and runs the script. :param repo: Repository URL :param branch: Branch ane :param task: :class:`Task` to run. :param git_repo: :class:`Repo <git.repo.base.Repo>` of the cloned repository. :param repo_...
Below is the the instruction that describes the task: ### Input: Gets or builds an image for the repo, gets or starts a container for the image and runs the script. :param repo: Repository URL :param branch: Branch ane :param task: :class:`Task` to run. :param git_repo: :class:`Repo...
def _get_fault_type_hanging_wall(self, rake): """ Return fault type (F) and hanging wall (HW) flags depending on rake angle. The method assumes 'reverse' (F = 1) if 45 <= rake <= 135, 'other' (F = 0) if otherwise. Hanging-wall flag is set to 1 if 'reverse', and 0 if 'oth...
Return fault type (F) and hanging wall (HW) flags depending on rake angle. The method assumes 'reverse' (F = 1) if 45 <= rake <= 135, 'other' (F = 0) if otherwise. Hanging-wall flag is set to 1 if 'reverse', and 0 if 'other'.
Below is the the instruction that describes the task: ### Input: Return fault type (F) and hanging wall (HW) flags depending on rake angle. The method assumes 'reverse' (F = 1) if 45 <= rake <= 135, 'other' (F = 0) if otherwise. Hanging-wall flag is set to 1 if 'reverse', and 0 if '...
def runInBackground(self, pollInterval=.1, encoding=False): ''' runInBackground - Create a background thread which will manage this process, automatically read from streams, and perform any cleanups The object returned is a "BackgroundTaskInfo" object, and represents the state of the process. It ...
runInBackground - Create a background thread which will manage this process, automatically read from streams, and perform any cleanups The object returned is a "BackgroundTaskInfo" object, and represents the state of the process. It is updated automatically as the program runs, and if stdout or s...
Below is the the instruction that describes the task: ### Input: runInBackground - Create a background thread which will manage this process, automatically read from streams, and perform any cleanups The object returned is a "BackgroundTaskInfo" object, and represents the state of the process. It is upda...
def uploadDeviceConfig(self): """Upload the device configuration of the fake device selected in the __init__ methodi to the google account.""" upload = googleplay_pb2.UploadDeviceConfigRequest() upload.deviceConfiguration.CopyFrom(self.deviceBuilder.getDeviceConfig()) headers = ...
Upload the device configuration of the fake device selected in the __init__ methodi to the google account.
Below is the the instruction that describes the task: ### Input: Upload the device configuration of the fake device selected in the __init__ methodi to the google account. ### Response: def uploadDeviceConfig(self): """Upload the device configuration of the fake device selected in the __ini...
def tryCommit(self, prepare: Prepare): """ Try to commit if the Prepare message is ready to be passed into the commit phase. """ rv, reason = self.canCommit(prepare) if rv: self.doCommit(prepare) else: self.logger.debug("{} cannot send COMM...
Try to commit if the Prepare message is ready to be passed into the commit phase.
Below is the the instruction that describes the task: ### Input: Try to commit if the Prepare message is ready to be passed into the commit phase. ### Response: def tryCommit(self, prepare: Prepare): """ Try to commit if the Prepare message is ready to be passed into the commit phas...
def random_rescale_to_mahalanobis(self, x): """change `x` like for injection, all on genotypic level""" x -= self.mean if any(x): x *= sum(self.randn(len(x))**2)**0.5 / self.mahalanobis_norm(x) x += self.mean return x
change `x` like for injection, all on genotypic level
Below is the the instruction that describes the task: ### Input: change `x` like for injection, all on genotypic level ### Response: def random_rescale_to_mahalanobis(self, x): """change `x` like for injection, all on genotypic level""" x -= self.mean if any(x): x *= sum(self.ra...
def distance(self, other): """ Distance between the center of this region and another. Parameters ---------- other : one region, or array-like Either another region, or the center of another region. """ from numpy.linalg import norm if isinsta...
Distance between the center of this region and another. Parameters ---------- other : one region, or array-like Either another region, or the center of another region.
Below is the the instruction that describes the task: ### Input: Distance between the center of this region and another. Parameters ---------- other : one region, or array-like Either another region, or the center of another region. ### Response: def distance(self, other): ...
def _url_to_prefix(node, id): '''_url_to_prefix Low-level api: Convert an identifier from `{namespace}tagname` notation to `prefix:tagname` notation by looking at nsmap of the node. If the identifier does not have a namespace, the identifier is simply returned without modificati...
_url_to_prefix Low-level api: Convert an identifier from `{namespace}tagname` notation to `prefix:tagname` notation by looking at nsmap of the node. If the identifier does not have a namespace, the identifier is simply returned without modification. Parameters ---------...
Below is the the instruction that describes the task: ### Input: _url_to_prefix Low-level api: Convert an identifier from `{namespace}tagname` notation to `prefix:tagname` notation by looking at nsmap of the node. If the identifier does not have a namespace, the identifier is simply returne...
def splitall(path): """Split a path into a list of directory names (and optionally a filename). Parameters ---------- path: str The path (absolute or relative). Returns ------- allparts: list[str] List of directory names (and optionally a filename) Example ------- ...
Split a path into a list of directory names (and optionally a filename). Parameters ---------- path: str The path (absolute or relative). Returns ------- allparts: list[str] List of directory names (and optionally a filename) Example ------- "foo/bar/baz.py" => ["f...
Below is the the instruction that describes the task: ### Input: Split a path into a list of directory names (and optionally a filename). Parameters ---------- path: str The path (absolute or relative). Returns ------- allparts: list[str] List of directory names (and option...
def _requeue_trial(self, trial): """Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress. """ self._scheduler_alg.on_trial_error(self, trial) self.trial_executor.set_status(trial, ...
Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress.
Below is the the instruction that describes the task: ### Input: Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress. ### Response: def _requeue_trial(self, trial): """Notification to TrialScheduler...
def _ss_matrices(self,beta): """ Creates the state space matrices required Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- T, Z, R, Q : np.array State space matrices use...
Creates the state space matrices required Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- T, Z, R, Q : np.array State space matrices used in KFS algorithm
Below is the the instruction that describes the task: ### Input: Creates the state space matrices required Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- T, Z, R, Q : np.array ...
def loop(self): """ Start all the added processes and multiplex their output onto the bound printer (which by default will print to STDOUT). If one process terminates, all the others will be terminated by Honcho, and :func:`~honcho.manager.Manager.loop` will return. Thi...
Start all the added processes and multiplex their output onto the bound printer (which by default will print to STDOUT). If one process terminates, all the others will be terminated by Honcho, and :func:`~honcho.manager.Manager.loop` will return. This method will block until all the pr...
Below is the the instruction that describes the task: ### Input: Start all the added processes and multiplex their output onto the bound printer (which by default will print to STDOUT). If one process terminates, all the others will be terminated by Honcho, and :func:`~honcho.manager.Manage...
def get_rate_limits(self): """ Returns a dict with the current rate limit information for domain and status requests. """ resp, body = self.method_get("/limits") rate_limits = body.get("limits", {}).get("rate") ret = [] for rate_limit in rate_limits: ...
Returns a dict with the current rate limit information for domain and status requests.
Below is the the instruction that describes the task: ### Input: Returns a dict with the current rate limit information for domain and status requests. ### Response: def get_rate_limits(self): """ Returns a dict with the current rate limit information for domain and status requests....
def render_latex_sub_super( name, subs=None, supers=None, translate_symbols=True, sep=','): r'''Assemble a string from the primary name and the given sub- and superscripts:: >>> render_latex_sub_super(name='alpha', subs=['mu', 'nu'], supers=[2]) '\\alpha_{\\mu,\\nu}^{2}' >>> re...
r'''Assemble a string from the primary name and the given sub- and superscripts:: >>> render_latex_sub_super(name='alpha', subs=['mu', 'nu'], supers=[2]) '\\alpha_{\\mu,\\nu}^{2}' >>> render_latex_sub_super( ... name='alpha', subs=['1', '2'], supers=['(1)'], sep='') '\\...
Below is the the instruction that describes the task: ### Input: r'''Assemble a string from the primary name and the given sub- and superscripts:: >>> render_latex_sub_super(name='alpha', subs=['mu', 'nu'], supers=[2]) '\\alpha_{\\mu,\\nu}^{2}' >>> render_latex_sub_super( ... ...
def healpix_plot(self, healpix_expression="source_id/34359738368", healpix_max_level=12, healpix_level=8, what="count(*)", selection=None, grid=None, healpix_input="equatorial", healpix_output="galactic", f=None, colormap="afmhot", grid_limits=None, image_s...
Viz data in 2d using a healpix column. :param healpix_expression: {healpix_max_level} :param healpix_max_level: {healpix_max_level} :param healpix_level: {healpix_level} :param what: {what} :param selection: {selection} :param grid: {grid} :param healpix_input: S...
Below is the the instruction that describes the task: ### Input: Viz data in 2d using a healpix column. :param healpix_expression: {healpix_max_level} :param healpix_max_level: {healpix_max_level} :param healpix_level: {healpix_level} :param what: {what} :param selection: {s...
def download_file(self, project, path): """ Read file of a project and download it :param project: A project object :param path: The path of the file in the project :returns: A file stream """ url = self._getUrl("/projects/{}/files/{}".format(project.id, path)) ...
Read file of a project and download it :param project: A project object :param path: The path of the file in the project :returns: A file stream
Below is the the instruction that describes the task: ### Input: Read file of a project and download it :param project: A project object :param path: The path of the file in the project :returns: A file stream ### Response: def download_file(self, project, path): """ Read f...
def readattr(path, name): """ Read attribute from sysfs and return as string """ try: f = open(USB_SYS_PREFIX + path + "/" + name) return f.readline().rstrip("\n") except IOError: return None
Read attribute from sysfs and return as string
Below is the the instruction that describes the task: ### Input: Read attribute from sysfs and return as string ### Response: def readattr(path, name): """ Read attribute from sysfs and return as string """ try: f = open(USB_SYS_PREFIX + path + "/" + name) return f.readline().rstrip...
def add_mappings(self, defn: Definition, target: Dict) -> None: """ Process any mappings in defn, adding all of the mappings prefixes to the namespace map and add a link to the first mapping to the target @param defn: Class or Slot definition @param target: context target """ ...
Process any mappings in defn, adding all of the mappings prefixes to the namespace map and add a link to the first mapping to the target @param defn: Class or Slot definition @param target: context target
Below is the the instruction that describes the task: ### Input: Process any mappings in defn, adding all of the mappings prefixes to the namespace map and add a link to the first mapping to the target @param defn: Class or Slot definition @param target: context target ### Response: def ad...
def iterGrid(self, minZoom, maxZoom): "Yields the tileBounds, zoom, tileCol and tileRow" assert minZoom in range(0, len(self.RESOLUTIONS)) assert maxZoom in range(0, len(self.RESOLUTIONS)) assert minZoom <= maxZoom for zoom in xrange(minZoom, maxZoom + 1): [minRow, m...
Yields the tileBounds, zoom, tileCol and tileRow
Below is the the instruction that describes the task: ### Input: Yields the tileBounds, zoom, tileCol and tileRow ### Response: def iterGrid(self, minZoom, maxZoom): "Yields the tileBounds, zoom, tileCol and tileRow" assert minZoom in range(0, len(self.RESOLUTIONS)) assert maxZoom in range(...
def _format_lat(self, lat): ''' Format latitude to fit the image name ''' if self.ppd in [4, 8, 16, 32, 64]: latcenter = '000N' elif self.ppd in [128]: if lat < 0: latcenter = '450S' else: latcenter = '450N' return lat...
Format latitude to fit the image name
Below is the the instruction that describes the task: ### Input: Format latitude to fit the image name ### Response: def _format_lat(self, lat): ''' Format latitude to fit the image name ''' if self.ppd in [4, 8, 16, 32, 64]: latcenter = '000N' elif self.ppd in [128]: ...
def ask_password(*question: Token) -> str: """Ask the user to enter a password. """ tokens = get_ask_tokens(question) info(*tokens) answer = read_password() return answer
Ask the user to enter a password.
Below is the the instruction that describes the task: ### Input: Ask the user to enter a password. ### Response: def ask_password(*question: Token) -> str: """Ask the user to enter a password. """ tokens = get_ask_tokens(question) info(*tokens) answer = read_password() return answer
def write(models, base=None, graph=None, rdfsonly=False, prefixes=None, logger=logging): ''' See the command line help ''' prefixes = prefixes or {} g = graph or rdflib.Graph() #g.bind('bf', BFNS) #g.bind('bfc', BFCNS) #g.bind('bfd', BFDNS) g.bind('v', VNS) for k, v in prefixes.i...
See the command line help
Below is the the instruction that describes the task: ### Input: See the command line help ### Response: def write(models, base=None, graph=None, rdfsonly=False, prefixes=None, logger=logging): ''' See the command line help ''' prefixes = prefixes or {} g = graph or rdflib.Graph() #g.bind('...
def _start_machine(machine, session): ''' Helper to try and start machines @param machine: @type machine: IMachine @param session: @type session: ISession @return: @rtype: IProgress or None ''' try: return machine.launchVMProcess(session, '', '') except Exception as ...
Helper to try and start machines @param machine: @type machine: IMachine @param session: @type session: ISession @return: @rtype: IProgress or None
Below is the the instruction that describes the task: ### Input: Helper to try and start machines @param machine: @type machine: IMachine @param session: @type session: ISession @return: @rtype: IProgress or None ### Response: def _start_machine(machine, session): ''' Helper to try...
def getIfStats(self): """Return dictionary of Traffic Stats for Network Interfaces. @return: Nested dictionary of statistics for each interface. """ info_dict = {} try: fp = open(ifaceStatsFile, 'r') data = fp.read() fp.close(...
Return dictionary of Traffic Stats for Network Interfaces. @return: Nested dictionary of statistics for each interface.
Below is the the instruction that describes the task: ### Input: Return dictionary of Traffic Stats for Network Interfaces. @return: Nested dictionary of statistics for each interface. ### Response: def getIfStats(self): """Return dictionary of Traffic Stats for Network Interfaces. ...
def set(self, key, value): """Set a configuration property.""" # Try to set self._jconf first if JVM is created, set self._conf if JVM is not created yet. if self._jconf is not None: self._jconf.set(key, unicode(value)) else: self._conf[key] = unicode(value) ...
Set a configuration property.
Below is the the instruction that describes the task: ### Input: Set a configuration property. ### Response: def set(self, key, value): """Set a configuration property.""" # Try to set self._jconf first if JVM is created, set self._conf if JVM is not created yet. if self._jconf is not None:...
def add_external_reference(self,markable_id, external_ref): """ Adds an external reference for the given markable @type markable_id: string @param markable_id: the markable identifier @type external_ref: L{CexternalReference} @param external_ref: the external reference ob...
Adds an external reference for the given markable @type markable_id: string @param markable_id: the markable identifier @type external_ref: L{CexternalReference} @param external_ref: the external reference object
Below is the the instruction that describes the task: ### Input: Adds an external reference for the given markable @type markable_id: string @param markable_id: the markable identifier @type external_ref: L{CexternalReference} @param external_ref: the external reference object ### Re...
def visit_For(self, node): """ OUT = (node,) + last body statements RAISES = body's that are not break or continue """ currs = (node,) break_currs = tuple() raises = () # handle body for n in node.body: self.result.add_node(n) ...
OUT = (node,) + last body statements RAISES = body's that are not break or continue
Below is the the instruction that describes the task: ### Input: OUT = (node,) + last body statements RAISES = body's that are not break or continue ### Response: def visit_For(self, node): """ OUT = (node,) + last body statements RAISES = body's that are not break or continue ...
def expand(self, info=b"", length=32): ''' Generate output key material based on an `info` value Arguments: - info - context to generate the OKM - length - length in bytes of the key to generate See the HKDF draft RFC for guidance. ''' return hkdf_expand(self._prk, info, length, self._hash)
Generate output key material based on an `info` value Arguments: - info - context to generate the OKM - length - length in bytes of the key to generate See the HKDF draft RFC for guidance.
Below is the the instruction that describes the task: ### Input: Generate output key material based on an `info` value Arguments: - info - context to generate the OKM - length - length in bytes of the key to generate See the HKDF draft RFC for guidance. ### Response: def expand(self, info=b"", length=32)...
def logging_active_formatter(self, value): """ Setter for **self.__logging_active_formatter** attribute. :param value: Attribute value. :type value: unicode or QString """ if value is not None: assert type(value) in ( unicode, QString), "'{0}...
Setter for **self.__logging_active_formatter** attribute. :param value: Attribute value. :type value: unicode or QString
Below is the the instruction that describes the task: ### Input: Setter for **self.__logging_active_formatter** attribute. :param value: Attribute value. :type value: unicode or QString ### Response: def logging_active_formatter(self, value): """ Setter for **self.__logging_active_...
def append_code_expr(self, code): """Compile argument and adds it to the list of code objects.""" # expects a string. if isinstance(code, str) and not isinstance(code, unicode): code = unicode(code) if not isinstance(code, unicode): raise TypeError("string expecte...
Compile argument and adds it to the list of code objects.
Below is the the instruction that describes the task: ### Input: Compile argument and adds it to the list of code objects. ### Response: def append_code_expr(self, code): """Compile argument and adds it to the list of code objects.""" # expects a string. if isinstance(code, str) and not isi...