code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _add_filter_node(root, filter_, value):
"""Adds filter xml node to root."""
filter_el = ElementTree.SubElement(root, 'Filter')
filter_el.set('name', filter_.name)
# Set filter value depending on type.
if filter_.type == 'boolean':
# Boolean case.
if v... | Adds filter xml node to root. | Below is the the instruction that describes the task:
### Input:
Adds filter xml node to root.
### Response:
def _add_filter_node(root, filter_, value):
"""Adds filter xml node to root."""
filter_el = ElementTree.SubElement(root, 'Filter')
filter_el.set('name', filter_.name)
# Set ... |
def fill_fw_dict_from_db(self, fw_data):
"""
This routine is called to create a local fw_dict with data from DB.
"""
rule_dict = fw_data.get('rules').get('rules')
fw_dict = {'fw_id': fw_data.get('fw_id'),
'fw_name': fw_data.get('name'),
'fire... | This routine is called to create a local fw_dict with data from DB. | Below is the the instruction that describes the task:
### Input:
This routine is called to create a local fw_dict with data from DB.
### Response:
def fill_fw_dict_from_db(self, fw_data):
"""
This routine is called to create a local fw_dict with data from DB.
"""
rule_dict = fw_data... |
def SetConsoleTitle(text: str) -> bool:
"""
SetConsoleTitle from Win32.
text: str.
Return bool, True if succeed otherwise False.
"""
return bool(ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(text))) | SetConsoleTitle from Win32.
text: str.
Return bool, True if succeed otherwise False. | Below is the the instruction that describes the task:
### Input:
SetConsoleTitle from Win32.
text: str.
Return bool, True if succeed otherwise False.
### Response:
def SetConsoleTitle(text: str) -> bool:
"""
SetConsoleTitle from Win32.
text: str.
Return bool, True if succeed otherwise False... |
def predict(self, X, break_ties="random", return_probs=False, **kwargs):
"""Predicts int labels for an input X on all tasks
Args:
X: The input for the predict_proba method
break_ties: A tie-breaking policy
return_probs: Return the predicted probabilities as well
... | Predicts int labels for an input X on all tasks
Args:
X: The input for the predict_proba method
break_ties: A tie-breaking policy
return_probs: Return the predicted probabilities as well
Returns:
Y_p: A t-length list of n-dim np.ndarrays of predictions i... | Below is the the instruction that describes the task:
### Input:
Predicts int labels for an input X on all tasks
Args:
X: The input for the predict_proba method
break_ties: A tie-breaking policy
return_probs: Return the predicted probabilities as well
Returns:
... |
def update_service(self, stack, service, args):
"""更新服务
更新指定名称服务的配置如容器镜像等参数,容器被重新部署后生效。
如果指定manualUpdate参数,则需要额外调用 部署服务 接口并指定参数进行部署;处于人工升级模式的服务禁止执行其他修改操作。
如果不指定manualUpdate参数,平台会自动完成部署。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
- args: ... | 更新服务
更新指定名称服务的配置如容器镜像等参数,容器被重新部署后生效。
如果指定manualUpdate参数,则需要额外调用 部署服务 接口并指定参数进行部署;处于人工升级模式的服务禁止执行其他修改操作。
如果不指定manualUpdate参数,平台会自动完成部署。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
- args: 服务具体描述请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/
... | Below is the the instruction that describes the task:
### Input:
更新服务
更新指定名称服务的配置如容器镜像等参数,容器被重新部署后生效。
如果指定manualUpdate参数,则需要额外调用 部署服务 接口并指定参数进行部署;处于人工升级模式的服务禁止执行其他修改操作。
如果不指定manualUpdate参数,平台会自动完成部署。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
-... |
def create_bool(help_string=NO_HELP, default=NO_DEFAULT):
# type: (str, Union[bool, NO_DEFAULT_TYPE]) -> bool
"""
Create a bool parameter
:param help_string:
:param default:
:return:
"""
# noinspection PyTypeChecker
return ParamFunctions(
... | Create a bool parameter
:param help_string:
:param default:
:return: | Below is the the instruction that describes the task:
### Input:
Create a bool parameter
:param help_string:
:param default:
:return:
### Response:
def create_bool(help_string=NO_HELP, default=NO_DEFAULT):
# type: (str, Union[bool, NO_DEFAULT_TYPE]) -> bool
"""
Creat... |
def get(self, path, *args, **kwargs):
'''GET the provided endpoint'''
target = self._host.relative(path).utf8
if not isinstance(target, basestring):
# on older versions of the `url` library, .utf8 is a method, not a property
target = target()
params = kwargs.get('... | GET the provided endpoint | Below is the the instruction that describes the task:
### Input:
GET the provided endpoint
### Response:
def get(self, path, *args, **kwargs):
'''GET the provided endpoint'''
target = self._host.relative(path).utf8
if not isinstance(target, basestring):
# on older versions of th... |
def tile(self, zoom, row, col):
"""
Return ``BufferedTile`` object of this ``BufferedTilePyramid``.
Parameters
----------
zoom : integer
zoom level
row : integer
tile matrix row
col : integer
tile matrix column
Returns... | Return ``BufferedTile`` object of this ``BufferedTilePyramid``.
Parameters
----------
zoom : integer
zoom level
row : integer
tile matrix row
col : integer
tile matrix column
Returns
-------
buffered tile : ``BufferedT... | Below is the the instruction that describes the task:
### Input:
Return ``BufferedTile`` object of this ``BufferedTilePyramid``.
Parameters
----------
zoom : integer
zoom level
row : integer
tile matrix row
col : integer
tile matrix column... |
def register_presence_callback(self, type_, from_, cb):
"""
Register a callback to be called when a presence stanza is received.
:param type_: Presence type to listen for.
:type type_: :class:`~.PresenceType`
:param from_: Sender JID to listen for, or :data:`None` for a wildcard... | Register a callback to be called when a presence stanza is received.
:param type_: Presence type to listen for.
:type type_: :class:`~.PresenceType`
:param from_: Sender JID to listen for, or :data:`None` for a wildcard
match.
:type from_: :class:`~aioxmpp.JID` or ... | Below is the the instruction that describes the task:
### Input:
Register a callback to be called when a presence stanza is received.
:param type_: Presence type to listen for.
:type type_: :class:`~.PresenceType`
:param from_: Sender JID to listen for, or :data:`None` for a wildcard
... |
def getargspec(method):
"""
Drill through layers of decorators attempting to locate the actual argspec
for a method.
"""
argspec = _getargspec(method)
args = argspec[0]
if args and args[0] == 'self':
return argspec
if hasattr(method, '__func__'):
method = method.__func__... | Drill through layers of decorators attempting to locate the actual argspec
for a method. | Below is the the instruction that describes the task:
### Input:
Drill through layers of decorators attempting to locate the actual argspec
for a method.
### Response:
def getargspec(method):
"""
Drill through layers of decorators attempting to locate the actual argspec
for a method.
"""
a... |
def handle(cls, vm, args):
"""
Setup forwarding connection to given VM and pipe docker cmds over SSH.
"""
docker = Iaas.info(vm)
if not docker:
raise Exception('docker vm %s not found' % vm)
if docker['state'] != 'running':
Iaas.start(vm)
... | Setup forwarding connection to given VM and pipe docker cmds over SSH. | Below is the the instruction that describes the task:
### Input:
Setup forwarding connection to given VM and pipe docker cmds over SSH.
### Response:
def handle(cls, vm, args):
"""
Setup forwarding connection to given VM and pipe docker cmds over SSH.
"""
docker = Iaas.info(vm)
... |
def cv(row, col_name, arg, current_data_model, df, con):
"""
row[col_name] must contain only values from the appropriate controlled vocabulary
"""
vocabulary = con.vocab.vocabularies
cell_value = str(row[col_name])
if not cell_value:
return None
elif cell_value == "None":
ret... | row[col_name] must contain only values from the appropriate controlled vocabulary | Below is the the instruction that describes the task:
### Input:
row[col_name] must contain only values from the appropriate controlled vocabulary
### Response:
def cv(row, col_name, arg, current_data_model, df, con):
"""
row[col_name] must contain only values from the appropriate controlled vocabulary
... |
def has(self, module_name, class_name, attribute_name):
"""
Parameters
----------
module_name: String
The analysis_path of the module
class_name: String
The analysis_path of the class
attribute_name: String
The analysis_path of the attr... | Parameters
----------
module_name: String
The analysis_path of the module
class_name: String
The analysis_path of the class
attribute_name: String
The analysis_path of the attribute
Returns
-------
has_prior: bool
T... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
module_name: String
The analysis_path of the module
class_name: String
The analysis_path of the class
attribute_name: String
The analysis_path of the attribute
... |
def remove_from_organization(self, delete_account=False):
"""
Remove a user from the organization's list of visible users. Optionally also delete the account.
Deleting the account can only be done if the organization owns the account's domain.
:param delete_account: Whether to delete th... | Remove a user from the organization's list of visible users. Optionally also delete the account.
Deleting the account can only be done if the organization owns the account's domain.
:param delete_account: Whether to delete the account after removing from the organization (default false)
:return... | Below is the the instruction that describes the task:
### Input:
Remove a user from the organization's list of visible users. Optionally also delete the account.
Deleting the account can only be done if the organization owns the account's domain.
:param delete_account: Whether to delete the account... |
def decrby(self, key, decrement):
"""Decrement the integer value of a key by the given number.
:raises TypeError: if decrement is not int
"""
if not isinstance(decrement, int):
raise TypeError("decrement must be of type int")
return self.execute(b'DECRBY', key, decre... | Decrement the integer value of a key by the given number.
:raises TypeError: if decrement is not int | Below is the the instruction that describes the task:
### Input:
Decrement the integer value of a key by the given number.
:raises TypeError: if decrement is not int
### Response:
def decrby(self, key, decrement):
"""Decrement the integer value of a key by the given number.
:raises TypeEr... |
def _estimate_runner_memory(json_file):
"""Estimate Java memory requirements based on number of samples.
A rough approach to selecting correct allocated memory for Cromwell.
"""
with open(json_file) as in_handle:
sinfo = json.load(in_handle)
num_parallel = 1
for key in ["config__algorit... | Estimate Java memory requirements based on number of samples.
A rough approach to selecting correct allocated memory for Cromwell. | Below is the the instruction that describes the task:
### Input:
Estimate Java memory requirements based on number of samples.
A rough approach to selecting correct allocated memory for Cromwell.
### Response:
def _estimate_runner_memory(json_file):
"""Estimate Java memory requirements based on number of ... |
def _elu(attrs, inputs, proto_obj):
"""Elu function"""
if 'alpha' in attrs:
new_attrs = translation_utils._fix_attribute_names(attrs, {'alpha' : 'slope'})
else:
new_attrs = translation_utils._add_extra_attributes(attrs, {'slope': 1.0})
new_attrs = translation_utils._add_extra_attributes(... | Elu function | Below is the the instruction that describes the task:
### Input:
Elu function
### Response:
def _elu(attrs, inputs, proto_obj):
"""Elu function"""
if 'alpha' in attrs:
new_attrs = translation_utils._fix_attribute_names(attrs, {'alpha' : 'slope'})
else:
new_attrs = translation_utils._add... |
def set_pd_mag_from_counts(photodict,
c='',
ec='',
lec='',
uec='',
zp=DEFAULT_ZP,
sig=DEFAULT_UL_SIGMA):
"""Set photometry dictionary from a counts measur... | Set photometry dictionary from a counts measurement. | Below is the the instruction that describes the task:
### Input:
Set photometry dictionary from a counts measurement.
### Response:
def set_pd_mag_from_counts(photodict,
c='',
ec='',
lec='',
uec='',
... |
def scale(arr, mn=0, mx=1):
"""
Apply min-max scaling (normalize)
then scale to (mn,mx)
"""
amn = arr.min()
amx = arr.max()
# normalize:
arr = (arr - amn) / (amx - amn)
# scale:
if amn != mn or amx != mx:
arr *= mx - mn
arr += mn
return arr | Apply min-max scaling (normalize)
then scale to (mn,mx) | Below is the the instruction that describes the task:
### Input:
Apply min-max scaling (normalize)
then scale to (mn,mx)
### Response:
def scale(arr, mn=0, mx=1):
"""
Apply min-max scaling (normalize)
then scale to (mn,mx)
"""
amn = arr.min()
amx = arr.max()
# normalize:
arr = (... |
def _compute(self, arrays, dates, assets, mask):
"""
For each row in the input, compute a like-shaped array of per-row
ranks.
"""
return masked_rankdata_2d(
arrays[0],
mask,
self.inputs[0].missing_value,
self._method,
se... | For each row in the input, compute a like-shaped array of per-row
ranks. | Below is the the instruction that describes the task:
### Input:
For each row in the input, compute a like-shaped array of per-row
ranks.
### Response:
def _compute(self, arrays, dates, assets, mask):
"""
For each row in the input, compute a like-shaped array of per-row
ranks.
... |
def get_translation_functions(package_name: str, names: Tuple[str, ...] = ('gettext',)):
"""finds and installs translation functions for package"""
translation = get_translation_for(package_name)
return [getattr(translation, x) for x in names] | finds and installs translation functions for package | Below is the the instruction that describes the task:
### Input:
finds and installs translation functions for package
### Response:
def get_translation_functions(package_name: str, names: Tuple[str, ...] = ('gettext',)):
"""finds and installs translation functions for package"""
translation = get_translati... |
def gilliland_cdpp(times, mags, errs,
windowlength=97,
polyorder=2,
binsize=23400, # in seconds: 6.5 hours for classic CDPP
sigclip=5.0,
magsarefluxes=False,
**kwargs):
'''This calculates the CDPP of a... | This calculates the CDPP of a timeseries using the method in the paper:
Gilliland, R. L., Chaplin, W. J., Dunham, E. W., et al. 2011, ApJS, 197, 6
(http://adsabs.harvard.edu/abs/2011ApJS..197....6G)
The steps are:
- pass the time-series through a Savitsky-Golay filter.
- we use `scipy.signal.s... | Below is the the instruction that describes the task:
### Input:
This calculates the CDPP of a timeseries using the method in the paper:
Gilliland, R. L., Chaplin, W. J., Dunham, E. W., et al. 2011, ApJS, 197, 6
(http://adsabs.harvard.edu/abs/2011ApJS..197....6G)
The steps are:
- pass the time-se... |
def download_file_part_run(download_context):
"""
Function run by CreateProjectCommand to create the project.
Runs in a background process.
:param download_context: UploadContext: contains data service setup and project name to create.
"""
destination_dir, file_url_data_dict, seek_amt, bytes_to_... | Function run by CreateProjectCommand to create the project.
Runs in a background process.
:param download_context: UploadContext: contains data service setup and project name to create. | Below is the the instruction that describes the task:
### Input:
Function run by CreateProjectCommand to create the project.
Runs in a background process.
:param download_context: UploadContext: contains data service setup and project name to create.
### Response:
def download_file_part_run(download_contex... |
def cql_encode_all_types(self, val, as_text_type=False):
"""
Converts any type into a CQL string, defaulting to ``cql_encode_object``
if :attr:`~Encoder.mapping` does not contain an entry for the type.
"""
encoded = self.mapping.get(type(val), self.cql_encode_object)(val)
... | Converts any type into a CQL string, defaulting to ``cql_encode_object``
if :attr:`~Encoder.mapping` does not contain an entry for the type. | Below is the the instruction that describes the task:
### Input:
Converts any type into a CQL string, defaulting to ``cql_encode_object``
if :attr:`~Encoder.mapping` does not contain an entry for the type.
### Response:
def cql_encode_all_types(self, val, as_text_type=False):
"""
Converts a... |
def set_property_filter(filter_proto, name, op, value):
"""Set property filter contraint in the given datastore.Filter proto message.
Args:
filter_proto: datastore.Filter proto message
name: property name
op: datastore.PropertyFilter.Operation
value: property value
Returns:
the same datastor... | Set property filter contraint in the given datastore.Filter proto message.
Args:
filter_proto: datastore.Filter proto message
name: property name
op: datastore.PropertyFilter.Operation
value: property value
Returns:
the same datastore.Filter.
Usage:
>>> set_property_filter(filter_proto,... | Below is the the instruction that describes the task:
### Input:
Set property filter contraint in the given datastore.Filter proto message.
Args:
filter_proto: datastore.Filter proto message
name: property name
op: datastore.PropertyFilter.Operation
value: property value
Returns:
the same ... |
def convert_money(self, money: Money, to: str, reverse: bool=False) -> Money:
"""Convert money to another currency"""
converted = self.convert(money.amount, money.currency, to, reverse)
return Money(converted, to) | Convert money to another currency | Below is the the instruction that describes the task:
### Input:
Convert money to another currency
### Response:
def convert_money(self, money: Money, to: str, reverse: bool=False) -> Money:
"""Convert money to another currency"""
converted = self.convert(money.amount, money.currency, to, reverse)
... |
def is_identity():
"""Check to see if this matrix is an identity matrix."""
for index, row in enumerate(self.dta):
if row[index] == 1:
for num, element in enumerate(row):
if num != index:
if element != 0:
... | Check to see if this matrix is an identity matrix. | Below is the the instruction that describes the task:
### Input:
Check to see if this matrix is an identity matrix.
### Response:
def is_identity():
"""Check to see if this matrix is an identity matrix."""
for index, row in enumerate(self.dta):
if row[index] == 1:
for nu... |
def _gen_unzip(it, elem_len):
"""Helper for unzip which checks the lengths of each element in it.
Parameters
----------
it : iterable[tuple]
An iterable of tuples. ``unzip`` should map ensure that these are
already tuples.
elem_len : int or None
The expected element length. I... | Helper for unzip which checks the lengths of each element in it.
Parameters
----------
it : iterable[tuple]
An iterable of tuples. ``unzip`` should map ensure that these are
already tuples.
elem_len : int or None
The expected element length. If this is None it is infered from the... | Below is the the instruction that describes the task:
### Input:
Helper for unzip which checks the lengths of each element in it.
Parameters
----------
it : iterable[tuple]
An iterable of tuples. ``unzip`` should map ensure that these are
already tuples.
elem_len : int or None
... |
def session_callback(self, signal):
"""Signalling from stream session.
Data - new data available for processing.
Playing - Connection is healthy.
Retry - if there is no connection to device.
"""
if signal == SIGNAL_DATA:
self.event.new_event(self.data)
... | Signalling from stream session.
Data - new data available for processing.
Playing - Connection is healthy.
Retry - if there is no connection to device. | Below is the the instruction that describes the task:
### Input:
Signalling from stream session.
Data - new data available for processing.
Playing - Connection is healthy.
Retry - if there is no connection to device.
### Response:
def session_callback(self, signal):
"""Signalling f... |
def list_subscriptions(self, topic_name):
'''
Retrieves the subscriptions in the specified topic.
topic_name:
Name of the topic.
'''
_validate_not_none('topic_name', topic_name)
request = HTTPRequest()
request.method = 'GET'
request.host = sel... | Retrieves the subscriptions in the specified topic.
topic_name:
Name of the topic. | Below is the the instruction that describes the task:
### Input:
Retrieves the subscriptions in the specified topic.
topic_name:
Name of the topic.
### Response:
def list_subscriptions(self, topic_name):
'''
Retrieves the subscriptions in the specified topic.
topic_nam... |
def center_blit(target, source, dest = (0, 0), area=None, special_flags=0):
'''
Blits surface @source to the center of surface @target. Takes the normal
Surface.blit() flags; however, @dest is used as an offset.
'''
loc = lambda d, s: _vec(d.get_size()) / 2 - _vec(s.get_size()) / 2
_blitter(loc... | Blits surface @source to the center of surface @target. Takes the normal
Surface.blit() flags; however, @dest is used as an offset. | Below is the the instruction that describes the task:
### Input:
Blits surface @source to the center of surface @target. Takes the normal
Surface.blit() flags; however, @dest is used as an offset.
### Response:
def center_blit(target, source, dest = (0, 0), area=None, special_flags=0):
'''
Blits surfa... |
def _range(self, memory, addr, **kwargs):
"""
Gets the (min, max) range of solutions for an address.
"""
return (self._min(memory, addr, **kwargs), self._max(memory, addr, **kwargs)) | Gets the (min, max) range of solutions for an address. | Below is the the instruction that describes the task:
### Input:
Gets the (min, max) range of solutions for an address.
### Response:
def _range(self, memory, addr, **kwargs):
"""
Gets the (min, max) range of solutions for an address.
"""
return (self._min(memory, addr, **kwargs), s... |
def get_name(component):
"""
Attempt to get the string name of component, including module and class if
applicable.
"""
if six.callable(component):
name = getattr(component, "__qualname__", component.__name__)
return '.'.join([component.__module__, name])
return str(component) | Attempt to get the string name of component, including module and class if
applicable. | Below is the the instruction that describes the task:
### Input:
Attempt to get the string name of component, including module and class if
applicable.
### Response:
def get_name(component):
"""
Attempt to get the string name of component, including module and class if
applicable.
"""
if si... |
def read(self, vals):
"""Read values.
Args:
vals (list): list of strings representing values
"""
i = 0
if len(vals[i]) == 0:
self.year = None
else:
self.year = vals[i]
i += 1
if len(vals[i]) == 0:
self.mont... | Read values.
Args:
vals (list): list of strings representing values | Below is the the instruction that describes the task:
### Input:
Read values.
Args:
vals (list): list of strings representing values
### Response:
def read(self, vals):
"""Read values.
Args:
vals (list): list of strings representing values
"""
i = ... |
def update(self, friendly_name=values.unset, code_length=values.unset,
lookup_enabled=values.unset, skip_sms_to_landlines=values.unset,
dtmf_input_required=values.unset, tts_name=values.unset,
psd2_enabled=values.unset):
"""
Update the ServiceInstance
... | Update the ServiceInstance
:param unicode friendly_name: A string to describe the verification service
:param unicode code_length: The length of the verification code to generate
:param bool lookup_enabled: Whether to perform a lookup with each verification
:param bool skip_sms_to_landl... | Below is the the instruction that describes the task:
### Input:
Update the ServiceInstance
:param unicode friendly_name: A string to describe the verification service
:param unicode code_length: The length of the verification code to generate
:param bool lookup_enabled: Whether to perform ... |
def _tracing_information():
"""Gets B3 distributed tracing information, if available.
This is returned as a list, ready to be formatted into Spring Cloud Sleuth compatible format.
"""
# We'll collate trace information if the B3 headers have been collected:
values = b3.values()
if values[b3.b3... | Gets B3 distributed tracing information, if available.
This is returned as a list, ready to be formatted into Spring Cloud Sleuth compatible format. | Below is the the instruction that describes the task:
### Input:
Gets B3 distributed tracing information, if available.
This is returned as a list, ready to be formatted into Spring Cloud Sleuth compatible format.
### Response:
def _tracing_information():
"""Gets B3 distributed tracing information, if ava... |
def load_labware(self, labware: Labware) -> Labware:
"""
Load labware onto a Magnetic Module, checking if it is compatible
"""
if labware.magdeck_engage_height is None:
MODULE_LOG.warning(
"This labware ({}) is not explicitly compatible with the"
... | Load labware onto a Magnetic Module, checking if it is compatible | Below is the the instruction that describes the task:
### Input:
Load labware onto a Magnetic Module, checking if it is compatible
### Response:
def load_labware(self, labware: Labware) -> Labware:
"""
Load labware onto a Magnetic Module, checking if it is compatible
"""
if labware.... |
def register_view(self, view):
"""Register callbacks for button press events and selection changed"""
super(ListViewController, self).register_view(view)
self.tree_view.connect('button_press_event', self.mouse_click) | Register callbacks for button press events and selection changed | Below is the the instruction that describes the task:
### Input:
Register callbacks for button press events and selection changed
### Response:
def register_view(self, view):
"""Register callbacks for button press events and selection changed"""
super(ListViewController, self).register_view(view)
... |
def resize(self, width, height):
"""
Sets the new size and buffer size internally
"""
self.width = width
self.height = height
self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window)
self.set_default_viewport() | Sets the new size and buffer size internally | Below is the the instruction that describes the task:
### Input:
Sets the new size and buffer size internally
### Response:
def resize(self, width, height):
"""
Sets the new size and buffer size internally
"""
self.width = width
self.height = height
self.buffer_width... |
def to(self, to):
"""
[Edge-only] especifica el destino del lado
"""
if self._type.lower() != 'edge':
raise ValueError('Cannot set From/To to non-edge objects')
self._to = to
return self | [Edge-only] especifica el destino del lado | Below is the the instruction that describes the task:
### Input:
[Edge-only] especifica el destino del lado
### Response:
def to(self, to):
"""
[Edge-only] especifica el destino del lado
"""
if self._type.lower() != 'edge':
raise ValueError('Cannot set From/To to non-edg... |
def from_raw_profiles(cls, raw_profiles, profile_name, cli_vars,
target_override=None, threads_override=None):
"""
:param raw_profiles dict: The profile data, from disk as yaml.
:param profile_name str: The profile name to use.
:param cli_vars dict: The command-... | :param raw_profiles dict: The profile data, from disk as yaml.
:param profile_name str: The profile name to use.
:param cli_vars dict: The command-line variables passed as arguments,
as a dict.
:param target_override Optional[str]: The target to use, if provided on
the co... | Below is the the instruction that describes the task:
### Input:
:param raw_profiles dict: The profile data, from disk as yaml.
:param profile_name str: The profile name to use.
:param cli_vars dict: The command-line variables passed as arguments,
as a dict.
:param target_overrid... |
def cfg_from_file(self, yaml_filename, config_dict):
"""Load a config file and merge it into the default options."""
import yaml
from easydict import EasyDict as edict
with open(yaml_filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
return self._merge_a_into_b(yaml... | Load a config file and merge it into the default options. | Below is the the instruction that describes the task:
### Input:
Load a config file and merge it into the default options.
### Response:
def cfg_from_file(self, yaml_filename, config_dict):
"""Load a config file and merge it into the default options."""
import yaml
from easydict import Easy... |
def _store(self, con):
"""Store a database connection for subsequent use."""
self._con = con
self._transaction = False
self._closed = False
self._usage = 0 | Store a database connection for subsequent use. | Below is the the instruction that describes the task:
### Input:
Store a database connection for subsequent use.
### Response:
def _store(self, con):
"""Store a database connection for subsequent use."""
self._con = con
self._transaction = False
self._closed = False
self._us... |
def getcal(self):
"""Retrieve the SDS calibration coefficients.
Args::
no argument
Returns::
5-element tuple holding:
- cal: calibration factor (attribute 'scale_factor')
- cal_error : calibration factor error
(attribute 'scale... | Retrieve the SDS calibration coefficients.
Args::
no argument
Returns::
5-element tuple holding:
- cal: calibration factor (attribute 'scale_factor')
- cal_error : calibration factor error
(attribute 'scale_factor_err')
- off... | Below is the the instruction that describes the task:
### Input:
Retrieve the SDS calibration coefficients.
Args::
no argument
Returns::
5-element tuple holding:
- cal: calibration factor (attribute 'scale_factor')
- cal_error : calibration factor error
... |
def insert_at_frontier(self,
operations: ops.OP_TREE,
start: int,
frontier: Dict[ops.Qid, int] = None
) -> Dict[ops.Qid, int]:
"""Inserts operations inline at frontier.
Args:
operatio... | Inserts operations inline at frontier.
Args:
operations: the operations to insert
start: the moment at which to start inserting the operations
frontier: frontier[q] is the earliest moment in which an operation
acting on qubit q can be placed. | Below is the the instruction that describes the task:
### Input:
Inserts operations inline at frontier.
Args:
operations: the operations to insert
start: the moment at which to start inserting the operations
frontier: frontier[q] is the earliest moment in which an operat... |
def _normalize_orders(self):
"""Helper: adjust orders based on cursors, where clauses."""
orders = list(self._orders)
_has_snapshot_cursor = False
if self._start_at:
if isinstance(self._start_at[0], document.DocumentSnapshot):
_has_snapshot_cursor = True
... | Helper: adjust orders based on cursors, where clauses. | Below is the the instruction that describes the task:
### Input:
Helper: adjust orders based on cursors, where clauses.
### Response:
def _normalize_orders(self):
"""Helper: adjust orders based on cursors, where clauses."""
orders = list(self._orders)
_has_snapshot_cursor = False
... |
def update_stats(self, stats, delta, sample_rate=1):
"""
Updates one or more stats counters by arbitrary amounts
>>> statsd_client.update_stats('some.int',10)
"""
if not isinstance(stats, list):
stats = [stats]
data = dict((stat, "%s|c" % delta) for stat in s... | Updates one or more stats counters by arbitrary amounts
>>> statsd_client.update_stats('some.int',10) | Below is the the instruction that describes the task:
### Input:
Updates one or more stats counters by arbitrary amounts
>>> statsd_client.update_stats('some.int',10)
### Response:
def update_stats(self, stats, delta, sample_rate=1):
"""
Updates one or more stats counters by arbitrary amoun... |
def display_eventtype(self):
"""Read the list of event types in the annotations and update widgets.
"""
if self.annot is not None:
event_types = sorted(self.annot.event_types, key=str.lower)
else:
event_types = []
self.idx_eventtype.clear()
evtty... | Read the list of event types in the annotations and update widgets. | Below is the the instruction that describes the task:
### Input:
Read the list of event types in the annotations and update widgets.
### Response:
def display_eventtype(self):
"""Read the list of event types in the annotations and update widgets.
"""
if self.annot is not None:
e... |
def plot_linear_relation(x, y, x_err=None, y_err=None, title=None, point_label=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, y_2_label=None, log_x=False, log_y=False, size=None, filename=None):
''' Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation ... | Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation to this line is also plotted, showing the offset.
Parameters
----------
x, y, x_err, y_err: iterable
filename: string, PdfPages object or None
PdfPages file object: plot is appended to the pdf
stri... | Below is the the instruction that describes the task:
### Input:
Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation to this line is also plotted, showing the offset.
Parameters
----------
x, y, x_err, y_err: iterable
filename: string, PdfPages object or None
... |
def _scheduleCombUpdateDoneEv(self) -> Event:
"""
Schedule combUpdateDoneEv event to let agents know that current
delta step is ending and values from combinational logic are stable
"""
assert not self._combUpdateDonePlaned, self.now
cud = Event(self)
cud.process_... | Schedule combUpdateDoneEv event to let agents know that current
delta step is ending and values from combinational logic are stable | Below is the the instruction that describes the task:
### Input:
Schedule combUpdateDoneEv event to let agents know that current
delta step is ending and values from combinational logic are stable
### Response:
def _scheduleCombUpdateDoneEv(self) -> Event:
"""
Schedule combUpdateDoneEv even... |
def handleResponseEnd(self):
"""
Extends handleResponseEnd to not care about the user closing/refreshing
their browser before the response is finished. Also calls cacheContent
in a thread that we don't care when it finishes.
"""
try:
if not self._finished:
... | Extends handleResponseEnd to not care about the user closing/refreshing
their browser before the response is finished. Also calls cacheContent
in a thread that we don't care when it finishes. | Below is the the instruction that describes the task:
### Input:
Extends handleResponseEnd to not care about the user closing/refreshing
their browser before the response is finished. Also calls cacheContent
in a thread that we don't care when it finishes.
### Response:
def handleResponseEnd(self):... |
def _decrypt(self, value, encrypted_value):
"""Decrypt encoded cookies
"""
if sys.platform == 'win32':
return self._decrypt_windows_chrome(value, encrypted_value)
if value or (encrypted_value[:3] != b'v10'):
return value
# Encrypted cookies should be pr... | Decrypt encoded cookies | Below is the the instruction that describes the task:
### Input:
Decrypt encoded cookies
### Response:
def _decrypt(self, value, encrypted_value):
"""Decrypt encoded cookies
"""
if sys.platform == 'win32':
return self._decrypt_windows_chrome(value, encrypted_value)
if ... |
def plot_or_print(my_turbine, e126, dummy_turbine):
r"""
Plots or prints power output and power (coefficient) curves.
Parameters
----------
my_turbine : WindTurbine
WindTurbine object with self provided power curve.
e126 : WindTurbine
WindTurbine object with power curve from dat... | r"""
Plots or prints power output and power (coefficient) curves.
Parameters
----------
my_turbine : WindTurbine
WindTurbine object with self provided power curve.
e126 : WindTurbine
WindTurbine object with power curve from data file provided by the
windpowerlib.
dummy_t... | Below is the the instruction that describes the task:
### Input:
r"""
Plots or prints power output and power (coefficient) curves.
Parameters
----------
my_turbine : WindTurbine
WindTurbine object with self provided power curve.
e126 : WindTurbine
WindTurbine object with power c... |
def get_model_and_form_class(model, form_class):
"""
Returns a model and form class based on the model and form_class
parameters that were passed to the generic view.
If ``form_class`` is given then its associated model will be returned along
with ``form_class`` itself. Otherwise, if ``model`` is ... | Returns a model and form class based on the model and form_class
parameters that were passed to the generic view.
If ``form_class`` is given then its associated model will be returned along
with ``form_class`` itself. Otherwise, if ``model`` is given, ``model``
itself will be returned along with a ``M... | Below is the the instruction that describes the task:
### Input:
Returns a model and form class based on the model and form_class
parameters that were passed to the generic view.
If ``form_class`` is given then its associated model will be returned along
with ``form_class`` itself. Otherwise, if ``mod... |
def mongoimport(json, database,
ip='localhost', port=27017,
user=None, password=None,
delim='_', delim1=None, delim2=None,
delim_occurance=1, delim1_occurance=1, delim2_occurance=1):
'''
Performs mongoimport on one or more json files.
Args:
... | Performs mongoimport on one or more json files.
Args:
json: Can be one of several things:
- path to a single JSON file
- an iterable (list or tuple) of one or more JSON file paths
- path to a directory containing one or more JSON files
database (str): Name of ... | Below is the the instruction that describes the task:
### Input:
Performs mongoimport on one or more json files.
Args:
json: Can be one of several things:
- path to a single JSON file
- an iterable (list or tuple) of one or more JSON file paths
- path to a director... |
def index(self, sub, start=None, end=None):
"""Like S.find() but raise ValueError when the substring is not found.
:param str sub: Substring to search.
:param int start: Beginning position.
:param int end: Stop comparison at this position.
"""
return self.value_no_colors... | Like S.find() but raise ValueError when the substring is not found.
:param str sub: Substring to search.
:param int start: Beginning position.
:param int end: Stop comparison at this position. | Below is the the instruction that describes the task:
### Input:
Like S.find() but raise ValueError when the substring is not found.
:param str sub: Substring to search.
:param int start: Beginning position.
:param int end: Stop comparison at this position.
### Response:
def index(self, su... |
def insort_right(a, x, lo=0, hi=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise V... | Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched. | Below is the the instruction that describes the task:
### Input:
Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
### Response:
d... |
def get_nearest_year_for_day(day):
"""
Returns the nearest year to now inferred from a Julian date.
"""
now = time.gmtime()
result = now.tm_year
# if the day is far greater than today, it must be from last year
if day - now.tm_yday > 365 // 2:
result -= 1
# if the day is far less than today, it must be for ne... | Returns the nearest year to now inferred from a Julian date. | Below is the the instruction that describes the task:
### Input:
Returns the nearest year to now inferred from a Julian date.
### Response:
def get_nearest_year_for_day(day):
"""
Returns the nearest year to now inferred from a Julian date.
"""
now = time.gmtime()
result = now.tm_year
# if the day is far grea... |
def create_version(self, project_id, model_name, version_spec):
"""
Creates the Version on Google Cloud ML Engine.
Returns the operation if the version was created successfully and
raises an error otherwise.
"""
parent_name = 'projects/{}/models/{}'.format(project_id, mo... | Creates the Version on Google Cloud ML Engine.
Returns the operation if the version was created successfully and
raises an error otherwise. | Below is the the instruction that describes the task:
### Input:
Creates the Version on Google Cloud ML Engine.
Returns the operation if the version was created successfully and
raises an error otherwise.
### Response:
def create_version(self, project_id, model_name, version_spec):
"""
... |
def find_users(self, *args):
"""
Returns the users to search given names as args.
Return all users if there are no args provided.
"""
if args:
names = reduce(lambda query, arg: query |
(Q(first_name__icontains=arg) | Q(last_name__icontains=arg)),
... | Returns the users to search given names as args.
Return all users if there are no args provided. | Below is the the instruction that describes the task:
### Input:
Returns the users to search given names as args.
Return all users if there are no args provided.
### Response:
def find_users(self, *args):
"""
Returns the users to search given names as args.
Return all users if there... |
def _nxapi_request(commands, method='cli_conf', **kwargs):
'''
Executes an nxapi_request request over NX-API.
commands
The exec or config commands to be sent.
method: ``cli_show``
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output... | Executes an nxapi_request request over NX-API.
commands
The exec or config commands to be sent.
method: ``cli_show``
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
... | Below is the the instruction that describes the task:
### Input:
Executes an nxapi_request request over NX-API.
commands
The exec or config commands to be sent.
method: ``cli_show``
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
... |
def _transactional(self, method, *argv, **argd):
"""
Begins a transaction and calls the given DAO method.
If the method executes successfully the transaction is commited.
If the method fails, the transaction is rolled back.
@type method: callable
@param method: Bound ... | Begins a transaction and calls the given DAO method.
If the method executes successfully the transaction is commited.
If the method fails, the transaction is rolled back.
@type method: callable
@param method: Bound method of this class or one of its subclasses.
The first ... | Below is the the instruction that describes the task:
### Input:
Begins a transaction and calls the given DAO method.
If the method executes successfully the transaction is commited.
If the method fails, the transaction is rolled back.
@type method: callable
@param method: Bound ... |
def _observers_for_notification(self, ntype, sender):
"""Find all registered observers that should recieve notification"""
keys = (
(ntype,sender),
(ntype, None),
(None, sender),
(None,None)
)
obs = set(... | Find all registered observers that should recieve notification | Below is the the instruction that describes the task:
### Input:
Find all registered observers that should recieve notification
### Response:
def _observers_for_notification(self, ntype, sender):
"""Find all registered observers that should recieve notification"""
keys = (
(ntyp... |
def ftp_url(self):
# type: () -> Text
"""Get the FTP url this filesystem will open."""
url = (
"ftp://{}".format(self.host)
if self.port == 21
else "ftp://{}:{}".format(self.host, self.port)
)
return url | Get the FTP url this filesystem will open. | Below is the the instruction that describes the task:
### Input:
Get the FTP url this filesystem will open.
### Response:
def ftp_url(self):
# type: () -> Text
"""Get the FTP url this filesystem will open."""
url = (
"ftp://{}".format(self.host)
if self.port == 21
... |
def get_chinese_new_year(self, year):
"""
Compute Chinese New Year days. To return a list of holidays.
By default, it'll at least return the Chinese New Year holidays chosen
using the following options:
* ``include_chinese_new_year_eve``
* ``include_chinese_new_year`` (... | Compute Chinese New Year days. To return a list of holidays.
By default, it'll at least return the Chinese New Year holidays chosen
using the following options:
* ``include_chinese_new_year_eve``
* ``include_chinese_new_year`` (on by default)
* ``include_chinese_second_day``
... | Below is the the instruction that describes the task:
### Input:
Compute Chinese New Year days. To return a list of holidays.
By default, it'll at least return the Chinese New Year holidays chosen
using the following options:
* ``include_chinese_new_year_eve``
* ``include_chinese_n... |
def compare_and_set(self, expect, update):
'''
Atomically sets the value to `update` if the current value is equal to
`expect`.
:param expect: The expected current value.
:param update: The value to set if and only if `expect` equals the
current value.
'''
... | Atomically sets the value to `update` if the current value is equal to
`expect`.
:param expect: The expected current value.
:param update: The value to set if and only if `expect` equals the
current value. | Below is the the instruction that describes the task:
### Input:
Atomically sets the value to `update` if the current value is equal to
`expect`.
:param expect: The expected current value.
:param update: The value to set if and only if `expect` equals the
current value.
### Resp... |
def add_or_update(self, app_id, value):
'''
Adding or updating the evalution.
:param app_id: the ID of the post.
:param value: the evaluation
:return: in JSON format.
'''
MEvaluation.add_or_update(self.userinfo.uid, app_id, value)
out_dic = {
... | Adding or updating the evalution.
:param app_id: the ID of the post.
:param value: the evaluation
:return: in JSON format. | Below is the the instruction that describes the task:
### Input:
Adding or updating the evalution.
:param app_id: the ID of the post.
:param value: the evaluation
:return: in JSON format.
### Response:
def add_or_update(self, app_id, value):
'''
Adding or updating the eval... |
def set(self, obj, build_kwargs):
"""Set cached value."""
if build_kwargs is None:
build_kwargs = {}
cached = {}
if 'queryset' in build_kwargs:
cached = {
'model': build_kwargs['queryset'].model,
'pks': list(build_kwargs['queryset'... | Set cached value. | Below is the the instruction that describes the task:
### Input:
Set cached value.
### Response:
def set(self, obj, build_kwargs):
"""Set cached value."""
if build_kwargs is None:
build_kwargs = {}
cached = {}
if 'queryset' in build_kwargs:
cached = {
... |
def play_audio(filename: str):
"""
Args:
filename: Audio filename
"""
import platform
from subprocess import Popen
player = 'play' if platform.system() == 'Darwin' else 'aplay'
Popen([player, '-q', filename]) | Args:
filename: Audio filename | Below is the the instruction that describes the task:
### Input:
Args:
filename: Audio filename
### Response:
def play_audio(filename: str):
"""
Args:
filename: Audio filename
"""
import platform
from subprocess import Popen
player = 'play' if platform.system() == 'Darwin' ... |
def kruskal_align(U, V, permute_U=False, permute_V=False):
"""Aligns two KTensors and returns a similarity score.
Parameters
----------
U : KTensor
First kruskal tensor to align.
V : KTensor
Second kruskal tensor to align.
permute_U : bool
If True, modifies 'U' to align ... | Aligns two KTensors and returns a similarity score.
Parameters
----------
U : KTensor
First kruskal tensor to align.
V : KTensor
Second kruskal tensor to align.
permute_U : bool
If True, modifies 'U' to align the KTensors (default is False).
permute_V : bool
If T... | Below is the the instruction that describes the task:
### Input:
Aligns two KTensors and returns a similarity score.
Parameters
----------
U : KTensor
First kruskal tensor to align.
V : KTensor
Second kruskal tensor to align.
permute_U : bool
If True, modifies 'U' to ali... |
def sql(self, stmt, parameters=None, bulk_parameters=None):
"""
Execute SQL stmt against the crate server.
"""
if stmt is None:
return None
data = _create_sql_payload(stmt, parameters, bulk_parameters)
logger.debug(
'Sending request to %s with pay... | Execute SQL stmt against the crate server. | Below is the the instruction that describes the task:
### Input:
Execute SQL stmt against the crate server.
### Response:
def sql(self, stmt, parameters=None, bulk_parameters=None):
"""
Execute SQL stmt against the crate server.
"""
if stmt is None:
return None
... |
def realpred(cls, lemma, pos, sense=None):
"""Instantiate a Pred from its components."""
string_tokens = [lemma]
if pos is not None:
string_tokens.append(pos)
if sense is not None:
sense = str(sense)
string_tokens.append(sense)
predstr = '_'.jo... | Instantiate a Pred from its components. | Below is the the instruction that describes the task:
### Input:
Instantiate a Pred from its components.
### Response:
def realpred(cls, lemma, pos, sense=None):
"""Instantiate a Pred from its components."""
string_tokens = [lemma]
if pos is not None:
string_tokens.append(pos)
... |
def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed between nodeshot2 objects only
"""
if obj1._meta.app_label != 'oldimporter' and obj2._meta.app_label != 'oldimporter':
return True
return None | Relations between objects are allowed between nodeshot2 objects only | Below is the the instruction that describes the task:
### Input:
Relations between objects are allowed between nodeshot2 objects only
### Response:
def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed between nodeshot2 objects only
"""
if obj1._me... |
def get_user_and_check_auth(self, username, password):
"""Check the combination username/password that is valid on the
database.
"""
constraint = sql.or_(
models.USERS.c.name == username,
models.USERS.c.email == username
)
user = self.identity_fro... | Check the combination username/password that is valid on the
database. | Below is the the instruction that describes the task:
### Input:
Check the combination username/password that is valid on the
database.
### Response:
def get_user_and_check_auth(self, username, password):
"""Check the combination username/password that is valid on the
database.
"""
... |
def _set_up_pool_config(self):
'''
Helper to configure pool options during DatabaseWrapper initialization.
'''
self._max_conns = self.settings_dict['OPTIONS'].get('MAX_CONNS', pool_config_defaults['MAX_CONNS'])
self._min_conns = self.settings_dict['OPTIONS'].get('MIN_CONNS', self._max_conns)
... | Helper to configure pool options during DatabaseWrapper initialization. | Below is the the instruction that describes the task:
### Input:
Helper to configure pool options during DatabaseWrapper initialization.
### Response:
def _set_up_pool_config(self):
'''
Helper to configure pool options during DatabaseWrapper initialization.
'''
self._max_conns = self.settings_dict[... |
def remove_mock(self, mock):
"""
Removes a specific mock instance by object reference.
Arguments:
mock (pook.Mock): mock instance to remove.
"""
self.mocks = [m for m in self.mocks if m is not mock] | Removes a specific mock instance by object reference.
Arguments:
mock (pook.Mock): mock instance to remove. | Below is the the instruction that describes the task:
### Input:
Removes a specific mock instance by object reference.
Arguments:
mock (pook.Mock): mock instance to remove.
### Response:
def remove_mock(self, mock):
"""
Removes a specific mock instance by object reference.
... |
def wrap_content(content, settings, hard_breaks=False):
"""
Returns *content* wrapped in a HTML structure.
If *hard_breaks* is set, line breaks are converted to `<br />` tags.
"""
settings.context['content'] = wrap_paragraphs(content, hard_breaks)
template = Template(settings.template)
try:
return t... | Returns *content* wrapped in a HTML structure.
If *hard_breaks* is set, line breaks are converted to `<br />` tags. | Below is the the instruction that describes the task:
### Input:
Returns *content* wrapped in a HTML structure.
If *hard_breaks* is set, line breaks are converted to `<br />` tags.
### Response:
def wrap_content(content, settings, hard_breaks=False):
"""
Returns *content* wrapped in a HTML structure.
If ... |
def isdisjoint(self, other):
"""Return True if the set has no elements in common with other."""
return not bool(self.db.sinter([self.key, other.key])) | Return True if the set has no elements in common with other. | Below is the the instruction that describes the task:
### Input:
Return True if the set has no elements in common with other.
### Response:
def isdisjoint(self, other):
"""Return True if the set has no elements in common with other."""
return not bool(self.db.sinter([self.key, other.key])) |
def addValue(self, protocolElement):
"""
Appends the specified protocolElement to the value list for this
response.
"""
self._numElements += 1
self._bufferSize += protocolElement.ByteSize()
attr = getattr(self._protoObject, self._valueListName)
obj = attr.... | Appends the specified protocolElement to the value list for this
response. | Below is the the instruction that describes the task:
### Input:
Appends the specified protocolElement to the value list for this
response.
### Response:
def addValue(self, protocolElement):
"""
Appends the specified protocolElement to the value list for this
response.
"""
... |
def get_occurrence(event_id, occurrence_id=None, year=None, month=None,
day=None, hour=None, minute=None, second=None,
tzinfo=None):
"""
Because occurrences don't have to be persisted, there must be two ways to
retrieve them. both need an event, but if its persisted the... | Because occurrences don't have to be persisted, there must be two ways to
retrieve them. both need an event, but if its persisted the occurrence can
be retrieved with an id. If it is not persisted it takes a date to
retrieve it. This function returns an event and occurrence regardless of
which method i... | Below is the the instruction that describes the task:
### Input:
Because occurrences don't have to be persisted, there must be two ways to
retrieve them. both need an event, but if its persisted the occurrence can
be retrieved with an id. If it is not persisted it takes a date to
retrieve it. This func... |
def get_source_metadata(self):
"""Gets the metadata for the source.
return: (osid.Metadata) - metadata for the source
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template
m... | Gets the metadata for the source.
return: (osid.Metadata) - metadata for the source
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the metadata for the source.
return: (osid.Metadata) - metadata for the source
*compliance: mandatory -- This method must be implemented.*
### Response:
def get_source_metadata(self):
"""Gets the metadata for the source.... |
def get_local_tzone():
"""Get the current time zone on the local host"""
if localtime().tm_isdst:
if altzone < 0:
tzone = '+' + \
str(int(float(altzone) / 60 // 60)).rjust(2,
'0') + \
str(int(float(
... | Get the current time zone on the local host | Below is the the instruction that describes the task:
### Input:
Get the current time zone on the local host
### Response:
def get_local_tzone():
"""Get the current time zone on the local host"""
if localtime().tm_isdst:
if altzone < 0:
tzone = '+' + \
str(int(float(... |
def relayIndextoCoord(self, i):
"""
Map 1D cell index to a 2D coordinate
:param i: integer 1D cell index
:return: (x, y), a 2D coordinate
"""
x = i % self.relayWidth
y = i / self.relayWidth
return x, y | Map 1D cell index to a 2D coordinate
:param i: integer 1D cell index
:return: (x, y), a 2D coordinate | Below is the the instruction that describes the task:
### Input:
Map 1D cell index to a 2D coordinate
:param i: integer 1D cell index
:return: (x, y), a 2D coordinate
### Response:
def relayIndextoCoord(self, i):
"""
Map 1D cell index to a 2D coordinate
:param i: integer 1D cell index
:... |
def tree_view_keypress_callback(self, widget, event):
"""Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to work wi... | Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to work with a Gtk.TreeView which model is a Gtk.ListStore and only uses te... | Below is the the instruction that describes the task:
### Input:
Tab back and forward tab-key motion in list widget and the scrollbar motion to follow key cursor motions
The method introduce motion and edit functionality by using "tab"- or "shift-tab"-key for a Gtk.TreeView.
It is designed to wor... |
def prepareToRemove(self):
"""
Handles any code that needs to run to cleanup the connection \
before it gets removed from the scene.
:return <bool> success
"""
# disconnect the signals from the input and output nodes
for node in (self._outputNode, sel... | Handles any code that needs to run to cleanup the connection \
before it gets removed from the scene.
:return <bool> success | Below is the the instruction that describes the task:
### Input:
Handles any code that needs to run to cleanup the connection \
before it gets removed from the scene.
:return <bool> success
### Response:
def prepareToRemove(self):
"""
Handles any code that needs to run ... |
def updateAnomalyLikelihoods(anomalyScores,
params,
verbosity=0):
"""
Compute updated probabilities for anomalyScores using the given params.
:param anomalyScores: a list of records. Each record is a list with the
following three e... | Compute updated probabilities for anomalyScores using the given params.
:param anomalyScores: a list of records. Each record is a list with the
following three elements: [timestamp, value, score]
Example::
[datetime.datetime(2013, 8, 10, 2... | Below is the the instruction that describes the task:
### Input:
Compute updated probabilities for anomalyScores using the given params.
:param anomalyScores: a list of records. Each record is a list with the
following three elements: [timestamp, value, score]
Exa... |
def request(self, method, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params):
"""Calls the service at the specified URL using the "CALL" method"""
raise NotImplementedError("Concrete services must define the request method") | Calls the service at the specified URL using the "CALL" method | Below is the the instruction that describes the task:
### Input:
Calls the service at the specified URL using the "CALL" method
### Response:
def request(self, method, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params):
"""Calls the service at the specified URL using the "CALL" method"... |
def generate(env):
"""Add Builders and construction variables for the OS/2 to an Environment."""
cc.generate(env)
env['CC'] = 'icc'
env['CCCOM'] = '$CC $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET'
env['CXXCOM'] = '$CXX $CXXFLAGS $CPPFLAGS $_CPPDEFF... | Add Builders and construction variables for the OS/2 to an Environment. | Below is the the instruction that describes the task:
### Input:
Add Builders and construction variables for the OS/2 to an Environment.
### Response:
def generate(env):
"""Add Builders and construction variables for the OS/2 to an Environment."""
cc.generate(env)
env['CC'] = 'icc'
env['CC... |
def get_contract(firma, pravni_forma, sidlo, ic, dic, zastoupen):
"""
Compose contract and create PDF.
Args:
firma (str): firma
pravni_forma (str): pravni_forma
sidlo (str): sidlo
ic (str): ic
dic (str): dic
zastoupen (str): zastoupen
Returns:
ob... | Compose contract and create PDF.
Args:
firma (str): firma
pravni_forma (str): pravni_forma
sidlo (str): sidlo
ic (str): ic
dic (str): dic
zastoupen (str): zastoupen
Returns:
obj: StringIO file instance containing PDF file. | Below is the the instruction that describes the task:
### Input:
Compose contract and create PDF.
Args:
firma (str): firma
pravni_forma (str): pravni_forma
sidlo (str): sidlo
ic (str): ic
dic (str): dic
zastoupen (str): zastoupen
Returns:
obj: String... |
def reschedule(self, date, callable_name=None, content_object=None,
expires='7d', args=None, kwargs=None):
"""Schedule a clone of this job."""
# Resolve date relative to the expected start of the current job.
if isinstance(date, basestring):
date = parse_timedelta(... | Schedule a clone of this job. | Below is the the instruction that describes the task:
### Input:
Schedule a clone of this job.
### Response:
def reschedule(self, date, callable_name=None, content_object=None,
expires='7d', args=None, kwargs=None):
"""Schedule a clone of this job."""
# Resolve date relative to t... |
def suggestion_list(input_: str, options: Collection[str]):
"""Get list with suggestions for a given input.
Given an invalid input string and list of valid options, returns a filtered list
of valid options sorted based on their similarity with the input.
"""
options_by_distance = {}
input_thres... | Get list with suggestions for a given input.
Given an invalid input string and list of valid options, returns a filtered list
of valid options sorted based on their similarity with the input. | Below is the the instruction that describes the task:
### Input:
Get list with suggestions for a given input.
Given an invalid input string and list of valid options, returns a filtered list
of valid options sorted based on their similarity with the input.
### Response:
def suggestion_list(input_: str, op... |
def t_ID(self, t):
r'[a-zA-Z]+'
if t.value in self._RESERVED.keys():
t.type = self._RESERVED[t.value]
return t
if Information.is_valid_symbol(t.value) or \
Information.is_valid_category(t.value):
t.type = self._INFORMATION_UNIT
ret... | r'[a-zA-Z]+ | Below is the the instruction that describes the task:
### Input:
r'[a-zA-Z]+
### Response:
def t_ID(self, t):
r'[a-zA-Z]+'
if t.value in self._RESERVED.keys():
t.type = self._RESERVED[t.value]
return t
if Information.is_valid_symbol(t.value) or \
Inf... |
def get_user_events(self, id, **data):
"""
GET /users/:id/events/
Returns a :ref:`paginated <pagination>` response of :format:`events <event>`, under the key ``events``, of all events the user has access to
"""
return self.get("/users/{0}/events/".format(id), data=data) | GET /users/:id/events/
Returns a :ref:`paginated <pagination>` response of :format:`events <event>`, under the key ``events``, of all events the user has access to | Below is the the instruction that describes the task:
### Input:
GET /users/:id/events/
Returns a :ref:`paginated <pagination>` response of :format:`events <event>`, under the key ``events``, of all events the user has access to
### Response:
def get_user_events(self, id, **data):
"""
GET /... |
def serialize_header(self, pyobj, typecode=None, **kw):
'''Serialize a Python object in SOAP-ENV:Header, make
sure everything in Header unique (no #href). Must call
serialize first to create a document.
Parameters:
pyobjs -- instances to serialize in SOAP Header
... | Serialize a Python object in SOAP-ENV:Header, make
sure everything in Header unique (no #href). Must call
serialize first to create a document.
Parameters:
pyobjs -- instances to serialize in SOAP Header
typecode -- default typecode | Below is the the instruction that describes the task:
### Input:
Serialize a Python object in SOAP-ENV:Header, make
sure everything in Header unique (no #href). Must call
serialize first to create a document.
Parameters:
pyobjs -- instances to serialize in SOAP Header
... |
def match(self, set_a, set_b):
"""
For each step in each track from set_a, identify all steps in all tracks from set_b that meet all
cost function criteria
Args:
set_a: List of STObjects
set_b: List of STObjects
Returns:
track_pairing... | For each step in each track from set_a, identify all steps in all tracks from set_b that meet all
cost function criteria
Args:
set_a: List of STObjects
set_b: List of STObjects
Returns:
track_pairings: pandas.DataFrame | Below is the the instruction that describes the task:
### Input:
For each step in each track from set_a, identify all steps in all tracks from set_b that meet all
cost function criteria
Args:
set_a: List of STObjects
set_b: List of STObjects
Returns:
... |
def discard_config(self):
"""Discard changes (rollback 0)."""
self.device.cu.rollback(rb_id=0)
if not self.config_lock:
self._unlock() | Discard changes (rollback 0). | Below is the the instruction that describes the task:
### Input:
Discard changes (rollback 0).
### Response:
def discard_config(self):
"""Discard changes (rollback 0)."""
self.device.cu.rollback(rb_id=0)
if not self.config_lock:
self._unlock() |
def fetch(self, start=None, stop=None):
"""
Fetch log records and return them as a list.
|Args|
* ``start`` (**int**): non-negative index of the first log
record to return.
* ``stop`` (**int**): non-negative index of the last log
record to return.
... | Fetch log records and return them as a list.
|Args|
* ``start`` (**int**): non-negative index of the first log
record to return.
* ``stop`` (**int**): non-negative index of the last log
record to return.
|Returns|
* **list**: list of log records (see ``lo... | Below is the the instruction that describes the task:
### Input:
Fetch log records and return them as a list.
|Args|
* ``start`` (**int**): non-negative index of the first log
record to return.
* ``stop`` (**int**): non-negative index of the last log
record to return.
... |
def publish_scene_remove(self, scene_id):
"""publish the removal of a scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_remove(self.sequence_number, scene_id))
return self.sequence_number | publish the removal of a scene | Below is the the instruction that describes the task:
### Input:
publish the removal of a scene
### Response:
def publish_scene_remove(self, scene_id):
"""publish the removal of a scene"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_remove(self.sequence... |
def add(self, *value):
'''convert value and add to self.value
Subclass must overwrite this method.
Subclass are responsible of creating whatever single instance it need from its ``add(*value)`` and call ``_add()`` to add them to ``self.value``
Args:
*value: the value to be ... | convert value and add to self.value
Subclass must overwrite this method.
Subclass are responsible of creating whatever single instance it need from its ``add(*value)`` and call ``_add()`` to add them to ``self.value``
Args:
*value: the value to be added | Below is the the instruction that describes the task:
### Input:
convert value and add to self.value
Subclass must overwrite this method.
Subclass are responsible of creating whatever single instance it need from its ``add(*value)`` and call ``_add()`` to add them to ``self.value``
Args:
... |
def backup(self):
"""Backups files with the same name of the instance filename"""
count = 0
name = "{}.bkp".format(self.filename)
backup = os.path.join(self.cwd, name)
while os.path.exists(backup):
count += 1
name = "{}.bkp{}".format(self.filename, count)
... | Backups files with the same name of the instance filename | Below is the the instruction that describes the task:
### Input:
Backups files with the same name of the instance filename
### Response:
def backup(self):
"""Backups files with the same name of the instance filename"""
count = 0
name = "{}.bkp".format(self.filename)
backup = os.path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.