code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def preview(request):
""" Render preview page.
:returns: A rendered preview
"""
if settings.MARKDOWN_PROTECT_PREVIEW:
user = getattr(request, 'user', None)
if not user or not user.is_staff:
from django.contrib.auth.views import redirect_to_login
return redirect_... | Render preview page.
:returns: A rendered preview | Below is the the instruction that describes the task:
### Input:
Render preview page.
:returns: A rendered preview
### Response:
def preview(request):
""" Render preview page.
:returns: A rendered preview
"""
if settings.MARKDOWN_PROTECT_PREVIEW:
user = getattr(request, 'user', None)... |
def overlaps(self, other, permissive=False):
"""
Test if intervals have any overlapping value.
If 'permissive' is set to True (default is False), then intervals that are contiguous
are considered as overlapping intervals as well (e.g. [1, 2) and [2, 3],
but not [1, 2) and (2, ... | Test if intervals have any overlapping value.
If 'permissive' is set to True (default is False), then intervals that are contiguous
are considered as overlapping intervals as well (e.g. [1, 2) and [2, 3],
but not [1, 2) and (2, 3] because 2 is not part of their union).
:param other:... | Below is the the instruction that describes the task:
### Input:
Test if intervals have any overlapping value.
If 'permissive' is set to True (default is False), then intervals that are contiguous
are considered as overlapping intervals as well (e.g. [1, 2) and [2, 3],
but not [1, 2) and ... |
def set_mode(self, value):
"""Set the currently active mode on the device (DAB, FM, Spotify)."""
mode = -1
modes = yield from self.get_modes()
for temp_mode in modes:
if temp_mode['label'] == value:
mode = temp_mode['band']
return (yield from self.han... | Set the currently active mode on the device (DAB, FM, Spotify). | Below is the the instruction that describes the task:
### Input:
Set the currently active mode on the device (DAB, FM, Spotify).
### Response:
def set_mode(self, value):
"""Set the currently active mode on the device (DAB, FM, Spotify)."""
mode = -1
modes = yield from self.get_modes()
... |
def app0(self):
"""
First APP0 marker in image markers.
"""
for m in self._markers:
if m.marker_code == JPEG_MARKER_CODE.APP0:
return m
raise KeyError('no APP0 marker in image') | First APP0 marker in image markers. | Below is the the instruction that describes the task:
### Input:
First APP0 marker in image markers.
### Response:
def app0(self):
"""
First APP0 marker in image markers.
"""
for m in self._markers:
if m.marker_code == JPEG_MARKER_CODE.APP0:
return m
... |
def get_annotation(self, id_):
"""Data for a specific annotation."""
endpoint = "annotations/{id}".format(id=id_)
return self._make_request(endpoint) | Data for a specific annotation. | Below is the the instruction that describes the task:
### Input:
Data for a specific annotation.
### Response:
def get_annotation(self, id_):
"""Data for a specific annotation."""
endpoint = "annotations/{id}".format(id=id_)
return self._make_request(endpoint) |
def tatoeba(language, word, minlength = 10, maxlength = 100):
''' Returns a list of suitable textsamples for a given word using Tatoeba.org. '''
word, sentences = unicode(word), []
page = requests.get('http://tatoeba.org/deu/sentences/search?query=%s&from=%s&to=und' % (word, lltk.locale.iso639_1to3(language)))
tre... | Returns a list of suitable textsamples for a given word using Tatoeba.org. | Below is the the instruction that describes the task:
### Input:
Returns a list of suitable textsamples for a given word using Tatoeba.org.
### Response:
def tatoeba(language, word, minlength = 10, maxlength = 100):
''' Returns a list of suitable textsamples for a given word using Tatoeba.org. '''
word, sentenc... |
def _wrap_jinja_filter(self, function):
"""Propagate exceptions as undefined values filter."""
def wrapper(*args, **kwargs):
"""Filter wrapper."""
try:
return function(*args, **kwargs)
except Exception: # pylint: disable=broad-except
r... | Propagate exceptions as undefined values filter. | Below is the the instruction that describes the task:
### Input:
Propagate exceptions as undefined values filter.
### Response:
def _wrap_jinja_filter(self, function):
"""Propagate exceptions as undefined values filter."""
def wrapper(*args, **kwargs):
"""Filter wrapper."""
... |
def renew_step_dir(step_dir: str):
"""Delete step directory if exists and create, reporting actions."""
if os.path.exists(step_dir):
logging.info("Remove unfinished step %s", step_dir)
shutil.rmtree(step_dir)
logging.info("Create: %s", step_dir)
os.makedirs(step_dir) | Delete step directory if exists and create, reporting actions. | Below is the the instruction that describes the task:
### Input:
Delete step directory if exists and create, reporting actions.
### Response:
def renew_step_dir(step_dir: str):
"""Delete step directory if exists and create, reporting actions."""
if os.path.exists(step_dir):
logging.info("Remove unf... |
def root_directory(self):
"""Map the root directory to user profile/inasafe so the minimum needs
profile will be placed there (user profile/inasafe/minimum_needs).
:returns: root directory
:rtype: QString
"""
if not QgsApplication.qgisSettingsDirPath() or (
... | Map the root directory to user profile/inasafe so the minimum needs
profile will be placed there (user profile/inasafe/minimum_needs).
:returns: root directory
:rtype: QString | Below is the the instruction that describes the task:
### Input:
Map the root directory to user profile/inasafe so the minimum needs
profile will be placed there (user profile/inasafe/minimum_needs).
:returns: root directory
:rtype: QString
### Response:
def root_directory(self):
... |
def get_network_as_xml_template(network_id,**kwargs):
"""
Turn an existing network into an xml template
using its attributes.
If an optional scenario ID is passed in, default
values will be populated from that scenario.
"""
template_xml = etree.Element("template_definition")
... | Turn an existing network into an xml template
using its attributes.
If an optional scenario ID is passed in, default
values will be populated from that scenario. | Below is the the instruction that describes the task:
### Input:
Turn an existing network into an xml template
using its attributes.
If an optional scenario ID is passed in, default
values will be populated from that scenario.
### Response:
def get_network_as_xml_template(network_id,**kwarg... |
def board_name(default):
"""Returns the boards name (if available)."""
try:
import board
try:
name = board.name
except AttributeError:
# There was a board.py file, but it didn't have an name attribute
# We also ignore this as an error
name ... | Returns the boards name (if available). | Below is the the instruction that describes the task:
### Input:
Returns the boards name (if available).
### Response:
def board_name(default):
"""Returns the boards name (if available)."""
try:
import board
try:
name = board.name
except AttributeError:
# The... |
def serve_forever_stoppable(self):
"""Handle one request at a time until stop_serve_forever().
http://code.activestate.com/recipes/336012/
"""
self.stop_request = False
self.stopped = False
while not self.stop_request:
self.handle_request()
# ... | Handle one request at a time until stop_serve_forever().
http://code.activestate.com/recipes/336012/ | Below is the the instruction that describes the task:
### Input:
Handle one request at a time until stop_serve_forever().
http://code.activestate.com/recipes/336012/
### Response:
def serve_forever_stoppable(self):
"""Handle one request at a time until stop_serve_forever().
http://code.ac... |
def process(self, context, lines):
"""Chop up individual lines into static and dynamic parts.
Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different
chunk types.
The processor protocol here requires the method to accept values by yielding resulting li... | Chop up individual lines into static and dynamic parts.
Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different
chunk types.
The processor protocol here requires the method to accept values by yielding resulting lines while accepting
sent chunks. Defer... | Below is the the instruction that describes the task:
### Input:
Chop up individual lines into static and dynamic parts.
Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different
chunk types.
The processor protocol here requires the method to accept va... |
def __get_vibration_code(self, left_motor, right_motor, duration):
"""This is some crazy voodoo, if you can simplify it, please do."""
inner_event = struct.pack(
'2h6x2h2x2H28x',
0x50,
-1,
duration,
0,
int(left_motor * 65535),
... | This is some crazy voodoo, if you can simplify it, please do. | Below is the the instruction that describes the task:
### Input:
This is some crazy voodoo, if you can simplify it, please do.
### Response:
def __get_vibration_code(self, left_motor, right_motor, duration):
"""This is some crazy voodoo, if you can simplify it, please do."""
inner_event = struct.pa... |
def zero_fill(self, corpus):
"""Adds rows to the results to ensure that, for every n-gram that is
attested in at least one witness, every witness for that text
has a row, with added rows having a count of zero.
:param corpus: corpus containing the texts appearing in the results
... | Adds rows to the results to ensure that, for every n-gram that is
attested in at least one witness, every witness for that text
has a row, with added rows having a count of zero.
:param corpus: corpus containing the texts appearing in the results
:type corpus: `Corpus` | Below is the the instruction that describes the task:
### Input:
Adds rows to the results to ensure that, for every n-gram that is
attested in at least one witness, every witness for that text
has a row, with added rows having a count of zero.
:param corpus: corpus containing the texts appe... |
def get_output_fields(self):
""" Get field names from output template.
"""
# Re-engineer list from output format
# XXX TODO: Would be better to use a FieldRecorder class to catch the full field names
emit_fields = list(i.lower() for i in re.sub(r"[^_A-Z]+", ' ', self.format_item(... | Get field names from output template. | Below is the the instruction that describes the task:
### Input:
Get field names from output template.
### Response:
def get_output_fields(self):
""" Get field names from output template.
"""
# Re-engineer list from output format
# XXX TODO: Would be better to use a FieldRecorder cl... |
def validate_refresh_token(self, refresh_token, client, request,
*args, **kwargs):
"""Ensure the token is valid and belongs to the client
This method is used by the authorization code grant indirectly by
issuing refresh tokens, resource owner password credentials ... | Ensure the token is valid and belongs to the client
This method is used by the authorization code grant indirectly by
issuing refresh tokens, resource owner password credentials grant
(also indirectly) and the refresh token grant. | Below is the the instruction that describes the task:
### Input:
Ensure the token is valid and belongs to the client
This method is used by the authorization code grant indirectly by
issuing refresh tokens, resource owner password credentials grant
(also indirectly) and the refresh token gr... |
def unsubscribe(self, connection, destination):
"""
Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/top... | Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str} | Below is the the instruction that describes the task:
### Input:
Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/to... |
def readImages(path, sc=None, minParitions = 1, bigdl_type="float"):
"""
Read the directory of images into DataFrame from the local or remote source.
:param path Directory to the input data files, the path can be comma separated paths as the
list of inputs. Wildcards path are sup... | Read the directory of images into DataFrame from the local or remote source.
:param path Directory to the input data files, the path can be comma separated paths as the
list of inputs. Wildcards path are supported similarly to sc.binaryFiles(path).
:param min_partitions A suggestion valu... | Below is the the instruction that describes the task:
### Input:
Read the directory of images into DataFrame from the local or remote source.
:param path Directory to the input data files, the path can be comma separated paths as the
list of inputs. Wildcards path are supported similarly to ... |
def synchronize(self):
"""Perform sync of the security groups between ML2 and EOS."""
# Get expected ACLs and rules
expected_acls = self.get_expected_acls()
# Get expected interface to ACL mappings
all_expected_bindings = self.get_expected_bindings()
# Check that confi... | Perform sync of the security groups between ML2 and EOS. | Below is the the instruction that describes the task:
### Input:
Perform sync of the security groups between ML2 and EOS.
### Response:
def synchronize(self):
"""Perform sync of the security groups between ML2 and EOS."""
# Get expected ACLs and rules
expected_acls = self.get_expected_acls... |
def n_forking_points(neurites, neurite_type=NeuriteType.all):
'''number of forking points in a collection of neurites'''
return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.iforking_point) | number of forking points in a collection of neurites | Below is the the instruction that describes the task:
### Input:
number of forking points in a collection of neurites
### Response:
def n_forking_points(neurites, neurite_type=NeuriteType.all):
'''number of forking points in a collection of neurites'''
return n_sections(neurites, neurite_type=neurite_type,... |
def _send_tune_ok(self, frame_in):
"""Send Tune OK frame.
:param specification.Connection.Tune frame_in: Tune frame.
:return:
"""
self.max_allowed_channels = self._negotiate(frame_in.channel_max,
MAX_CHANNELS)
self.max... | Send Tune OK frame.
:param specification.Connection.Tune frame_in: Tune frame.
:return: | Below is the the instruction that describes the task:
### Input:
Send Tune OK frame.
:param specification.Connection.Tune frame_in: Tune frame.
:return:
### Response:
def _send_tune_ok(self, frame_in):
"""Send Tune OK frame.
:param specification.Connection.Tune frame_in: Tune fra... |
def multivariate_multiply(m1, c1, m2, c2):
"""
Multiplies the two multivariate Gaussians together and returns the
results as the tuple (mean, covariance).
Examples
--------
.. code-block:: Python
m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
... | Multiplies the two multivariate Gaussians together and returns the
results as the tuple (mean, covariance).
Examples
--------
.. code-block:: Python
m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
[3.2, 0], [[8.0, 1.1], [1.1,8.0]])
Pa... | Below is the the instruction that describes the task:
### Input:
Multiplies the two multivariate Gaussians together and returns the
results as the tuple (mean, covariance).
Examples
--------
.. code-block:: Python
m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
... |
def keyword(self, name=None, identifier=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.Keyword` objects in database
:param name: keyword name(s)
:type name: str or tuple(str) or None
:param identifier: keyword identifier(s)
:type identifier:... | Method to query :class:`.models.Keyword` objects in database
:param name: keyword name(s)
:type name: str or tuple(str) or None
:param identifier: keyword identifier(s)
:type identifier: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:ty... | Below is the the instruction that describes the task:
### Input:
Method to query :class:`.models.Keyword` objects in database
:param name: keyword name(s)
:type name: str or tuple(str) or None
:param identifier: keyword identifier(s)
:type identifier: str or tuple(str) or None
... |
def run(self, order=None):
"""
self.runner must be present
"""
for event in self.runner.run(order=order):
self.receive(event) | self.runner must be present | Below is the the instruction that describes the task:
### Input:
self.runner must be present
### Response:
def run(self, order=None):
"""
self.runner must be present
"""
for event in self.runner.run(order=order):
self.receive(event) |
def search(request, template="search_results.html", extra_context=None):
"""
Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model.
"""
query = request.GET.get("q", "")
page = request.GET.get("page", 1)
... | Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model. | Below is the the instruction that describes the task:
### Input:
Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model.
### Response:
def search(request, template="search_results.html", extra_context=None):
"""
D... |
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_12l_16h_imagenet_large()
hparams.num_hidden_layers = 16
hparams.local_attention = True
hparams.batch_size = 1
hparams.block_length = 256
return hparams | separate rgb embeddings. | Below is the the instruction that describes the task:
### Input:
separate rgb embeddings.
### Response:
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_12l_16h_imagenet_large()
hparams.num_hidden_layers = 16
hparams.local_at... |
def hello(self):
"""http://docs.fiesta.cc/index.html#getting-started"""
path = 'hello'
response = self.request(path, do_authentication=False)
return response | http://docs.fiesta.cc/index.html#getting-started | Below is the the instruction that describes the task:
### Input:
http://docs.fiesta.cc/index.html#getting-started
### Response:
def hello(self):
"""http://docs.fiesta.cc/index.html#getting-started"""
path = 'hello'
response = self.request(path, do_authentication=False)
return respon... |
def list_revisions_groups(self, url, group_id):
"""
List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
... | List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history. | Below is the the instruction that describes the task:
### Input:
List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history.
### Response:
def list_revisions_groups(self, url, group_id):
"""
List revisions.
List the... |
def find_subdirectories(basepath):
'''
Return directories (and sub) starting from a base
'''
directories = []
for root, dirnames, filenames in os.walk(basepath):
new_directories = [d for d in dirnames if d not in directories]
directories = directories + new_directories
return dir... | Return directories (and sub) starting from a base | Below is the the instruction that describes the task:
### Input:
Return directories (and sub) starting from a base
### Response:
def find_subdirectories(basepath):
'''
Return directories (and sub) starting from a base
'''
directories = []
for root, dirnames, filenames in os.walk(basepath):
... |
def get(self):
"""
Get selected color.
:return: color under cursor as a (RGB, HSV, HEX) tuple
"""
x = self.coords('cross_v')[0]
y = self.coords('cross_h')[1]
xp = min(x, self.bg.width() - 1)
yp = min(y, self.bg.height() - 1)
try:
r, g,... | Get selected color.
:return: color under cursor as a (RGB, HSV, HEX) tuple | Below is the the instruction that describes the task:
### Input:
Get selected color.
:return: color under cursor as a (RGB, HSV, HEX) tuple
### Response:
def get(self):
"""
Get selected color.
:return: color under cursor as a (RGB, HSV, HEX) tuple
"""
x = self.coor... |
def overlaps(self, other):
"""Tell if self is partly contained in other."""
return self.network_address in other or (
self.broadcast_address in other or (
other.network_address in self or (
other.broadcast_address in self))) | Tell if self is partly contained in other. | Below is the the instruction that describes the task:
### Input:
Tell if self is partly contained in other.
### Response:
def overlaps(self, other):
"""Tell if self is partly contained in other."""
return self.network_address in other or (
self.broadcast_address in other or (
... |
def on_namreply(self, connection, event):
"""
Initial list of nicknames received - remove op/voice prefixes,
and send the list to the WebSocket.
"""
for nickname in event.arguments()[-1].split():
nickname = nickname.lstrip("@+")
self.nicknames[nickname] = ... | Initial list of nicknames received - remove op/voice prefixes,
and send the list to the WebSocket. | Below is the the instruction that describes the task:
### Input:
Initial list of nicknames received - remove op/voice prefixes,
and send the list to the WebSocket.
### Response:
def on_namreply(self, connection, event):
"""
Initial list of nicknames received - remove op/voice prefixes,
... |
def start(self, timeout=None):
"""
Start child process
:param timeout: the maximum time to wait for child process to report it has actually started.
None waits until the context manager has been entered, but update might not have been called yet.
"""
# we lazily create o... | Start child process
:param timeout: the maximum time to wait for child process to report it has actually started.
None waits until the context manager has been entered, but update might not have been called yet. | Below is the the instruction that describes the task:
### Input:
Start child process
:param timeout: the maximum time to wait for child process to report it has actually started.
None waits until the context manager has been entered, but update might not have been called yet.
### Response:
def star... |
def toxml(self):
"""
Exports this object into a LEMS XML object
"""
return '<With ' + \
(' instance="{0}"'.format(self.instance) if self.instance else '') +\
(' list="{0}"'.format(self.list) if self.list else '') + \
(' index="{0}"'.format(self.index) if se... | Exports this object into a LEMS XML object | Below is the the instruction that describes the task:
### Input:
Exports this object into a LEMS XML object
### Response:
def toxml(self):
"""
Exports this object into a LEMS XML object
"""
return '<With ' + \
(' instance="{0}"'.format(self.instance) if self.instance else... |
def get_fieldsets(self, request, obj=None):
"""
Add fieldsets of placeholders to the list of already
existing fieldsets.
"""
# some ugly business to remove freeze_date
# from the field list
general_module = {
'fields': list(self.general_fields),
... | Add fieldsets of placeholders to the list of already
existing fieldsets. | Below is the the instruction that describes the task:
### Input:
Add fieldsets of placeholders to the list of already
existing fieldsets.
### Response:
def get_fieldsets(self, request, obj=None):
"""
Add fieldsets of placeholders to the list of already
existing fieldsets.
""... |
def _write_tree(self, tree: dict, output: Union[str, BinaryIO], file_mode: int=0o666) -> None:
"""
Write the model to disk.
:param tree: The data dict - will be the ASDF tree.
:param output: The output file path or a file object.
:param file_mode: The output file's permissions.
... | Write the model to disk.
:param tree: The data dict - will be the ASDF tree.
:param output: The output file path or a file object.
:param file_mode: The output file's permissions.
:return: None | Below is the the instruction that describes the task:
### Input:
Write the model to disk.
:param tree: The data dict - will be the ASDF tree.
:param output: The output file path or a file object.
:param file_mode: The output file's permissions.
:return: None
### Response:
def _writ... |
def inspect_image(name):
'''
Retrieves image information. Equivalent to running the ``docker inspect``
Docker CLI command, but will only look for image information.
.. note::
To inspect an image, it must have been pulled from a registry or built
locally. Images on a Docker registry whic... | Retrieves image information. Equivalent to running the ``docker inspect``
Docker CLI command, but will only look for image information.
.. note::
To inspect an image, it must have been pulled from a registry or built
locally. Images on a Docker registry which have not been pulled cannot
... | Below is the the instruction that describes the task:
### Input:
Retrieves image information. Equivalent to running the ``docker inspect``
Docker CLI command, but will only look for image information.
.. note::
To inspect an image, it must have been pulled from a registry or built
locally. ... |
def refresh(self):
"""Force a refresh of the Elasticsearch index
"""
self.client.indices.refresh(index=self.model.search_objects.mapping.index) | Force a refresh of the Elasticsearch index | Below is the the instruction that describes the task:
### Input:
Force a refresh of the Elasticsearch index
### Response:
def refresh(self):
"""Force a refresh of the Elasticsearch index
"""
self.client.indices.refresh(index=self.model.search_objects.mapping.index) |
def mean_imls(self):
"""
Compute the mean IMLs (Intensity Measure Level)
for the given vulnerability function.
:param vulnerability_function: the vulnerability function where
the IMLs (Intensity Measure Level) are taken from.
:type vuln_function:
:py:class... | Compute the mean IMLs (Intensity Measure Level)
for the given vulnerability function.
:param vulnerability_function: the vulnerability function where
the IMLs (Intensity Measure Level) are taken from.
:type vuln_function:
:py:class:`openquake.risklib.vulnerability_functio... | Below is the the instruction that describes the task:
### Input:
Compute the mean IMLs (Intensity Measure Level)
for the given vulnerability function.
:param vulnerability_function: the vulnerability function where
the IMLs (Intensity Measure Level) are taken from.
:type vuln_fu... |
def fcsp_sa_fcsp_auth_proto_group(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcsp_sa = ET.SubElement(config, "fcsp-sa", xmlns="urn:brocade.com:mgmt:brocade-fc-auth")
fcsp = ET.SubElement(fcsp_sa, "fcsp")
auth = ET.SubElement(fcsp, "auth")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fcsp_sa_fcsp_auth_proto_group(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcsp_sa = ET.SubElement(config, "fcsp-sa", xmlns="urn:brocade.com:mgmt:broca... |
def require_openid(f):
"""Require user to be logged in."""
@wraps(f)
def decorator(*args, **kwargs):
if g.user is None:
next_url = url_for("login") + "?next=" + request.url
return redirect(next_url)
else:
return f(*args, **kwargs)
return decorator | Require user to be logged in. | Below is the the instruction that describes the task:
### Input:
Require user to be logged in.
### Response:
def require_openid(f):
"""Require user to be logged in."""
@wraps(f)
def decorator(*args, **kwargs):
if g.user is None:
next_url = url_for("login") + "?next=" + request.url
... |
def invoke(self, function_name, raw_python=False, command=None, no_color=False):
"""
Invoke a remote function.
"""
# There are three likely scenarios for 'command' here:
# command, which is a modular function path
# raw_command, which is a string of python to execute... | Invoke a remote function. | Below is the the instruction that describes the task:
### Input:
Invoke a remote function.
### Response:
def invoke(self, function_name, raw_python=False, command=None, no_color=False):
"""
Invoke a remote function.
"""
# There are three likely scenarios for 'command' here:
... |
def run_step(self, is_shell):
"""Run a command.
Runs a program or executable. If is_shell is True, executes the command
through the shell.
Args:
is_shell: bool. defaults False. Set to true to execute cmd through
the default shell.
"""
a... | Run a command.
Runs a program or executable. If is_shell is True, executes the command
through the shell.
Args:
is_shell: bool. defaults False. Set to true to execute cmd through
the default shell. | Below is the the instruction that describes the task:
### Input:
Run a command.
Runs a program or executable. If is_shell is True, executes the command
through the shell.
Args:
is_shell: bool. defaults False. Set to true to execute cmd through
the default ... |
def connexity(self):
"""
A boolean matrix, m[i, j] == True if there is a relation term(i) -> term(j)
:return: a np.matrix (len(dictionary), len(dictionary)) of boolean
"""
return np.matrix(sum(self.relations.values()).todense(), dtype=bool) | A boolean matrix, m[i, j] == True if there is a relation term(i) -> term(j)
:return: a np.matrix (len(dictionary), len(dictionary)) of boolean | Below is the the instruction that describes the task:
### Input:
A boolean matrix, m[i, j] == True if there is a relation term(i) -> term(j)
:return: a np.matrix (len(dictionary), len(dictionary)) of boolean
### Response:
def connexity(self):
"""
A boolean matrix, m[i, j] == True if there i... |
def public_key_to_connection_id(self, public_key):
"""
Get stored connection id for a public key.
"""
with self._connections_lock:
for connection_id, connection_info in self._connections.items():
if connection_info.public_key == public_key:
... | Get stored connection id for a public key. | Below is the the instruction that describes the task:
### Input:
Get stored connection id for a public key.
### Response:
def public_key_to_connection_id(self, public_key):
"""
Get stored connection id for a public key.
"""
with self._connections_lock:
for connection_id,... |
async def get_txn(self, seq_no: int) -> str:
"""
Find a transaction on the distributed ledger by its sequence number.
:param seq_no: transaction number
:return: json sequence number of transaction, null for no match
"""
LOGGER.debug('BaseAnchor.get_txn >>> seq_no: %s', ... | Find a transaction on the distributed ledger by its sequence number.
:param seq_no: transaction number
:return: json sequence number of transaction, null for no match | Below is the the instruction that describes the task:
### Input:
Find a transaction on the distributed ledger by its sequence number.
:param seq_no: transaction number
:return: json sequence number of transaction, null for no match
### Response:
async def get_txn(self, seq_no: int) -> str:
... |
def decode_complementarity(comp, control):
'''
# comp can be either:
- None
- "a<=expr" where a is a controls
- "expr<=a" where a is a control
- "expr1<=a<=expr2"
'''
try:
res = regex.match(comp).groups()
except:
raise Exception("Unable to parse complementarity cond... | # comp can be either:
- None
- "a<=expr" where a is a controls
- "expr<=a" where a is a control
- "expr1<=a<=expr2" | Below is the the instruction that describes the task:
### Input:
# comp can be either:
- None
- "a<=expr" where a is a controls
- "expr<=a" where a is a control
- "expr1<=a<=expr2"
### Response:
def decode_complementarity(comp, control):
'''
# comp can be either:
- None
- "a<=expr"... |
def press_enter(multiple=False, silent=False):
"""Return a generator function which yields every time the user presses
return."""
def f():
try:
while True:
if silent:
yield input()
else:
sys.stderr.write("<press ent... | Return a generator function which yields every time the user presses
return. | Below is the the instruction that describes the task:
### Input:
Return a generator function which yields every time the user presses
return.
### Response:
def press_enter(multiple=False, silent=False):
"""Return a generator function which yields every time the user presses
return."""
def f():
... |
def error_response(self, kwargs_lens, kwargs_ps):
"""
returns the 1d array of the error estimate corresponding to the data response
:return: 1d numpy array of response, 2d array of additonal errors (e.g. point source uncertainties)
"""
model_error = self.error_map(kwargs_lens, k... | returns the 1d array of the error estimate corresponding to the data response
:return: 1d numpy array of response, 2d array of additonal errors (e.g. point source uncertainties) | Below is the the instruction that describes the task:
### Input:
returns the 1d array of the error estimate corresponding to the data response
:return: 1d numpy array of response, 2d array of additonal errors (e.g. point source uncertainties)
### Response:
def error_response(self, kwargs_lens, kwargs_ps):... |
def eval_table(tbl, expression, vm='python', blen=None, storage=None,
create='array', vm_kwargs=None, **kwargs):
"""Evaluate `expression` against columns of a table."""
# setup
storage = _util.get_storage(storage)
names, columns = _util.check_table_like(tbl)
length = len(columns[0])
... | Evaluate `expression` against columns of a table. | Below is the the instruction that describes the task:
### Input:
Evaluate `expression` against columns of a table.
### Response:
def eval_table(tbl, expression, vm='python', blen=None, storage=None,
create='array', vm_kwargs=None, **kwargs):
"""Evaluate `expression` against columns of a table.""... |
def set_model(self, model):
'''
Set the model to fuzz
:type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass
:param model: Model object to fuzz
'''
self.model = model
if self.model:
self.model.set_notification_handler(self)
... | Set the model to fuzz
:type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass
:param model: Model object to fuzz | Below is the the instruction that describes the task:
### Input:
Set the model to fuzz
:type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass
:param model: Model object to fuzz
### Response:
def set_model(self, model):
'''
Set the model to fuzz
:type mo... |
def bitstring_probs_to_z_moments(p):
"""
Convert between bitstring probabilities and joint Z moment expectations.
:param np.array p: An array that enumerates bitstring probabilities. When
flattened out ``p = [p_00...0, p_00...1, ...,p_11...1]``. The total number of elements must
therefore b... | Convert between bitstring probabilities and joint Z moment expectations.
:param np.array p: An array that enumerates bitstring probabilities. When
flattened out ``p = [p_00...0, p_00...1, ...,p_11...1]``. The total number of elements must
therefore be a power of 2. The canonical shape has a separat... | Below is the the instruction that describes the task:
### Input:
Convert between bitstring probabilities and joint Z moment expectations.
:param np.array p: An array that enumerates bitstring probabilities. When
flattened out ``p = [p_00...0, p_00...1, ...,p_11...1]``. The total number of elements must... |
def parse_deps(orig_doc, options={}):
"""Generate dependency parse in {'words': [], 'arcs': []} format.
doc (Doc): Document do parse.
RETURNS (dict): Generated dependency parse keyed by words and arcs.
"""
doc = Doc(orig_doc.vocab).from_bytes(orig_doc.to_bytes())
if not doc.is_parsed:
u... | Generate dependency parse in {'words': [], 'arcs': []} format.
doc (Doc): Document do parse.
RETURNS (dict): Generated dependency parse keyed by words and arcs. | Below is the the instruction that describes the task:
### Input:
Generate dependency parse in {'words': [], 'arcs': []} format.
doc (Doc): Document do parse.
RETURNS (dict): Generated dependency parse keyed by words and arcs.
### Response:
def parse_deps(orig_doc, options={}):
"""Generate dependency p... |
async def create_guild(self, name, region=None, icon=None):
"""|coro|
Creates a :class:`.Guild`.
Bot accounts in more than 10 guilds are not allowed to create guilds.
Parameters
----------
name: :class:`str`
The name of the guild.
region: :class:`Vo... | |coro|
Creates a :class:`.Guild`.
Bot accounts in more than 10 guilds are not allowed to create guilds.
Parameters
----------
name: :class:`str`
The name of the guild.
region: :class:`VoiceRegion`
The region for the voice communication server.
... | Below is the the instruction that describes the task:
### Input:
|coro|
Creates a :class:`.Guild`.
Bot accounts in more than 10 guilds are not allowed to create guilds.
Parameters
----------
name: :class:`str`
The name of the guild.
region: :class:`Voic... |
def get_object_type_by_name(object_type_name):
"""
:return: type suitable to handle the given object type name.
Use the type to create new instances.
:param object_type_name: Member of TYPES
:raise ValueError: In case object_type_name is unknown"""
if object_type_name == b"commit":
... | :return: type suitable to handle the given object type name.
Use the type to create new instances.
:param object_type_name: Member of TYPES
:raise ValueError: In case object_type_name is unknown | Below is the the instruction that describes the task:
### Input:
:return: type suitable to handle the given object type name.
Use the type to create new instances.
:param object_type_name: Member of TYPES
:raise ValueError: In case object_type_name is unknown
### Response:
def get_object_type_by_... |
def check_order_triggers(self, current_price):
"""
Given an order and a trade event, return a tuple of
(stop_reached, limit_reached).
For market orders, will return (False, False).
For stop orders, limit_reached will always be False.
For limit orders, stop_reached will al... | Given an order and a trade event, return a tuple of
(stop_reached, limit_reached).
For market orders, will return (False, False).
For stop orders, limit_reached will always be False.
For limit orders, stop_reached will always be False.
For stop limit orders a Boolean is returned ... | Below is the the instruction that describes the task:
### Input:
Given an order and a trade event, return a tuple of
(stop_reached, limit_reached).
For market orders, will return (False, False).
For stop orders, limit_reached will always be False.
For limit orders, stop_reached will ... |
def _get_prelim_dependencies(command_template, all_templates):
""" Given a command_template determine which other templates it
depends on. This should not be used as the be-all end-all of
dependencies and before calling each command, ensure that it's
requirements are met.
"""
deps = []
for ... | Given a command_template determine which other templates it
depends on. This should not be used as the be-all end-all of
dependencies and before calling each command, ensure that it's
requirements are met. | Below is the the instruction that describes the task:
### Input:
Given a command_template determine which other templates it
depends on. This should not be used as the be-all end-all of
dependencies and before calling each command, ensure that it's
requirements are met.
### Response:
def _get_prelim_d... |
def get_err_msg(self):
"""
Return a multi-line error message for being printed, in the following
format. The text in angle brackets refers to the same-named properties
of the exception instance:
::
Syntax error:<file>:<lineno>: <msg>
<context - MOF line>... | Return a multi-line error message for being printed, in the following
format. The text in angle brackets refers to the same-named properties
of the exception instance:
::
Syntax error:<file>:<lineno>: <msg>
<context - MOF line>
<context - position indicator ... | Below is the the instruction that describes the task:
### Input:
Return a multi-line error message for being printed, in the following
format. The text in angle brackets refers to the same-named properties
of the exception instance:
::
Syntax error:<file>:<lineno>: <msg>
... |
def decorator(caller, _func=None):
"""decorator(caller) converts a caller function into a decorator"""
if _func is not None: # return a decorated function
# this is obsolete behavior; you should use decorate instead
return decorate(_func, caller)
# else return a decorator function
defau... | decorator(caller) converts a caller function into a decorator | Below is the the instruction that describes the task:
### Input:
decorator(caller) converts a caller function into a decorator
### Response:
def decorator(caller, _func=None):
"""decorator(caller) converts a caller function into a decorator"""
if _func is not None: # return a decorated function
# ... |
def positionMinError(G, vmini, extension=0.0):
"""
Calculate the minimum position errors from G and (V-I). These correspond to the sky regions with the
smallest astrometric errors.
NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS ... | Calculate the minimum position errors from G and (V-I). These correspond to the sky regions with the
smallest astrometric errors.
NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS ALSO ON THE ICRS.
Parameters
----------
G -... | Below is the the instruction that describes the task:
### Input:
Calculate the minimum position errors from G and (V-I). These correspond to the sky regions with the
smallest astrometric errors.
NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ... |
def docker_list(registry_pass):
# type: (str) -> None
""" List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker registry password.
"""
registry = conf.get('docker.registry', None)
if registry is None:
log.err("You must define doc... | List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker registry password. | Below is the the instruction that describes the task:
### Input:
List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker registry password.
### Response:
def docker_list(registry_pass):
# type: (str) -> None
""" List docker images stored in the re... |
def get_first(self, sql, parameters=None):
"""
Executes the sql and returns the first resulting row.
:param sql: the sql statement to be executed (str) or a list of
sql statements to execute
:type sql: str or list
:param parameters: The parameters to render the SQL q... | Executes the sql and returns the first resulting row.
:param sql: the sql statement to be executed (str) or a list of
sql statements to execute
:type sql: str or list
:param parameters: The parameters to render the SQL query with.
:type parameters: mapping or iterable | Below is the the instruction that describes the task:
### Input:
Executes the sql and returns the first resulting row.
:param sql: the sql statement to be executed (str) or a list of
sql statements to execute
:type sql: str or list
:param parameters: The parameters to render the... |
def getlist(self, name):
"""
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
"""
value = self.getvalue(name)
complex = {}
def... | Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list) | Below is the the instruction that describes the task:
### Input:
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
### Response:
def getlist(self, name):
"""
... |
def set_settings(key, value):
"""Set Hitman internal settings."""
with Database("settings") as settings:
if value in ['0', 'false', 'no', 'off', 'False']:
del settings[key]
print("Disabled setting")
else:
print(value)
settings[key] = value
... | Set Hitman internal settings. | Below is the the instruction that describes the task:
### Input:
Set Hitman internal settings.
### Response:
def set_settings(key, value):
"""Set Hitman internal settings."""
with Database("settings") as settings:
if value in ['0', 'false', 'no', 'off', 'False']:
del settings[key]
... |
def convert_video(in_file, out_file, print_cmd=False, pre_options='',
**kwargs):
"""Convert a video with ffmpeg.
This provides a general api to ffmpeg, the executed command is::
`ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`
Options(kwargs) are mapped to ffmpeg comm... | Convert a video with ffmpeg.
This provides a general api to ffmpeg, the executed command is::
`ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`
Options(kwargs) are mapped to ffmpeg commands with the following rules:
- key=val: "-key val"
- key=True: "-key"
- key=False: ""
... | Below is the the instruction that describes the task:
### Input:
Convert a video with ffmpeg.
This provides a general api to ffmpeg, the executed command is::
`ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`
Options(kwargs) are mapped to ffmpeg commands with the following rules:
-... |
def make_shared_result(result, key, trajectory, new_class=None):
"""Turns an ordinary data item into a shared one.
Removes the old result from the trajectory and replaces it.
Empties the given result.
:param result: The result containing ordinary data
:param key: Name of ordinary data item
:pa... | Turns an ordinary data item into a shared one.
Removes the old result from the trajectory and replaces it.
Empties the given result.
:param result: The result containing ordinary data
:param key: Name of ordinary data item
:param trajectory: Trajectory container
:param new_class:
Clas... | Below is the the instruction that describes the task:
### Input:
Turns an ordinary data item into a shared one.
Removes the old result from the trajectory and replaces it.
Empties the given result.
:param result: The result containing ordinary data
:param key: Name of ordinary data item
:param... |
def linkHasRel(link_attrs, target_rel):
"""Does this link have target_rel as a relationship?"""
# XXX: TESTME
rel_attr = link_attrs.get('rel')
return rel_attr and relMatches(rel_attr, target_rel) | Does this link have target_rel as a relationship? | Below is the the instruction that describes the task:
### Input:
Does this link have target_rel as a relationship?
### Response:
def linkHasRel(link_attrs, target_rel):
"""Does this link have target_rel as a relationship?"""
# XXX: TESTME
rel_attr = link_attrs.get('rel')
return rel_attr and relMatc... |
def watering_time(self):
"""Return watering_time from zone."""
# zone starts with index 0
index = self.id - 1
auto_watering_time =\
self._attributes['rain_delay_mode'][index]['auto_watering_time']
manual_watering_time =\
self._attributes['rain_delay_mode'... | Return watering_time from zone. | Below is the the instruction that describes the task:
### Input:
Return watering_time from zone.
### Response:
def watering_time(self):
"""Return watering_time from zone."""
# zone starts with index 0
index = self.id - 1
auto_watering_time =\
self._attributes['rain_delay... |
def _get_calculated_value(self, value):
"""
Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value
"""
if isinstance(value, types.LambdaType... | Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value | Below is the the instruction that describes the task:
### Input:
Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value
### Response:
def _get_calculated_value(self, v... |
def decode_ay(ay):
"""Convert binary blob from DBus queries to strings."""
if ay is None:
return ''
elif isinstance(ay, str):
return ay
elif isinstance(ay, bytes):
return ay.decode('utf-8')
else:
# dbus.Array([dbus.Byte]) or any similar sequence type:
return b... | Convert binary blob from DBus queries to strings. | Below is the the instruction that describes the task:
### Input:
Convert binary blob from DBus queries to strings.
### Response:
def decode_ay(ay):
"""Convert binary blob from DBus queries to strings."""
if ay is None:
return ''
elif isinstance(ay, str):
return ay
elif isinstance(ay... |
def _set_interface_dynamic_bypass_name_prefix(self, v, load=False):
"""
Setter method for interface_dynamic_bypass_name_prefix, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/interface_dynamic_bypass_name_prefix ... | Setter method for interface_dynamic_bypass_name_prefix, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/interface_dynamic_bypass_name_prefix (string)
If this variable is read-only (config: false) in the
source YAN... | Below is the the instruction that describes the task:
### Input:
Setter method for interface_dynamic_bypass_name_prefix, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/interface_dynamic_bypass_name_prefix (string)
... |
def parse_sidebar(self, user_page):
"""Parses the DOM and returns user attributes in the sidebar.
:type user_page: :class:`bs4.BeautifulSoup`
:param user_page: MAL user page's DOM
:rtype: dict
:return: User attributes
:raises: :class:`.InvalidUserError`, :class:`.MalformedUserPageError`
"... | Parses the DOM and returns user attributes in the sidebar.
:type user_page: :class:`bs4.BeautifulSoup`
:param user_page: MAL user page's DOM
:rtype: dict
:return: User attributes
:raises: :class:`.InvalidUserError`, :class:`.MalformedUserPageError` | Below is the the instruction that describes the task:
### Input:
Parses the DOM and returns user attributes in the sidebar.
:type user_page: :class:`bs4.BeautifulSoup`
:param user_page: MAL user page's DOM
:rtype: dict
:return: User attributes
:raises: :class:`.InvalidUserError`, :class:`.Mal... |
def as_tuple(ireq):
"""
Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.
"""
if not is_pinned_requirement(ireq):
raise TypeError("Expected a pinned InstallRequirement, got {}".format(ireq))
name = key_from_req(ireq.req)
version = first(ireq... | Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement. | Below is the the instruction that describes the task:
### Input:
Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.
### Response:
def as_tuple(ireq):
"""
Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.
"""
i... |
def hyperbolic_errors(hyp_axes, xvals,
transformation=None, axes=None,
means=None, correct_apparent_dip=True,
reverse=False):
"""
Returns a function that can be used to create a view of the
hyperbolic error ellipse from a specific direction.
... | Returns a function that can be used to create a view of the
hyperbolic error ellipse from a specific direction.
This creates a hyperbolic quadric and slices it to form a conic
on a 2d cartesian plane aligned with the requested direction.
A function is returned that takes x values (distance along nomin... | Below is the the instruction that describes the task:
### Input:
Returns a function that can be used to create a view of the
hyperbolic error ellipse from a specific direction.
This creates a hyperbolic quadric and slices it to form a conic
on a 2d cartesian plane aligned with the requested direction.
... |
def from_id(cls, context: InstaloaderContext, profile_id: int):
"""Create a Profile instance from a given userid. If possible, use :meth:`Profile.from_username`
or constructor directly rather than this method, since it requires more requests.
:param context: :attr:`Instaloader.context`
... | Create a Profile instance from a given userid. If possible, use :meth:`Profile.from_username`
or constructor directly rather than this method, since it requires more requests.
:param context: :attr:`Instaloader.context`
:param profile_id: userid
:raises: :class:`ProfileNotExistsExceptio... | Below is the the instruction that describes the task:
### Input:
Create a Profile instance from a given userid. If possible, use :meth:`Profile.from_username`
or constructor directly rather than this method, since it requires more requests.
:param context: :attr:`Instaloader.context`
:param... |
def on_demand_annotation(twitter_app_key, twitter_app_secret, user_twitter_id):
"""
A service that leverages twitter lists for on-demand annotation of popular users.
TODO: Do this.
"""
##################################################################################################################... | A service that leverages twitter lists for on-demand annotation of popular users.
TODO: Do this. | Below is the the instruction that describes the task:
### Input:
A service that leverages twitter lists for on-demand annotation of popular users.
TODO: Do this.
### Response:
def on_demand_annotation(twitter_app_key, twitter_app_secret, user_twitter_id):
"""
A service that leverages twitter lists for... |
def ensure_utf8(image_tag):
"""wrapper for ensuring image_tag returns utf8-encoded str on Python 2"""
if py3compat.PY3:
# nothing to do on Python 3
return image_tag
def utf8_image_tag(*args, **kwargs):
s = image_tag(*args, **kwargs)
if isinstance(s, unicode):
... | wrapper for ensuring image_tag returns utf8-encoded str on Python 2 | Below is the the instruction that describes the task:
### Input:
wrapper for ensuring image_tag returns utf8-encoded str on Python 2
### Response:
def ensure_utf8(image_tag):
"""wrapper for ensuring image_tag returns utf8-encoded str on Python 2"""
if py3compat.PY3:
# nothing to do on Python 3
... |
def shared_client(ClientType, *args, **kwargs):
"""Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared.
"""
kwarg_key = tuple(... | Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared. | Below is the the instruction that describes the task:
### Input:
Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared.
### Response:
d... |
def pawn_from_dummy(self, dummy):
"""Make a real thing and its pawn from a dummy pawn.
Create a new :class:`board.Pawn` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
location, and imagery of the provided dummy.
"""
dummy.pos = s... | Make a real thing and its pawn from a dummy pawn.
Create a new :class:`board.Pawn` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
location, and imagery of the provided dummy. | Below is the the instruction that describes the task:
### Input:
Make a real thing and its pawn from a dummy pawn.
Create a new :class:`board.Pawn` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
location, and imagery of the provided dummy.
### Respon... |
def map_(cache: Mapping[Domain, Range]) -> Operator[Map[Domain, Range]]:
"""
Returns decorator that calls wrapped function
if nothing was found in cache for its argument.
Wrapped function arguments should be hashable.
"""
def wrapper(function: Map[Domain, Range]) -> Map[Domain, Range]:
... | Returns decorator that calls wrapped function
if nothing was found in cache for its argument.
Wrapped function arguments should be hashable. | Below is the the instruction that describes the task:
### Input:
Returns decorator that calls wrapped function
if nothing was found in cache for its argument.
Wrapped function arguments should be hashable.
### Response:
def map_(cache: Mapping[Domain, Range]) -> Operator[Map[Domain, Range]]:
"""
R... |
def ids2strids(ids: Iterable[int]) -> str:
"""
Returns a string representation of a sequence of integers.
:param ids: Sequence of integers.
:return: String sequence
"""
return C.TOKEN_SEPARATOR.join(map(str, ids)) | Returns a string representation of a sequence of integers.
:param ids: Sequence of integers.
:return: String sequence | Below is the the instruction that describes the task:
### Input:
Returns a string representation of a sequence of integers.
:param ids: Sequence of integers.
:return: String sequence
### Response:
def ids2strids(ids: Iterable[int]) -> str:
"""
Returns a string representation of a sequence of integ... |
def _sim_WA(trace, PAZ, seedresp, water_level, velocity=False):
"""
Remove the instrument response from a trace and simulate a Wood-Anderson.
Returns a de-meaned, de-trended, Wood Anderson simulated trace in
its place.
Works in-place on data and will destroy your original data, copy the
trace ... | Remove the instrument response from a trace and simulate a Wood-Anderson.
Returns a de-meaned, de-trended, Wood Anderson simulated trace in
its place.
Works in-place on data and will destroy your original data, copy the
trace before giving it to this function!
:type trace: obspy.core.trace.Trace
... | Below is the the instruction that describes the task:
### Input:
Remove the instrument response from a trace and simulate a Wood-Anderson.
Returns a de-meaned, de-trended, Wood Anderson simulated trace in
its place.
Works in-place on data and will destroy your original data, copy the
trace before ... |
def parse_args(args):
''' Parse an argument string
http://stackoverflow.com/questions/18160078/
how-do-you-write-tests-for-the-argparse-portion-of-a-python-module
'''
parser = argparse.ArgumentParser()
parser.add_argument('config_file', nargs='?',
help='Configura... | Parse an argument string
http://stackoverflow.com/questions/18160078/
how-do-you-write-tests-for-the-argparse-portion-of-a-python-module | Below is the the instruction that describes the task:
### Input:
Parse an argument string
http://stackoverflow.com/questions/18160078/
how-do-you-write-tests-for-the-argparse-portion-of-a-python-module
### Response:
def parse_args(args):
''' Parse an argument string
http://stackoverfl... |
def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
# If initial Y is non-zero, initial U is chosen so that
# the relevant dual optimality criterion (see (3.10) i... | Return initialiser for working variable U. | Below is the the instruction that describes the task:
### Input:
Return initialiser for working variable U.
### Response:
def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
... |
def upload_to_picture(instance, filename):
"""
Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and
saving it under unique hash for the image. This is for privacy
reasons so others can't just browse through the picture directory.
"""
extension = filename.split('.')[-1].lower()
... | Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and
saving it under unique hash for the image. This is for privacy
reasons so others can't just browse through the picture directory. | Below is the the instruction that describes the task:
### Input:
Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and
saving it under unique hash for the image. This is for privacy
reasons so others can't just browse through the picture directory.
### Response:
def upload_to_picture(instance... |
def get(cls, bucket, key, upload_id, with_completed=False):
"""Fetch a specific multipart object."""
q = cls.query.filter_by(
upload_id=upload_id,
bucket_id=as_bucket_id(bucket),
key=key,
)
if not with_completed:
q = q.filter(cls.completed.... | Fetch a specific multipart object. | Below is the the instruction that describes the task:
### Input:
Fetch a specific multipart object.
### Response:
def get(cls, bucket, key, upload_id, with_completed=False):
"""Fetch a specific multipart object."""
q = cls.query.filter_by(
upload_id=upload_id,
bucket_id=as_b... |
def delete(self, **kwds):
"""
Endpoint: /tag/<id>/delete.json
Deletes this tag.
Returns True if successful.
Raises a TroveboxError if not.
"""
result = self._client.tag.delete(self, **kwds)
self._delete_fields()
return result | Endpoint: /tag/<id>/delete.json
Deletes this tag.
Returns True if successful.
Raises a TroveboxError if not. | Below is the the instruction that describes the task:
### Input:
Endpoint: /tag/<id>/delete.json
Deletes this tag.
Returns True if successful.
Raises a TroveboxError if not.
### Response:
def delete(self, **kwds):
"""
Endpoint: /tag/<id>/delete.json
Deletes this ta... |
def general_eq(a, b, attributes):
"""Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All other attributes are compared ... | Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All other attributes are compared with
:func:`numpy_aware_eq`. | Below is the the instruction that describes the task:
### Input:
Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All ot... |
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
re... | Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result. | Below is the the instruction that describes the task:
### Input:
Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included i... |
def Lookup(self, x):
"""Looks up x and returns the corresponding value of y."""
return self._Bisect(x, self.xs, self.ys) | Looks up x and returns the corresponding value of y. | Below is the the instruction that describes the task:
### Input:
Looks up x and returns the corresponding value of y.
### Response:
def Lookup(self, x):
"""Looks up x and returns the corresponding value of y."""
return self._Bisect(x, self.xs, self.ys) |
def _column_type(strings, has_invisible=True):
"""The least generic type all column values are convertible to.
>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _column_type(["f... | The least generic type all column values are convertible to.
>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _column_type(["four", '\u043f\u044f\u0442\u044c']) is _text_type
T... | Below is the the instruction that describes the task:
### Input:
The least generic type all column values are convertible to.
>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _... |
def failure_message(description, options):
"""
Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure.
"""... | Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure. | Below is the the instruction that describes the task:
### Input:
Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the fa... |
def killBatchJobs(self, jobIDs):
"""Kills jobs by ID."""
log.debug('Killing jobs: {}'.format(jobIDs))
for jobID in jobIDs:
if jobID in self.runningJobs:
info = self.runningJobs[jobID]
info.killIntended = True
if info.popen != None:
... | Kills jobs by ID. | Below is the the instruction that describes the task:
### Input:
Kills jobs by ID.
### Response:
def killBatchJobs(self, jobIDs):
"""Kills jobs by ID."""
log.debug('Killing jobs: {}'.format(jobIDs))
for jobID in jobIDs:
if jobID in self.runningJobs:
info = self.r... |
def t_UINTN(t):
r"uint(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)"
size = int(t.lexer.lexmatch.group('size'))
t.value = ('uint', size)
return t | r"uint(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8) | Below is the the instruction that describes the task:
### Input:
r"uint(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)
### Response:
def t_UINTN(t):
r"uint(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|12... |
def cublasDspr(handle, uplo, n, alpha, x, incx, AP):
"""
Rank-1 operation on real symmetric-packed matrix.
"""
status = _libcublas.cublasDspr_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctype... | Rank-1 operation on real symmetric-packed matrix. | Below is the the instruction that describes the task:
### Input:
Rank-1 operation on real symmetric-packed matrix.
### Response:
def cublasDspr(handle, uplo, n, alpha, x, incx, AP):
"""
Rank-1 operation on real symmetric-packed matrix.
"""
status = _libcublas.cublasDspr_v2(handle,
... |
def update_version(self, service_id, version_number, **kwargs):
"""Update a particular version for a particular service."""
body = self._formdata(kwargs, FastlyVersion.FIELDS)
content = self._fetch("/service/%s/version/%d/" % (service_id, version_number), method="PUT", body=body)
return FastlyVersion(self, cont... | Update a particular version for a particular service. | Below is the the instruction that describes the task:
### Input:
Update a particular version for a particular service.
### Response:
def update_version(self, service_id, version_number, **kwargs):
"""Update a particular version for a particular service."""
body = self._formdata(kwargs, FastlyVersion.FIELDS)
... |
def populate_from_staging(self, staging_table, from_column_list, output_table):
"""
generate SQL to insert staging table records into
the core table based on column_list (If no column list
then insert sequentially)
"""
self.sql_text += 'INSERT INTO ' + output_table + ' (... | generate SQL to insert staging table records into
the core table based on column_list (If no column list
then insert sequentially) | Below is the the instruction that describes the task:
### Input:
generate SQL to insert staging table records into
the core table based on column_list (If no column list
then insert sequentially)
### Response:
def populate_from_staging(self, staging_table, from_column_list, output_table):
"... |
def begin(self):
""" At the start of the run, we want to record the test
execution information in the database. """
exec_payload = ExecutionQueryPayload()
exec_payload.execution_start_time = int(time.time() * 1000)
self.execution_start_time = exec_payload.execution_start_time... | At the start of the run, we want to record the test
execution information in the database. | Below is the the instruction that describes the task:
### Input:
At the start of the run, we want to record the test
execution information in the database.
### Response:
def begin(self):
""" At the start of the run, we want to record the test
execution information in the database. "... |
def update_from_xlsx_blob(self, xlsx_blob):
"""
Replace the Excel spreadsheet in the related |EmbeddedXlsxPart| with
the Excel binary in *xlsx_blob*, adding a new |EmbeddedXlsxPart| if
there isn't one.
"""
xlsx_part = self.xlsx_part
if xlsx_part is None:
... | Replace the Excel spreadsheet in the related |EmbeddedXlsxPart| with
the Excel binary in *xlsx_blob*, adding a new |EmbeddedXlsxPart| if
there isn't one. | Below is the the instruction that describes the task:
### Input:
Replace the Excel spreadsheet in the related |EmbeddedXlsxPart| with
the Excel binary in *xlsx_blob*, adding a new |EmbeddedXlsxPart| if
there isn't one.
### Response:
def update_from_xlsx_blob(self, xlsx_blob):
"""
Re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.