code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def is_filter_selected(self, selection_id, value):
"""
Compares whether the 'selection_id' parameter value saved in the
cookie is the same value as the "value" parameter.
:param selection_id: a string as a dashboard_cookie key.
:param value: The value to compare against the valu... | Compares whether the 'selection_id' parameter value saved in the
cookie is the same value as the "value" parameter.
:param selection_id: a string as a dashboard_cookie key.
:param value: The value to compare against the value from
dashboard_cookie key.
:return: Boolean. | Below is the the instruction that describes the task:
### Input:
Compares whether the 'selection_id' parameter value saved in the
cookie is the same value as the "value" parameter.
:param selection_id: a string as a dashboard_cookie key.
:param value: The value to compare against the value ... |
def add_tweets(self, url, last_modified, tweets):
"""Adds new tweets to the cache."""
try:
self.cache[url] = {"last_modified": last_modified, "tweets": tweets}
self.mark_updated()
return True
except TypeError:
return False | Adds new tweets to the cache. | Below is the the instruction that describes the task:
### Input:
Adds new tweets to the cache.
### Response:
def add_tweets(self, url, last_modified, tweets):
"""Adds new tweets to the cache."""
try:
self.cache[url] = {"last_modified": last_modified, "tweets": tweets}
self.m... |
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):
""" In-place segment simplification
See `drp` and `compression` modules
Args:
eps (float): Distance threshold for the `drp` function
max_dist_error (float): Max distance error, in meters
... | In-place segment simplification
See `drp` and `compression` modules
Args:
eps (float): Distance threshold for the `drp` function
max_dist_error (float): Max distance error, in meters
max_speed_error (float): Max speed error, in km/h
topology_only (bool, ... | Below is the the instruction that describes the task:
### Input:
In-place segment simplification
See `drp` and `compression` modules
Args:
eps (float): Distance threshold for the `drp` function
max_dist_error (float): Max distance error, in meters
max_speed_erro... |
def _build_document_scrapers(cls, session: AppSession):
'''Create the document scrapers.
Returns:
A list of document scrapers
'''
html_parser = session.factory['HTMLParser']
element_walker = session.factory.new('ElementWalker')
scrapers = [
sessi... | Create the document scrapers.
Returns:
A list of document scrapers | Below is the the instruction that describes the task:
### Input:
Create the document scrapers.
Returns:
A list of document scrapers
### Response:
def _build_document_scrapers(cls, session: AppSession):
'''Create the document scrapers.
Returns:
A list of document sc... |
def getColorName(c):
"""Find the name of a color.
.. hint:: |colorpalette| |colorpalette.py|_
"""
c = np.array(getColor(c)) # reformat to rgb
mdist = 99.0
kclosest = ""
for key in colors.keys():
ci = np.array(getColor(key))
d = np.linalg.norm(c - ci)
if d < mdist:
... | Find the name of a color.
.. hint:: |colorpalette| |colorpalette.py|_ | Below is the the instruction that describes the task:
### Input:
Find the name of a color.
.. hint:: |colorpalette| |colorpalette.py|_
### Response:
def getColorName(c):
"""Find the name of a color.
.. hint:: |colorpalette| |colorpalette.py|_
"""
c = np.array(getColor(c)) # reformat to rgb
... |
def train(self, ftrain):
'''Trains the polynomial expansion.
:param numpy.ndarray/function ftrain: output values corresponding to the
quadrature points given by the getQuadraturePoints method to
which the expansion should be trained. Or a function that should be evaluated
... | Trains the polynomial expansion.
:param numpy.ndarray/function ftrain: output values corresponding to the
quadrature points given by the getQuadraturePoints method to
which the expansion should be trained. Or a function that should be evaluated
at the quadrature points to gi... | Below is the the instruction that describes the task:
### Input:
Trains the polynomial expansion.
:param numpy.ndarray/function ftrain: output values corresponding to the
quadrature points given by the getQuadraturePoints method to
which the expansion should be trained. Or a functio... |
def encrypt_file(self, inpath, force_nocompress=False, force_compress=False, armored=False, checksum=False):
"""public method for single file encryption with optional compression, ASCII armored formatting, and file hash digest generation"""
if armored:
if force_compress:
comm... | public method for single file encryption with optional compression, ASCII armored formatting, and file hash digest generation | Below is the the instruction that describes the task:
### Input:
public method for single file encryption with optional compression, ASCII armored formatting, and file hash digest generation
### Response:
def encrypt_file(self, inpath, force_nocompress=False, force_compress=False, armored=False, checksum=False):
... |
def install_scripts(distributions):
"""
Regenerate the entry_points console_scripts for the named distribution.
"""
try:
from setuptools.command import easy_install
import pkg_resources
except ImportError:
raise RuntimeError("'wheel install_scripts' needs setuptools.")
f... | Regenerate the entry_points console_scripts for the named distribution. | Below is the the instruction that describes the task:
### Input:
Regenerate the entry_points console_scripts for the named distribution.
### Response:
def install_scripts(distributions):
"""
Regenerate the entry_points console_scripts for the named distribution.
"""
try:
from setuptools.com... |
def run(command, parser, cl_args, unknown_args):
'''
:param command:
:param parser:
:param args:
:param unknown_args:
:return:
'''
configcommand = cl_args.get('configcommand', None)
if configcommand == 'set':
return _set(cl_args)
elif configcommand == 'unset':
return _unset(cl_args)
else:
... | :param command:
:param parser:
:param args:
:param unknown_args:
:return: | Below is the the instruction that describes the task:
### Input:
:param command:
:param parser:
:param args:
:param unknown_args:
:return:
### Response:
def run(command, parser, cl_args, unknown_args):
'''
:param command:
:param parser:
:param args:
:param unknown_args:
:return:
'''
configc... |
def load_building_sample_data(bd):
"""
Sample data for the Building object
:param bd:
:return:
"""
number_of_storeys = 6
interstorey_height = 3.4 # m
masses = 40.0e3 # kg
bd.interstorey_heights = interstorey_height * np.ones(number_of_storeys)
bd.floor_length = 18.0 # m
b... | Sample data for the Building object
:param bd:
:return: | Below is the the instruction that describes the task:
### Input:
Sample data for the Building object
:param bd:
:return:
### Response:
def load_building_sample_data(bd):
"""
Sample data for the Building object
:param bd:
:return:
"""
number_of_storeys = 6
interstorey_height = 3.... |
def speak(self):
'''
a function for the client to announce him or herself, depending
on the level specified. If you want your client to have additional
announced things here, then implement the class `_speak` for your
client.
'''
if self.quiet is Fals... | a function for the client to announce him or herself, depending
on the level specified. If you want your client to have additional
announced things here, then implement the class `_speak` for your
client. | Below is the the instruction that describes the task:
### Input:
a function for the client to announce him or herself, depending
on the level specified. If you want your client to have additional
announced things here, then implement the class `_speak` for your
client.
### Response:... |
def edit_miz( # noqa: C901
infile: str,
outfile: str = None,
metar: typing.Union[str, Metar] = None,
time: str = None,
min_wind: int = 0,
max_wind: int = 40
) -> str:
# noinspection SpellCheckingInspection
"""
Edit an opened MIZ file and sets the time and dat... | Edit an opened MIZ file and sets the time and date and the weather
Args:
infile: source file
outfile: output file (will default to source file)
metar: metar string, ICAO or object to apply
time: time string to apply (YYYYMMDDHHMMSS)
min_wind: minimum wind
max_wind: m... | Below is the the instruction that describes the task:
### Input:
Edit an opened MIZ file and sets the time and date and the weather
Args:
infile: source file
outfile: output file (will default to source file)
metar: metar string, ICAO or object to apply
time: time string to appl... |
def installProductOn(self, userstore):
"""
Creates an Installation in this user store for our collection
of powerups, and then install those powerups on the user's
store.
"""
def install():
i = Installation(store=userstore)
i.types = self.types
... | Creates an Installation in this user store for our collection
of powerups, and then install those powerups on the user's
store. | Below is the the instruction that describes the task:
### Input:
Creates an Installation in this user store for our collection
of powerups, and then install those powerups on the user's
store.
### Response:
def installProductOn(self, userstore):
"""
Creates an Installation in this u... |
def runGetReference(self, id_):
"""
Runs a getReference request for the specified ID.
"""
compoundId = datamodel.ReferenceCompoundId.parse(id_)
referenceSet = self.getDataRepository().getReferenceSet(
compoundId.reference_set_id)
reference = referenceSet.getRe... | Runs a getReference request for the specified ID. | Below is the the instruction that describes the task:
### Input:
Runs a getReference request for the specified ID.
### Response:
def runGetReference(self, id_):
"""
Runs a getReference request for the specified ID.
"""
compoundId = datamodel.ReferenceCompoundId.parse(id_)
re... |
def get_option_list(self, name, section=None, vars=None,
expect=None, separator=','):
"""Just like ``get_option`` but parse as a list using ``split``.
"""
val = self.get_option(name, section, vars, expect)
return val.split(separator) if val else [] | Just like ``get_option`` but parse as a list using ``split``. | Below is the the instruction that describes the task:
### Input:
Just like ``get_option`` but parse as a list using ``split``.
### Response:
def get_option_list(self, name, section=None, vars=None,
expect=None, separator=','):
"""Just like ``get_option`` but parse as a list using ``... |
def expand_zip(zip_fname,cwd=None):
"expand a zip"
unzip_path = '/usr/bin/unzip'
if not os.path.exists(unzip_path):
log.error('ERROR: {} does not exist'.format(unzip_path))
sys.exit(1)
args = [unzip_path, zip_fname]
# Does it have a top dir
res = subprocess.Popen(
[args[0... | expand a zip | Below is the the instruction that describes the task:
### Input:
expand a zip
### Response:
def expand_zip(zip_fname,cwd=None):
"expand a zip"
unzip_path = '/usr/bin/unzip'
if not os.path.exists(unzip_path):
log.error('ERROR: {} does not exist'.format(unzip_path))
sys.exit(1)
args =... |
def setShowOptionsButton(self, state):
"""
Sets whether or not the option button is visible.
:param state | <bool>
"""
self._showOptionsButton = state
self._optionsButton.setVisible(state) | Sets whether or not the option button is visible.
:param state | <bool> | Below is the the instruction that describes the task:
### Input:
Sets whether or not the option button is visible.
:param state | <bool>
### Response:
def setShowOptionsButton(self, state):
"""
Sets whether or not the option button is visible.
:param ... |
def call():
"""Execute command line helper."""
args = get_arguments()
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log_level = logging.INFO
setup_logging(log_level)
lupusec = None
if not args.username or not args.pas... | Execute command line helper. | Below is the the instruction that describes the task:
### Input:
Execute command line helper.
### Response:
def call():
"""Execute command line helper."""
args = get_arguments()
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log... |
def facets(self, *args, **kwargs):
"""
Returns a dictionary with the requested facets.
The facets function supports string args, and keyword
args.
q.facets('field_1', 'field_2') will return facets for
field_1 and field_2.
q.facets(field_1={'limit': 0}, field_2={... | Returns a dictionary with the requested facets.
The facets function supports string args, and keyword
args.
q.facets('field_1', 'field_2') will return facets for
field_1 and field_2.
q.facets(field_1={'limit': 0}, field_2={'limit': 10})
will return all facets for field_... | Below is the the instruction that describes the task:
### Input:
Returns a dictionary with the requested facets.
The facets function supports string args, and keyword
args.
q.facets('field_1', 'field_2') will return facets for
field_1 and field_2.
q.facets(field_1={'limit':... |
def addReward(self, r=None):
""" A filtered mapping towards performAction of the underlying
environment.
"""
r = self.getReward() if r is None else r
# by default, the cumulative reward is just the sum over the episode
if self.discount:
self.cumulativeRew... | A filtered mapping towards performAction of the underlying
environment. | Below is the the instruction that describes the task:
### Input:
A filtered mapping towards performAction of the underlying
environment.
### Response:
def addReward(self, r=None):
""" A filtered mapping towards performAction of the underlying
environment.
"""
r = sel... |
def TableDescriptionParser(table_description, depth=0):
"""Parses the table_description object for internal use.
Parses the user-submitted table description into an internal format used
by the Python DataTable class. Returns the flat list of parsed columns.
Args:
table_description: A description... | Parses the table_description object for internal use.
Parses the user-submitted table description into an internal format used
by the Python DataTable class. Returns the flat list of parsed columns.
Args:
table_description: A description of the table which should comply
with... | Below is the the instruction that describes the task:
### Input:
Parses the table_description object for internal use.
Parses the user-submitted table description into an internal format used
by the Python DataTable class. Returns the flat list of parsed columns.
Args:
table_description: A descr... |
def apps_installations_job_status_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/apps#get-requirements-install-status"
api_path = "/api/v2/apps/installations/job_statuses/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/apps#get-requirements-install-status | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/apps#get-requirements-install-status
### Response:
def apps_installations_job_status_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/apps#get-requirements-install-st... |
def get_or_instantiate_db_state(working_dir):
"""
Get a read-only handle to the DB.
Instantiate it first if it doesn't exist.
DO NOT CALL WHILE INDEXING
Returns the handle on success
Raises on error
"""
# instantiates
new_db = BlockstackDB.borrow_readwrite_instance(working_dir, -1... | Get a read-only handle to the DB.
Instantiate it first if it doesn't exist.
DO NOT CALL WHILE INDEXING
Returns the handle on success
Raises on error | Below is the the instruction that describes the task:
### Input:
Get a read-only handle to the DB.
Instantiate it first if it doesn't exist.
DO NOT CALL WHILE INDEXING
Returns the handle on success
Raises on error
### Response:
def get_or_instantiate_db_state(working_dir):
"""
Get a read-... |
def _validate_player(player):
'''
Checks that a player is a valid player. Valid players are: 0, 1, 2, and 3.
:param int player: player to be validated
:return: None
:raises NoSuchPlayerException: if the player is invalid
'''
valid_players = range(4)
if player not in valid_players:
... | Checks that a player is a valid player. Valid players are: 0, 1, 2, and 3.
:param int player: player to be validated
:return: None
:raises NoSuchPlayerException: if the player is invalid | Below is the the instruction that describes the task:
### Input:
Checks that a player is a valid player. Valid players are: 0, 1, 2, and 3.
:param int player: player to be validated
:return: None
:raises NoSuchPlayerException: if the player is invalid
### Response:
def _validate_player(player):
''... |
def dependency_sort(dependency_tree):
"""
Sorts items 'dependencies first' in a given dependency tree.
A dependency tree is a dictionary mapping an object to a collection its
dependency objects.
Result is a properly sorted list of items, where each item is a 2-tuple
containing an object and it... | Sorts items 'dependencies first' in a given dependency tree.
A dependency tree is a dictionary mapping an object to a collection its
dependency objects.
Result is a properly sorted list of items, where each item is a 2-tuple
containing an object and its dependency list, as given in the input
depen... | Below is the the instruction that describes the task:
### Input:
Sorts items 'dependencies first' in a given dependency tree.
A dependency tree is a dictionary mapping an object to a collection its
dependency objects.
Result is a properly sorted list of items, where each item is a 2-tuple
containi... |
def check_shastore_version(from_store, settings):
"""
This function gives us the option to emit errors or warnings
after sake upgrades
"""
sprint = settings["sprint"]
error = settings["error"]
sprint("checking .shastore version for potential incompatibilities",
level="verbose")
... | This function gives us the option to emit errors or warnings
after sake upgrades | Below is the the instruction that describes the task:
### Input:
This function gives us the option to emit errors or warnings
after sake upgrades
### Response:
def check_shastore_version(from_store, settings):
"""
This function gives us the option to emit errors or warnings
after sake upgrades
... |
def cmd(send, msg, args):
"""Checks if a website is up.
Syntax: {command} <website>
"""
if not msg:
send("What are you trying to get to?")
return
nick = args['nick']
isup = get("http://isup.me/%s" % msg).text
if "looks down from here" in isup:
send("%s: %s is down" ... | Checks if a website is up.
Syntax: {command} <website> | Below is the the instruction that describes the task:
### Input:
Checks if a website is up.
Syntax: {command} <website>
### Response:
def cmd(send, msg, args):
"""Checks if a website is up.
Syntax: {command} <website>
"""
if not msg:
send("What are you trying to get to?")
ret... |
def __mesh_coords(ax_type, coords, n, **kwargs):
'''Compute axis coordinates'''
if coords is not None:
if len(coords) < n:
raise ParameterError('Coordinate shape mismatch: '
'{}<{}'.format(len(coords), n))
return coords
coord_map = {'linear': __... | Compute axis coordinates | Below is the the instruction that describes the task:
### Input:
Compute axis coordinates
### Response:
def __mesh_coords(ax_type, coords, n, **kwargs):
'''Compute axis coordinates'''
if coords is not None:
if len(coords) < n:
raise ParameterError('Coordinate shape mismatch: '
... |
def compute_efficiency(f_dist, m_dist, dbins):
'''
Compute the efficiency as a function of distance for the given sets of found
and missed injection distances.
Note that injections that do not fit into any dbin get lost :(
'''
efficiency = numpy.zeros(len(dbins) - 1)
error = numpy.zeros(len(... | Compute the efficiency as a function of distance for the given sets of found
and missed injection distances.
Note that injections that do not fit into any dbin get lost :( | Below is the the instruction that describes the task:
### Input:
Compute the efficiency as a function of distance for the given sets of found
and missed injection distances.
Note that injections that do not fit into any dbin get lost :(
### Response:
def compute_efficiency(f_dist, m_dist, dbins):
'''
... |
def recv_exit_status(self, command, timeout=10, get_pty=False):
"""
Execute a command and get its return value
@param command: command to execute
@type command: str
@param timeout: command execution timeout
@type timeout: int
@param get_pty: get pty
@ty... | Execute a command and get its return value
@param command: command to execute
@type command: str
@param timeout: command execution timeout
@type timeout: int
@param get_pty: get pty
@type get_pty: bool
@return: the exit code of the process or None in case of t... | Below is the the instruction that describes the task:
### Input:
Execute a command and get its return value
@param command: command to execute
@type command: str
@param timeout: command execution timeout
@type timeout: int
@param get_pty: get pty
@type get_pty: boo... |
def get_alias(self):
"""
Gets the alias for the field or the auto_alias if one is set.
If there isn't any kind of alias, None is returned.
:return: The field alias, auto_alias, or None
:rtype: str or None
"""
alias = None
if self.alias:
alias ... | Gets the alias for the field or the auto_alias if one is set.
If there isn't any kind of alias, None is returned.
:return: The field alias, auto_alias, or None
:rtype: str or None | Below is the the instruction that describes the task:
### Input:
Gets the alias for the field or the auto_alias if one is set.
If there isn't any kind of alias, None is returned.
:return: The field alias, auto_alias, or None
:rtype: str or None
### Response:
def get_alias(self):
""... |
def sort_item(iterable, number, reverse=False):
"""Sort the itertable according to the given number item."""
return sorted(iterable, key=itemgetter(number), reverse=reverse) | Sort the itertable according to the given number item. | Below is the the instruction that describes the task:
### Input:
Sort the itertable according to the given number item.
### Response:
def sort_item(iterable, number, reverse=False):
"""Sort the itertable according to the given number item."""
return sorted(iterable, key=itemgetter(number), reverse=reverse) |
def get_custom_renderer(self, dir_path, layout=True):
"""
Create a template renderer on templates in the directory specified, and returns it.
:param dir_path: the path to the template dir. If it is not absolute, it will be taken from the root of the inginious package.
:param layout: can ... | Create a template renderer on templates in the directory specified, and returns it.
:param dir_path: the path to the template dir. If it is not absolute, it will be taken from the root of the inginious package.
:param layout: can either be True (use the base layout of the running app), False (use no lay... | Below is the the instruction that describes the task:
### Input:
Create a template renderer on templates in the directory specified, and returns it.
:param dir_path: the path to the template dir. If it is not absolute, it will be taken from the root of the inginious package.
:param layout: can eithe... |
def try_serialize_handler(handler):
"""Try to serialize map/reduce handler.
Args:
handler: handler function/instance. Handler can be a function or an
instance of a callable class. In the latter case, the handler will
be serialized across slices to allow users to save states.
Returns:
seriali... | Try to serialize map/reduce handler.
Args:
handler: handler function/instance. Handler can be a function or an
instance of a callable class. In the latter case, the handler will
be serialized across slices to allow users to save states.
Returns:
serialized handler string or None. | Below is the the instruction that describes the task:
### Input:
Try to serialize map/reduce handler.
Args:
handler: handler function/instance. Handler can be a function or an
instance of a callable class. In the latter case, the handler will
be serialized across slices to allow users to save sta... |
def static_singleton(*args, **kwargs):
"""
STATIC Singleton Design Pattern Decorator
Class is initialized with arguments passed into the decorator.
:Usage:
>>> @static_singleton('yop')
class Bob(Person):
def __init__(arg1):
self.info = arg1
def says... | STATIC Singleton Design Pattern Decorator
Class is initialized with arguments passed into the decorator.
:Usage:
>>> @static_singleton('yop')
class Bob(Person):
def __init__(arg1):
self.info = arg1
def says(self):
print self.info
b1 ... | Below is the the instruction that describes the task:
### Input:
STATIC Singleton Design Pattern Decorator
Class is initialized with arguments passed into the decorator.
:Usage:
>>> @static_singleton('yop')
class Bob(Person):
def __init__(arg1):
self.info = arg1
... |
def GetActiveComposition(self) -> TextRange:
"""
Call IUIAutomationTextEditPattern::GetActiveComposition.
Return `TextRange` or None, the active composition.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtexteditpattern-g... | Call IUIAutomationTextEditPattern::GetActiveComposition.
Return `TextRange` or None, the active composition.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtexteditpattern-getactivecomposition | Below is the the instruction that describes the task:
### Input:
Call IUIAutomationTextEditPattern::GetActiveComposition.
Return `TextRange` or None, the active composition.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtexteditpatte... |
def iter_conditions(condition):
"""Yield all conditions within the given condition.
If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found)."""
conditions = list()
visited = set()
# Has to be split out, since we don't want to visit the root (for cyclic cond... | Yield all conditions within the given condition.
If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found). | Below is the the instruction that describes the task:
### Input:
Yield all conditions within the given condition.
If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found).
### Response:
def iter_conditions(condition):
"""Yield all conditions within the given condit... |
def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name
model: Model,
batch_grad_norm: float) -> None:
"""
Send the mean and std of all parameters and gradients to tensorboard, as well
... | Send the mean and std of all parameters and gradients to tensorboard, as well
as logging the average gradient norm. | Below is the the instruction that describes the task:
### Input:
Send the mean and std of all parameters and gradients to tensorboard, as well
as logging the average gradient norm.
### Response:
def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name
... |
def get(self, url, instance, service_check_tags, run_check=False):
"Hit a given URL and return the parsed json"
self.log.debug('Fetching CouchDB stats at url: %s' % url)
auth = None
if 'user' in instance and 'password' in instance:
auth = (instance['user'], instance['passwor... | Hit a given URL and return the parsed json | Below is the the instruction that describes the task:
### Input:
Hit a given URL and return the parsed json
### Response:
def get(self, url, instance, service_check_tags, run_check=False):
"Hit a given URL and return the parsed json"
self.log.debug('Fetching CouchDB stats at url: %s' % url)
... |
def role_show(self, role_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/roles#get-role"
api_path = "/api/v2/roles/{role_id}"
api_path = api_path.format(role_id=role_id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/chat/roles#get-role | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/chat/roles#get-role
### Response:
def role_show(self, role_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/roles#get-role"
api_path = "/api/v2/roles/{role_id}"
api_p... |
def rotation_coefs(self):
""" get the rotation coefficents in radians
Returns
-------
rotation_coefs : list
the rotation coefficients implied by Vario2d.bearing
"""
return [np.cos(self.bearing_rads),
np.sin(self.bearing_rads),
... | get the rotation coefficents in radians
Returns
-------
rotation_coefs : list
the rotation coefficients implied by Vario2d.bearing | Below is the the instruction that describes the task:
### Input:
get the rotation coefficents in radians
Returns
-------
rotation_coefs : list
the rotation coefficients implied by Vario2d.bearing
### Response:
def rotation_coefs(self):
""" get the rotation coefficents i... |
def load_kb_mappings_file(kbname, kbfile, separator):
"""Add KB values from file to given KB returning rows added."""
num_added = 0
with open(kbfile) as kb_fd:
for line in kb_fd:
if not line.strip():
continue
try:
key, value = line.split(separa... | Add KB values from file to given KB returning rows added. | Below is the the instruction that describes the task:
### Input:
Add KB values from file to given KB returning rows added.
### Response:
def load_kb_mappings_file(kbname, kbfile, separator):
"""Add KB values from file to given KB returning rows added."""
num_added = 0
with open(kbfile) as kb_fd:
... |
def __WriteProtoServiceDeclaration(self, printer, name, method_info_map):
"""Write a single service declaration to a proto file."""
printer()
printer('service %s {', self.__GetServiceClassName(name))
with printer.Indent():
for method_name, method_info in method_info_map.items... | Write a single service declaration to a proto file. | Below is the the instruction that describes the task:
### Input:
Write a single service declaration to a proto file.
### Response:
def __WriteProtoServiceDeclaration(self, printer, name, method_info_map):
"""Write a single service declaration to a proto file."""
printer()
printer('service %... |
def build_c(self):
"""Calculates the total attenuation from the total absorption and total scattering
c = a + b
"""
lg.info('Building total attenuation C')
self.c = self.a + self.b | Calculates the total attenuation from the total absorption and total scattering
c = a + b | Below is the the instruction that describes the task:
### Input:
Calculates the total attenuation from the total absorption and total scattering
c = a + b
### Response:
def build_c(self):
"""Calculates the total attenuation from the total absorption and total scattering
c = a + b
... |
def read(self, offset, length):
"""
Return *length* bytes from this stream starting at *offset*.
"""
self._file.seek(offset)
return self._file.read(length) | Return *length* bytes from this stream starting at *offset*. | Below is the the instruction that describes the task:
### Input:
Return *length* bytes from this stream starting at *offset*.
### Response:
def read(self, offset, length):
"""
Return *length* bytes from this stream starting at *offset*.
"""
self._file.seek(offset)
return sel... |
def slice_locs(self, start=None, end=None, step=None, kind=None):
"""
For an ordered MultiIndex, compute the slice locations for input
labels.
The input labels can be tuples representing partial levels, e.g. for a
MultiIndex with 3 levels, you can pass a single value (correspond... | For an ordered MultiIndex, compute the slice locations for input
labels.
The input labels can be tuples representing partial levels, e.g. for a
MultiIndex with 3 levels, you can pass a single value (corresponding to
the first level), or a 1-, 2-, or 3-tuple.
Parameters
... | Below is the the instruction that describes the task:
### Input:
For an ordered MultiIndex, compute the slice locations for input
labels.
The input labels can be tuples representing partial levels, e.g. for a
MultiIndex with 3 levels, you can pass a single value (corresponding to
th... |
def thickest(self, n=1, index=False):
"""
Returns the thickest interval(s) as a striplog.
Args:
n (int): The number of thickest intervals to return. Default: 1.
index (bool): If True, only the indices of the intervals are
returned. You can use this to ind... | Returns the thickest interval(s) as a striplog.
Args:
n (int): The number of thickest intervals to return. Default: 1.
index (bool): If True, only the indices of the intervals are
returned. You can use this to index into the striplog.
Returns:
Interv... | Below is the the instruction that describes the task:
### Input:
Returns the thickest interval(s) as a striplog.
Args:
n (int): The number of thickest intervals to return. Default: 1.
index (bool): If True, only the indices of the intervals are
returned. You can use ... |
def get_presig(self, target, source, env, executor=None):
"""Return the signature contents of this action's command line.
This strips $(-$) and everything in between the string,
since those parts don't affect signatures.
"""
from SCons.Subst import SUBST_SIG
cmd = self.c... | Return the signature contents of this action's command line.
This strips $(-$) and everything in between the string,
since those parts don't affect signatures. | Below is the the instruction that describes the task:
### Input:
Return the signature contents of this action's command line.
This strips $(-$) and everything in between the string,
since those parts don't affect signatures.
### Response:
def get_presig(self, target, source, env, executor=None):
... |
def resize_imgs(self, targ, new_path, resume=True, fn=None):
"""
resize all images in the dataset and save them to `new_path`
Arguments:
targ (int): the target size
new_path (string): the new folder to save the images
resume (bool): if true (default), allow resum... | resize all images in the dataset and save them to `new_path`
Arguments:
targ (int): the target size
new_path (string): the new folder to save the images
resume (bool): if true (default), allow resuming a partial resize operation by checking for the existence
of individua... | Below is the the instruction that describes the task:
### Input:
resize all images in the dataset and save them to `new_path`
Arguments:
targ (int): the target size
new_path (string): the new folder to save the images
resume (bool): if true (default), allow resuming a partia... |
def bristow_campbell(tmin, tmax, pot_rad_daily, A, C):
"""calculates potential shortwave radiation based on minimum and maximum temperature
This routine calculates global radiation as described in:
Bristow, Keith L., and Gaylon S. Campbell: On the relationship between
incoming solar radiation and ... | calculates potential shortwave radiation based on minimum and maximum temperature
This routine calculates global radiation as described in:
Bristow, Keith L., and Gaylon S. Campbell: On the relationship between
incoming solar radiation and daily maximum and minimum temperature.
Agricultural and fo... | Below is the the instruction that describes the task:
### Input:
calculates potential shortwave radiation based on minimum and maximum temperature
This routine calculates global radiation as described in:
Bristow, Keith L., and Gaylon S. Campbell: On the relationship between
incoming solar radiatio... |
def select_valid_methods(self, T):
r'''Method to obtain a sorted list of methods which are valid at `T`
according to `test_method_validity`. Considers either only user methods
if forced is True, or all methods. User methods are first tested
according to their listed order, and unless for... | r'''Method to obtain a sorted list of methods which are valid at `T`
according to `test_method_validity`. Considers either only user methods
if forced is True, or all methods. User methods are first tested
according to their listed order, and unless forced is True, then all
methods are t... | Below is the the instruction that describes the task:
### Input:
r'''Method to obtain a sorted list of methods which are valid at `T`
according to `test_method_validity`. Considers either only user methods
if forced is True, or all methods. User methods are first tested
according to their li... |
def call(self, **data):
"""Issue the call.
:param data: Data to pass in the *body* of the request.
"""
uri, body, headers = self.prepare(data)
return self.dispatch(uri, body, headers) | Issue the call.
:param data: Data to pass in the *body* of the request. | Below is the the instruction that describes the task:
### Input:
Issue the call.
:param data: Data to pass in the *body* of the request.
### Response:
def call(self, **data):
"""Issue the call.
:param data: Data to pass in the *body* of the request.
"""
uri, body, headers ... |
def has_delete_permission(self, request):
""" Can delete this object """
return request.user.is_authenticated and request.user.is_active and request.user.is_superuser | Can delete this object | Below is the the instruction that describes the task:
### Input:
Can delete this object
### Response:
def has_delete_permission(self, request):
""" Can delete this object """
return request.user.is_authenticated and request.user.is_active and request.user.is_superuser |
def _request_exc_message(exc):
"""
Return a reasonable exception message from a
:exc:`request.exceptions.RequestException` exception.
The approach is to dig deep to the original reason, if the original
exception is present, skipping irrelevant exceptions such as
`urllib3.exceptions.MaxRetryErro... | Return a reasonable exception message from a
:exc:`request.exceptions.RequestException` exception.
The approach is to dig deep to the original reason, if the original
exception is present, skipping irrelevant exceptions such as
`urllib3.exceptions.MaxRetryError`, and eliminating useless object
repr... | Below is the the instruction that describes the task:
### Input:
Return a reasonable exception message from a
:exc:`request.exceptions.RequestException` exception.
The approach is to dig deep to the original reason, if the original
exception is present, skipping irrelevant exceptions such as
`urlli... |
def _list_records_in_zone(self, zone, rdtype=None, name=None, content=None):
"""
Iterates over all records of the zone and returns a list of records filtered
by record type, name and content. The list is empty if no records found.
"""
records = []
rrsets = zone.iterate_rd... | Iterates over all records of the zone and returns a list of records filtered
by record type, name and content. The list is empty if no records found. | Below is the the instruction that describes the task:
### Input:
Iterates over all records of the zone and returns a list of records filtered
by record type, name and content. The list is empty if no records found.
### Response:
def _list_records_in_zone(self, zone, rdtype=None, name=None, content=None):
... |
def wal_archive(self, wal_path, concurrency=1):
"""
Uploads a WAL file to S3 or Windows Azure Blob Service
This code is intended to typically be called from Postgres's
archive_command feature.
"""
# Upload the segment expressly indicated. It's special
# relativ... | Uploads a WAL file to S3 or Windows Azure Blob Service
This code is intended to typically be called from Postgres's
archive_command feature. | Below is the the instruction that describes the task:
### Input:
Uploads a WAL file to S3 or Windows Azure Blob Service
This code is intended to typically be called from Postgres's
archive_command feature.
### Response:
def wal_archive(self, wal_path, concurrency=1):
"""
Uploads a ... |
def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Proof object
from the dictionary.
:param dict: the dictionary to convert
"""
key = hb_decode(dict['key'])
check_fraction = dict['check_fraction']
return Merkle(check_fraction, key) | Takes a dictionary as an argument and returns a new Proof object
from the dictionary.
:param dict: the dictionary to convert | Below is the the instruction that describes the task:
### Input:
Takes a dictionary as an argument and returns a new Proof object
from the dictionary.
:param dict: the dictionary to convert
### Response:
def fromdict(dict):
"""Takes a dictionary as an argument and returns a new Proof objec... |
def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = (not ... | if screenshot is None, only failed case will take screenshot | Below is the the instruction that describes the task:
### Input:
if screenshot is None, only failed case will take screenshot
### Response:
def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path fro... |
def _text_filter_input(self, input_gen):
"""
Filters out the text input line by line to avoid parsing and processing
metrics we know we don't want to process. This only works on `text/plain`
payloads, and is an INTERNAL FEATURE implemented for the kubelet check
:param input_get: ... | Filters out the text input line by line to avoid parsing and processing
metrics we know we don't want to process. This only works on `text/plain`
payloads, and is an INTERNAL FEATURE implemented for the kubelet check
:param input_get: line generator
:output: generator of filtered lines | Below is the the instruction that describes the task:
### Input:
Filters out the text input line by line to avoid parsing and processing
metrics we know we don't want to process. This only works on `text/plain`
payloads, and is an INTERNAL FEATURE implemented for the kubelet check
:param inp... |
async def disconnect(self, sid, namespace=None):
"""Disconnect a client.
The only difference with the :func:`socketio.Server.disconnect` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
Note: this method is a coroutine... | Disconnect a client.
The only difference with the :func:`socketio.Server.disconnect` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
Note: this method is a coroutine. | Below is the the instruction that describes the task:
### Input:
Disconnect a client.
The only difference with the :func:`socketio.Server.disconnect` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
Note: this method is a ... |
def registerStatsHandler(app, serverName, prefix='/status/'):
"""Register the stats handler with a Flask app, serving routes
with a given prefix. The prefix defaults to '/status/', which is
generally what you want."""
if prefix[-1] != '/':
prefix += '/'
handler = functools.partial(statsHandler, serverName... | Register the stats handler with a Flask app, serving routes
with a given prefix. The prefix defaults to '/status/', which is
generally what you want. | Below is the the instruction that describes the task:
### Input:
Register the stats handler with a Flask app, serving routes
with a given prefix. The prefix defaults to '/status/', which is
generally what you want.
### Response:
def registerStatsHandler(app, serverName, prefix='/status/'):
"""Register the st... |
def samples_to_batches(samples: Iterable, batch_size: int):
"""Chunk a series of network inputs and outputs into larger batches"""
it = iter(samples)
while True:
with suppress(StopIteration):
batch_in, batch_out = [], []
for i in range(batch_size):
... | Chunk a series of network inputs and outputs into larger batches | Below is the the instruction that describes the task:
### Input:
Chunk a series of network inputs and outputs into larger batches
### Response:
def samples_to_batches(samples: Iterable, batch_size: int):
"""Chunk a series of network inputs and outputs into larger batches"""
it = iter(samples)
... |
def get_pk_descriptors(cls):
"""Return tuple of tuples with attribute name and descriptor on the
`cls` that is defined as the primary keys."""
pk_fields = {
name: descriptor
for name, descriptor in vars_class(cls).items()
if isinstance(descriptor, ObjectField) and is_pk_descriptor(de... | Return tuple of tuples with attribute name and descriptor on the
`cls` that is defined as the primary keys. | Below is the the instruction that describes the task:
### Input:
Return tuple of tuples with attribute name and descriptor on the
`cls` that is defined as the primary keys.
### Response:
def get_pk_descriptors(cls):
"""Return tuple of tuples with attribute name and descriptor on the
`cls` that is defin... |
def explode_filename(name: str, scheme: str) -> dict:
"""
Removes any path components from the input filename and returns a
dictionary containing the name of the file without extension and the
extension (if an extension exists)
:param name:
:param scheme:
:return:
"""
if not scheme... | Removes any path components from the input filename and returns a
dictionary containing the name of the file without extension and the
extension (if an extension exists)
:param name:
:param scheme:
:return: | Below is the the instruction that describes the task:
### Input:
Removes any path components from the input filename and returns a
dictionary containing the name of the file without extension and the
extension (if an extension exists)
:param name:
:param scheme:
:return:
### Response:
def expl... |
def exec_commands(self, action, c_name, run_cmds, **kwargs):
"""
Runs a single command inside a container.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param c_name: Container name.
:type c_name: unicode | str
:param run_c... | Runs a single command inside a container.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param c_name: Container name.
:type c_name: unicode | str
:param run_cmds: Commands to run.
:type run_cmds: list[dockermap.map.input.ExecComman... | Below is the the instruction that describes the task:
### Input:
Runs a single command inside a container.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param c_name: Container name.
:type c_name: unicode | str
:param run_cmds: Command... |
def sort_by_fields(items, fields):
"""
Sort a list of objects on the given fields. The field list works analogously to
queryset.order_by(*fields): each field is either a property of the object,
or is prefixed by '-' (e.g. '-name') to indicate reverse ordering.
"""
# To get the desired behaviour,... | Sort a list of objects on the given fields. The field list works analogously to
queryset.order_by(*fields): each field is either a property of the object,
or is prefixed by '-' (e.g. '-name') to indicate reverse ordering. | Below is the the instruction that describes the task:
### Input:
Sort a list of objects on the given fields. The field list works analogously to
queryset.order_by(*fields): each field is either a property of the object,
or is prefixed by '-' (e.g. '-name') to indicate reverse ordering.
### Response:
def so... |
def set_network_settings(self, mtu, sock_snd, sock_rcv, tcp_wnd_snd, tcp_wnd_rcv):
"""Sets network configuration of the NAT engine.
in mtu of type int
MTU (maximum transmission unit) of the NAT engine in bytes.
in sock_snd of type int
Capacity of the socket send buffer ... | Sets network configuration of the NAT engine.
in mtu of type int
MTU (maximum transmission unit) of the NAT engine in bytes.
in sock_snd of type int
Capacity of the socket send buffer in bytes when creating a new socket.
in sock_rcv of type int
Capacity of ... | Below is the the instruction that describes the task:
### Input:
Sets network configuration of the NAT engine.
in mtu of type int
MTU (maximum transmission unit) of the NAT engine in bytes.
in sock_snd of type int
Capacity of the socket send buffer in bytes when creating a ... |
def findall(self):
"""Find all files under the base and set ``allfiles`` to the absolute
pathnames of files found.
"""
from stat import S_ISREG, S_ISDIR, S_ISLNK
self.allfiles = allfiles = []
root = self.base
stack = [root]
pop = stack.pop
push = ... | Find all files under the base and set ``allfiles`` to the absolute
pathnames of files found. | Below is the the instruction that describes the task:
### Input:
Find all files under the base and set ``allfiles`` to the absolute
pathnames of files found.
### Response:
def findall(self):
"""Find all files under the base and set ``allfiles`` to the absolute
pathnames of files found.
... |
def pre_release(self):
""" Return true if version is a pre-release. """
label = self.version_info.get('label', None)
pre = self.version_info.get('pre', None)
return True if (label is not None and pre is not None) else False | Return true if version is a pre-release. | Below is the the instruction that describes the task:
### Input:
Return true if version is a pre-release.
### Response:
def pre_release(self):
""" Return true if version is a pre-release. """
label = self.version_info.get('label', None)
pre = self.version_info.get('pre', None)
retu... |
def get_assign_annotation(node):
"""Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None... | Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None | Below is the the instruction that describes the task:
### Input:
Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not ... |
def field_dict_from_row(row, model,
field_names=None, ignore_fields=('id', 'pk'),
strip=True,
blank_none=True,
ignore_related=True,
ignore_values=(None,),
ignore_errors=Tr... | Construct a Mapping (dict) from field names to values from a row of data
Args:
row (list or dict): Data (values) to be assigned to field_names in the dict.
If `row` is a list, then the column names (header row) can be provided in `field_names`.
If `row` is a list and no field_names are provid... | Below is the the instruction that describes the task:
### Input:
Construct a Mapping (dict) from field names to values from a row of data
Args:
row (list or dict): Data (values) to be assigned to field_names in the dict.
If `row` is a list, then the column names (header row) can be provided in `f... |
def AllBalancesZeroOrLess(self):
"""
Flag indicating if all balances are 0 or less.
Returns:
bool: True if all balances are <= 0. False, otherwise.
"""
for key, fixed8 in self.Balances.items():
if fixed8.value > 0:
return False
ret... | Flag indicating if all balances are 0 or less.
Returns:
bool: True if all balances are <= 0. False, otherwise. | Below is the the instruction that describes the task:
### Input:
Flag indicating if all balances are 0 or less.
Returns:
bool: True if all balances are <= 0. False, otherwise.
### Response:
def AllBalancesZeroOrLess(self):
"""
Flag indicating if all balances are 0 or less.
... |
def CheckHashes(self, hashes, external=True):
"""Checks a list of hashes for presence in the store.
Sub stores need to pass back the original HashDigest objects since they
carry state about the original file source.
Only unique hashes are checked, if there is duplication in the hashes input
it is ... | Checks a list of hashes for presence in the store.
Sub stores need to pass back the original HashDigest objects since they
carry state about the original file source.
Only unique hashes are checked, if there is duplication in the hashes input
it is the caller's responsibility to maintain any necessary... | Below is the the instruction that describes the task:
### Input:
Checks a list of hashes for presence in the store.
Sub stores need to pass back the original HashDigest objects since they
carry state about the original file source.
Only unique hashes are checked, if there is duplication in the hashes ... |
def connect1(self, A, B, distance):
"Add a link from A to B of given distance, in one direction only."
self.dict.setdefault(A,{})[B] = distance | Add a link from A to B of given distance, in one direction only. | Below is the the instruction that describes the task:
### Input:
Add a link from A to B of given distance, in one direction only.
### Response:
def connect1(self, A, B, distance):
"Add a link from A to B of given distance, in one direction only."
self.dict.setdefault(A,{})[B] = distance |
def timescales_samples(self):
r""" Samples of the timescales """
res = np.empty((self.nsamples, self.nstates-1), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].timescales
return res | r""" Samples of the timescales | Below is the the instruction that describes the task:
### Input:
r""" Samples of the timescales
### Response:
def timescales_samples(self):
r""" Samples of the timescales """
res = np.empty((self.nsamples, self.nstates-1), dtype=config.dtype)
for i in range(self.nsamples):
res[i... |
def __getVariables(self):
"""Parses the P4 env vars using 'set p4'"""
try:
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
output = subprocess.check_ou... | Parses the P4 env vars using 'set p4 | Below is the the instruction that describes the task:
### Input:
Parses the P4 env vars using 'set p4
### Response:
def __getVariables(self):
"""Parses the P4 env vars using 'set p4'"""
try:
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STAR... |
def del_piper(self, piper, forced=False):
"""
Removes a ``Piper`` from the ``Dagger`` instance.
Arguments:
- piper(``Piper`` or id(``Piper``)) ``Piper`` instance or ``Piper``
instance id.
- forced(bool) [default: ``False``] If "forced" is ``True``, wil... | Removes a ``Piper`` from the ``Dagger`` instance.
Arguments:
- piper(``Piper`` or id(``Piper``)) ``Piper`` instance or ``Piper``
instance id.
- forced(bool) [default: ``False``] If "forced" is ``True``, will not
raise a ``DaggerError`` if the ``Piper`` ha... | Below is the the instruction that describes the task:
### Input:
Removes a ``Piper`` from the ``Dagger`` instance.
Arguments:
- piper(``Piper`` or id(``Piper``)) ``Piper`` instance or ``Piper``
instance id.
- forced(bool) [default: ``False``] If "forced" is ``True... |
def unlink_f(path):
"""Unlink path but do not complain if file does not exist."""
try:
os.unlink(path)
except OSError as err:
if err.errno != errno.ENOENT:
raise | Unlink path but do not complain if file does not exist. | Below is the the instruction that describes the task:
### Input:
Unlink path but do not complain if file does not exist.
### Response:
def unlink_f(path):
"""Unlink path but do not complain if file does not exist."""
try:
os.unlink(path)
except OSError as err:
if err.errno != errno.ENOE... |
def grouping_delta_stats(old, new):
"""
Returns statistics about grouping changes
Args:
old (set of frozenset): old grouping
new (set of frozenset): new grouping
Returns:
pd.DataFrame: df: data frame of size statistics
Example:
>>> # ENABLE_DOCTEST
>>> from... | Returns statistics about grouping changes
Args:
old (set of frozenset): old grouping
new (set of frozenset): new grouping
Returns:
pd.DataFrame: df: data frame of size statistics
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> imp... | Below is the the instruction that describes the task:
### Input:
Returns statistics about grouping changes
Args:
old (set of frozenset): old grouping
new (set of frozenset): new grouping
Returns:
pd.DataFrame: df: data frame of size statistics
Example:
>>> # ENABLE_DOC... |
def create_trainer(self, username, team, start_date=None, has_cheated=None, last_cheated=None, currently_cheats=None, statistics=True, daily_goal=None, total_goal=None, prefered=True, account=None, verified=False):
"""Add a trainer to the database"""
args = locals()
url = api_url+'trainers/'
payload = {
'use... | Add a trainer to the database | Below is the the instruction that describes the task:
### Input:
Add a trainer to the database
### Response:
def create_trainer(self, username, team, start_date=None, has_cheated=None, last_cheated=None, currently_cheats=None, statistics=True, daily_goal=None, total_goal=None, prefered=True, account=None, verified... |
def make_gettext_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'msgid msgstr'
kw = r"\b" + any("keyword", kwstr.split()) + r"\b"
fuzzy = any("builtin", [r"#,[^\n]*"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = an... | Strongly inspired from idlelib.ColorDelegator.make_pat | Below is the the instruction that describes the task:
### Input:
Strongly inspired from idlelib.ColorDelegator.make_pat
### Response:
def make_gettext_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'msgid msgstr'
kw = r"\b" + any("keyword", kwstr.split()) + r"\b"
f... |
def users(self):
"""
:class:`~zhmcclient.UserManager`: Access to the :term:`Users <User>` in
this Console.
"""
# We do here some lazy loading.
if not self._users:
self._users = UserManager(self)
return self._users | :class:`~zhmcclient.UserManager`: Access to the :term:`Users <User>` in
this Console. | Below is the the instruction that describes the task:
### Input:
:class:`~zhmcclient.UserManager`: Access to the :term:`Users <User>` in
this Console.
### Response:
def users(self):
"""
:class:`~zhmcclient.UserManager`: Access to the :term:`Users <User>` in
this Console.
"""... |
async def close(self, code: int = 1006, reason: str = "Connection closed"):
"""
Closes the websocket.
"""
if self._closed:
return
self._closed = True
if self._scope is not None:
await self._scope.cancel()
# cancel any outstanding list... | Closes the websocket. | Below is the the instruction that describes the task:
### Input:
Closes the websocket.
### Response:
async def close(self, code: int = 1006, reason: str = "Connection closed"):
"""
Closes the websocket.
"""
if self._closed:
return
self._closed = True
if... |
def overlay_gateway_access_lists_ipv6_out_ipv6_acl_out_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway,... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def overlay_gateway_access_lists_ipv6_out_ipv6_acl_out_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-g... |
def get_pdf_from_html(html: str,
header_html: str = None,
footer_html: str = None,
wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME,
wkhtmltopdf_options: Dict[str, Any] = None,
file_encoding: str = "utf-8",
... | Takes HTML and returns a PDF.
See the arguments to :func:`make_pdf_from_html` (except ``on_disk``).
Returns:
the PDF binary as a ``bytes`` object | Below is the the instruction that describes the task:
### Input:
Takes HTML and returns a PDF.
See the arguments to :func:`make_pdf_from_html` (except ``on_disk``).
Returns:
the PDF binary as a ``bytes`` object
### Response:
def get_pdf_from_html(html: str,
header_html: str ... |
def leftsibling(node):
"""
Return Left Sibling of `node`.
>>> from anytree import Node
>>> dan = Node("Dan")
>>> jet = Node("Jet", parent=dan)
>>> jan = Node("Jan", parent=dan)
>>> joe = Node("Joe", parent=dan)
>>> leftsibling(dan)
>>> leftsibling(jet)
>>> leftsibling(jan)
N... | Return Left Sibling of `node`.
>>> from anytree import Node
>>> dan = Node("Dan")
>>> jet = Node("Jet", parent=dan)
>>> jan = Node("Jan", parent=dan)
>>> joe = Node("Joe", parent=dan)
>>> leftsibling(dan)
>>> leftsibling(jet)
>>> leftsibling(jan)
Node('/Dan/Jet')
>>> leftsibling... | Below is the the instruction that describes the task:
### Input:
Return Left Sibling of `node`.
>>> from anytree import Node
>>> dan = Node("Dan")
>>> jet = Node("Jet", parent=dan)
>>> jan = Node("Jan", parent=dan)
>>> joe = Node("Joe", parent=dan)
>>> leftsibling(dan)
>>> leftsibling(j... |
def imread(filename):
'''
Like cv2.imread
This function will make sure filename exists
'''
im = cv2.imread(filename)
if im is None:
raise RuntimeError("file: '%s' not exists" % filename)
return im | Like cv2.imread
This function will make sure filename exists | Below is the the instruction that describes the task:
### Input:
Like cv2.imread
This function will make sure filename exists
### Response:
def imread(filename):
'''
Like cv2.imread
This function will make sure filename exists
'''
im = cv2.imread(filename)
if im is None:
raise... |
def get_line_flux(line_wave, wave, flux, **kwargs):
"""Interpolated flux at a given wavelength (calls np.interp)."""
return np.interp(line_wave, wave, flux, **kwargs) | Interpolated flux at a given wavelength (calls np.interp). | Below is the the instruction that describes the task:
### Input:
Interpolated flux at a given wavelength (calls np.interp).
### Response:
def get_line_flux(line_wave, wave, flux, **kwargs):
"""Interpolated flux at a given wavelength (calls np.interp)."""
return np.interp(line_wave, wave, flux, **kwargs) |
def _get_filepath(self, ext):
"""
Returns a file path relative to this page
"""
filename = ("%s%d.%s" % (self.FILE_PREFIX, self.page_nb + 1, ext))
return self.fs.join(self.doc.path, filename) | Returns a file path relative to this page | Below is the the instruction that describes the task:
### Input:
Returns a file path relative to this page
### Response:
def _get_filepath(self, ext):
"""
Returns a file path relative to this page
"""
filename = ("%s%d.%s" % (self.FILE_PREFIX, self.page_nb + 1, ext))
return ... |
def has_header(self, hdrclass):
'''
Return True if the packet has a header of the given hdrclass,
False otherwise.
'''
if isinstance(hdrclass, str):
return self.get_header_by_name(hdrclass) is not None
return self.get_header(hdrclass) is not None | Return True if the packet has a header of the given hdrclass,
False otherwise. | Below is the the instruction that describes the task:
### Input:
Return True if the packet has a header of the given hdrclass,
False otherwise.
### Response:
def has_header(self, hdrclass):
'''
Return True if the packet has a header of the given hdrclass,
False otherwise.
... |
def does_fragment_condition_match(
self,
fragment: Union[FragmentDefinitionNode, InlineFragmentNode],
type_: GraphQLObjectType,
) -> bool:
"""Determine if a fragment is applicable to the given type."""
type_condition_node = fragment.type_condition
if not type_conditio... | Determine if a fragment is applicable to the given type. | Below is the the instruction that describes the task:
### Input:
Determine if a fragment is applicable to the given type.
### Response:
def does_fragment_condition_match(
self,
fragment: Union[FragmentDefinitionNode, InlineFragmentNode],
type_: GraphQLObjectType,
) -> bool:
"""D... |
def _create_record(self, rtype, name, content):
"""
Create a resource record. If a record already exists with the same
content, do nothing.
"""
result = False
name = self._relative_name(name)
ttl = None
# TODO: shoud assert that this is an int
if ... | Create a resource record. If a record already exists with the same
content, do nothing. | Below is the the instruction that describes the task:
### Input:
Create a resource record. If a record already exists with the same
content, do nothing.
### Response:
def _create_record(self, rtype, name, content):
"""
Create a resource record. If a record already exists with the same
... |
def get_vndmat_attr(d,keypath,attr,**kwargs):
'''
get_vndmat_attr(d,['x'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['t'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['u'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['y'],'lsib_path',path2keypath=True)
'''
kt... | get_vndmat_attr(d,['x'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['t'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['u'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['y'],'lsib_path',path2keypath=True) | Below is the the instruction that describes the task:
### Input:
get_vndmat_attr(d,['x'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['t'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['u'],'lsib_path',path2keypath=True)
get_vndmat_attr(d,['y'],'lsib_path',path2keypath=True)
### Res... |
def export_coreml(self, filename):
"""
Export the model in Core ML format.
Parameters
----------
filename: str
A valid filename where the model can be saved.
Examples
--------
>>> model.export_coreml('myModel.mlmodel')
"""
print... | Export the model in Core ML format.
Parameters
----------
filename: str
A valid filename where the model can be saved.
Examples
--------
>>> model.export_coreml('myModel.mlmodel') | Below is the the instruction that describes the task:
### Input:
Export the model in Core ML format.
Parameters
----------
filename: str
A valid filename where the model can be saved.
Examples
--------
>>> model.export_coreml('myModel.mlmodel')
### Respons... |
def _post(self, uri, data):
"""
HTTP POST function
:param uri: REST endpoint to POST to
:param data: list of dicts to be passed to the endpoint
:return: list of dicts, usually will be a list of objects or id's
Example:
ret = cli.post('/indicators', { 'indica... | HTTP POST function
:param uri: REST endpoint to POST to
:param data: list of dicts to be passed to the endpoint
:return: list of dicts, usually will be a list of objects or id's
Example:
ret = cli.post('/indicators', { 'indicator': 'example.com' }) | Below is the the instruction that describes the task:
### Input:
HTTP POST function
:param uri: REST endpoint to POST to
:param data: list of dicts to be passed to the endpoint
:return: list of dicts, usually will be a list of objects or id's
Example:
ret = cli.post('/i... |
def press_keycode(self, keycode, metastate=None):
"""Sends a press of keycode to the device.
Android only.
Possible keycodes & meta states can be found in
http://developer.android.com/reference/android/view/KeyEvent.html
Meta state describe the pressed state of key modifiers s... | Sends a press of keycode to the device.
Android only.
Possible keycodes & meta states can be found in
http://developer.android.com/reference/android/view/KeyEvent.html
Meta state describe the pressed state of key modifiers such as
Shift, Ctrl & Alt keys. The Meta State is an i... | Below is the the instruction that describes the task:
### Input:
Sends a press of keycode to the device.
Android only.
Possible keycodes & meta states can be found in
http://developer.android.com/reference/android/view/KeyEvent.html
Meta state describe the pressed state of key mod... |
def _op_method(self, data, extra_factor=1.0):
"""Operator
This method returns the input data after the singular values have been
thresholded
Parameters
----------
data : np.ndarray
Input data array
extra_factor : float
Additional multipli... | Operator
This method returns the input data after the singular values have been
thresholded
Parameters
----------
data : np.ndarray
Input data array
extra_factor : float
Additional multiplication factor
Returns
-------
np... | Below is the the instruction that describes the task:
### Input:
Operator
This method returns the input data after the singular values have been
thresholded
Parameters
----------
data : np.ndarray
Input data array
extra_factor : float
Additio... |
def _compile_mapping(self, schema, invalid_msg=None):
"""Create validator for given mapping."""
invalid_msg = invalid_msg or 'mapping value'
# Keys that may be required
all_required_keys = set(key for key in schema
if key is not Extra and
... | Create validator for given mapping. | Below is the the instruction that describes the task:
### Input:
Create validator for given mapping.
### Response:
def _compile_mapping(self, schema, invalid_msg=None):
"""Create validator for given mapping."""
invalid_msg = invalid_msg or 'mapping value'
# Keys that may be required
... |
def basic_auth(self, username, password):
"""Set the Basic Auth credentials on this Session.
:param str username: Your GitHub username
:param str password: Your GitHub password
"""
if not (username and password):
return
self.auth = (username, password)
... | Set the Basic Auth credentials on this Session.
:param str username: Your GitHub username
:param str password: Your GitHub password | Below is the the instruction that describes the task:
### Input:
Set the Basic Auth credentials on this Session.
:param str username: Your GitHub username
:param str password: Your GitHub password
### Response:
def basic_auth(self, username, password):
"""Set the Basic Auth credentials on ... |
def kill(config, container, *args, **kwargs):
'''
Kill a running container
:type container: string
:param container: The container id to kill
:rtype: dict
:returns: boolean
'''
err = "Unknown"
client = _get_client(config)
try:
dcontainer = _get_container_infos(config, c... | Kill a running container
:type container: string
:param container: The container id to kill
:rtype: dict
:returns: boolean | Below is the the instruction that describes the task:
### Input:
Kill a running container
:type container: string
:param container: The container id to kill
:rtype: dict
:returns: boolean
### Response:
def kill(config, container, *args, **kwargs):
'''
Kill a running container
:type c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.