code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _get_log_rho_metropolis_hastings(self, proposed_point, proposed_eval): """calculate log(metropolis ratio times hastings factor)""" return self._get_log_rho_metropolis(proposed_point, proposed_eval)\ - self.proposal.evaluate (proposed_point, self.current) \ + self.propo...
calculate log(metropolis ratio times hastings factor)
Below is the the instruction that describes the task: ### Input: calculate log(metropolis ratio times hastings factor) ### Response: def _get_log_rho_metropolis_hastings(self, proposed_point, proposed_eval): """calculate log(metropolis ratio times hastings factor)""" return self._get_log_rho_metrop...
def getPassagePlus(self, reference=None): """ Retrieve a passage and informations around it and store it in the object :param reference: Reference of the passage :type reference: CtsReference or List of text_type :rtype: CtsPassage :returns: Object representing the passage ...
Retrieve a passage and informations around it and store it in the object :param reference: Reference of the passage :type reference: CtsReference or List of text_type :rtype: CtsPassage :returns: Object representing the passage :raises: *TypeError* when reference is not a list o...
Below is the the instruction that describes the task: ### Input: Retrieve a passage and informations around it and store it in the object :param reference: Reference of the passage :type reference: CtsReference or List of text_type :rtype: CtsPassage :returns: Object representing th...
def missing_fun_string(self, function_name): ''' Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ''' mod_name = function_name.split('.')[0] if mod_name in self.loaded_modules: return '\'{0}\'...
Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False
Below is the the instruction that describes the task: ### Input: Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False ### Response: def missing_fun_string(self, function_name): ''' Return the error string for a missing function...
def ohlc(self, pair, timeframe=None, **kwargs): """ Subscribe to the passed pair's OHLC data channel. :param pair: str, Pair to request data for. :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :re...
Subscribe to the passed pair's OHLC data channel. :param pair: str, Pair to request data for. :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :return:
Below is the the instruction that describes the task: ### Input: Subscribe to the passed pair's OHLC data channel. :param pair: str, Pair to request data for. :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :r...
def connect(*, dsn, autocommit=False, ansi=False, timeout=0, loop=None, executor=None, echo=False, after_created=None, **kwargs): """Accepts an ODBC connection string and returns a new Connection object. The connection string can be passed as the string `str`, as a list of keywords,or a combina...
Accepts an ODBC connection string and returns a new Connection object. The connection string can be passed as the string `str`, as a list of keywords,or a combination of the two. Any keywords except autocommit, ansi, and timeout are simply added to the connection string. :param autocommit bool: False...
Below is the the instruction that describes the task: ### Input: Accepts an ODBC connection string and returns a new Connection object. The connection string can be passed as the string `str`, as a list of keywords,or a combination of the two. Any keywords except autocommit, ansi, and timeout are simp...
def compute_merkle_tree(items: Iterable[bytes]) -> MerkleTree: """ Calculates the merkle root for a given list of items """ if not all(isinstance(l, bytes) and len(l) == 32 for l in items): raise ValueError('Not all items are hashes') leaves = sorted(items) if len(leaves) == 0: return ...
Calculates the merkle root for a given list of items
Below is the the instruction that describes the task: ### Input: Calculates the merkle root for a given list of items ### Response: def compute_merkle_tree(items: Iterable[bytes]) -> MerkleTree: """ Calculates the merkle root for a given list of items """ if not all(isinstance(l, bytes) and len(l) == 32 f...
def remove_plus(orig): """Remove a fils, including biological index files. """ for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]: if os.path.exists(orig + ext): remove_safe(orig + ext)
Remove a fils, including biological index files.
Below is the the instruction that describes the task: ### Input: Remove a fils, including biological index files. ### Response: def remove_plus(orig): """Remove a fils, including biological index files. """ for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]: if os.path.exists(orig + ext): ...
def trim(self, inplace=False): '''Return a DataFrame, where all columns are 'trimmed' by the active range. For the returned DataFrame, df.get_active_range() returns (0, df.length_original()). {note_copy} :param inplace: {inplace} :rtype: DataFrame ''' df = self...
Return a DataFrame, where all columns are 'trimmed' by the active range. For the returned DataFrame, df.get_active_range() returns (0, df.length_original()). {note_copy} :param inplace: {inplace} :rtype: DataFrame
Below is the the instruction that describes the task: ### Input: Return a DataFrame, where all columns are 'trimmed' by the active range. For the returned DataFrame, df.get_active_range() returns (0, df.length_original()). {note_copy} :param inplace: {inplace} :rtype: DataFrame ##...
def get_isotopic_ratio(self, compound='', element=''): """returns the list of isotopes for the element of the compound defined with their stoichiometric values Parameters: =========== compound: string (default is empty). If empty, all the stoichiometric will be displayed element...
returns the list of isotopes for the element of the compound defined with their stoichiometric values Parameters: =========== compound: string (default is empty). If empty, all the stoichiometric will be displayed element: string (default is same as compound). Raises: =...
Below is the the instruction that describes the task: ### Input: returns the list of isotopes for the element of the compound defined with their stoichiometric values Parameters: =========== compound: string (default is empty). If empty, all the stoichiometric will be displayed elem...
def clearAnnouncements(self): """ Flushes the announcement table. """ try: q = models.Announcement.delete().where( models.Announcement.id > 0) q.execute() except Exception as e: raise exceptions.RepoManagerException(e)
Flushes the announcement table.
Below is the the instruction that describes the task: ### Input: Flushes the announcement table. ### Response: def clearAnnouncements(self): """ Flushes the announcement table. """ try: q = models.Announcement.delete().where( models.Announcement.id > 0) ...
def get_authorization_url(self): """Get the authorization Url for the current client.""" return self._format_url( OAUTH2_ROOT + 'authorize', query = { 'response_type': 'code', 'client_id': self.client.get('client_id', ''), 'redirect...
Get the authorization Url for the current client.
Below is the the instruction that describes the task: ### Input: Get the authorization Url for the current client. ### Response: def get_authorization_url(self): """Get the authorization Url for the current client.""" return self._format_url( OAUTH2_ROOT + 'authorize', query...
def start(self, sockets=None, **kwargs): """ Present the PTY of the container inside the current process. This will take over the current process' TTY until the container's PTY is closed. """ pty_stdin, pty_stdout, pty_stderr = sockets or self.sockets() pumps = ...
Present the PTY of the container inside the current process. This will take over the current process' TTY until the container's PTY is closed.
Below is the the instruction that describes the task: ### Input: Present the PTY of the container inside the current process. This will take over the current process' TTY until the container's PTY is closed. ### Response: def start(self, sockets=None, **kwargs): """ Present the PTY...
def payload(self): """ Returns: `str` when not json. `dict` when json. """ if self.is_json: if not self._body_parsed: if hasattr(self._body, 'decode'): body = self._body.decode('utf-8') else: ...
Returns: `str` when not json. `dict` when json.
Below is the the instruction that describes the task: ### Input: Returns: `str` when not json. `dict` when json. ### Response: def payload(self): """ Returns: `str` when not json. `dict` when json. """ if self.is_json: if not self....
def calc_mean_var_weights(returns, weight_bounds=(0., 1.), rf=0., covar_method='ledoit-wolf', options=None): """ Calculates the mean-variance weights given a DataFrame of returns. Args: * returns (DataFrame): Returns for ...
Calculates the mean-variance weights given a DataFrame of returns. Args: * returns (DataFrame): Returns for multiple securities. * weight_bounds ((low, high)): Weigh limits for optimization. * rf (float): `Risk-free rate <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ used in uti...
Below is the the instruction that describes the task: ### Input: Calculates the mean-variance weights given a DataFrame of returns. Args: * returns (DataFrame): Returns for multiple securities. * weight_bounds ((low, high)): Weigh limits for optimization. * rf (float): `Risk-free rate <...
def save_tensorflow(self, inputs, path, byte_order="little_endian", data_format="nhwc"): """ Save a model to protobuf files so that it can be used in tensorflow inference. When saving the model, placeholders will be added to the tf model as input nodes. So you need to pass in the names ...
Save a model to protobuf files so that it can be used in tensorflow inference. When saving the model, placeholders will be added to the tf model as input nodes. So you need to pass in the names and shapes of the placeholders. BigDL model doesn't have such information. The order of the placehold...
Below is the the instruction that describes the task: ### Input: Save a model to protobuf files so that it can be used in tensorflow inference. When saving the model, placeholders will be added to the tf model as input nodes. So you need to pass in the names and shapes of the placeholders. BigDL mo...
def tvd(x0, rho, gamma): """ Proximal operator for the total variation denoising penalty Requires scikit-image be installed Parameters ---------- x0 : array_like The starting or initial point used in the proximal update step rho : float Momentum parameter for the proximal ...
Proximal operator for the total variation denoising penalty Requires scikit-image be installed Parameters ---------- x0 : array_like The starting or initial point used in the proximal update step rho : float Momentum parameter for the proximal step (larger value -> stays closer to...
Below is the the instruction that describes the task: ### Input: Proximal operator for the total variation denoising penalty Requires scikit-image be installed Parameters ---------- x0 : array_like The starting or initial point used in the proximal update step rho : float Mome...
def decode(self, encoded): """ Decodes ``encoded`` label. Args: encoded (torch.Tensor): Encoded label. Returns: object: Label decoded from ``encoded``. """ encoded = super().decode(encoded) if encoded.numel() > 1: raise ValueError( ...
Decodes ``encoded`` label. Args: encoded (torch.Tensor): Encoded label. Returns: object: Label decoded from ``encoded``.
Below is the the instruction that describes the task: ### Input: Decodes ``encoded`` label. Args: encoded (torch.Tensor): Encoded label. Returns: object: Label decoded from ``encoded``. ### Response: def decode(self, encoded): """ Decodes ``encoded`` label. ...
def add_linear_constraints(self, *relations): """Add constraints to the problem Each constraint is represented by a Relation, and the expression in that relation can be a set expression. """ constraints = [] for relation in relations: if self._check_relation...
Add constraints to the problem Each constraint is represented by a Relation, and the expression in that relation can be a set expression.
Below is the the instruction that describes the task: ### Input: Add constraints to the problem Each constraint is represented by a Relation, and the expression in that relation can be a set expression. ### Response: def add_linear_constraints(self, *relations): """Add constraints to the p...
def delete(self, digest): """ Delete a blob :param digest: the hex digest of the blob to be deleted :return: True if blob existed """ return self.conn.client.blob_del(self.container_name, digest)
Delete a blob :param digest: the hex digest of the blob to be deleted :return: True if blob existed
Below is the the instruction that describes the task: ### Input: Delete a blob :param digest: the hex digest of the blob to be deleted :return: True if blob existed ### Response: def delete(self, digest): """ Delete a blob :param digest: the hex digest of the blob to be de...
def get_style_bits(match=False, comment=False, selected=False, data=False, diff=False, user=0): """ Return an int value that contains the specified style bits set. Available styles for each byte are: match: part of the currently matched search comment: user commented area selected: selected region...
Return an int value that contains the specified style bits set. Available styles for each byte are: match: part of the currently matched search comment: user commented area selected: selected region data: labeled in the disassembler as a data region (i.e. not disassembled)
Below is the the instruction that describes the task: ### Input: Return an int value that contains the specified style bits set. Available styles for each byte are: match: part of the currently matched search comment: user commented area selected: selected region data: labeled in the disassemb...
def publish(self, message, routing_key=None): """Publish message to exchange :param message: message for publishing :type message: any serializable object :param routing_key: routing key for queue :return: None """ if routing_key is None: routing_key ...
Publish message to exchange :param message: message for publishing :type message: any serializable object :param routing_key: routing key for queue :return: None
Below is the the instruction that describes the task: ### Input: Publish message to exchange :param message: message for publishing :type message: any serializable object :param routing_key: routing key for queue :return: None ### Response: def publish(self, message, routing_key=No...
def _find_resource_by_key(self, resource_list, key, value): """ Finds a resource by key, first case insensitive match. Returns tuple of (key, resource) Raises KeyError if the given key cannot be found. """ original = value value = unicode(value.upper()) for k, resource in resource_list.iteritems(): ...
Finds a resource by key, first case insensitive match. Returns tuple of (key, resource) Raises KeyError if the given key cannot be found.
Below is the the instruction that describes the task: ### Input: Finds a resource by key, first case insensitive match. Returns tuple of (key, resource) Raises KeyError if the given key cannot be found. ### Response: def _find_resource_by_key(self, resource_list, key, value): """ Finds a resource by key,...
def distros_for_location(location, basename, metadata=None): """Yield egg or source distribution objects based on basename""" if basename.endswith('.egg.zip'): basename = basename[:-4] # strip the .zip if basename.endswith('.egg') and '-' in basename: # only one, unambiguous interpretatio...
Yield egg or source distribution objects based on basename
Below is the the instruction that describes the task: ### Input: Yield egg or source distribution objects based on basename ### Response: def distros_for_location(location, basename, metadata=None): """Yield egg or source distribution objects based on basename""" if basename.endswith('.egg.zip'): b...
def _retrieve_html_page(self, uri): """ Download the requested HTML page. Given a relative link, download the requested page and strip it of all comment tags before returning a pyquery object which will be used to parse the data. Parameters ---------- ur...
Download the requested HTML page. Given a relative link, download the requested page and strip it of all comment tags before returning a pyquery object which will be used to parse the data. Parameters ---------- uri : string The relative link to the boxscore...
Below is the the instruction that describes the task: ### Input: Download the requested HTML page. Given a relative link, download the requested page and strip it of all comment tags before returning a pyquery object which will be used to parse the data. Parameters --------...
def BGPNeighborPrefixExceeded_originator_switch_info_switchIpV4Address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") BGPNeighborPrefixExceeded = ET.SubElement(config, "BGPNeighborPrefixExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def BGPNeighborPrefixExceeded_originator_switch_info_switchIpV4Address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") BGPNeighborPrefixExceeded = ET.SubEleme...
def std(self, ddof=1, *args, **kwargs): """ Compute standard deviation of groups, excluding missing values. Parameters ---------- ddof : integer, default 1 Degrees of freedom. """ nv.validate_resampler_func('std', args, kwargs) return self._do...
Compute standard deviation of groups, excluding missing values. Parameters ---------- ddof : integer, default 1 Degrees of freedom.
Below is the the instruction that describes the task: ### Input: Compute standard deviation of groups, excluding missing values. Parameters ---------- ddof : integer, default 1 Degrees of freedom. ### Response: def std(self, ddof=1, *args, **kwargs): """ Compute...
def rosmsg(self): """:obj:`sensor_msgs.Image` : ROS Image """ from cv_bridge import CvBridge, CvBridgeError cv_bridge = CvBridge() try: return cv_bridge.cv2_to_imgmsg(self._data, encoding=self._encoding) except CvBridgeError as cv_bridge_exception: ...
:obj:`sensor_msgs.Image` : ROS Image
Below is the the instruction that describes the task: ### Input: :obj:`sensor_msgs.Image` : ROS Image ### Response: def rosmsg(self): """:obj:`sensor_msgs.Image` : ROS Image """ from cv_bridge import CvBridge, CvBridgeError cv_bridge = CvBridge() try: return cv_b...
def _imm_getattribute(self, name): ''' An immutable's getattribute calculates lazy values when not yet cached in the object then adds them as attributes. ''' if _imm_is_init(self): return _imm_init_getattribute(self, name) else: dd = object.__getattribute__(self, '__dict__') ...
An immutable's getattribute calculates lazy values when not yet cached in the object then adds them as attributes.
Below is the the instruction that describes the task: ### Input: An immutable's getattribute calculates lazy values when not yet cached in the object then adds them as attributes. ### Response: def _imm_getattribute(self, name): ''' An immutable's getattribute calculates lazy values when not yet cached...
def drop_genes(self, build=None): """Delete the genes collection""" if build: LOG.info("Dropping the hgnc_gene collection, build %s", build) self.hgnc_collection.delete_many({'build': build}) else: LOG.info("Dropping the hgnc_gene collection") self...
Delete the genes collection
Below is the the instruction that describes the task: ### Input: Delete the genes collection ### Response: def drop_genes(self, build=None): """Delete the genes collection""" if build: LOG.info("Dropping the hgnc_gene collection, build %s", build) self.hgnc_collection.delete...
def color_greedy(self): '''Returns a greedy vertex coloring as an array of ints.''' n = self.num_vertices() coloring = np.zeros(n, dtype=int) for i, nbrs in enumerate(self.adj_list()): nbr_colors = set(coloring[nbrs]) for c in count(1): if c not in nbr_colors: coloring[i] =...
Returns a greedy vertex coloring as an array of ints.
Below is the the instruction that describes the task: ### Input: Returns a greedy vertex coloring as an array of ints. ### Response: def color_greedy(self): '''Returns a greedy vertex coloring as an array of ints.''' n = self.num_vertices() coloring = np.zeros(n, dtype=int) for i, nbrs in enumerate...
def encode(self, method, uri): '''Called by the client to encode Authentication header.''' if not self.username or not self.password: return o = self.options qop = o.get('qop') realm = o.get('realm') nonce = o.get('nonce') entdig = None p_parse...
Called by the client to encode Authentication header.
Below is the the instruction that describes the task: ### Input: Called by the client to encode Authentication header. ### Response: def encode(self, method, uri): '''Called by the client to encode Authentication header.''' if not self.username or not self.password: return o = s...
def add(self, byte_sig: str, text_sig: str) -> None: """ Adds a new byte - text signature pair to the database. :param byte_sig: 4-byte signature string :param text_sig: resolved text signature :return: """ byte_sig = self._normalize_byte_sig(byte_sig) wit...
Adds a new byte - text signature pair to the database. :param byte_sig: 4-byte signature string :param text_sig: resolved text signature :return:
Below is the the instruction that describes the task: ### Input: Adds a new byte - text signature pair to the database. :param byte_sig: 4-byte signature string :param text_sig: resolved text signature :return: ### Response: def add(self, byte_sig: str, text_sig: str) -> None: """ ...
def put(self, thing_id='0', action_name=None, action_id=None): """ Handle a PUT request. TODO: this is not yet defined in the spec thing_id -- ID of the thing this request is for action_name -- name of the action from the URL path action_id -- the action ID from the URL...
Handle a PUT request. TODO: this is not yet defined in the spec thing_id -- ID of the thing this request is for action_name -- name of the action from the URL path action_id -- the action ID from the URL path
Below is the the instruction that describes the task: ### Input: Handle a PUT request. TODO: this is not yet defined in the spec thing_id -- ID of the thing this request is for action_name -- name of the action from the URL path action_id -- the action ID from the URL path ### Resp...
def _read_object(self, correlation_id, parameters): """ Reads configuration file, parameterizes its content and converts it into JSON object. :param correlation_id: (optional) transaction id to trace execution through call chain. :param parameters: values to parameters the configuratio...
Reads configuration file, parameterizes its content and converts it into JSON object. :param correlation_id: (optional) transaction id to trace execution through call chain. :param parameters: values to parameters the configuration. :return: a JSON object with configuration.
Below is the the instruction that describes the task: ### Input: Reads configuration file, parameterizes its content and converts it into JSON object. :param correlation_id: (optional) transaction id to trace execution through call chain. :param parameters: values to parameters the configuration. ...
def tokenize(sentence): """ Converts a single sentence into a list of individual significant units Args: sentence (str): Input string ie. 'This is a sentence.' Returns: list<str>: List of tokens ie. ['this', 'is', 'a', 'sentence'] """ tokens = [] class Vars: start_po...
Converts a single sentence into a list of individual significant units Args: sentence (str): Input string ie. 'This is a sentence.' Returns: list<str>: List of tokens ie. ['this', 'is', 'a', 'sentence']
Below is the the instruction that describes the task: ### Input: Converts a single sentence into a list of individual significant units Args: sentence (str): Input string ie. 'This is a sentence.' Returns: list<str>: List of tokens ie. ['this', 'is', 'a', 'sentence'] ### Response: def token...
def get_primary_keys(model): """Get primary key properties for a SQLAlchemy model. :param model: SQLAlchemy model class """ mapper = model.__mapper__ return [mapper.get_property_by_column(column) for column in mapper.primary_key]
Get primary key properties for a SQLAlchemy model. :param model: SQLAlchemy model class
Below is the the instruction that describes the task: ### Input: Get primary key properties for a SQLAlchemy model. :param model: SQLAlchemy model class ### Response: def get_primary_keys(model): """Get primary key properties for a SQLAlchemy model. :param model: SQLAlchemy model class """ ma...
def wif(self, is_compressed=None): """ Return the WIF representation of this key, if available. """ secret_exponent = self.secret_exponent() if secret_exponent is None: return None if is_compressed is None: is_compressed = self.is_compressed() ...
Return the WIF representation of this key, if available.
Below is the the instruction that describes the task: ### Input: Return the WIF representation of this key, if available. ### Response: def wif(self, is_compressed=None): """ Return the WIF representation of this key, if available. """ secret_exponent = self.secret_exponent() ...
def getrepaymentsurl(idcred, *args, **kwargs): """Request loan Repayments URL. If idcred is set, you'll get a response adequate for a MambuRepayments object. There's a MambuRepayment object too, but you'll get a list first and each element of it will be automatically converted to a MambuRepayment o...
Request loan Repayments URL. If idcred is set, you'll get a response adequate for a MambuRepayments object. There's a MambuRepayment object too, but you'll get a list first and each element of it will be automatically converted to a MambuRepayment object that you may use. If not set, you'll get a ...
Below is the the instruction that describes the task: ### Input: Request loan Repayments URL. If idcred is set, you'll get a response adequate for a MambuRepayments object. There's a MambuRepayment object too, but you'll get a list first and each element of it will be automatically converted to a M...
def _check_shape(var, name, shape, shape2=None): r"""Check that <var> has shape <shape>; if false raise ValueError(name)""" varshape = np.shape(var) if shape != varshape: if shape2: if shape2 != varshape: print('* ERROR :: Parameter ' + name + ' has wrong shape!' + ...
r"""Check that <var> has shape <shape>; if false raise ValueError(name)
Below is the the instruction that describes the task: ### Input: r"""Check that <var> has shape <shape>; if false raise ValueError(name) ### Response: def _check_shape(var, name, shape, shape2=None): r"""Check that <var> has shape <shape>; if false raise ValueError(name)""" varshape = np.shape(var) if ...
def ConsultarUltimoComprobante(self, tipo_cbte=151, pto_vta=1): "Consulta el último No de Comprobante registrado" ret = self.client.consultarUltimoNroComprobantePorPtoVta( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit...
Consulta el último No de Comprobante registrado
Below is the the instruction that describes the task: ### Input: Consulta el último No de Comprobante registrado ### Response: def ConsultarUltimoComprobante(self, tipo_cbte=151, pto_vta=1): "Consulta el último No de Comprobante registrado" ret = self.client.consultarUltimoNroComprobantePorPtoVta( ...
def selfSignCert(self, cert, pkey): ''' Self-sign a certificate. Args: cert (OpenSSL.crypto.X509): The certificate to sign. pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate. Examples: Sign a given certificate with a given priva...
Self-sign a certificate. Args: cert (OpenSSL.crypto.X509): The certificate to sign. pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate. Examples: Sign a given certificate with a given private key: cdir.selfSignCert(mycert, myoth...
Below is the the instruction that describes the task: ### Input: Self-sign a certificate. Args: cert (OpenSSL.crypto.X509): The certificate to sign. pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate. Examples: Sign a given certificate with ...
def partial_distance_correlation(x, y, z): # pylint:disable=too-many-locals """ Partial distance correlation estimator. Compute the estimator for the partial distance correlation of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :ma...
Partial distance correlation estimator. Compute the estimator for the partial distance correlation of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------- x: array_like First random vector. The...
Below is the the instruction that describes the task: ### Input: Partial distance correlation estimator. Compute the estimator for the partial distance correlation of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Paramet...
def download_file_job(entry, directory, checksums, filetype='genbank', symlink_path=None): """Generate a DownloadJob that actually triggers a file download.""" pattern = NgdConfig.get_fileending(filetype) filename, expected_checksum = get_name_and_checksum(checksums, pattern) base_url = convert_ftp_url(...
Generate a DownloadJob that actually triggers a file download.
Below is the the instruction that describes the task: ### Input: Generate a DownloadJob that actually triggers a file download. ### Response: def download_file_job(entry, directory, checksums, filetype='genbank', symlink_path=None): """Generate a DownloadJob that actually triggers a file download.""" patte...
def status(name='all'): ''' Using drbdadm to show status of the DRBD devices, available in the latest drbd9. Support multiple nodes, multiple volumes. :type name: str :param name: Resource name. :return: drbd status of resource. :rtype: list(dict(res)) CLI Example: .....
Using drbdadm to show status of the DRBD devices, available in the latest drbd9. Support multiple nodes, multiple volumes. :type name: str :param name: Resource name. :return: drbd status of resource. :rtype: list(dict(res)) CLI Example: .. code-block:: bash salt '*'...
Below is the the instruction that describes the task: ### Input: Using drbdadm to show status of the DRBD devices, available in the latest drbd9. Support multiple nodes, multiple volumes. :type name: str :param name: Resource name. :return: drbd status of resource. :rtype: list(dic...
def colorbar(ax, im, fig=None, loc="right", size="5%", pad="3%"): """ Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely. .. versionadded:: 1.3 Parameters ---------- ax : :class:`matplotlib.axis.Axis` The axis to plot to. im : :class:`m...
Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely. .. versionadded:: 1.3 Parameters ---------- ax : :class:`matplotlib.axis.Axis` The axis to plot to. im : :class:`matplotlib.image.AxesImage` The plotted image to use for the colorbar. ...
Below is the the instruction that describes the task: ### Input: Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely. .. versionadded:: 1.3 Parameters ---------- ax : :class:`matplotlib.axis.Axis` The axis to plot to. im : :class:`matplotlib...
def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): ''' Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f7...
Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova
Below is the the instruction that describes the task: ### Input: Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 ...
def send_request(self, api_name, *api_args, **api_kwargs): """Refer to SDK API documentation. :param api_name: SDK API name :param *api_args: SDK API sequence parameters :param **api_kwargs: SDK API keyword parameters """ return self.conn.request(api_name, *...
Refer to SDK API documentation. :param api_name: SDK API name :param *api_args: SDK API sequence parameters :param **api_kwargs: SDK API keyword parameters
Below is the the instruction that describes the task: ### Input: Refer to SDK API documentation. :param api_name: SDK API name :param *api_args: SDK API sequence parameters :param **api_kwargs: SDK API keyword parameters ### Response: def send_request(self, api_name, *api_args...
def safe_str_cmp(a, b): """This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7 """ if _builtin_safe_str_cmp is not None...
This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7
Below is the the instruction that describes the task: ### Input: This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7 ### Respon...
def clean_attribute(attribute): ''' Normalize attribute names for shorthand and work arounds for limitations in Python's syntax ''' # Shorthand attribute = { 'cls': 'class', 'className': 'class', 'class_name': 'class', 'fr': 'for', 'html_for': 'for', 'htmlFor...
Normalize attribute names for shorthand and work arounds for limitations in Python's syntax
Below is the the instruction that describes the task: ### Input: Normalize attribute names for shorthand and work arounds for limitations in Python's syntax ### Response: def clean_attribute(attribute): ''' Normalize attribute names for shorthand and work arounds for limitations in Python's syntax ...
def engineer_list_commands(self): """ Returns a list of all api end points (commands) exposed to engineer """ rv = [] for k in dir(self): attr = getattr(self,k) if type(getattr(attr, "engineer", None)) == dict: rv.append(k) ...
Returns a list of all api end points (commands) exposed to engineer
Below is the the instruction that describes the task: ### Input: Returns a list of all api end points (commands) exposed to engineer ### Response: def engineer_list_commands(self): """ Returns a list of all api end points (commands) exposed to engineer """ rv = [] ...
def get_inferred_data_table(table, pc): """ Table level: Dive down, calculate data, then return the new table with the inferred data. :param str pc: paleo or chron :param dict table: Metadata :return dict table: Metadata """ age = None if pc == "paleo": # Get the age values data...
Table level: Dive down, calculate data, then return the new table with the inferred data. :param str pc: paleo or chron :param dict table: Metadata :return dict table: Metadata
Below is the the instruction that describes the task: ### Input: Table level: Dive down, calculate data, then return the new table with the inferred data. :param str pc: paleo or chron :param dict table: Metadata :return dict table: Metadata ### Response: def get_inferred_data_table(table, pc): ""...
def nb_cluster(data, k, P_init=None, R_init=None, assignments=None, means=None, max_iters=10): """ Performs negative binomial clustering on the given data. If some genes have mean > variance, then these genes are fitted to a Poisson distribution. Args: data (array): genes x cells k (int): n...
Performs negative binomial clustering on the given data. If some genes have mean > variance, then these genes are fitted to a Poisson distribution. Args: data (array): genes x cells k (int): number of clusters P_init (array): NB success prob param - genes x k. Default: random R_init...
Below is the the instruction that describes the task: ### Input: Performs negative binomial clustering on the given data. If some genes have mean > variance, then these genes are fitted to a Poisson distribution. Args: data (array): genes x cells k (int): number of clusters P_init (arra...
def get_form(self, request, obj=None, **kwargs): """ Returns a Form class for use in the admin add view. This is used by add_view and change_view. """ parent_id = request.GET.get('parent_id', None) if not parent_id: parent_id = request.POST.get('parent_id', No...
Returns a Form class for use in the admin add view. This is used by add_view and change_view.
Below is the the instruction that describes the task: ### Input: Returns a Form class for use in the admin add view. This is used by add_view and change_view. ### Response: def get_form(self, request, obj=None, **kwargs): """ Returns a Form class for use in the admin add view. This is used ...
def set_quoted_text(self, quoted_text): """Sets the context's ``quoted_text`` flag. Useful when entering and exiting quoted text tokens.""" self.quoted_text = quoted_text self.line_comment = False return self
Sets the context's ``quoted_text`` flag. Useful when entering and exiting quoted text tokens.
Below is the the instruction that describes the task: ### Input: Sets the context's ``quoted_text`` flag. Useful when entering and exiting quoted text tokens. ### Response: def set_quoted_text(self, quoted_text): """Sets the context's ``quoted_text`` flag. Useful when entering and exiting quoted text token...
def add_bytes(self, data, **kwargs): """Adds a set of bytes as a file to IPFS. .. code-block:: python >>> c.add_bytes(b"Mary had a little lamb") 'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab' Also accepts and will stream generator objects. Parameters ...
Adds a set of bytes as a file to IPFS. .. code-block:: python >>> c.add_bytes(b"Mary had a little lamb") 'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab' Also accepts and will stream generator objects. Parameters ---------- data : bytes Con...
Below is the the instruction that describes the task: ### Input: Adds a set of bytes as a file to IPFS. .. code-block:: python >>> c.add_bytes(b"Mary had a little lamb") 'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab' Also accepts and will stream generator objects. ...
def remove_end_NaN(self, data, var=None): """ Remove end NaN. CHECK: Note issue with multi-column df. Parameters ---------- data : pd.DataFrame() Input dataframe. var : list(str) List that specifies specific columns of data...
Remove end NaN. CHECK: Note issue with multi-column df. Parameters ---------- data : pd.DataFrame() Input dataframe. var : list(str) List that specifies specific columns of dataframe. Returns ------- pd.Dat...
Below is the the instruction that describes the task: ### Input: Remove end NaN. CHECK: Note issue with multi-column df. Parameters ---------- data : pd.DataFrame() Input dataframe. var : list(str) List that specifies specific ...
def getElementById(id: str) -> Optional[Node]: """Get element with ``id``.""" elm = Element._elements_with_id.get(id) return elm
Get element with ``id``.
Below is the the instruction that describes the task: ### Input: Get element with ``id``. ### Response: def getElementById(id: str) -> Optional[Node]: """Get element with ``id``.""" elm = Element._elements_with_id.get(id) return elm
def update_user_password(new_pwd_user_id, new_password,**kwargs): """ Update a user's password """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one() user_i.password = bcrypt.hashpw(str(new_password).encod...
Update a user's password
Below is the the instruction that describes the task: ### Input: Update a user's password ### Response: def update_user_password(new_pwd_user_id, new_password,**kwargs): """ Update a user's password """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query...
def _get_hba_type(hba_type): ''' Convert a string representation of a HostHostBusAdapter into an object reference. ''' if hba_type == "parallel": return vim.host.ParallelScsiHba elif hba_type == "block": return vim.host.BlockHba elif hba_type == "iscsi": return vim.ho...
Convert a string representation of a HostHostBusAdapter into an object reference.
Below is the the instruction that describes the task: ### Input: Convert a string representation of a HostHostBusAdapter into an object reference. ### Response: def _get_hba_type(hba_type): ''' Convert a string representation of a HostHostBusAdapter into an object reference. ''' if hba_type...
def premier_da_la_annee(jd): '''Determine the year in the French revolutionary calendar in which a given Julian day falls. Returns Julian day number containing fall equinox (first day of the FR year)''' p = ephem.previous_fall_equinox(dublin.from_jd(jd)) previous = trunc(dublin.to_jd(p) - 0.5) + 0.5 ...
Determine the year in the French revolutionary calendar in which a given Julian day falls. Returns Julian day number containing fall equinox (first day of the FR year)
Below is the the instruction that describes the task: ### Input: Determine the year in the French revolutionary calendar in which a given Julian day falls. Returns Julian day number containing fall equinox (first day of the FR year) ### Response: def premier_da_la_annee(jd): '''Determine the year in the Fr...
def age(self): """Age of the video""" if self.exists: return datetime.utcnow() - datetime.utcfromtimestamp(os.path.getmtime(self.name)) return timedelta()
Age of the video
Below is the the instruction that describes the task: ### Input: Age of the video ### Response: def age(self): """Age of the video""" if self.exists: return datetime.utcnow() - datetime.utcfromtimestamp(os.path.getmtime(self.name)) return timedelta()
def auth_criteria(self): """ This attribute provides the mapping of services to their auth requirement Returns: (dict) : the mapping from services to their auth requirements. """ # the dictionary we will return auth = {} # go over each at...
This attribute provides the mapping of services to their auth requirement Returns: (dict) : the mapping from services to their auth requirements.
Below is the the instruction that describes the task: ### Input: This attribute provides the mapping of services to their auth requirement Returns: (dict) : the mapping from services to their auth requirements. ### Response: def auth_criteria(self): """ This attribu...
def introspect_access_token(self, access_token_value): # type: (str) -> Dict[str, Union[str, List[str]]] """ Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection", Section 2.2</a>. """ if acces...
Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection", Section 2.2</a>.
Below is the the instruction that describes the task: ### Input: Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection", Section 2.2</a>. ### Response: def introspect_access_token(self, access_token_value): # type: (str) ...
def case_synopsis(institute_id, case_name): """Update (PUT) synopsis of a specific case.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) user_obj = store.user(current_user.email) new_synopsis = request.form.get('synopsis') controllers.update_synopsis(store, institute_...
Update (PUT) synopsis of a specific case.
Below is the the instruction that describes the task: ### Input: Update (PUT) synopsis of a specific case. ### Response: def case_synopsis(institute_id, case_name): """Update (PUT) synopsis of a specific case.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) user_obj = st...
def get_functions(fname): """ get a list of functions from a Python program """ txt = '' with open(fname, 'r') as f: for line in f: if line.strip()[0:4] == 'def ': txt += '<PRE>' + strip_text_after_string(strip_text_after_string(line, '#')[4:], ':') + '</PRE>\n' ...
get a list of functions from a Python program
Below is the the instruction that describes the task: ### Input: get a list of functions from a Python program ### Response: def get_functions(fname): """ get a list of functions from a Python program """ txt = '' with open(fname, 'r') as f: for line in f: if line.strip()[0:4] == '...
def begin_commit(): """ Allow a client to begin a commit and acquire the write lock """ session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if curre...
Allow a client to begin a commit and acquire the write lock
Below is the the instruction that describes the task: ### Input: Allow a client to begin a commit and acquire the write lock ### Response: def begin_commit(): """ Allow a client to begin a commit and acquire the write lock """ session_token = request.headers['session_token'] repository = request.he...
def get_conf_path(filename=None): """Return absolute path to the config file with the specified filename.""" # Define conf_dir if running_under_pytest() or SAFE_MODE: # Use clean config dir if running tests or the user requests it. conf_dir = get_clean_conf_dir() elif sys.platform....
Return absolute path to the config file with the specified filename.
Below is the the instruction that describes the task: ### Input: Return absolute path to the config file with the specified filename. ### Response: def get_conf_path(filename=None): """Return absolute path to the config file with the specified filename.""" # Define conf_dir if running_under_pytest()...
def unique_string(length=UUID_LENGTH): '''Generate a unique string''' # We need a string at least as long as length string = str(uuid4()) * int(math.ceil(length / float(UUID_LENGTH))) return string[:length] if length else string
Generate a unique string
Below is the the instruction that describes the task: ### Input: Generate a unique string ### Response: def unique_string(length=UUID_LENGTH): '''Generate a unique string''' # We need a string at least as long as length string = str(uuid4()) * int(math.ceil(length / float(UUID_LENGTH))) return stri...
def dump_options_header(header, options): """The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of options to append. """ segments = [] if header is not None: segments.append(header) for key, value in iteritems(options): ...
The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of options to append.
Below is the the instruction that describes the task: ### Input: The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of options to append. ### Response: def dump_options_header(header, options): """The reverse function to :func:`parse_options_...
def _onMenuButton(self, evt): """Handle menu button pressed.""" x, y = self.GetPositionTuple() w, h = self.GetSizeTuple() self.PopupMenuXY(self._menu, x, y+h-4) # When menu returned, indicate selection in button evt.Skip()
Handle menu button pressed.
Below is the the instruction that describes the task: ### Input: Handle menu button pressed. ### Response: def _onMenuButton(self, evt): """Handle menu button pressed.""" x, y = self.GetPositionTuple() w, h = self.GetSizeTuple() self.PopupMenuXY(self._menu, x, y+h-4) ...
def get_variables(): """ Send a dictionary of variables associated with the selected run. Usage description: This function is usually called to get and display the list of runs associated with a selected project available in the database for the user to view. :return: JSON, {<int_keys>: <run_n...
Send a dictionary of variables associated with the selected run. Usage description: This function is usually called to get and display the list of runs associated with a selected project available in the database for the user to view. :return: JSON, {<int_keys>: <run_name>}
Below is the the instruction that describes the task: ### Input: Send a dictionary of variables associated with the selected run. Usage description: This function is usually called to get and display the list of runs associated with a selected project available in the database for the user to view. ...
def nm2lt7(short_nm: float, long_nm: float, step_cminv: float = 20) -> Tuple[float, float, float]: """converts wavelength in nm to cm^-1 minimum meaningful step is 20, but 5 is minimum before crashing lowtran short: shortest wavelength e.g. 200 nm long: longest wavelength e.g. 30000 nm step: step s...
converts wavelength in nm to cm^-1 minimum meaningful step is 20, but 5 is minimum before crashing lowtran short: shortest wavelength e.g. 200 nm long: longest wavelength e.g. 30000 nm step: step size in cm^-1 e.g. 20 output in cm^-1
Below is the the instruction that describes the task: ### Input: converts wavelength in nm to cm^-1 minimum meaningful step is 20, but 5 is minimum before crashing lowtran short: shortest wavelength e.g. 200 nm long: longest wavelength e.g. 30000 nm step: step size in cm^-1 e.g. 20 output in c...
def get_projected_plot(self, selection, mode='rgb', interpolate_factor=4, circle_size=150, projection_cutoff=0.001, zero_to_efermi=True, ymin=-6., ymax=6., width=None, height=None, vbm_cbm_marker=False, ylabel='E...
Get a :obj:`matplotlib.pyplot` of the projected band structure. If the system is spin polarised and ``mode = 'rgb'`` spin up and spin down bands are differentiated by solid and dashed lines, respectively. For the other modes, spin up and spin down are plotted separately. Args: ...
Below is the the instruction that describes the task: ### Input: Get a :obj:`matplotlib.pyplot` of the projected band structure. If the system is spin polarised and ``mode = 'rgb'`` spin up and spin down bands are differentiated by solid and dashed lines, respectively. For the other modes, ...
def get_converted(self, symbol, units='CAD', system=None, tag=None): """ Uses a Symbol's Dataframe, to build a new Dataframe, with the data converted to the new units Parameters ---------- symbol : str or tuple of the form (Dataframe, str) Str...
Uses a Symbol's Dataframe, to build a new Dataframe, with the data converted to the new units Parameters ---------- symbol : str or tuple of the form (Dataframe, str) String representing a symbol's name, or a dataframe with the data required to be ...
Below is the the instruction that describes the task: ### Input: Uses a Symbol's Dataframe, to build a new Dataframe, with the data converted to the new units Parameters ---------- symbol : str or tuple of the form (Dataframe, str) String representing a sym...
def factorize(self): """ Factorize s.t. CUR = data Updated Values -------------- .C : updated values for C. .U : updated values for U. .R : updated values for R. """ [prow, pcol] = self.sample_probability() self._rid = self.s...
Factorize s.t. CUR = data Updated Values -------------- .C : updated values for C. .U : updated values for U. .R : updated values for R.
Below is the the instruction that describes the task: ### Input: Factorize s.t. CUR = data Updated Values -------------- .C : updated values for C. .U : updated values for U. .R : updated values for R. ### Response: def factorize(self): """ Facto...
def guess_process(query_str, process_map): """ Function to guess processes based on strings that are not available in process_map. If the string has typos and is somewhat similar (50%) to any process available in flowcraft it will print info to the terminal, suggesting the most similar processes ava...
Function to guess processes based on strings that are not available in process_map. If the string has typos and is somewhat similar (50%) to any process available in flowcraft it will print info to the terminal, suggesting the most similar processes available in flowcraft. Parameters ---------- ...
Below is the the instruction that describes the task: ### Input: Function to guess processes based on strings that are not available in process_map. If the string has typos and is somewhat similar (50%) to any process available in flowcraft it will print info to the terminal, suggesting the most similar...
def create_table(cls): """ create_table Manually create a temporary table for model in test data base. :return: """ schema_editor = getattr(connection, 'schema_editor', None) if schema_editor: with schema_editor() as schema_editor: sch...
create_table Manually create a temporary table for model in test data base. :return:
Below is the the instruction that describes the task: ### Input: create_table Manually create a temporary table for model in test data base. :return: ### Response: def create_table(cls): """ create_table Manually create a temporary table for model in test data base. ...
def ungzip(data): """Decompresses data for Content-Encoding: gzip. """ from io import BytesIO import gzip buffer = BytesIO(data) f = gzip.GzipFile(fileobj=buffer) return f.read()
Decompresses data for Content-Encoding: gzip.
Below is the the instruction that describes the task: ### Input: Decompresses data for Content-Encoding: gzip. ### Response: def ungzip(data): """Decompresses data for Content-Encoding: gzip. """ from io import BytesIO import gzip buffer = BytesIO(data) f = gzip.GzipFile(fileobj=buffer) ...
def from_geometry(cls, molecule, do_orders=False, scaling=1.0): """Construct a MolecularGraph object based on interatomic distances All short distances are computed with the binning module and compared with a database of bond lengths. Based on this comparison, bonded atoms are ...
Construct a MolecularGraph object based on interatomic distances All short distances are computed with the binning module and compared with a database of bond lengths. Based on this comparison, bonded atoms are detected. Before marking a pair of atoms A and B as bonded, it ...
Below is the the instruction that describes the task: ### Input: Construct a MolecularGraph object based on interatomic distances All short distances are computed with the binning module and compared with a database of bond lengths. Based on this comparison, bonded atoms are detect...
def request_info(self, request_id): """ Get information of a single pull request. :param request_id: the id of the request :return: """ request_url = "{}pull-request/{}".format(self.create_basic_url(), request_id) ...
Get information of a single pull request. :param request_id: the id of the request :return:
Below is the the instruction that describes the task: ### Input: Get information of a single pull request. :param request_id: the id of the request :return: ### Response: def request_info(self, request_id): """ Get information of a single pull request. :param request_id: the...
def get(self, names_to_get, convert_to_numpy=True): """ Loads the requested variables from the matlab com client. names_to_get can be either a variable name or a list of variable names. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is returned...
Loads the requested variables from the matlab com client. names_to_get can be either a variable name or a list of variable names. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is returned. If convert_to_numpy is true, the method will all arra...
Below is the the instruction that describes the task: ### Input: Loads the requested variables from the matlab com client. names_to_get can be either a variable name or a list of variable names. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is...
async def _start_server(python, port, venv_site_pkgs=None, cwd=None) -> sp.Popen: """ Starts an update server sandboxed in the virtual env, and attempts to read the health endpoint with retries to determine when the server is available. If the number of retries is exceeded, the r...
Starts an update server sandboxed in the virtual env, and attempts to read the health endpoint with retries to determine when the server is available. If the number of retries is exceeded, the returned server process will already be terminated. :return: the server process
Below is the the instruction that describes the task: ### Input: Starts an update server sandboxed in the virtual env, and attempts to read the health endpoint with retries to determine when the server is available. If the number of retries is exceeded, the returned server process will already be termin...
def created_at(self): """ :return: When the document was created :rtype: :py:class:`datetime.datetime` """ if self._created_at: return self._created_at elif not self.abstract: return self.read_meta()._created_at raise EmptyDocumentExceptio...
:return: When the document was created :rtype: :py:class:`datetime.datetime`
Below is the the instruction that describes the task: ### Input: :return: When the document was created :rtype: :py:class:`datetime.datetime` ### Response: def created_at(self): """ :return: When the document was created :rtype: :py:class:`datetime.datetime` """ if s...
def create_url(self, path, params={}, opts={}): """ Create URL with supplied path and `opts` parameters dict. Parameters ---------- path : str opts : dict Dictionary specifying URL parameters. Non-imgix parameters are added to the URL unprocessed....
Create URL with supplied path and `opts` parameters dict. Parameters ---------- path : str opts : dict Dictionary specifying URL parameters. Non-imgix parameters are added to the URL unprocessed. For a complete list of imgix supported parameters, visi...
Below is the the instruction that describes the task: ### Input: Create URL with supplied path and `opts` parameters dict. Parameters ---------- path : str opts : dict Dictionary specifying URL parameters. Non-imgix parameters are added to the URL unprocessed...
def fit_plots(ax,xfit,xraw,yfit,yraw): ''' #==================================================================== plot the fitted results for data fit and refit #==================================================================== ''' global _yfits_ _yfits_ = yfit ax.plot(xfit, yfit) ...
#==================================================================== plot the fitted results for data fit and refit #====================================================================
Below is the the instruction that describes the task: ### Input: #==================================================================== plot the fitted results for data fit and refit #==================================================================== ### Response: def fit_plots(ax,xfit,xraw,yfit,yraw): ...
def query(cls, automation=None, offset=None, limit=None, api=None): """ Query (List) apps. :param automation: Automation id. :param offset: Pagination offset. :param limit: Pagination limit. :param api: Api instance. :return: collection object """ ...
Query (List) apps. :param automation: Automation id. :param offset: Pagination offset. :param limit: Pagination limit. :param api: Api instance. :return: collection object
Below is the the instruction that describes the task: ### Input: Query (List) apps. :param automation: Automation id. :param offset: Pagination offset. :param limit: Pagination limit. :param api: Api instance. :return: collection object ### Response: def query(cls, automatio...
def get_text_alignment(pos): """Return 'verticalalignment'('va') and 'horizontalalignment'('ha') for given 'pos' (position)""" pos = pos.lower() # to make it case insensitive va, ha = None, None if pos == 'nw': va, ha = 'top', 'left' elif pos == 'ne': va, ha = 'top', 'right' elif pos == 'sw': v...
Return 'verticalalignment'('va') and 'horizontalalignment'('ha') for given 'pos' (position)
Below is the the instruction that describes the task: ### Input: Return 'verticalalignment'('va') and 'horizontalalignment'('ha') for given 'pos' (position) ### Response: def get_text_alignment(pos): """Return 'verticalalignment'('va') and 'horizontalalignment'('ha') for given 'pos' (position)""" pos = pos...
def _build_sliced_filepath(filename, slice_count): """ append slice_count to the end of a filename """ root = os.path.splitext(filename)[0] ext = os.path.splitext(filename)[1] new_filepath = ''.join((root, str(slice_count), ext)) return _build_filepath_for_phantomcss(new_filepath)
append slice_count to the end of a filename
Below is the the instruction that describes the task: ### Input: append slice_count to the end of a filename ### Response: def _build_sliced_filepath(filename, slice_count): """ append slice_count to the end of a filename """ root = os.path.splitext(filename)[0] ext = os.path.splitext(filename)[1] ...
def reset_password_view(self, token): """ Verify the password reset token, Prompt for new password, and set the user's password.""" # Verify token if self.call_or_get(current_user.is_authenticated): logout_user() data_items = self.token_manager.verify_token( tok...
Verify the password reset token, Prompt for new password, and set the user's password.
Below is the the instruction that describes the task: ### Input: Verify the password reset token, Prompt for new password, and set the user's password. ### Response: def reset_password_view(self, token): """ Verify the password reset token, Prompt for new password, and set the user's password.""" #...
def is_generator(self, node): """Traverse the tree below node looking for 'yield [expr]'.""" results = {} if self.yield_expr.match(node, results): return True for child in node.children: if child.type not in (syms.funcdef, syms.classdef): if self.i...
Traverse the tree below node looking for 'yield [expr]'.
Below is the the instruction that describes the task: ### Input: Traverse the tree below node looking for 'yield [expr]'. ### Response: def is_generator(self, node): """Traverse the tree below node looking for 'yield [expr]'.""" results = {} if self.yield_expr.match(node, results): ...
def _get_bonds(self, mol): """ Find all the bond in a molcule Args: mol: the molecule. pymatgen Molecule object Returns: List of tuple. Each tuple correspond to a bond represented by the id of the two end atoms. """ num_atoms = len(mo...
Find all the bond in a molcule Args: mol: the molecule. pymatgen Molecule object Returns: List of tuple. Each tuple correspond to a bond represented by the id of the two end atoms.
Below is the the instruction that describes the task: ### Input: Find all the bond in a molcule Args: mol: the molecule. pymatgen Molecule object Returns: List of tuple. Each tuple correspond to a bond represented by the id of the two end atoms. ### Response: d...
def cli_decrypt(context, key): """ Decrypts context.io_manager's stdin and sends that to context.io_manager's stdout. See :py:mod:`swiftly.cli.decrypt` for context usage information. See :py:class:`CLIDecrypt` for more information. """ with context.io_manager.with_stdout() as stdout: ...
Decrypts context.io_manager's stdin and sends that to context.io_manager's stdout. See :py:mod:`swiftly.cli.decrypt` for context usage information. See :py:class:`CLIDecrypt` for more information.
Below is the the instruction that describes the task: ### Input: Decrypts context.io_manager's stdin and sends that to context.io_manager's stdout. See :py:mod:`swiftly.cli.decrypt` for context usage information. See :py:class:`CLIDecrypt` for more information. ### Response: def cli_decrypt(context, ...
def get_django_user(self, username, password=None): """ Get the Django user with the given username, or create one if it doesn't already exist. If `password` is given, then set the user's password to that (regardless of whether the user was created or not). """ try: ...
Get the Django user with the given username, or create one if it doesn't already exist. If `password` is given, then set the user's password to that (regardless of whether the user was created or not).
Below is the the instruction that describes the task: ### Input: Get the Django user with the given username, or create one if it doesn't already exist. If `password` is given, then set the user's password to that (regardless of whether the user was created or not). ### Response: def get_django_use...
def add_document(self, doc_url, data): """ Add the given document to the cache, updating the existing content data if the document is already present :type doc_url: String or Document :param doc_url: the URL of the document, or a Document object :type data: String :param...
Add the given document to the cache, updating the existing content data if the document is already present :type doc_url: String or Document :param doc_url: the URL of the document, or a Document object :type data: String :param data: the document's content data
Below is the the instruction that describes the task: ### Input: Add the given document to the cache, updating the existing content data if the document is already present :type doc_url: String or Document :param doc_url: the URL of the document, or a Document object :type data: Str...
def growth_curve(self, method='best', **method_options): """ Return QMED estimate using best available methodology depending on what catchment attributes are available. ====================== ====================== ================================================================== `meth...
Return QMED estimate using best available methodology depending on what catchment attributes are available. ====================== ====================== ================================================================== `method` `method_options` notes ======================...
Below is the the instruction that describes the task: ### Input: Return QMED estimate using best available methodology depending on what catchment attributes are available. ====================== ====================== ================================================================== `method` ...
def obj_box_coords_rescale(coords=None, shape=None): """Scale down a list of coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1]. Parameters ------------ coords : list of list of 4 ints or None For coordinates of more than one images .e.g.[[x, y, w, h], [x, y, w, ...
Scale down a list of coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1]. Parameters ------------ coords : list of list of 4 ints or None For coordinates of more than one images .e.g.[[x, y, w, h], [x, y, w, h], ...]. shape : list of 2 int or None 【height,...
Below is the the instruction that describes the task: ### Input: Scale down a list of coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1]. Parameters ------------ coords : list of list of 4 ints or None For coordinates of more than one images .e.g.[[x, y, w, h], [...
def build_request_signature(self, saml_request, relay_state, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1): """ Builds the Signature of the SAML Request. :param saml_request: The SAML Request :type saml_request: string :param relay_state: The target URL the user should be r...
Builds the Signature of the SAML Request. :param saml_request: The SAML Request :type saml_request: string :param relay_state: The target URL the user should be redirected to :type relay_state: string :param sign_algorithm: Signature algorithm method :type sign_algorit...
Below is the the instruction that describes the task: ### Input: Builds the Signature of the SAML Request. :param saml_request: The SAML Request :type saml_request: string :param relay_state: The target URL the user should be redirected to :type relay_state: string :param ...
def cli(obj): """List API keys.""" client = obj['client'] if obj['output'] == 'json': r = client.http.get('/keys') click.echo(json.dumps(r['keys'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj['timezone'] headers = { 'id': 'ID', 'key': ...
List API keys.
Below is the the instruction that describes the task: ### Input: List API keys. ### Response: def cli(obj): """List API keys.""" client = obj['client'] if obj['output'] == 'json': r = client.http.get('/keys') click.echo(json.dumps(r['keys'], sort_keys=True, indent=4, ensure_ascii=False...
def _get_request(self, url, headers, params=None): """ Issue a GET request to the specified endpoint with the data provided. :param url: str :pararm headers: dict :param params: dict """ return self._session.get(url, headers=headers, params=params)
Issue a GET request to the specified endpoint with the data provided. :param url: str :pararm headers: dict :param params: dict
Below is the the instruction that describes the task: ### Input: Issue a GET request to the specified endpoint with the data provided. :param url: str :pararm headers: dict :param params: dict ### Response: def _get_request(self, url, headers, params=None): """ Issue a GET ...
def render(template_file, saltenv='base', sls='', argline='', context=None, tmplpath=None, **kws): ''' Render the template_file, passing the functions and grains into the Jinja rendering system. :rtype: string ''' from_str = argline == '-s' if not from_str and argl...
Render the template_file, passing the functions and grains into the Jinja rendering system. :rtype: string
Below is the the instruction that describes the task: ### Input: Render the template_file, passing the functions and grains into the Jinja rendering system. :rtype: string ### Response: def render(template_file, saltenv='base', sls='', argline='', context=None, tmplpath=None, **k...