code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def mbcs_work_around():
'''
work around for mbcs codec to make "bdist_wininst" work
https://mail.python.org/pipermail/python-list/2012-February/620326.html
'''
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
codecs.register(... | work around for mbcs codec to make "bdist_wininst" work
https://mail.python.org/pipermail/python-list/2012-February/620326.html | Below is the the instruction that describes the task:
### Input:
work around for mbcs codec to make "bdist_wininst" work
https://mail.python.org/pipermail/python-list/2012-February/620326.html
### Response:
def mbcs_work_around():
'''
work around for mbcs codec to make "bdist_wininst" work
https://... |
def emit(self, action, payload):
"""Emit action with payload via `requests.post`."""
url = self.get_emit_api(action)
headers = {
'User-Agent': 'rio/%s' % VERSION,
'X-Rio-Protocol': '1',
}
args = dict(
url=url,
json=payload,
... | Emit action with payload via `requests.post`. | Below is the the instruction that describes the task:
### Input:
Emit action with payload via `requests.post`.
### Response:
def emit(self, action, payload):
"""Emit action with payload via `requests.post`."""
url = self.get_emit_api(action)
headers = {
'User-Agent': 'rio/%s' % ... |
def _fill_capture_regions(data):
"""Fill short-hand specification of BED capture regions.
"""
special_targets = {"sv_regions": ("exons", "transcripts")}
ref_file = dd.get_ref_file(data)
for target in ["variant_regions", "sv_regions", "coverage"]:
val = tz.get_in(["config", "algorithm", targe... | Fill short-hand specification of BED capture regions. | Below is the the instruction that describes the task:
### Input:
Fill short-hand specification of BED capture regions.
### Response:
def _fill_capture_regions(data):
"""Fill short-hand specification of BED capture regions.
"""
special_targets = {"sv_regions": ("exons", "transcripts")}
ref_file = dd... |
def goBack(self):
"""
Goes up one level if possible and returns the url at the current level.
If it cannot go up, then a blank string will be returned.
:return <str>
"""
if not self.canGoBack():
return ''
self._blockStack = Tru... | Goes up one level if possible and returns the url at the current level.
If it cannot go up, then a blank string will be returned.
:return <str> | Below is the the instruction that describes the task:
### Input:
Goes up one level if possible and returns the url at the current level.
If it cannot go up, then a blank string will be returned.
:return <str>
### Response:
def goBack(self):
"""
Goes up one level if poss... |
def find_modules_with_decorators(path,decorator_module,decorator_name):
'''
Finds all the modules decorated with the specified decorator in the path, file or module specified.
Args :
path : All modules in the directory and its sub-directories will be scanned.
decorato... | Finds all the modules decorated with the specified decorator in the path, file or module specified.
Args :
path : All modules in the directory and its sub-directories will be scanned.
decorator_module : Then full name of the module defining the decorator.
decorator... | Below is the the instruction that describes the task:
### Input:
Finds all the modules decorated with the specified decorator in the path, file or module specified.
Args :
path : All modules in the directory and its sub-directories will be scanned.
decorator_module : Then ... |
def from_args(cls, args):
"""
Initialize a WorkflowConfigParser instance using the command line values
parsed in args. args must contain the values provided by the
workflow_command_line_group() function. If you are not using the standard
workflow command line interface, you shoul... | Initialize a WorkflowConfigParser instance using the command line values
parsed in args. args must contain the values provided by the
workflow_command_line_group() function. If you are not using the standard
workflow command line interface, you should probably initialize directly
using _... | Below is the the instruction that describes the task:
### Input:
Initialize a WorkflowConfigParser instance using the command line values
parsed in args. args must contain the values provided by the
workflow_command_line_group() function. If you are not using the standard
workflow command li... |
def find_case_control(items):
"""Find case/control items in a population of multiple samples.
"""
cases = []
controls = []
for data in items:
if population.get_affected_status(data) == 1:
controls.append(data)
else:
cases.append(data)
return cases, control... | Find case/control items in a population of multiple samples. | Below is the the instruction that describes the task:
### Input:
Find case/control items in a population of multiple samples.
### Response:
def find_case_control(items):
"""Find case/control items in a population of multiple samples.
"""
cases = []
controls = []
for data in items:
if po... |
def get_unpermitted_fields(self):
"""
Gives unpermitted fields for current context/user.
Returns:
List of unpermitted field names.
"""
return (self._unpermitted_fields if self._is_unpermitted_fields_set else
self._apply_cell_filters(self._context)) | Gives unpermitted fields for current context/user.
Returns:
List of unpermitted field names. | Below is the the instruction that describes the task:
### Input:
Gives unpermitted fields for current context/user.
Returns:
List of unpermitted field names.
### Response:
def get_unpermitted_fields(self):
"""
Gives unpermitted fields for current context/user.
Returns:... |
def sql_like_fragments(self) -> List[str]:
"""
Returns all the string literals to which a database column should be
compared using the SQL ``LIKE`` operator, to match this drug.
This isn't as accurate as the regex, but ``LIKE`` can do less.
``LIKE`` uses the wildcards ``?`` and... | Returns all the string literals to which a database column should be
compared using the SQL ``LIKE`` operator, to match this drug.
This isn't as accurate as the regex, but ``LIKE`` can do less.
``LIKE`` uses the wildcards ``?`` and ``%``. | Below is the the instruction that describes the task:
### Input:
Returns all the string literals to which a database column should be
compared using the SQL ``LIKE`` operator, to match this drug.
This isn't as accurate as the regex, but ``LIKE`` can do less.
``LIKE`` uses the wildcards ``?... |
def getWindowByTitle(self, wildcard, order=0):
""" Returns a handle for the first window that matches the provided "wildcard" regex """
for w in self._get_window_list():
if "kCGWindowName" in w and re.search(wildcard, w["kCGWindowName"], flags=re.I):
# Matches - make sure we ... | Returns a handle for the first window that matches the provided "wildcard" regex | Below is the the instruction that describes the task:
### Input:
Returns a handle for the first window that matches the provided "wildcard" regex
### Response:
def getWindowByTitle(self, wildcard, order=0):
""" Returns a handle for the first window that matches the provided "wildcard" regex """
for... |
def register_event(self, direction, verb, child_fn, priority=10):
"""Register an event with all servers.
Args:
direction (str): `in`, `out`, `both`, or `girc`.
verb (str): Event name, `all`, or `raw`.
child_fn (function): Handler function.
priority (int):... | Register an event with all servers.
Args:
direction (str): `in`, `out`, `both`, or `girc`.
verb (str): Event name, `all`, or `raw`.
child_fn (function): Handler function.
priority (int): Handler priority (lower priority executes first).
Note: `all` will ... | Below is the the instruction that describes the task:
### Input:
Register an event with all servers.
Args:
direction (str): `in`, `out`, `both`, or `girc`.
verb (str): Event name, `all`, or `raw`.
child_fn (function): Handler function.
priority (int): Handler... |
def SummaryMetadata(self, run, tag):
"""Return the summary metadata for the given tag on the given run.
Args:
run: A string name of the run for which summary metadata is to be
retrieved.
tag: A string name of the tag whose summary metadata is to be
retrieved.
Raises:
KeyE... | Return the summary metadata for the given tag on the given run.
Args:
run: A string name of the run for which summary metadata is to be
retrieved.
tag: A string name of the tag whose summary metadata is to be
retrieved.
Raises:
KeyError: If the run is not found, or the tag is... | Below is the the instruction that describes the task:
### Input:
Return the summary metadata for the given tag on the given run.
Args:
run: A string name of the run for which summary metadata is to be
retrieved.
tag: A string name of the tag whose summary metadata is to be
retrieved... |
def run_compare_gold_standard(in_prefix, in_type, out_prefix, base_dir,
options):
"""Compares with a gold standard data set (compare_gold_standard.
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output p... | Compares with a gold standard data set (compare_gold_standard.
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: the options needed.
:type in_prefix: str
... | Below is the the instruction that describes the task:
### Input:
Compares with a gold standard data set (compare_gold_standard.
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
... |
def remove_member_from_group(self, group_id, user_id):
"""
Add a user to a group as a member
:param group_id:
:param user_id:
"""
url = self.TEAM_MEMBERS_URL % (group_id, user_id)
connection = Connection(self.token)
connection.set_url(self.production, url... | Add a user to a group as a member
:param group_id:
:param user_id: | Below is the the instruction that describes the task:
### Input:
Add a user to a group as a member
:param group_id:
:param user_id:
### Response:
def remove_member_from_group(self, group_id, user_id):
"""
Add a user to a group as a member
:param group_id:
:param user... |
def to_content_range_header(self, length):
"""Converts the object into `Content-Range` HTTP header,
based on given length
"""
range_for_length = self.range_for_length(length)
if range_for_length is not None:
return "%s %d-%d/%d" % (
self.units,
... | Converts the object into `Content-Range` HTTP header,
based on given length | Below is the the instruction that describes the task:
### Input:
Converts the object into `Content-Range` HTTP header,
based on given length
### Response:
def to_content_range_header(self, length):
"""Converts the object into `Content-Range` HTTP header,
based on given length
"""
... |
def get_company_user(self, email):
"""Get company user based on email.
:param email: address of contact
:type email: ``str``, ``unicode``
:rtype: ``dict`` with contact information
"""
users = self.get_company_users()
for user in users:
if user['email... | Get company user based on email.
:param email: address of contact
:type email: ``str``, ``unicode``
:rtype: ``dict`` with contact information | Below is the the instruction that describes the task:
### Input:
Get company user based on email.
:param email: address of contact
:type email: ``str``, ``unicode``
:rtype: ``dict`` with contact information
### Response:
def get_company_user(self, email):
"""Get company user based ... |
def scramble_value(self, value):
"""Duck-type value and scramble appropriately"""
try:
type, format = typeof_rave_data(value)
if type == 'float':
i, f = value.split('.')
return self.scramble_float(len(value) - 1, len(f))
elif type == 'i... | Duck-type value and scramble appropriately | Below is the the instruction that describes the task:
### Input:
Duck-type value and scramble appropriately
### Response:
def scramble_value(self, value):
"""Duck-type value and scramble appropriately"""
try:
type, format = typeof_rave_data(value)
if type == 'float':
... |
def get_list(self, **kwargs):
"""Get list of items from Model
---
get:
parameters:
- $ref: '#/components/parameters/get_list_schema'
responses:
200:
description: Items from Model
content:
application/json:
... | Get list of items from Model
---
get:
parameters:
- $ref: '#/components/parameters/get_list_schema'
responses:
200:
description: Items from Model
content:
application/json:
schema:
... | Below is the the instruction that describes the task:
### Input:
Get list of items from Model
---
get:
parameters:
- $ref: '#/components/parameters/get_list_schema'
responses:
200:
description: Items from Model
content:
... |
def _get_gradient_log_pdf(self):
"""
Method that finds gradient and its log at position
"""
sub_vec = self.variable_assignments - self.model.mean.flatten()
grad = - np.dot(self.model.precision_matrix, sub_vec)
log_pdf = 0.5 * np.dot(sub_vec, grad)
return grad, lo... | Method that finds gradient and its log at position | Below is the the instruction that describes the task:
### Input:
Method that finds gradient and its log at position
### Response:
def _get_gradient_log_pdf(self):
"""
Method that finds gradient and its log at position
"""
sub_vec = self.variable_assignments - self.model.mean.flatten... |
def parse_url(self):
""" Parses a URL of the form:
- ws://host[:port][path]
- wss://host[:port][path]
- ws+unix:///path/to/my.socket
"""
self.scheme = None
self.resource = None
self.host = None
self.port = None
if self.url is None:
... | Parses a URL of the form:
- ws://host[:port][path]
- wss://host[:port][path]
- ws+unix:///path/to/my.socket | Below is the the instruction that describes the task:
### Input:
Parses a URL of the form:
- ws://host[:port][path]
- wss://host[:port][path]
- ws+unix:///path/to/my.socket
### Response:
def parse_url(self):
""" Parses a URL of the form:
- ws://host[:port][path]
- ... |
def set_state(self, state, enable):
"""Set the state."""
is_enabled = self.get_state(state)
if is_enabled == enable:
return True
key = None
desired_states = [{'state': state, 'enabled': not is_enabled}]
if state == States.FILTER_LOW_SPEED:
if no... | Set the state. | Below is the the instruction that describes the task:
### Input:
Set the state.
### Response:
def set_state(self, state, enable):
"""Set the state."""
is_enabled = self.get_state(state)
if is_enabled == enable:
return True
key = None
desired_states = [{'state':... |
def looks_like_issubclass(obj, classname):
""" Return True if the object has a class or superclass with the given class
name.
Ignores old-style classes.
"""
t = obj
if t.__name__ == classname:
return True
for klass in t.__mro__:
if klass.__name__ == classname:
re... | Return True if the object has a class or superclass with the given class
name.
Ignores old-style classes. | Below is the the instruction that describes the task:
### Input:
Return True if the object has a class or superclass with the given class
name.
Ignores old-style classes.
### Response:
def looks_like_issubclass(obj, classname):
""" Return True if the object has a class or superclass with the given cla... |
def index(self, collection, docs, params=None, min_rf=None, **kwargs):
"""
:param str collection: The name of the collection for the request.
:param docs list docs: List of dicts. ex: [{"title": "testing solr indexing", "id": "test1"}]
:param min_rf int min_rf: Required number of replica... | :param str collection: The name of the collection for the request.
:param docs list docs: List of dicts. ex: [{"title": "testing solr indexing", "id": "test1"}]
:param min_rf int min_rf: Required number of replicas to write to'
Sends supplied list of dicts to solr for indexing. ::
... | Below is the the instruction that describes the task:
### Input:
:param str collection: The name of the collection for the request.
:param docs list docs: List of dicts. ex: [{"title": "testing solr indexing", "id": "test1"}]
:param min_rf int min_rf: Required number of replicas to write to'
... |
def next(self):
"""Advance the cursor."""
if self.__empty:
raise StopIteration
if len(self.__data) or self._refresh():
if self.__manipulate:
_db = self.__collection.database
return _db._fix_outgoing(self.__data.popleft(),
... | Advance the cursor. | Below is the the instruction that describes the task:
### Input:
Advance the cursor.
### Response:
def next(self):
"""Advance the cursor."""
if self.__empty:
raise StopIteration
if len(self.__data) or self._refresh():
if self.__manipulate:
_db = self.... |
def output(data, **kwargs): # pylint: disable=unused-argument
'''
Rather basic....
'''
if not isinstance(data, six.string_types):
data = six.text_type(data)
return salt.utils.stringutils.to_unicode(data) | Rather basic.... | Below is the the instruction that describes the task:
### Input:
Rather basic....
### Response:
def output(data, **kwargs): # pylint: disable=unused-argument
'''
Rather basic....
'''
if not isinstance(data, six.string_types):
data = six.text_type(data)
return salt.utils.stringutils.to_... |
def datetime_to_ms(d):
"""Convert a Python datetime object to a millisecond epoch (UTC) time value."""
try:
millisecond = d.microsecond // 1000
return calendar.timegm(_add_tzone(d).utctimetuple()) * 1000 + millisecond
except AttributeError:
raise TypeError('expect Python datetime obj... | Convert a Python datetime object to a millisecond epoch (UTC) time value. | Below is the the instruction that describes the task:
### Input:
Convert a Python datetime object to a millisecond epoch (UTC) time value.
### Response:
def datetime_to_ms(d):
"""Convert a Python datetime object to a millisecond epoch (UTC) time value."""
try:
millisecond = d.microsecond // 1000
... |
def get_default_env(self):
"""
Vanilla Ansible local commands execute with an environment inherited
from WorkerProcess, we must emulate that.
"""
return dict_diff(
old=ansible_mitogen.process.MuxProcess.original_env,
new=os.environ,
) | Vanilla Ansible local commands execute with an environment inherited
from WorkerProcess, we must emulate that. | Below is the the instruction that describes the task:
### Input:
Vanilla Ansible local commands execute with an environment inherited
from WorkerProcess, we must emulate that.
### Response:
def get_default_env(self):
"""
Vanilla Ansible local commands execute with an environment inherited
... |
def dispatchlist(self, *, author=None, category=None,
subcategory=None, sort='new'):
"""Find dispatches by certain criteria.
Parameters
----------
author : str
Name of the nation authoring the dispatch.
category : str
Dispatch's prima... | Find dispatches by certain criteria.
Parameters
----------
author : str
Name of the nation authoring the dispatch.
category : str
Dispatch's primary category.
subcategory : str
Dispatch's secondary category.
sort : str
Sort... | Below is the the instruction that describes the task:
### Input:
Find dispatches by certain criteria.
Parameters
----------
author : str
Name of the nation authoring the dispatch.
category : str
Dispatch's primary category.
subcategory : str
... |
def deps_tree(self):
"""Package dependencies image map file
"""
dependencies = self.dependencies + [self.name]
if self.repo == "sbo":
for dep in dependencies:
deps = Requires(flag="").sbo(dep)
if dep not in self.deps_dict.values():
... | Package dependencies image map file | Below is the the instruction that describes the task:
### Input:
Package dependencies image map file
### Response:
def deps_tree(self):
"""Package dependencies image map file
"""
dependencies = self.dependencies + [self.name]
if self.repo == "sbo":
for dep in dependencie... |
def hist(hists,
stacked=True,
reverse=False,
xpadding=0, ypadding=.1,
yerror_in_padding=True,
logy=None,
snap=True,
axes=None,
**kwargs):
"""
Make a matplotlib hist plot from a ROOT histogram, stack or
list of histograms.
Parameter... | Make a matplotlib hist plot from a ROOT histogram, stack or
list of histograms.
Parameters
----------
hists : Hist, list of Hist, HistStack
The histogram(s) to be plotted
stacked : bool, optional (default=True)
If True then stack the histograms with the first histogram on the
... | Below is the the instruction that describes the task:
### Input:
Make a matplotlib hist plot from a ROOT histogram, stack or
list of histograms.
Parameters
----------
hists : Hist, list of Hist, HistStack
The histogram(s) to be plotted
stacked : bool, optional (default=True)
I... |
def _get_related_series(parse_info):
"""get related_series from parse info.
:param parse_info: Parsed info from html soup.
"""
seriesother_tags = [x for x in parse_info.select('h5.seriesother')]
sibling_tag = [x for x in seriesother_tags if x.text == 'Related Series'][0]
... | get related_series from parse info.
:param parse_info: Parsed info from html soup. | Below is the the instruction that describes the task:
### Input:
get related_series from parse info.
:param parse_info: Parsed info from html soup.
### Response:
def _get_related_series(parse_info):
"""get related_series from parse info.
:param parse_info: Parsed info from html soup.
... |
def system_monitor_SFM_threshold_down_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
SFM = ET.SubElement(system_monitor, "SFM")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def system_monitor_SFM_threshold_down_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns... |
def string_for_count(dictionary, count):
"""Create a random string of N=`count` words"""
string_to_print = ""
if count is not None:
if count == 0:
return ""
ranger = count
else:
ranger = 2
for index in range(ranger):
string_to_print += "{} ".format(get_ran... | Create a random string of N=`count` words | Below is the the instruction that describes the task:
### Input:
Create a random string of N=`count` words
### Response:
def string_for_count(dictionary, count):
"""Create a random string of N=`count` words"""
string_to_print = ""
if count is not None:
if count == 0:
return ""
... |
def http_basic_auth_superuser_required(func=None):
"""Decorator. Use it to specify a RPC method is available only to logged superusers"""
wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_superuser])
# If @http_basic_auth_superuser_required() is used (with parenthesis)
... | Decorator. Use it to specify a RPC method is available only to logged superusers | Below is the the instruction that describes the task:
### Input:
Decorator. Use it to specify a RPC method is available only to logged superusers
### Response:
def http_basic_auth_superuser_required(func=None):
"""Decorator. Use it to specify a RPC method is available only to logged superusers"""
wrapper ... |
def get_normalized_parameters(request):
"""
Returns a string that contains the parameters that must be signed.
This function is called by SignatureMethod subclass CustomSignatureMethod_HMAC_SHA1
"""
# See issues #10 and #12
if ('Content-Type' not in request.headers or \
... | Returns a string that contains the parameters that must be signed.
This function is called by SignatureMethod subclass CustomSignatureMethod_HMAC_SHA1 | Below is the the instruction that describes the task:
### Input:
Returns a string that contains the parameters that must be signed.
This function is called by SignatureMethod subclass CustomSignatureMethod_HMAC_SHA1
### Response:
def get_normalized_parameters(request):
"""
Returns a string ... |
def find_globals_and_nonlocals(node, globs, nonlocals, code, version):
"""search a node of parse tree to find variable names that need a
either 'global' or 'nonlocal' statements added."""
for n in node:
if isinstance(n, SyntaxTree):
globs, nonlocals = find_globals_and_nonlocals(n, globs,... | search a node of parse tree to find variable names that need a
either 'global' or 'nonlocal' statements added. | Below is the the instruction that describes the task:
### Input:
search a node of parse tree to find variable names that need a
either 'global' or 'nonlocal' statements added.
### Response:
def find_globals_and_nonlocals(node, globs, nonlocals, code, version):
"""search a node of parse tree to find variabl... |
def bytes_base64(x):
"""Turn bytes into base64"""
if six.PY2:
return base64.encodestring(x).replace('\n', '')
return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'') | Turn bytes into base64 | Below is the the instruction that describes the task:
### Input:
Turn bytes into base64
### Response:
def bytes_base64(x):
"""Turn bytes into base64"""
if six.PY2:
return base64.encodestring(x).replace('\n', '')
return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'') |
async def change_directory(self, path=".."):
"""
:py:func:`asyncio.coroutine`
Change current directory. Goes «up» if no parameters passed.
:param path: new directory, goes «up» if omitted
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
"""
path ... | :py:func:`asyncio.coroutine`
Change current directory. Goes «up» if no parameters passed.
:param path: new directory, goes «up» if omitted
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` | Below is the the instruction that describes the task:
### Input:
:py:func:`asyncio.coroutine`
Change current directory. Goes «up» if no parameters passed.
:param path: new directory, goes «up» if omitted
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
### Response:
async ... |
def __assert_false(returned):
'''
Test if an boolean is False
'''
result = "Pass"
if isinstance(returned, str):
try:
returned = bool(returned)
except ValueError:
raise
try:
assert (returned is False), "{0... | Test if an boolean is False | Below is the the instruction that describes the task:
### Input:
Test if an boolean is False
### Response:
def __assert_false(returned):
'''
Test if an boolean is False
'''
result = "Pass"
if isinstance(returned, str):
try:
returned = bool(returne... |
def set_area_geometry(w, src):
"""
Set area polygon as shapefile geometry
"""
assert "areaSource" in src.tag
geometry_node = src.nodes[get_taglist(src).index("areaGeometry")]
area_attrs = parse_area_geometry(geometry_node)
w.poly(parts=[area_attrs["polygon"].tolist()]) | Set area polygon as shapefile geometry | Below is the the instruction that describes the task:
### Input:
Set area polygon as shapefile geometry
### Response:
def set_area_geometry(w, src):
"""
Set area polygon as shapefile geometry
"""
assert "areaSource" in src.tag
geometry_node = src.nodes[get_taglist(src).index("areaGeometry")]
... |
def get_stp_mst_detail_output_msti_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_stp_mst_detail_output_msti_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
... |
def remove_imath_operators(lines):
"""Remove mathematical expressions that require Pythons global
interpreter locking mechanism.
This is not a exhaustive test, but shows how the method works:
>>> lines = [' x += 1*1']
>>> from hydpy.cythons.modelutils import FuncConverter
... | Remove mathematical expressions that require Pythons global
interpreter locking mechanism.
This is not a exhaustive test, but shows how the method works:
>>> lines = [' x += 1*1']
>>> from hydpy.cythons.modelutils import FuncConverter
>>> FuncConverter.remove_imath_operators... | Below is the the instruction that describes the task:
### Input:
Remove mathematical expressions that require Pythons global
interpreter locking mechanism.
This is not a exhaustive test, but shows how the method works:
>>> lines = [' x += 1*1']
>>> from hydpy.cythons.modelutils ... |
def code_to_names(category, code):
"""
Given the code for a language, script, or region, get a dictionary of its
names in various languages.
"""
trie_name = '{}_to_name'.format(category)
if trie_name not in TRIES:
TRIES[trie_name] = load_trie(data_filename('trie/{}.marisa'.format(trie_na... | Given the code for a language, script, or region, get a dictionary of its
names in various languages. | Below is the the instruction that describes the task:
### Input:
Given the code for a language, script, or region, get a dictionary of its
names in various languages.
### Response:
def code_to_names(category, code):
"""
Given the code for a language, script, or region, get a dictionary of its
names... |
def authorize_url(self):
"""获取授权跳转地址
:return: URL 地址
"""
redirect_uri = quote(self.redirect_uri, safe=b'')
url_list = [
self.OAUTH_BASE_URL,
'oauth2/authorize?appid=',
self.app_id,
'&redirect_uri=',
redirect_uri,
... | 获取授权跳转地址
:return: URL 地址 | Below is the the instruction that describes the task:
### Input:
获取授权跳转地址
:return: URL 地址
### Response:
def authorize_url(self):
"""获取授权跳转地址
:return: URL 地址
"""
redirect_uri = quote(self.redirect_uri, safe=b'')
url_list = [
self.OAUTH_BASE_URL,
... |
def plot_frequencies(self, mindB=None, maxdB=None, norm=True):
"""Plot the window in the frequency domain
:param mindB: change the default lower y bound
:param maxdB: change the default upper lower bound
:param bool norm: if True, normalise the frequency response.
.. plot::
... | Plot the window in the frequency domain
:param mindB: change the default lower y bound
:param maxdB: change the default upper lower bound
:param bool norm: if True, normalise the frequency response.
.. plot::
:width: 80%
:include-source:
from spectr... | Below is the the instruction that describes the task:
### Input:
Plot the window in the frequency domain
:param mindB: change the default lower y bound
:param maxdB: change the default upper lower bound
:param bool norm: if True, normalise the frequency response.
.. plot::
... |
def process_result(self, new_sia, min_sia):
"""Check if the new SIA has smaller |big_phi| than the standing
result.
"""
if new_sia.phi == 0:
self.done = True # Short-circuit
return new_sia
elif new_sia < min_sia:
return new_sia
retur... | Check if the new SIA has smaller |big_phi| than the standing
result. | Below is the the instruction that describes the task:
### Input:
Check if the new SIA has smaller |big_phi| than the standing
result.
### Response:
def process_result(self, new_sia, min_sia):
"""Check if the new SIA has smaller |big_phi| than the standing
result.
"""
if new_... |
async def update_api(request: web.Request) -> web.Response:
"""
This handler accepts a POST request with Content-Type: multipart/form-data
and file fields in the body named "whl", "serverlib", and "fw". The "whl"
and "serverlib" files should be valid Python wheels to be installed ("whl"
is expected ... | This handler accepts a POST request with Content-Type: multipart/form-data
and file fields in the body named "whl", "serverlib", and "fw". The "whl"
and "serverlib" files should be valid Python wheels to be installed ("whl"
is expected generally to be the API server wheel, and "serverlib" is
expected to... | Below is the the instruction that describes the task:
### Input:
This handler accepts a POST request with Content-Type: multipart/form-data
and file fields in the body named "whl", "serverlib", and "fw". The "whl"
and "serverlib" files should be valid Python wheels to be installed ("whl"
is expected gen... |
def SendSms(self, *TargetNumbers, **Properties):
"""Creates and sends an SMS message.
:Parameters:
TargetNumbers : str
One or more target SMS numbers.
Properties
Message properties. Properties available are same as `SmsMessage` object properties.
:re... | Creates and sends an SMS message.
:Parameters:
TargetNumbers : str
One or more target SMS numbers.
Properties
Message properties. Properties available are same as `SmsMessage` object properties.
:return: An sms message object. The message is already sent at ... | Below is the the instruction that describes the task:
### Input:
Creates and sends an SMS message.
:Parameters:
TargetNumbers : str
One or more target SMS numbers.
Properties
Message properties. Properties available are same as `SmsMessage` object properties.
... |
def format_unix_var(text):
"""
Example::
this_is_very_good
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
raise ValueError("can not be empty string!")
else:
if text[0] in string.digits:
raise ValueError("variable can not start with d... | Example::
this_is_very_good | Below is the the instruction that describes the task:
### Input:
Example::
this_is_very_good
### Response:
def format_unix_var(text):
"""
Example::
this_is_very_good
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
raise ValueError("can not be e... |
def process_directory(source, target, apikey, handler, overwrite=False):
"""Optimize and save png files form source to target directory.
@param source: path to input directory
@param target: path to output directory
@param handler: callback holder, instance of handlers.BaseHandler
@param overwrite:... | Optimize and save png files form source to target directory.
@param source: path to input directory
@param target: path to output directory
@param handler: callback holder, instance of handlers.BaseHandler
@param overwrite: boolean flag to allow overwrite already existing
files in... | Below is the the instruction that describes the task:
### Input:
Optimize and save png files form source to target directory.
@param source: path to input directory
@param target: path to output directory
@param handler: callback holder, instance of handlers.BaseHandler
@param overwrite: boolean fl... |
def list_names():
""" List all known color names. """
names = get_all_names()
# This is 375 right now. Probably won't ever change, but I'm not sure.
nameslen = len(names)
print('\nListing {} names:\n'.format(nameslen))
# Using 3 columns of names, still alphabetically sorted from the top down.
... | List all known color names. | Below is the the instruction that describes the task:
### Input:
List all known color names.
### Response:
def list_names():
""" List all known color names. """
names = get_all_names()
# This is 375 right now. Probably won't ever change, but I'm not sure.
nameslen = len(names)
print('\nListing ... |
def _resolve(value, model_instance=None, context=None):
""" Resolves any template references in the given value.
"""
if isinstance(value, basestring) and "{" in value:
if context is None:
context = Context()
if model_instance is not None:
context[model_instance._met... | Resolves any template references in the given value. | Below is the the instruction that describes the task:
### Input:
Resolves any template references in the given value.
### Response:
def _resolve(value, model_instance=None, context=None):
""" Resolves any template references in the given value.
"""
if isinstance(value, basestring) and "{" in value:
... |
def power_chisq_at_points_from_precomputed(corr, snr, snr_norm, bins, indices):
"""Calculate the chisq timeseries from precomputed values for only select points.
This function calculates the chisq at each point by explicitly time shifting
and summing each bin. No FFT is involved.
Parameters
------... | Calculate the chisq timeseries from precomputed values for only select points.
This function calculates the chisq at each point by explicitly time shifting
and summing each bin. No FFT is involved.
Parameters
----------
corr: FrequencySeries
The product of the template and data in the freq... | Below is the the instruction that describes the task:
### Input:
Calculate the chisq timeseries from precomputed values for only select points.
This function calculates the chisq at each point by explicitly time shifting
and summing each bin. No FFT is involved.
Parameters
----------
corr: Fre... |
def dipole(src, rec, depth, res, freqtime, signal=None, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, xdirect=False,
ht='fht', htarg=None, ft='sin', ftarg=None, opt=None, loop=None,
verb=2):
r"""Return the electromagnetic field due to a dipole source.
C... | r"""Return the electromagnetic field due to a dipole source.
Calculate the electromagnetic frequency- or time-domain field due to
infinitesimal small electric or magnetic dipole source(s), measured by
infinitesimal small electric or magnetic dipole receiver(s); sources and
receivers are directed along ... | Below is the the instruction that describes the task:
### Input:
r"""Return the electromagnetic field due to a dipole source.
Calculate the electromagnetic frequency- or time-domain field due to
infinitesimal small electric or magnetic dipole source(s), measured by
infinitesimal small electric or magne... |
def shutdown(name, message=None, timeout=5, force_close=True, reboot=False,
in_seconds=False, only_on_pending_reboot=False):
'''
Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
... | Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minutes or seconds before a shutdown will occur. Whether
this numbe... | Below is the the instruction that describes the task:
### Input:
Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minute... |
def _parse_s3_file(original_file):
"""
Convert `s3://bucketname/path/to/file.txt` to ('bucketname', 'path/to/file.txt')
"""
bits = original_file.replace('s3://', '').split("/")
bucket = bits[0]
object_key = "/".join(bits[1:])
return bucket, object_key | Convert `s3://bucketname/path/to/file.txt` to ('bucketname', 'path/to/file.txt') | Below is the the instruction that describes the task:
### Input:
Convert `s3://bucketname/path/to/file.txt` to ('bucketname', 'path/to/file.txt')
### Response:
def _parse_s3_file(original_file):
"""
Convert `s3://bucketname/path/to/file.txt` to ('bucketname', 'path/to/file.txt')
"""
bits = original... |
def _full_code_scan(self):
"""
Perform a full code scan on the target binary.
"""
# We gotta time this function
start_time = datetime.now()
traced_address = set()
self.functions = set()
self.call_map = networkx.DiGraph()
self.cfg = networkx.DiGra... | Perform a full code scan on the target binary. | Below is the the instruction that describes the task:
### Input:
Perform a full code scan on the target binary.
### Response:
def _full_code_scan(self):
"""
Perform a full code scan on the target binary.
"""
# We gotta time this function
start_time = datetime.now()
... |
def createCategoryFilter(self, retina_name, filter_name, body, ):
"""get filter for classifier
Args:
filter_name, str: A unique name for the filter. (required)
body, FilterTrainingObject: The list of positive and negative (optional) example items. (required)
retina_na... | get filter for classifier
Args:
filter_name, str: A unique name for the filter. (required)
body, FilterTrainingObject: The list of positive and negative (optional) example items. (required)
retina_name, str: The retina name (required)
Returns: CategoryFilter | Below is the the instruction that describes the task:
### Input:
get filter for classifier
Args:
filter_name, str: A unique name for the filter. (required)
body, FilterTrainingObject: The list of positive and negative (optional) example items. (required)
retina_name, str:... |
async def send_job_result(self, job_id: BackendJobId, result: str, text: str = "", grade: float = None, problems: Dict[str, SPResult] = None,
tests: Dict[str, Any] = None, custom: Dict[str, Any] = None, state: str = "", archive: Optional[bytes] = None,
stdout:... | Send the result of a job back to the backend. Must be called *once and only once* for each job
:exception JobNotRunningException: is raised when send_job_result is called more than once for a given job_id | Below is the the instruction that describes the task:
### Input:
Send the result of a job back to the backend. Must be called *once and only once* for each job
:exception JobNotRunningException: is raised when send_job_result is called more than once for a given job_id
### Response:
async def send_job_resu... |
def from_labels(labels):
"""
Creates list of cell features based on label image (1-oo pixel values)
@return: list of cell features in the same order as labels
"""
labels = labels.astype(int)
areas = scipy.ndimage.measurements.sum(labels != 0, labels, list(range(1, numpy... | Creates list of cell features based on label image (1-oo pixel values)
@return: list of cell features in the same order as labels | Below is the the instruction that describes the task:
### Input:
Creates list of cell features based on label image (1-oo pixel values)
@return: list of cell features in the same order as labels
### Response:
def from_labels(labels):
"""
Creates list of cell features based on label image (... |
def get_call_function_name(frame):
"""If f_back is looking at a call function, return
the name for it. Otherwise return None"""
f_back = frame.f_back
if not f_back: return None
if 'CALL_FUNCTION' != Mbytecode.op_at_frame(f_back): return None
co = f_back.f_code
code = co.co_cod... | If f_back is looking at a call function, return
the name for it. Otherwise return None | Below is the the instruction that describes the task:
### Input:
If f_back is looking at a call function, return
the name for it. Otherwise return None
### Response:
def get_call_function_name(frame):
"""If f_back is looking at a call function, return
the name for it. Otherwise return None"""
f_bac... |
def _vertex_list_to_dataframe(ls, id_column_name):
"""
Convert a list of vertices into dataframe.
"""
assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.'
cols = reduce(set.union, (set(v.attr.keys()) for v in ls))
df = pd.DataFrame({id_column_name: [v.... | Convert a list of vertices into dataframe. | Below is the the instruction that describes the task:
### Input:
Convert a list of vertices into dataframe.
### Response:
def _vertex_list_to_dataframe(ls, id_column_name):
"""
Convert a list of vertices into dataframe.
"""
assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or... |
def parseFile(self, filename):
"""Parse a single file."""
modname = self.filenameToModname(filename)
module = Module(modname, filename)
self.modules[modname] = module
if self.trackUnusedNames:
module.imported_names, module.unused_names = \
find_imports... | Parse a single file. | Below is the the instruction that describes the task:
### Input:
Parse a single file.
### Response:
def parseFile(self, filename):
"""Parse a single file."""
modname = self.filenameToModname(filename)
module = Module(modname, filename)
self.modules[modname] = module
if self.... |
def fap_davies(Z, fmax, t, y, dy, normalization='standard'):
"""Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008)
"""
N = len(t)
fap_s = fap_single(Z, N, normalization=normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return fap_s + tau | Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008) | Below is the the instruction that describes the task:
### Input:
Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008)
### Response:
def fap_davies(Z, fmax, t, y, dy, normalization='standard'):
"""Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008)
"""
... |
def load_gene(ensembl, gene_id, de_novos=[]):
""" sort out all the necessary sequences and positions for a gene
Args:
ensembl: EnsemblRequest object to request data from ensembl
gene_id: HGNC symbol for gene
de_novos: list of de novo positions, so we can check they all fit in
... | sort out all the necessary sequences and positions for a gene
Args:
ensembl: EnsemblRequest object to request data from ensembl
gene_id: HGNC symbol for gene
de_novos: list of de novo positions, so we can check they all fit in
the gene transcript
Returns:
... | Below is the the instruction that describes the task:
### Input:
sort out all the necessary sequences and positions for a gene
Args:
ensembl: EnsemblRequest object to request data from ensembl
gene_id: HGNC symbol for gene
de_novos: list of de novo positions, so we can check they al... |
def t_IDENTIFER(self, t):
r'\#?[a-zA-Z_][a-zA-Z_0-9]*'
t.type = SpecParser.reserved.get(t.value, 'IDENTIFIER')
return t | r'\#?[a-zA-Z_][a-zA-Z_0-9]* | Below is the the instruction that describes the task:
### Input:
r'\#?[a-zA-Z_][a-zA-Z_0-9]*
### Response:
def t_IDENTIFER(self, t):
r'\#?[a-zA-Z_][a-zA-Z_0-9]*'
t.type = SpecParser.reserved.get(t.value, 'IDENTIFIER')
return t |
async def spawn_slaves(self, slave_addrs, slave_env_cls, slave_mgr_cls,
slave_kwargs=None):
"""Spawn slave environments.
:param slave_addrs:
List of (HOST, PORT) addresses for the slave-environments.
:param slave_env_cls: Class for the slave environments.... | Spawn slave environments.
:param slave_addrs:
List of (HOST, PORT) addresses for the slave-environments.
:param slave_env_cls: Class for the slave environments.
:param slave_kwargs:
If not None, must be a list of the same size as *addrs*. Each item
in the l... | Below is the the instruction that describes the task:
### Input:
Spawn slave environments.
:param slave_addrs:
List of (HOST, PORT) addresses for the slave-environments.
:param slave_env_cls: Class for the slave environments.
:param slave_kwargs:
If not None, must ... |
def get_task_instance(dag_id, task_id, execution_date):
"""Return the task object identified by the given dag_id and task_id."""
dagbag = DagBag()
# Check DAG exists.
if dag_id not in dagbag.dags:
error_message = "Dag id {} not found".format(dag_id)
raise DagNotFound(error_message)
... | Return the task object identified by the given dag_id and task_id. | Below is the the instruction that describes the task:
### Input:
Return the task object identified by the given dag_id and task_id.
### Response:
def get_task_instance(dag_id, task_id, execution_date):
"""Return the task object identified by the given dag_id and task_id."""
dagbag = DagBag()
# Check ... |
def exists(Name, region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent regio... | Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1 | Below is the the instruction that describes the task:
### Input:
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-... |
def create(self, stage_url, tileset, name=None, patch=False, bypass=False):
"""Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object whe... | Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object where the json() contents are
an upload dict. Completion of the tileset may take s... | Below is the the instruction that describes the task:
### Input:
Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object where the json() cont... |
async def open(self) -> 'HolderProver':
"""
Explicit entry. Perform ancestor opening operations,
then parse cache from archive if so configured, and
synchronize revocation registry to tails tree content.
:return: current object
"""
LOGGER.debug('Verifier.open >>... | Explicit entry. Perform ancestor opening operations,
then parse cache from archive if so configured, and
synchronize revocation registry to tails tree content.
:return: current object | Below is the the instruction that describes the task:
### Input:
Explicit entry. Perform ancestor opening operations,
then parse cache from archive if so configured, and
synchronize revocation registry to tails tree content.
:return: current object
### Response:
async def open(self) -> 'Ho... |
def rpc_put_zonefiles( self, zonefile_datas, **con_info ):
"""
Replicate one or more zonefiles, given as serialized strings.
Only stores zone files whose zone file hashes were announced on the blockchain (i.e. not subdomain zone files)
Returns {'status': True, 'saved': [0|1]'} on success... | Replicate one or more zonefiles, given as serialized strings.
Only stores zone files whose zone file hashes were announced on the blockchain (i.e. not subdomain zone files)
Returns {'status': True, 'saved': [0|1]'} on success ('saved' is a vector of success/failure)
Returns {'error': ...} on err... | Below is the the instruction that describes the task:
### Input:
Replicate one or more zonefiles, given as serialized strings.
Only stores zone files whose zone file hashes were announced on the blockchain (i.e. not subdomain zone files)
Returns {'status': True, 'saved': [0|1]'} on success ('saved' ... |
def parse(f, encoding='utf-8'):
"""
Parse the TDL file *f* and yield the interpreted contents.
If *f* is a filename, the file is opened and closed when the
generator has finished, otherwise *f* is an open file object and
will not be closed when the generator has finished.
Args:
f (str,... | Parse the TDL file *f* and yield the interpreted contents.
If *f* is a filename, the file is opened and closed when the
generator has finished, otherwise *f* is an open file object and
will not be closed when the generator has finished.
Args:
f (str, file): a filename or open file object
... | Below is the the instruction that describes the task:
### Input:
Parse the TDL file *f* and yield the interpreted contents.
If *f* is a filename, the file is opened and closed when the
generator has finished, otherwise *f* is an open file object and
will not be closed when the generator has finished.
... |
def get_objective_bank_lookup_session(self, proxy):
"""Gets the OsidSession associated with the objective bank lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveBankLookupSession) - an
``ObjectiveBankLookupSession``
raise: NullArg... | Gets the OsidSession associated with the objective bank lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveBankLookupSession) - an
``ObjectiveBankLookupSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed -... | Below is the the instruction that describes the task:
### Input:
Gets the OsidSession associated with the objective bank lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveBankLookupSession) - an
``ObjectiveBankLookupSession``
raise: N... |
def backtrace_on_usr1 ():
"""Install a signal handler such that this program prints a Python traceback
upon receipt of SIGUSR1. This could be useful for checking that
long-running programs are behaving properly, or for discovering where an
infinite loop is occurring.
Note, however, that the Python ... | Install a signal handler such that this program prints a Python traceback
upon receipt of SIGUSR1. This could be useful for checking that
long-running programs are behaving properly, or for discovering where an
infinite loop is occurring.
Note, however, that the Python interpreter does not invoke Pytho... | Below is the the instruction that describes the task:
### Input:
Install a signal handler such that this program prints a Python traceback
upon receipt of SIGUSR1. This could be useful for checking that
long-running programs are behaving properly, or for discovering where an
infinite loop is occurring.
... |
def detectTizenTV(self):
"""Return detection of a Tizen smart TV
Detects if the current browser is on a Tizen smart TV.
"""
return UAgentInfo.deviceTizen in self.__userAgent \
and UAgentInfo.smartTV1 in self.__userAgent | Return detection of a Tizen smart TV
Detects if the current browser is on a Tizen smart TV. | Below is the the instruction that describes the task:
### Input:
Return detection of a Tizen smart TV
Detects if the current browser is on a Tizen smart TV.
### Response:
def detectTizenTV(self):
"""Return detection of a Tizen smart TV
Detects if the current browser is on a Tizen smart TV... |
def add_schema(self, schema):
"""
Merges in an existing schema.
arguments:
* `schema` (required - `dict` or `SchemaNode`):
an existing JSON Schema to merge.
"""
# serialize instances of SchemaNode before parsing
if isinstance(schema, SchemaNode):
... | Merges in an existing schema.
arguments:
* `schema` (required - `dict` or `SchemaNode`):
an existing JSON Schema to merge. | Below is the the instruction that describes the task:
### Input:
Merges in an existing schema.
arguments:
* `schema` (required - `dict` or `SchemaNode`):
an existing JSON Schema to merge.
### Response:
def add_schema(self, schema):
"""
Merges in an existing schema.
... |
def handle_request(self):
"""simply collect requests and put them on the queue for the workers."""
try:
request, client_address = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
self.requests.put((reques... | simply collect requests and put them on the queue for the workers. | Below is the the instruction that describes the task:
### Input:
simply collect requests and put them on the queue for the workers.
### Response:
def handle_request(self):
"""simply collect requests and put them on the queue for the workers."""
try:
request, client_address = self.get_re... |
def predict(self, dataset, confidence_threshold=0.25, iou_threshold=None, verbose=True):
"""
Predict object instances in an sframe of images.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
The images on which to perform object detection.
... | Predict object instances in an sframe of images.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
The images on which to perform object detection.
If dataset is an SFrame, it must have a column with the same name
as the feature column during... | Below is the the instruction that describes the task:
### Input:
Predict object instances in an sframe of images.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
The images on which to perform object detection.
If dataset is an SFrame, it must have... |
def construct_graph(sakefile, settings):
"""
Takes the sakefile dictionary and builds a NetworkX graph
Args:
A dictionary that is the parsed Sakefile (from sake.py)
The settings dictionary
Returns:
A NetworkX graph
"""
verbose = settings["verbose"]
sprint = settings... | Takes the sakefile dictionary and builds a NetworkX graph
Args:
A dictionary that is the parsed Sakefile (from sake.py)
The settings dictionary
Returns:
A NetworkX graph | Below is the the instruction that describes the task:
### Input:
Takes the sakefile dictionary and builds a NetworkX graph
Args:
A dictionary that is the parsed Sakefile (from sake.py)
The settings dictionary
Returns:
A NetworkX graph
### Response:
def construct_graph(sakefile, se... |
def _isbtaddr(address):
"""
Returns whether the given address is a valid bluetooth address.
For example, "00:0e:6d:7b:a2:0a" is a valid address.
Returns False if the argument is None or is not a string.
"""
# Define validity regex. Accept either ":" or "-" as separators.
global _validbtaddr... | Returns whether the given address is a valid bluetooth address.
For example, "00:0e:6d:7b:a2:0a" is a valid address.
Returns False if the argument is None or is not a string. | Below is the the instruction that describes the task:
### Input:
Returns whether the given address is a valid bluetooth address.
For example, "00:0e:6d:7b:a2:0a" is a valid address.
Returns False if the argument is None or is not a string.
### Response:
def _isbtaddr(address):
"""
Returns whether ... |
def compute_symm_block_tridiag_covariances(H_diag, H_upper_diag):
"""
use the info smoother to solve a symmetric block tridiagonal system
"""
T, D, _ = H_diag.shape
assert H_diag.ndim == 3 and H_diag.shape[2] == D
assert H_upper_diag.shape == (T - 1, D, D)
J_init = J_11 = J_22 = np.zeros((D... | use the info smoother to solve a symmetric block tridiagonal system | Below is the the instruction that describes the task:
### Input:
use the info smoother to solve a symmetric block tridiagonal system
### Response:
def compute_symm_block_tridiag_covariances(H_diag, H_upper_diag):
"""
use the info smoother to solve a symmetric block tridiagonal system
"""
T, D, _ = ... |
def _logprob_obs(self, data, mean_pat, var):
"""Log probability of observing each timepoint under each event model
Computes the log probability of each observed timepoint being
generated by the Gaussian distribution for each event pattern
Parameters
----------
data: vox... | Log probability of observing each timepoint under each event model
Computes the log probability of each observed timepoint being
generated by the Gaussian distribution for each event pattern
Parameters
----------
data: voxel by time ndarray
fMRI data on which to com... | Below is the the instruction that describes the task:
### Input:
Log probability of observing each timepoint under each event model
Computes the log probability of each observed timepoint being
generated by the Gaussian distribution for each event pattern
Parameters
----------
... |
def join(rasters):
"""
This method takes a list of rasters and returns a raster that is constructed of all of them
"""
raster = rasters[0] # using the first raster to understand what is the type of data we have
mask_band = None
nodata = None
with raster._raster_opener(raster.source_file) a... | This method takes a list of rasters and returns a raster that is constructed of all of them | Below is the the instruction that describes the task:
### Input:
This method takes a list of rasters and returns a raster that is constructed of all of them
### Response:
def join(rasters):
"""
This method takes a list of rasters and returns a raster that is constructed of all of them
"""
raster =... |
def convert_to_merged_ids(self, id_run):
"""
Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases
:param id_run: a run of token ids
:param dictionary: a dictionary of acceptable phrases described as there component token ids
... | Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases
:param id_run: a run of token ids
:param dictionary: a dictionary of acceptable phrases described as there component token ids
:return: a run of token and phrase ids. | Below is the the instruction that describes the task:
### Input:
Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases
:param id_run: a run of token ids
:param dictionary: a dictionary of acceptable phrases described as there component token ids
... |
def remove_listener(self, listener):
"""Remove the given listener from the wrapped client.
:param listener: A listener previously passed to :meth:`add_listener`.
"""
internal_listener = self._internal_listeners.pop(listener)
return self._client.remove_listener(internal_listener) | Remove the given listener from the wrapped client.
:param listener: A listener previously passed to :meth:`add_listener`. | Below is the the instruction that describes the task:
### Input:
Remove the given listener from the wrapped client.
:param listener: A listener previously passed to :meth:`add_listener`.
### Response:
def remove_listener(self, listener):
"""Remove the given listener from the wrapped client.
... |
def job(self, func_or_queue=None, timeout=None, result_ttl=None, ttl=None,
depends_on=None, at_front=None, meta=None, description=None):
"""
Decorator to mark functions for queuing via RQ, e.g.::
rq = RQ()
@rq.job
def add(x, y):
return x ... | Decorator to mark functions for queuing via RQ, e.g.::
rq = RQ()
@rq.job
def add(x, y):
return x + y
or::
@rq.job(timeout=60, result_ttl=60 * 60)
def add(x, y):
return x + y
Adds various functions to the job... | Below is the the instruction that describes the task:
### Input:
Decorator to mark functions for queuing via RQ, e.g.::
rq = RQ()
@rq.job
def add(x, y):
return x + y
or::
@rq.job(timeout=60, result_ttl=60 * 60)
def add(x, y):
... |
def _try_get_string(dev, index, langid = None, default_str_i0 = "",
default_access_error = "Error Accessing String"):
""" try to get a string, but return a string no matter what
"""
if index == 0 :
string = default_str_i0
else:
try:
if langid is None:
... | try to get a string, but return a string no matter what | Below is the the instruction that describes the task:
### Input:
try to get a string, but return a string no matter what
### Response:
def _try_get_string(dev, index, langid = None, default_str_i0 = "",
default_access_error = "Error Accessing String"):
""" try to get a string, but return a string no ma... |
def get_vcenter_version(kwargs=None, call=None):
'''
Show the vCenter Server version with build number.
CLI Example:
.. code-block:: bash
salt-cloud -f get_vcenter_version my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_vcenter_versi... | Show the vCenter Server version with build number.
CLI Example:
.. code-block:: bash
salt-cloud -f get_vcenter_version my-vmware-config | Below is the the instruction that describes the task:
### Input:
Show the vCenter Server version with build number.
CLI Example:
.. code-block:: bash
salt-cloud -f get_vcenter_version my-vmware-config
### Response:
def get_vcenter_version(kwargs=None, call=None):
'''
Show the vCenter Ser... |
def sync(self, api_token, sync_token, resource_types='["all"]', **kwargs):
"""Update and retrieve Todoist data.
:param api_token: The user's login api_token.
:type api_token: str
:param seq_no: The request sequence number. On initial request pass
``0``. On all others pass th... | Update and retrieve Todoist data.
:param api_token: The user's login api_token.
:type api_token: str
:param seq_no: The request sequence number. On initial request pass
``0``. On all others pass the last seq_no you received.
:type seq_no: int
:param seq_no_global: Th... | Below is the the instruction that describes the task:
### Input:
Update and retrieve Todoist data.
:param api_token: The user's login api_token.
:type api_token: str
:param seq_no: The request sequence number. On initial request pass
``0``. On all others pass the last seq_no you... |
def ports_open(name, ports, proto='tcp', direction='in'):
'''
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one... | Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one of 'tcp', 'udp',
'tcp6', or 'udp6'.
direction
Ch... | Below is the the instruction that describes the task:
### Input:
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one ... |
def buildlist(self, enabled):
"""Run dialog buildlist
"""
choice = []
for item in self.data:
choice.append((item, False))
for item in enabled:
choice.append((item, True))
items = [(tag, tag, sta) for (tag, sta) in choice]
code, self.tags = ... | Run dialog buildlist | Below is the the instruction that describes the task:
### Input:
Run dialog buildlist
### Response:
def buildlist(self, enabled):
"""Run dialog buildlist
"""
choice = []
for item in self.data:
choice.append((item, False))
for item in enabled:
choice.a... |
def delete_secret(self, path, mount_point=DEFAULT_MOUNT_POINT):
"""Delete the secret at the specified location.
Supported methods:
DELETE: /{mount_point}/{path}. Produces: 204 (empty body)
:param path: Specifies the path of the secret to delete.
This is specified as pa... | Delete the secret at the specified location.
Supported methods:
DELETE: /{mount_point}/{path}. Produces: 204 (empty body)
:param path: Specifies the path of the secret to delete.
This is specified as part of the URL.
:type path: str | unicode
:param mount_point... | Below is the the instruction that describes the task:
### Input:
Delete the secret at the specified location.
Supported methods:
DELETE: /{mount_point}/{path}. Produces: 204 (empty body)
:param path: Specifies the path of the secret to delete.
This is specified as part of ... |
def get_icon(brain_or_object, html_tag=True):
"""Get the icon of the content object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param html_tag: A value of 'True' returns the HTML tag, else the image url
:ty... | Get the icon of the content object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param html_tag: A value of 'True' returns the HTML tag, else the image url
:type html_tag: bool
:returns: HTML '<img>' tag if '... | Below is the the instruction that describes the task:
### Input:
Get the icon of the content object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param html_tag: A value of 'True' returns the HTML tag, else the i... |
def MessageReceived(self, m):
"""
Process a message.
Args:
m (neo.Network.Message):
"""
if m.Command == 'verack':
# only respond with a verack when we connect to another client, not when a client connected to us or
# we might end up in a verac... | Process a message.
Args:
m (neo.Network.Message): | Below is the the instruction that describes the task:
### Input:
Process a message.
Args:
m (neo.Network.Message):
### Response:
def MessageReceived(self, m):
"""
Process a message.
Args:
m (neo.Network.Message):
"""
if m.Command == 'verack'... |
def hostname(self):
"""Get the hostname that this connection is associated with"""
from six.moves.urllib.parse import urlparse
return urlparse(self._base_url).netloc.split(':', 1)[0] | Get the hostname that this connection is associated with | Below is the the instruction that describes the task:
### Input:
Get the hostname that this connection is associated with
### Response:
def hostname(self):
"""Get the hostname that this connection is associated with"""
from six.moves.urllib.parse import urlparse
return urlparse(self._base_u... |
def getLiftOps(self, valu, cmpr='='):
'''
Get a set of lift operations for use with an Xact.
'''
if valu is None:
iops = (('pref', b''),)
return (
('indx', ('byprop', self.pref, iops)),
)
# TODO: In an ideal world, this would g... | Get a set of lift operations for use with an Xact. | Below is the the instruction that describes the task:
### Input:
Get a set of lift operations for use with an Xact.
### Response:
def getLiftOps(self, valu, cmpr='='):
'''
Get a set of lift operations for use with an Xact.
'''
if valu is None:
iops = (('pref', b''),)
... |
def controlled(self, control_qubit):
"""
Add the CONTROLLED modifier to the gate with the given control qubit.
"""
control_qubit = unpack_qubit(control_qubit)
self.modifiers.insert(0, "CONTROLLED")
self.qubits.insert(0, control_qubit)
return self | Add the CONTROLLED modifier to the gate with the given control qubit. | Below is the the instruction that describes the task:
### Input:
Add the CONTROLLED modifier to the gate with the given control qubit.
### Response:
def controlled(self, control_qubit):
"""
Add the CONTROLLED modifier to the gate with the given control qubit.
"""
control_qubit = unp... |
def del_action_role(ctx):
"""Deletes a role from an action on objects"""
objects = ctx.obj['objects']
action = ctx.obj['action']
role = ctx.obj['role']
if action is None or role is None:
log('You need to specify an action or role to the RBAC command group for this to work.', lvl=warn)
... | Deletes a role from an action on objects | Below is the the instruction that describes the task:
### Input:
Deletes a role from an action on objects
### Response:
def del_action_role(ctx):
"""Deletes a role from an action on objects"""
objects = ctx.obj['objects']
action = ctx.obj['action']
role = ctx.obj['role']
if action is None or ... |
def limit_x(
self,
limit_lower = None, # float
limit_upper = None # float
):
"""
get or set x limits of the current axes
x_min, x_max = limit_x() # return the current limit_x
limit_x(x_min, x_max) # set the limit_x to x_min, x_max
"""
... | get or set x limits of the current axes
x_min, x_max = limit_x() # return the current limit_x
limit_x(x_min, x_max) # set the limit_x to x_min, x_max | Below is the the instruction that describes the task:
### Input:
get or set x limits of the current axes
x_min, x_max = limit_x() # return the current limit_x
limit_x(x_min, x_max) # set the limit_x to x_min, x_max
### Response:
def limit_x(
self,
limit_lower = None, # float
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.