code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def __hash_and_stat_file(self, path, saltenv='base'):
'''
Common code for hashing and stating files
'''
try:
path = self._check_proto(path)
except MinionError as err:
if not os.path.isfile(path):
log.warning(
'specified ... | Common code for hashing and stating files | Below is the the instruction that describes the task:
### Input:
Common code for hashing and stating files
### Response:
def __hash_and_stat_file(self, path, saltenv='base'):
'''
Common code for hashing and stating files
'''
try:
path = self._check_proto(path)
ex... |
def _lt_from_ge(self, other):
"""Return a < b. Computed by @total_ordering from (not a >= b)."""
op_result = self.__ge__(other)
if op_result is NotImplemented:
return NotImplemented
return not op_result | Return a < b. Computed by @total_ordering from (not a >= b). | Below is the the instruction that describes the task:
### Input:
Return a < b. Computed by @total_ordering from (not a >= b).
### Response:
def _lt_from_ge(self, other):
"""Return a < b. Computed by @total_ordering from (not a >= b)."""
op_result = self.__ge__(other)
if op_result is NotImplemented:
... |
def _decompose_(self, qubits):
"""A quantum circuit (QFT_inv) with the following structure.
---H--@-------@--------@----------------------------------------------
| | |
------@^-0.5--+--------+---------H--@-------@-------------------------
| ... | A quantum circuit (QFT_inv) with the following structure.
---H--@-------@--------@----------------------------------------------
| | |
------@^-0.5--+--------+---------H--@-------@-------------------------
| | | |
--------... | Below is the the instruction that describes the task:
### Input:
A quantum circuit (QFT_inv) with the following structure.
---H--@-------@--------@----------------------------------------------
| | |
------@^-0.5--+--------+---------H--@-------@-------------------------
... |
def _parse_substitutions(self, element):
"""
Parse word substitutions
:param element: The XML Element object
:type element: etree._Element
"""
subs = element.findall('sub')
for sub in subs:
self.agentml.set_substitution(attribute(sub, 'word'), sub.te... | Parse word substitutions
:param element: The XML Element object
:type element: etree._Element | Below is the the instruction that describes the task:
### Input:
Parse word substitutions
:param element: The XML Element object
:type element: etree._Element
### Response:
def _parse_substitutions(self, element):
"""
Parse word substitutions
:param element: The XML Element... |
def should_build_with_cython(previous_cython_version, is_release):
"""
Returns the previously used Cython version (or 'unknown' if not
previously built) if Cython should be used to build extension modules from
pyx files.
"""
# Only build with Cython if, of course, Cython is installed, we're in ... | Returns the previously used Cython version (or 'unknown' if not
previously built) if Cython should be used to build extension modules from
pyx files. | Below is the the instruction that describes the task:
### Input:
Returns the previously used Cython version (or 'unknown' if not
previously built) if Cython should be used to build extension modules from
pyx files.
### Response:
def should_build_with_cython(previous_cython_version, is_release):
"""
... |
def readsGenerator(self, request):
"""
Returns a generator over the (read, nextPageToken) pairs defined
by the specified request
"""
if not request.reference_id:
raise exceptions.UnmappedReadsNotSupported()
if len(request.read_group_ids) < 1:
raise... | Returns a generator over the (read, nextPageToken) pairs defined
by the specified request | Below is the the instruction that describes the task:
### Input:
Returns a generator over the (read, nextPageToken) pairs defined
by the specified request
### Response:
def readsGenerator(self, request):
"""
Returns a generator over the (read, nextPageToken) pairs defined
by the spe... |
def tr(self, args, color=None):
"""
Method to print ASCII patterns to terminal
"""
width = self._term_size()[1]
if not args:
if color is not None:
print(self._echo("#" * width, color))
else:
print(self._echo("#" * width, "gr... | Method to print ASCII patterns to terminal | Below is the the instruction that describes the task:
### Input:
Method to print ASCII patterns to terminal
### Response:
def tr(self, args, color=None):
"""
Method to print ASCII patterns to terminal
"""
width = self._term_size()[1]
if not args:
if color is not ... |
def query_string_attribute(self, target, display_mask, attr):
"""Return the value of a string attribute"""
reply = NVCtrlQueryStringAttributeReplyRequest(display=self.display,
opcode=self.display.get_extension_major(extname),
... | Return the value of a string attribute | Below is the the instruction that describes the task:
### Input:
Return the value of a string attribute
### Response:
def query_string_attribute(self, target, display_mask, attr):
"""Return the value of a string attribute"""
reply = NVCtrlQueryStringAttributeReplyRequest(display=self.display,
... |
def create_collection(self, name="collection", position=None, **kwargs):
"""Create a new child colleciton.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
... | Create a new child colleciton.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
Additional arguments to child collection instantiation.
Returns
... | Below is the the instruction that describes the task:
### Input:
Create a new child colleciton.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
Addit... |
def connect(self, packet=None):
"""Connect to the server.
:param packet: RTMPPacket, this packet will be sent instead
of the regular "connect" packet.
Raises :exc:`RTMPError` if the connect attempt fails.
"""
if isinstance(packet, RTMPPacket):
... | Connect to the server.
:param packet: RTMPPacket, this packet will be sent instead
of the regular "connect" packet.
Raises :exc:`RTMPError` if the connect attempt fails. | Below is the the instruction that describes the task:
### Input:
Connect to the server.
:param packet: RTMPPacket, this packet will be sent instead
of the regular "connect" packet.
Raises :exc:`RTMPError` if the connect attempt fails.
### Response:
def connect(self, packet=... |
def _handle_tag_text(self, text):
"""Handle regular *text* inside of an HTML open tag."""
next = self._read(1)
if not self._can_recurse() or text not in self.MARKERS:
self._emit_text(text)
elif text == next == "{":
self._parse_template_or_argument()
elif t... | Handle regular *text* inside of an HTML open tag. | Below is the the instruction that describes the task:
### Input:
Handle regular *text* inside of an HTML open tag.
### Response:
def _handle_tag_text(self, text):
"""Handle regular *text* inside of an HTML open tag."""
next = self._read(1)
if not self._can_recurse() or text not in self.MARK... |
def _gen_3spec(op, path, xattr=False):
"""
Returns a Spec tuple suitable for passing to the underlying C extension.
This variant is called for operations that lack an input value.
:param str path: The path to fetch
:param bool xattr: Whether this is an extended attribute
:return: a spec suitabl... | Returns a Spec tuple suitable for passing to the underlying C extension.
This variant is called for operations that lack an input value.
:param str path: The path to fetch
:param bool xattr: Whether this is an extended attribute
:return: a spec suitable for passing to the underlying C extension | Below is the the instruction that describes the task:
### Input:
Returns a Spec tuple suitable for passing to the underlying C extension.
This variant is called for operations that lack an input value.
:param str path: The path to fetch
:param bool xattr: Whether this is an extended attribute
:retu... |
def _get(pseudodict, key, single=True):
"""Helper method for getting values from "multi-dict"s"""
matches = [item[1] for item in pseudodict if item[0] == key]
if single:
return matches[0]
else:
return matches | Helper method for getting values from "multi-dict"s | Below is the the instruction that describes the task:
### Input:
Helper method for getting values from "multi-dict"s
### Response:
def _get(pseudodict, key, single=True):
"""Helper method for getting values from "multi-dict"s"""
matches = [item[1] for item in pseudodict if item[0] == key]
if single:
... |
def tobytes(s, encoding='ascii'):
""" Convert string s to the 'bytes' type, in all Pythons, even
back before Python 2.6. What 'str' means varies by PY3K or not.
In Pythons before 3.0, this is technically the same as the str type
in terms of the character data in memory. """
# NOTE: after we abandon... | Convert string s to the 'bytes' type, in all Pythons, even
back before Python 2.6. What 'str' means varies by PY3K or not.
In Pythons before 3.0, this is technically the same as the str type
in terms of the character data in memory. | Below is the the instruction that describes the task:
### Input:
Convert string s to the 'bytes' type, in all Pythons, even
back before Python 2.6. What 'str' means varies by PY3K or not.
In Pythons before 3.0, this is technically the same as the str type
in terms of the character data in memory.
### R... |
def setup_deploy_key(keypath='github_deploy_key', key_ext='.enc', env_name='DOCTR_DEPLOY_ENCRYPTION_KEY'):
"""
Decrypts the deploy key and configures it with ssh
The key is assumed to be encrypted as keypath + key_ext, and the
encryption key is assumed to be set in the environment variable
``env_na... | Decrypts the deploy key and configures it with ssh
The key is assumed to be encrypted as keypath + key_ext, and the
encryption key is assumed to be set in the environment variable
``env_name``. If ``env_name`` is not set, it falls back to
``DOCTR_DEPLOY_ENCRYPTION_KEY`` for backwards compatibility.
... | Below is the the instruction that describes the task:
### Input:
Decrypts the deploy key and configures it with ssh
The key is assumed to be encrypted as keypath + key_ext, and the
encryption key is assumed to be set in the environment variable
``env_name``. If ``env_name`` is not set, it falls back to... |
def download_release(download_file, release=None):
"""Downloads the "go-basic.obo" file for the specified release."""
if release is None:
release = get_latest_release()
url = 'http://viewvc.geneontology.org/viewvc/GO-SVN/ontology-releases/%s/go-basic.obo' % release
#download_file = 'go-basic_%s.... | Downloads the "go-basic.obo" file for the specified release. | Below is the the instruction that describes the task:
### Input:
Downloads the "go-basic.obo" file for the specified release.
### Response:
def download_release(download_file, release=None):
"""Downloads the "go-basic.obo" file for the specified release."""
if release is None:
release = get_latest_... |
def plot_ppc(
data,
kind="density",
alpha=None,
mean=True,
figsize=None,
textsize=None,
data_pairs=None,
var_names=None,
coords=None,
flatten=None,
flatten_pp=None,
num_pp_samples=None,
random_seed=None,
jitter=None,
animated=False,
animation_kwargs=None,
... | Plot for posterior predictive checks.
Parameters
----------
data : az.InferenceData object
InferenceData object containing the observed and posterior
predictive data.
kind : str
Type of plot to display (density, cumulative, or scatter). Defaults to density.
alpha : float
... | Below is the the instruction that describes the task:
### Input:
Plot for posterior predictive checks.
Parameters
----------
data : az.InferenceData object
InferenceData object containing the observed and posterior
predictive data.
kind : str
Type of plot to display (density... |
def greater_equal(lhs, rhs):
"""Returns the result of element-wise **greater than or equal to** (>=) comparison
operation with broadcasting.
For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs,
otherwise return 0(false).
Equivalent to ``lhs >= rhs`` and `... | Returns the result of element-wise **greater than or equal to** (>=) comparison
operation with broadcasting.
For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs,
otherwise return 0(false).
Equivalent to ``lhs >= rhs`` and ``mx.nd.broadcast_greater_equal(lhs, ... | Below is the the instruction that describes the task:
### Input:
Returns the result of element-wise **greater than or equal to** (>=) comparison
operation with broadcasting.
For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs,
otherwise return 0(false).
E... |
def get_peak_number(self, sample):
"""
Counts number of peaks from a sample's peak file.
:param pipelines.Sample sample: Sample object with "peaks" attribute.
"""
proc = subprocess.Popen(["wc", "-l", sample.peaks], stdout=subprocess.PIPE)
out, err = proc.communicate()
... | Counts number of peaks from a sample's peak file.
:param pipelines.Sample sample: Sample object with "peaks" attribute. | Below is the the instruction that describes the task:
### Input:
Counts number of peaks from a sample's peak file.
:param pipelines.Sample sample: Sample object with "peaks" attribute.
### Response:
def get_peak_number(self, sample):
"""
Counts number of peaks from a sample's peak file.
... |
def DEFINE_choice(self, name, default, choices, help, constant=False):
"""A helper for defining choice string options."""
self.AddOption(
type_info.Choice(
name=name, default=default, choices=choices, description=help),
constant=constant) | A helper for defining choice string options. | Below is the the instruction that describes the task:
### Input:
A helper for defining choice string options.
### Response:
def DEFINE_choice(self, name, default, choices, help, constant=False):
"""A helper for defining choice string options."""
self.AddOption(
type_info.Choice(
name=na... |
def make_matrix(version, reserve_regions=True, add_timing=True):
"""\
Creates a matrix of the provided `size` (w x h) initialized with the
(illegal) value 0x2.
The "timing pattern" is already added to the matrix and the version
and format areas are initialized with 0x0.
:param int version: The... | \
Creates a matrix of the provided `size` (w x h) initialized with the
(illegal) value 0x2.
The "timing pattern" is already added to the matrix and the version
and format areas are initialized with 0x0.
:param int version: The (Micro) QR Code version
:rtype: tuple of bytearrays | Below is the the instruction that describes the task:
### Input:
\
Creates a matrix of the provided `size` (w x h) initialized with the
(illegal) value 0x2.
The "timing pattern" is already added to the matrix and the version
and format areas are initialized with 0x0.
:param int version: The (M... |
def _translate_dst_oprnd(self, operand):
"""Translate destination operand to a SMT expression.
"""
if isinstance(operand, ReilRegisterOperand):
return self._translate_dst_register_oprnd(operand)
else:
raise Exception("Invalid operand type") | Translate destination operand to a SMT expression. | Below is the the instruction that describes the task:
### Input:
Translate destination operand to a SMT expression.
### Response:
def _translate_dst_oprnd(self, operand):
"""Translate destination operand to a SMT expression.
"""
if isinstance(operand, ReilRegisterOperand):
retur... |
def separate_groups(groups, key, total):
"""Separate the group into overloaded and under-loaded groups.
The revised over-loaded groups increases the choice space for future
selection of most suitable group based on search criteria.
For example:
Given the groups (a:4, b:4, c:3, d:2) where the numbe... | Separate the group into overloaded and under-loaded groups.
The revised over-loaded groups increases the choice space for future
selection of most suitable group based on search criteria.
For example:
Given the groups (a:4, b:4, c:3, d:2) where the number represents the number
of elements for each... | Below is the the instruction that describes the task:
### Input:
Separate the group into overloaded and under-loaded groups.
The revised over-loaded groups increases the choice space for future
selection of most suitable group based on search criteria.
For example:
Given the groups (a:4, b:4, c:3,... |
def split_by_commas(maybe_s: str) -> Tuple[str, ...]:
"""Split a string by commas, but allow escaped commas.
- If maybe_s is falsey, returns an empty tuple
- Ignore backslashed commas
"""
if not maybe_s:
return ()
parts: List[str] = []
split_by_backslash = maybe_s.split(r'\,')
fo... | Split a string by commas, but allow escaped commas.
- If maybe_s is falsey, returns an empty tuple
- Ignore backslashed commas | Below is the the instruction that describes the task:
### Input:
Split a string by commas, but allow escaped commas.
- If maybe_s is falsey, returns an empty tuple
- Ignore backslashed commas
### Response:
def split_by_commas(maybe_s: str) -> Tuple[str, ...]:
"""Split a string by commas, but allow esca... |
def combine_first(self, other):
"""
Update null elements with value in the same location in `other`.
Combine two DataFrame objects by filling null values in one DataFrame
with non-null values from other DataFrame. The row and column indexes
of the resulting DataFrame will be the... | Update null elements with value in the same location in `other`.
Combine two DataFrame objects by filling null values in one DataFrame
with non-null values from other DataFrame. The row and column indexes
of the resulting DataFrame will be the union of the two.
Parameters
-----... | Below is the the instruction that describes the task:
### Input:
Update null elements with value in the same location in `other`.
Combine two DataFrame objects by filling null values in one DataFrame
with non-null values from other DataFrame. The row and column indexes
of the resulting Data... |
def is_valid(self):
"""
Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
... | Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
-------
bool
i... | Below is the the instruction that describes the task:
### Input:
Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520... |
def topic_detail(request, slug):
"""
A detail view of a Topic
Templates:
:template:`faq/topic_detail.html`
Context:
topic
An :model:`faq.Topic` object.
question_list
A list of all published :model:`faq.Question` objects that relate
to the give... | A detail view of a Topic
Templates:
:template:`faq/topic_detail.html`
Context:
topic
An :model:`faq.Topic` object.
question_list
A list of all published :model:`faq.Question` objects that relate
to the given :model:`faq.Topic`. | Below is the the instruction that describes the task:
### Input:
A detail view of a Topic
Templates:
:template:`faq/topic_detail.html`
Context:
topic
An :model:`faq.Topic` object.
question_list
A list of all published :model:`faq.Question` objects that relate... |
def update_selection(self):
"""
Convenience function update display (figures, text boxes and
statistics windows) with a new selection of specimen
"""
self.clear_boxes()
# commented out to allow propogation of higher level viewing state
self.clear_high_level_pars(... | Convenience function update display (figures, text boxes and
statistics windows) with a new selection of specimen | Below is the the instruction that describes the task:
### Input:
Convenience function update display (figures, text boxes and
statistics windows) with a new selection of specimen
### Response:
def update_selection(self):
"""
Convenience function update display (figures, text boxes and
... |
def provision(self, instance_id: str, service_details: ProvisionDetails, async_allowed: bool) -> ProvisionedServiceSpec:
"""Provision the new instance
see openbrokerapi documentation
Returns:
ProvisionedServiceSpec
"""
if service_details.pla... | Provision the new instance
see openbrokerapi documentation
Returns:
ProvisionedServiceSpec | Below is the the instruction that describes the task:
### Input:
Provision the new instance
see openbrokerapi documentation
Returns:
ProvisionedServiceSpec
### Response:
def provision(self, instance_id: str, service_details: ProvisionDetails, async_allowed: bool) -> Pr... |
def dot_solve(self, y):
r"""
Compute the inner product of a vector with the inverse of the
covariance matrix applied to itself:
.. math::
y\,K^{-1}\,y
Args:
y (ndarray[nsamples]): The vector :math:`y`.
"""
return np.dot(y.T, cho_solve(s... | r"""
Compute the inner product of a vector with the inverse of the
covariance matrix applied to itself:
.. math::
y\,K^{-1}\,y
Args:
y (ndarray[nsamples]): The vector :math:`y`. | Below is the the instruction that describes the task:
### Input:
r"""
Compute the inner product of a vector with the inverse of the
covariance matrix applied to itself:
.. math::
y\,K^{-1}\,y
Args:
y (ndarray[nsamples]): The vector :math:`y`.
### Response: ... |
def _extract_services_list_helper(services):
"""Extract a OrderedDict of {service: [ports]} of the supplied services
for use by the other functions.
The services object can either be:
- None : no services were passed (an empty dict is returned)
- a list of strings
- A dictionary (optional... | Extract a OrderedDict of {service: [ports]} of the supplied services
for use by the other functions.
The services object can either be:
- None : no services were passed (an empty dict is returned)
- a list of strings
- A dictionary (optionally OrderedDict) {service_name: {'service': ..}}
... | Below is the the instruction that describes the task:
### Input:
Extract a OrderedDict of {service: [ports]} of the supplied services
for use by the other functions.
The services object can either be:
- None : no services were passed (an empty dict is returned)
- a list of strings
- A dic... |
def monitors(self, **kwargs):
'''Return expressions that should be computed to monitor training.
Returns
-------
monitors : list of (name, expression) pairs
A list of named monitor expressions to compute for this network.
'''
monitors = super(Classifier, self... | Return expressions that should be computed to monitor training.
Returns
-------
monitors : list of (name, expression) pairs
A list of named monitor expressions to compute for this network. | Below is the the instruction that describes the task:
### Input:
Return expressions that should be computed to monitor training.
Returns
-------
monitors : list of (name, expression) pairs
A list of named monitor expressions to compute for this network.
### Response:
def monito... |
def blink(self, state=True):
"""
Starts or stops the blinking state for this button. This only
works for when the toolbutton is in Shadowed or Colored mode.
:param state | <bool>
:return <bool> | success
"""
if self._blinking =... | Starts or stops the blinking state for this button. This only
works for when the toolbutton is in Shadowed or Colored mode.
:param state | <bool>
:return <bool> | success | Below is the the instruction that describes the task:
### Input:
Starts or stops the blinking state for this button. This only
works for when the toolbutton is in Shadowed or Colored mode.
:param state | <bool>
:return <bool> | success
### Response:
def blin... |
def forward(self, data_batch, is_train=None):
"""Forward computation. Here we do nothing but to keep a reference to
the scores and the labels so that we can do backward computation.
Parameters
----------
data_batch : DataBatch
Could be anything with similar API imple... | Forward computation. Here we do nothing but to keep a reference to
the scores and the labels so that we can do backward computation.
Parameters
----------
data_batch : DataBatch
Could be anything with similar API implemented.
is_train : bool
Default is ``... | Below is the the instruction that describes the task:
### Input:
Forward computation. Here we do nothing but to keep a reference to
the scores and the labels so that we can do backward computation.
Parameters
----------
data_batch : DataBatch
Could be anything with simil... |
def get_grouped(self, go_ntsets, go_all, gosubdag, **kws):
"""Get Grouped object."""
kws_grpd = {k:v for k, v in kws.items() if k in Grouped.kws_dict}
kws_grpd['go2nt'] = self._init_go2ntpresent(go_ntsets, go_all, gosubdag)
return Grouped(gosubdag, self.godag.version, **kws_grpd) | Get Grouped object. | Below is the the instruction that describes the task:
### Input:
Get Grouped object.
### Response:
def get_grouped(self, go_ntsets, go_all, gosubdag, **kws):
"""Get Grouped object."""
kws_grpd = {k:v for k, v in kws.items() if k in Grouped.kws_dict}
kws_grpd['go2nt'] = self._init_go2ntprese... |
def _delete(self, url):
"""Wrapper around request.delete() to use the API prefix. Returns a JSON response."""
req = self._session.delete(self._api_prefix + url)
return self._action(req) | Wrapper around request.delete() to use the API prefix. Returns a JSON response. | Below is the the instruction that describes the task:
### Input:
Wrapper around request.delete() to use the API prefix. Returns a JSON response.
### Response:
def _delete(self, url):
"""Wrapper around request.delete() to use the API prefix. Returns a JSON response."""
req = self._session.delete(sel... |
def rank_width(self):
"""
Returns the width of each rank in the graph. #TODO
"""
rank_width = defaultdict(int)
node_rank = self.node_rank()
for rank in node_rank.values():
rank_width[rank] += 1
return dict(rank_width) | Returns the width of each rank in the graph. #TODO | Below is the the instruction that describes the task:
### Input:
Returns the width of each rank in the graph. #TODO
### Response:
def rank_width(self):
"""
Returns the width of each rank in the graph. #TODO
"""
rank_width = defaultdict(int)
node_rank = self.node_ran... |
def _build_connstr(host, port, bucket):
"""
Converts a 1.x host:port specification to a connection string
"""
hostlist = []
if isinstance(host, (tuple, list)):
for curhost in host:
if isinstance(curhost, (list, tuple)):
hostlist.append(_fmthost(*curhost))
... | Converts a 1.x host:port specification to a connection string | Below is the the instruction that describes the task:
### Input:
Converts a 1.x host:port specification to a connection string
### Response:
def _build_connstr(host, port, bucket):
"""
Converts a 1.x host:port specification to a connection string
"""
hostlist = []
if isinstance(host, (tuple, li... |
def get_manylinux_wheel_url(self, package_name, package_version):
"""
For a given package name, returns a link to the download URL,
else returns None.
Related: https://github.com/Miserlou/Zappa/issues/398
Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b5688... | For a given package name, returns a link to the download URL,
else returns None.
Related: https://github.com/Miserlou/Zappa/issues/398
Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b56880adbae
This function downloads metadata JSON of `package_name` from Pypi
... | Below is the the instruction that describes the task:
### Input:
For a given package name, returns a link to the download URL,
else returns None.
Related: https://github.com/Miserlou/Zappa/issues/398
Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b56880adbae
T... |
def set_version(context: Context, version=None, bump=False):
"""
Updates the version of MTP-common
"""
if bump and version:
raise TaskError('You cannot bump and set a specific version')
if bump:
from mtp_common import VERSION
version = list(VERSION)
version[-1] += 1
... | Updates the version of MTP-common | Below is the the instruction that describes the task:
### Input:
Updates the version of MTP-common
### Response:
def set_version(context: Context, version=None, bump=False):
"""
Updates the version of MTP-common
"""
if bump and version:
raise TaskError('You cannot bump and set a specific ve... |
def _convert_date_to_dict(field_date):
"""
Convert native python ``datetime.date`` object to a format supported by the API
"""
return {DAY: field_date.day, MONTH: field_date.month, YEAR: field_date.year} | Convert native python ``datetime.date`` object to a format supported by the API | Below is the the instruction that describes the task:
### Input:
Convert native python ``datetime.date`` object to a format supported by the API
### Response:
def _convert_date_to_dict(field_date):
"""
Convert native python ``datetime.date`` object to a format supported by the API
"""
... |
def union(self, other, rename=False):
'''
Union/add two topologies together to form a larger topology.
If rename is False, the method assumes that node names
don't clash (i.e., you've called addNodeLabelPrefix or
you've explicitly chosen names to avoid clashes).
If r... | Union/add two topologies together to form a larger topology.
If rename is False, the method assumes that node names
don't clash (i.e., you've called addNodeLabelPrefix or
you've explicitly chosen names to avoid clashes).
If rename is True, nodes/links are relabeled such that the
... | Below is the the instruction that describes the task:
### Input:
Union/add two topologies together to form a larger topology.
If rename is False, the method assumes that node names
don't clash (i.e., you've called addNodeLabelPrefix or
you've explicitly chosen names to avoid clashes).
... |
def check_repository_existence(params):
"""Check repository existence.
:param argparse.Namespace params: parameters
"""
repodir = os.path.join(params.outdir, params.name)
if os.path.isdir(repodir):
raise Conflict(
'Package repository "{0}" has already exists.'.format(repodir)) | Check repository existence.
:param argparse.Namespace params: parameters | Below is the the instruction that describes the task:
### Input:
Check repository existence.
:param argparse.Namespace params: parameters
### Response:
def check_repository_existence(params):
"""Check repository existence.
:param argparse.Namespace params: parameters
"""
repodir = os.path.joi... |
def egress(self, envelope, http_headers, operation, binding_options):
"""Overriding the egress function to set our headers.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation instance.
binding_options: An... | Overriding the egress function to set our headers.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation instance.
binding_options: An options dict for the SOAP binding.
Returns:
A tuple of the envelo... | Below is the the instruction that describes the task:
### Input:
Overriding the egress function to set our headers.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation instance.
binding_options: An options... |
def validate_url(value):
""" Validate url. """
if not re.match(VIMEO_URL_RE, value) and not re.match(YOUTUBE_URL_RE, value):
raise ValidationError('Invalid URL - only Youtube, Vimeo can be used.') | Validate url. | Below is the the instruction that describes the task:
### Input:
Validate url.
### Response:
def validate_url(value):
""" Validate url. """
if not re.match(VIMEO_URL_RE, value) and not re.match(YOUTUBE_URL_RE, value):
raise ValidationError('Invalid URL - only Youtube, Vimeo can be used.') |
def does_not_contain_duplicates(self):
"""Asserts that val is iterable and does not contain any duplicate items."""
try:
if len(self.val) == len(set(self.val)):
return self
except TypeError:
raise TypeError('val is not iterable')
self._err('Expecte... | Asserts that val is iterable and does not contain any duplicate items. | Below is the the instruction that describes the task:
### Input:
Asserts that val is iterable and does not contain any duplicate items.
### Response:
def does_not_contain_duplicates(self):
"""Asserts that val is iterable and does not contain any duplicate items."""
try:
if len(self.val)... |
def flagants(self, threshold=50):
""" Flags solutions with amplitude more than threshold larger than median.
"""
# identify very low gain amps not already flagged
badsols = n.where( (n.median(self.amp)/self.amp > threshold) & (self.flagged == False))[0]
if len(badsols):
... | Flags solutions with amplitude more than threshold larger than median. | Below is the the instruction that describes the task:
### Input:
Flags solutions with amplitude more than threshold larger than median.
### Response:
def flagants(self, threshold=50):
""" Flags solutions with amplitude more than threshold larger than median.
"""
# identify very low gain am... |
def set_log_type_name(self, logType, name):
"""
Set a logtype name.
:Parameters:
#. logType (string): A defined logging type.
#. name (string): The logtype new name.
"""
assert logType in self.__logTypeStdoutFlags.keys(), "logType '%s' not defined" %logType... | Set a logtype name.
:Parameters:
#. logType (string): A defined logging type.
#. name (string): The logtype new name. | Below is the the instruction that describes the task:
### Input:
Set a logtype name.
:Parameters:
#. logType (string): A defined logging type.
#. name (string): The logtype new name.
### Response:
def set_log_type_name(self, logType, name):
"""
Set a logtype name.
... |
def write(self, symbol, item, metadata=None, chunker=DateChunker(), audit=None, **kwargs):
"""
Writes data from item to symbol in the database
Parameters
----------
symbol: str
the symbol that will be used to reference the written data
item: Dataframe or Seri... | Writes data from item to symbol in the database
Parameters
----------
symbol: str
the symbol that will be used to reference the written data
item: Dataframe or Series
the data to write the database
metadata: ?
optional per symbol metadata
... | Below is the the instruction that describes the task:
### Input:
Writes data from item to symbol in the database
Parameters
----------
symbol: str
the symbol that will be used to reference the written data
item: Dataframe or Series
the data to write the datab... |
def clean(self):
"""
Clean form fields prior to database entry.
In this case, the major cleaning operation is substituting a None value for a blank
value in the Catalog field.
"""
cleaned_data = super(EnterpriseCustomerAdminForm, self).clean()
if 'catalog' in cle... | Clean form fields prior to database entry.
In this case, the major cleaning operation is substituting a None value for a blank
value in the Catalog field. | Below is the the instruction that describes the task:
### Input:
Clean form fields prior to database entry.
In this case, the major cleaning operation is substituting a None value for a blank
value in the Catalog field.
### Response:
def clean(self):
"""
Clean form fields prior to ... |
def flatten_check(out:Tensor, targ:Tensor) -> Tensor:
"Check that `out` and `targ` have the same number of elements and flatten them."
out,targ = out.contiguous().view(-1),targ.contiguous().view(-1)
assert len(out) == len(targ), f"Expected output and target to have the same number of elements but got {len(o... | Check that `out` and `targ` have the same number of elements and flatten them. | Below is the the instruction that describes the task:
### Input:
Check that `out` and `targ` have the same number of elements and flatten them.
### Response:
def flatten_check(out:Tensor, targ:Tensor) -> Tensor:
"Check that `out` and `targ` have the same number of elements and flatten them."
out,targ = out... |
def complete(self):
"""
Called by the associated task to let us know that its state
has changed (e.g. from FUTURE to COMPLETED.)
"""
self._set_state(self.COMPLETED)
return self.task_spec._on_complete(self) | Called by the associated task to let us know that its state
has changed (e.g. from FUTURE to COMPLETED.) | Below is the the instruction that describes the task:
### Input:
Called by the associated task to let us know that its state
has changed (e.g. from FUTURE to COMPLETED.)
### Response:
def complete(self):
"""
Called by the associated task to let us know that its state
has changed (e.... |
def split_on_condition(seq, condition):
"""Split a sequence into two iterables without looping twice"""
l1, l2 = tee((condition(item), item) for item in seq)
return (i for p, i in l1 if p), (i for p, i in l2 if not p) | Split a sequence into two iterables without looping twice | Below is the the instruction that describes the task:
### Input:
Split a sequence into two iterables without looping twice
### Response:
def split_on_condition(seq, condition):
"""Split a sequence into two iterables without looping twice"""
l1, l2 = tee((condition(item), item) for item in seq)
return (... |
def parameter_values(self):
"""
Parameter values for this inspection situation. This correlate to
the the situation_context.
:rtype: list(SituationParameterValue)
"""
for param in self.data.get('parameter_values', []):
cache = ElementCache(data=self.m... | Parameter values for this inspection situation. This correlate to
the the situation_context.
:rtype: list(SituationParameterValue) | Below is the the instruction that describes the task:
### Input:
Parameter values for this inspection situation. This correlate to
the the situation_context.
:rtype: list(SituationParameterValue)
### Response:
def parameter_values(self):
"""
Parameter values for this inspec... |
def build_standard_field(self, field_name, model_field):
"""
Create regular model fields.
"""
field_mapping = ClassLookupDict(self.serializer_field_mapping)
field_class = field_mapping[model_field]
field_kwargs = get_field_kwargs(field_name, model_field)
if 'cho... | Create regular model fields. | Below is the the instruction that describes the task:
### Input:
Create regular model fields.
### Response:
def build_standard_field(self, field_name, model_field):
"""
Create regular model fields.
"""
field_mapping = ClassLookupDict(self.serializer_field_mapping)
field_cla... |
def pop_header(self, hkey, ignore_error=False):
"""
This will remove and return the specified header value.
Parameters
----------
hkey
Header key you wish to pop.
You can specify either a key string or an index.
ignore_error=False
Whe... | This will remove and return the specified header value.
Parameters
----------
hkey
Header key you wish to pop.
You can specify either a key string or an index.
ignore_error=False
Whether to quietly ignore any errors (i.e., hkey not found). | Below is the the instruction that describes the task:
### Input:
This will remove and return the specified header value.
Parameters
----------
hkey
Header key you wish to pop.
You can specify either a key string or an index.
ignore_error=False
Wh... |
def messages(self):
"""Return remaining messages before limiting."""
return int(math.floor(((self.limit.unit_value - self.level) /
self.limit.unit_value) * self.limit.value)) | Return remaining messages before limiting. | Below is the the instruction that describes the task:
### Input:
Return remaining messages before limiting.
### Response:
def messages(self):
"""Return remaining messages before limiting."""
return int(math.floor(((self.limit.unit_value - self.level) /
self.limit.uni... |
def _check_buffer(self, data, ctype):
"""Convert buffer to cdata and check for valid size."""
assert ctype in _ffi_types.values()
if not isinstance(data, bytes):
data = _ffi.from_buffer(data)
frames, remainder = divmod(len(data),
self.channe... | Convert buffer to cdata and check for valid size. | Below is the the instruction that describes the task:
### Input:
Convert buffer to cdata and check for valid size.
### Response:
def _check_buffer(self, data, ctype):
"""Convert buffer to cdata and check for valid size."""
assert ctype in _ffi_types.values()
if not isinstance(data, bytes):
... |
def realms(self, details=False):
"""Return the realms / satellites configuration
Returns an object containing the hierarchical realms configuration with the main
information about each realm:
{
All: {
satellites: {
pollers: [
... | Return the realms / satellites configuration
Returns an object containing the hierarchical realms configuration with the main
information about each realm:
{
All: {
satellites: {
pollers: [
"poller-master"
... | Below is the the instruction that describes the task:
### Input:
Return the realms / satellites configuration
Returns an object containing the hierarchical realms configuration with the main
information about each realm:
{
All: {
satellites: {
... |
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
type = msg.get_type()
master = self.master
# add some status fields
if type in [ 'RC_CHANNELS' ]:
ilock = self.get_rc_input(msg, self.interlock_channel)
if ilock <= 0:
... | handle an incoming mavlink packet | Below is the the instruction that describes the task:
### Input:
handle an incoming mavlink packet
### Response:
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
type = msg.get_type()
master = self.master
# add some status fields
if type in [ 'RC_CHAN... |
def listBlockSummaries(self, block_name="", dataset="", detail=False):
"""
API that returns summary information like total size and total number of events in a dataset or a list of blocks
:param block_name: list block summaries for block_name(s)
:type block_name: str, list
:para... | API that returns summary information like total size and total number of events in a dataset or a list of blocks
:param block_name: list block summaries for block_name(s)
:type block_name: str, list
:param dataset: list block summaries for all blocks in dataset
:type dataset: str
... | Below is the the instruction that describes the task:
### Input:
API that returns summary information like total size and total number of events in a dataset or a list of blocks
:param block_name: list block summaries for block_name(s)
:type block_name: str, list
:param dataset: list block ... |
def _compose_restart(services):
"""Well, this is annoying. Compose 1.2 shipped with the
restart functionality fucking broken, so we can't set a faster
timeout than 10 seconds (which is way too long) using Compose.
We are therefore resigned to trying to hack this together
ourselves. Lame.
Releva... | Well, this is annoying. Compose 1.2 shipped with the
restart functionality fucking broken, so we can't set a faster
timeout than 10 seconds (which is way too long) using Compose.
We are therefore resigned to trying to hack this together
ourselves. Lame.
Relevant fix which will make it into the next... | Below is the the instruction that describes the task:
### Input:
Well, this is annoying. Compose 1.2 shipped with the
restart functionality fucking broken, so we can't set a faster
timeout than 10 seconds (which is way too long) using Compose.
We are therefore resigned to trying to hack this together
... |
def launch_cif_clean(cif_filter, cif_select, group_cif_raw, group_cif_clean, group_structure, group_workchain, node,
max_entries, skip_check, parse_engine, daemon):
"""Run the `CifCleanWorkChain` on the entries in a group with raw imported CifData nodes.
It will use the `cif_filter` and `cif_select` script... | Run the `CifCleanWorkChain` on the entries in a group with raw imported CifData nodes.
It will use the `cif_filter` and `cif_select` scripts of `cod-tools` to clean the input cif file. Additionally, if
the `group-structure` option is passed, the workchain will also attempt to use the given parse engine to pars... | Below is the the instruction that describes the task:
### Input:
Run the `CifCleanWorkChain` on the entries in a group with raw imported CifData nodes.
It will use the `cif_filter` and `cif_select` scripts of `cod-tools` to clean the input cif file. Additionally, if
the `group-structure` option is passed, ... |
def merge(self, other_roc):
"""
Ingest the values of another DistributedROC object into this one and update the statistics inplace.
Args:
other_roc: another DistributedROC object.
"""
if other_roc.thresholds.size == self.thresholds.size and np.all(other_roc.threshold... | Ingest the values of another DistributedROC object into this one and update the statistics inplace.
Args:
other_roc: another DistributedROC object. | Below is the the instruction that describes the task:
### Input:
Ingest the values of another DistributedROC object into this one and update the statistics inplace.
Args:
other_roc: another DistributedROC object.
### Response:
def merge(self, other_roc):
"""
Ingest the values o... |
def create_message(self, channel_id, text):
"""
Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message
"""
baseurl = self.rest_baseurl + \
'/ch... | Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message | Below is the the instruction that describes the task:
### Input:
Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message
### Response:
def create_message(self, channel_id, text):
... |
def OSPFNeighborState_NeighborState(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
OSPFNeighborState = ET.SubElement(config, "OSPFNeighborState", xmlns="http://brocade.com/ns/brocade-notification-stream")
NeighborState = ET.SubElement(OSPFNeighborState,... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def OSPFNeighborState_NeighborState(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
OSPFNeighborState = ET.SubElement(config, "OSPFNeighborState", xmlns="http... |
def toVerticalPotential(Pot,R,phi=None):
"""
NAME:
toVerticalPotential
PURPOSE:
convert a Potential to a vertical potential at a given R
INPUT:
Pot - Potential instance or list of such instances
R - Galactocentric radius at which to evaluate the vertical potential (can ... | NAME:
toVerticalPotential
PURPOSE:
convert a Potential to a vertical potential at a given R
INPUT:
Pot - Potential instance or list of such instances
R - Galactocentric radius at which to evaluate the vertical potential (can be Quantity)
phi= (None) Galactocentric azimu... | Below is the the instruction that describes the task:
### Input:
NAME:
toVerticalPotential
PURPOSE:
convert a Potential to a vertical potential at a given R
INPUT:
Pot - Potential instance or list of such instances
R - Galactocentric radius at which to evaluate the vertical... |
def _register_factory(self, factory_name, factory, override):
# type: (str, type, bool) -> None
"""
Registers a component factory
:param factory_name: The name of the factory
:param factory: The factory class object
:param override: If true, previous factory is overridde... | Registers a component factory
:param factory_name: The name of the factory
:param factory: The factory class object
:param override: If true, previous factory is overridden, else an
exception is risen if a previous factory with that
name already... | Below is the the instruction that describes the task:
### Input:
Registers a component factory
:param factory_name: The name of the factory
:param factory: The factory class object
:param override: If true, previous factory is overridden, else an
exception is risen ... |
def pdfdump(self, filename=None, **kargs):
"""pdfdump(filename=None, layer_shift=0, rebuild=1)
Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called."""
canvas = self.canvas_dump(**kargs)
if filename is None:
fname ... | pdfdump(filename=None, layer_shift=0, rebuild=1)
Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called. | Below is the the instruction that describes the task:
### Input:
pdfdump(filename=None, layer_shift=0, rebuild=1)
Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called.
### Response:
def pdfdump(self, filename=None, **kargs):
"""pdfdump(f... |
def qs_alphabet_filter(parser, token):
"""
The parser/tokenizer for the queryset alphabet filter.
{% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %}
{% qs_alphabet_filter objects lastname myapp/template.html %}
The template name is optional and uses... | The parser/tokenizer for the queryset alphabet filter.
{% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %}
{% qs_alphabet_filter objects lastname myapp/template.html %}
The template name is optional and uses alphafilter/alphabet.html if not
specified | Below is the the instruction that describes the task:
### Input:
The parser/tokenizer for the queryset alphabet filter.
{% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %}
{% qs_alphabet_filter objects lastname myapp/template.html %}
The template name is... |
def do_rewind(self, line):
"""
rewind
"""
self.print_response("Rewinding from frame %s to 0" % self.bot._frame)
self.bot._frame = 0 | rewind | Below is the the instruction that describes the task:
### Input:
rewind
### Response:
def do_rewind(self, line):
"""
rewind
"""
self.print_response("Rewinding from frame %s to 0" % self.bot._frame)
self.bot._frame = 0 |
def list_sessions(self, updated_since=None, max_results=100, skip=0, **kwargs):
"""List session IDs.
List the Session IDs with pending messages in the queue where the state of the session
has been updated since the timestamp provided. If no timestamp is provided, all will be returned.
I... | List session IDs.
List the Session IDs with pending messages in the queue where the state of the session
has been updated since the timestamp provided. If no timestamp is provided, all will be returned.
If the state of a session has never been set, it will not be returned regardless of whether
... | Below is the the instruction that describes the task:
### Input:
List session IDs.
List the Session IDs with pending messages in the queue where the state of the session
has been updated since the timestamp provided. If no timestamp is provided, all will be returned.
If the state of a sessi... |
def mcmc(transform, loglikelihood, parameter_names, nsteps=40000, nburn=400,
stdevs=0.1, start = 0.5, **problem):
"""
**Metropolis Hastings MCMC**
with automatic step width adaption.
Burnin period is also used to guess steps.
:param nburn: number of burnin steps
:param stdevs: step widths to start with
"... | **Metropolis Hastings MCMC**
with automatic step width adaption.
Burnin period is also used to guess steps.
:param nburn: number of burnin steps
:param stdevs: step widths to start with | Below is the the instruction that describes the task:
### Input:
**Metropolis Hastings MCMC**
with automatic step width adaption.
Burnin period is also used to guess steps.
:param nburn: number of burnin steps
:param stdevs: step widths to start with
### Response:
def mcmc(transform, loglikelihood, paramet... |
def Wang_Chiang_Lu(m, x, rhol, rhog, mul, mug, D, roughness=0, L=1):
r'''Calculates two-phase pressure drop with the Wang, Chiang, and Lu (1997)
correlation given in [1]_ and reviewed in [2]_ and [3]_.
.. math::
\Delta P = \Delta P_{g} \phi_g^2
.. math::
\phi_g^2 = 1 + 9.397X^{0.62} + ... | r'''Calculates two-phase pressure drop with the Wang, Chiang, and Lu (1997)
correlation given in [1]_ and reviewed in [2]_ and [3]_.
.. math::
\Delta P = \Delta P_{g} \phi_g^2
.. math::
\phi_g^2 = 1 + 9.397X^{0.62} + 0.564X^{2.45} \text{ for } G >= 200 kg/m^2/s
.. math::
\phi_... | Below is the the instruction that describes the task:
### Input:
r'''Calculates two-phase pressure drop with the Wang, Chiang, and Lu (1997)
correlation given in [1]_ and reviewed in [2]_ and [3]_.
.. math::
\Delta P = \Delta P_{g} \phi_g^2
.. math::
\phi_g^2 = 1 + 9.397X^{0.62} + 0.56... |
def update(self, data, length=None):
"""
Hashes given byte string
@param data - string to hash
@param length - if not specifed, entire string is hashed,
otherwise only first length bytes
"""
if self.digest_finalized:
raise DigestError("No upda... | Hashes given byte string
@param data - string to hash
@param length - if not specifed, entire string is hashed,
otherwise only first length bytes | Below is the the instruction that describes the task:
### Input:
Hashes given byte string
@param data - string to hash
@param length - if not specifed, entire string is hashed,
otherwise only first length bytes
### Response:
def update(self, data, length=None):
"""
... |
def press_event(self):
""" The mouse press event that initiated a mouse drag, if any.
"""
if self.mouse_event.press_event is None:
return None
ev = self.copy()
ev.mouse_event = self.mouse_event.press_event
return ev | The mouse press event that initiated a mouse drag, if any. | Below is the the instruction that describes the task:
### Input:
The mouse press event that initiated a mouse drag, if any.
### Response:
def press_event(self):
""" The mouse press event that initiated a mouse drag, if any.
"""
if self.mouse_event.press_event is None:
return Non... |
def _observe_timeseries_fn(timeseries):
"""Build an observation_noise_fn that observes a Tensor timeseries."""
def observation_noise_fn(t):
current_slice = timeseries[..., t, :]
return tfd.MultivariateNormalDiag(
loc=current_slice,
scale_diag=tf.zeros_like(current_slice))
return observatio... | Build an observation_noise_fn that observes a Tensor timeseries. | Below is the the instruction that describes the task:
### Input:
Build an observation_noise_fn that observes a Tensor timeseries.
### Response:
def _observe_timeseries_fn(timeseries):
"""Build an observation_noise_fn that observes a Tensor timeseries."""
def observation_noise_fn(t):
current_slice = timeser... |
def get_ddG_results(self):
"""Parse the results from BuildModel and get the delta delta G's.
A positive ddG means that the mutation(s) is destabilzing, negative means stabilizing.
- highly stabilising (ΔΔG < −1.84 kcal/mol);
- stabilising (−1.84 kcal/mol ≤ ΔΔG < −0.92 kcal/mol)... | Parse the results from BuildModel and get the delta delta G's.
A positive ddG means that the mutation(s) is destabilzing, negative means stabilizing.
- highly stabilising (ΔΔG < −1.84 kcal/mol);
- stabilising (−1.84 kcal/mol ≤ ΔΔG < −0.92 kcal/mol);
- slightly stabilising (... | Below is the the instruction that describes the task:
### Input:
Parse the results from BuildModel and get the delta delta G's.
A positive ddG means that the mutation(s) is destabilzing, negative means stabilizing.
- highly stabilising (ΔΔG < −1.84 kcal/mol);
- stabilising (−1.84 k... |
def build_dir_tree(self, files):
""" Convert a flat file dict into the tree format used for storage """
def helper(split_files):
this_dir = {'files' : {}, 'dirs' : {}}
dirs = defaultdict(list)
for fle in split_files:
index = fle[0]; fileinfo = fle[1]... | Convert a flat file dict into the tree format used for storage | Below is the the instruction that describes the task:
### Input:
Convert a flat file dict into the tree format used for storage
### Response:
def build_dir_tree(self, files):
""" Convert a flat file dict into the tree format used for storage """
def helper(split_files):
this_dir = {'fi... |
def version(self):
"""
Compute the version identifier for this functional node using the
func code and local names. Optionally, also allow closed-over variable
values to affect the version number when closure_fingerprint is
specified
"""
try:
f = self... | Compute the version identifier for this functional node using the
func code and local names. Optionally, also allow closed-over variable
values to affect the version number when closure_fingerprint is
specified | Below is the the instruction that describes the task:
### Input:
Compute the version identifier for this functional node using the
func code and local names. Optionally, also allow closed-over variable
values to affect the version number when closure_fingerprint is
specified
### Response:
... |
def _srm(self, data):
"""Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
Returns
-... | Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
Returns
-------
w : list of array... | Below is the the instruction that describes the task:
### Input:
Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one ... |
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgradi... | Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root | Below is the the instruction that describes the task:
### Input:
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgradin... |
def parse(self, fail_callback=None):
""" Parse text fields and file fields for values and files """
# get text fields
for field in self.field_arguments:
self.values[field['name']] = self.__get_value(field['name'])
if self.values[field['name']] is None and field['requ... | Parse text fields and file fields for values and files | Below is the the instruction that describes the task:
### Input:
Parse text fields and file fields for values and files
### Response:
def parse(self, fail_callback=None):
""" Parse text fields and file fields for values and files """
# get text fields
for field in self.field_arguments:
... |
def parse(self, input_text, syncmap):
"""
Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be popul... | Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be populated | Below is the the instruction that describes the task:
### Input:
Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` mu... |
def register_func_list(self, func_and_handler):
""" register a function to determine if the handle
should be used for the type
"""
for func, handler in func_and_handler:
self._function_dispatch.register(func, handler)
self.dispatch.cache_clear() | register a function to determine if the handle
should be used for the type | Below is the the instruction that describes the task:
### Input:
register a function to determine if the handle
should be used for the type
### Response:
def register_func_list(self, func_and_handler):
""" register a function to determine if the handle
should be used for the type
... |
def callback_prototype(prototype):
"""Decorator to process a callback prototype.
A callback prototype is a function whose signature includes all the values
that will be passed by the callback API in question.
The original function will be returned, with a ``prototype.adapt`` attribute
whic... | Decorator to process a callback prototype.
A callback prototype is a function whose signature includes all the values
that will be passed by the callback API in question.
The original function will be returned, with a ``prototype.adapt`` attribute
which can be used to prepare third party callb... | Below is the the instruction that describes the task:
### Input:
Decorator to process a callback prototype.
A callback prototype is a function whose signature includes all the values
that will be passed by the callback API in question.
The original function will be returned, with a ``prototype... |
def _make_exception(self, response):
"""
In case of exception, construct the exception
object that holds all important values returned by
the response.
:return: The exception instance
:rtype: PocketException
"""
headers = response.headers
limit_he... | In case of exception, construct the exception
object that holds all important values returned by
the response.
:return: The exception instance
:rtype: PocketException | Below is the the instruction that describes the task:
### Input:
In case of exception, construct the exception
object that holds all important values returned by
the response.
:return: The exception instance
:rtype: PocketException
### Response:
def _make_exception(self, response):
... |
def _basis_notes_path(name, data_dir):
'''Form a path to the notes for a basis set'''
data_dir = fix_data_dir(data_dir)
bs_data = _get_basis_metadata(name, data_dir)
# the notes file is the same as the base file name, with a .notes extension
filebase = bs_data['basename']
file_path = os.path.j... | Form a path to the notes for a basis set | Below is the the instruction that describes the task:
### Input:
Form a path to the notes for a basis set
### Response:
def _basis_notes_path(name, data_dir):
'''Form a path to the notes for a basis set'''
data_dir = fix_data_dir(data_dir)
bs_data = _get_basis_metadata(name, data_dir)
# the notes... |
def _deserialize(self, value, attr, data):
"""Deserialize string value."""
value = super(TrimmedString, self)._deserialize(value, attr, data)
return value.strip() | Deserialize string value. | Below is the the instruction that describes the task:
### Input:
Deserialize string value.
### Response:
def _deserialize(self, value, attr, data):
"""Deserialize string value."""
value = super(TrimmedString, self)._deserialize(value, attr, data)
return value.strip() |
def police_priority_map_exceed_map_pri3_exceed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name_key = ET.SubElement(police_priority_map, ... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def police_priority_map_exceed_map_pri3_exceed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-ma... |
def plot_punchcard(df, metric='lines', title='punchcard', by=None):
"""
Uses modified plotting code from https://bitbucket.org/birkenfeld/hgpunchcard
:param df:
:param metric:
:param title:
:return:
"""
if not HAS_MPL:
raise ImportError('Must have matplotlib installed to use th... | Uses modified plotting code from https://bitbucket.org/birkenfeld/hgpunchcard
:param df:
:param metric:
:param title:
:return: | Below is the the instruction that describes the task:
### Input:
Uses modified plotting code from https://bitbucket.org/birkenfeld/hgpunchcard
:param df:
:param metric:
:param title:
:return:
### Response:
def plot_punchcard(df, metric='lines', title='punchcard', by=None):
"""
Uses modifie... |
def cache_name(self):
"""
Used in django 1.x
"""
lang = get_language()
cache = build_localized_fieldname(self.accessor, lang)
return "_%s_cache" % cache | Used in django 1.x | Below is the the instruction that describes the task:
### Input:
Used in django 1.x
### Response:
def cache_name(self):
"""
Used in django 1.x
"""
lang = get_language()
cache = build_localized_fieldname(self.accessor, lang)
return "_%s_cache" % cache |
def _execute(self, execute_inputs, execute_outputs, backward_execution=False):
"""Calls the custom execute function of the script.py of the state
"""
self._script.build_module()
outcome_item = self._script.execute(self, execute_inputs, execute_outputs, backward_execution)
# in... | Calls the custom execute function of the script.py of the state | Below is the the instruction that describes the task:
### Input:
Calls the custom execute function of the script.py of the state
### Response:
def _execute(self, execute_inputs, execute_outputs, backward_execution=False):
"""Calls the custom execute function of the script.py of the state
"""
... |
def length_of_national_destination_code(numobj):
"""Return length of the national destination code code for a number.
Gets the length of the national destination code (NDC) from the
PhoneNumber object passed in, so that clients could use it to split a
national significant number into NDC and subscriber... | Return length of the national destination code code for a number.
Gets the length of the national destination code (NDC) from the
PhoneNumber object passed in, so that clients could use it to split a
national significant number into NDC and subscriber number. The NDC of a
phone number is normally the f... | Below is the the instruction that describes the task:
### Input:
Return length of the national destination code code for a number.
Gets the length of the national destination code (NDC) from the
PhoneNumber object passed in, so that clients could use it to split a
national significant number into NDC a... |
def get_offset(self, envelope):
"""Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size).
Arguments:
envelope -- coordinate extent tuple or Envelope
"""
if isinstance(envelope, collections.Sequence):
envelope = Envelope(envelope)
if not (self.en... | Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size).
Arguments:
envelope -- coordinate extent tuple or Envelope | Below is the the instruction that describes the task:
### Input:
Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size).
Arguments:
envelope -- coordinate extent tuple or Envelope
### Response:
def get_offset(self, envelope):
"""Returns a 4-tuple pixel window (x_offset, y_offs... |
async def get_entry(self, entry):
"""
GET /api/entries/{entry}.{_format}
Retrieve a single entry
:param entry: \w+ an integer The Entry ID
:return data related to the ext
"""
params = {'access_token': self.token}
url = '/api/entries/{entry}.{ext}'.format... | GET /api/entries/{entry}.{_format}
Retrieve a single entry
:param entry: \w+ an integer The Entry ID
:return data related to the ext | Below is the the instruction that describes the task:
### Input:
GET /api/entries/{entry}.{_format}
Retrieve a single entry
:param entry: \w+ an integer The Entry ID
:return data related to the ext
### Response:
async def get_entry(self, entry):
"""
GET /api/entries/{entry... |
def parse_func_body(self):
"""If success, return a tuple (args, body)"""
self.save()
self._expected = []
if self.next_is_rc(Tokens.OPAR, False): # do not render right hidden
self.handle_hidden_right() # render hidden after new level
args = self.parse_param_list(... | If success, return a tuple (args, body) | Below is the the instruction that describes the task:
### Input:
If success, return a tuple (args, body)
### Response:
def parse_func_body(self):
"""If success, return a tuple (args, body)"""
self.save()
self._expected = []
if self.next_is_rc(Tokens.OPAR, False): # do not render ri... |
def no_intersection(to_validate, constraint, violation_cfg):
"""
Returns violation message if validated and constraint sets have no intersection
:param to_validate:
:param constraint:
:param violation_cfg:
:return:
"""
if len(constraint) == 0 or len(set(constraint).intersection(to_valida... | Returns violation message if validated and constraint sets have no intersection
:param to_validate:
:param constraint:
:param violation_cfg:
:return: | Below is the the instruction that describes the task:
### Input:
Returns violation message if validated and constraint sets have no intersection
:param to_validate:
:param constraint:
:param violation_cfg:
:return:
### Response:
def no_intersection(to_validate, constraint, violation_cfg):
"""
... |
def pack_req(cls, trd_side, order_type, price, qty,
code, adjust_limit, trd_env, sec_mkt_str, acc_id, trd_mkt, conn_id):
"""Convert from user request for place order to PLS request"""
from futuquant.common.pb.Trd_PlaceOrder_pb2 import Request
req = Request()
serial_no = ... | Convert from user request for place order to PLS request | Below is the the instruction that describes the task:
### Input:
Convert from user request for place order to PLS request
### Response:
def pack_req(cls, trd_side, order_type, price, qty,
code, adjust_limit, trd_env, sec_mkt_str, acc_id, trd_mkt, conn_id):
"""Convert from user request for ... |
def do_erase(self):
"""! @brief Handle 'erase' subcommand."""
self._increase_logging(["pyocd.tools.loader", "pyocd"])
session = ConnectHelper.session_with_chosen_probe(
project_dir=self._args.project_dir,
config_file=self._args.con... | ! @brief Handle 'erase' subcommand. | Below is the the instruction that describes the task:
### Input:
! @brief Handle 'erase' subcommand.
### Response:
def do_erase(self):
"""! @brief Handle 'erase' subcommand."""
self._increase_logging(["pyocd.tools.loader", "pyocd"])
session = ConnectHelper.session_with_chosen_probe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.