code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def initialize_media_descriptor(self) -> None:
"""
Returns the media descriptor for the first media descriptor where
the file can be found.
"""
for md in self.media_descriptors:
media_path = self.get_media_path(md)
if media_path.is_file():
... | Returns the media descriptor for the first media descriptor where
the file can be found. | Below is the the instruction that describes the task:
### Input:
Returns the media descriptor for the first media descriptor where
the file can be found.
### Response:
def initialize_media_descriptor(self) -> None:
"""
Returns the media descriptor for the first media descriptor where
... |
def clear_time_value(self):
"""stub"""
if (self.get_time_value_metadata().is_read_only() or
self.get_time_value_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map['timeValue'] = \
dict(self.get_time_value_metadata().get_default_du... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def clear_time_value(self):
"""stub"""
if (self.get_time_value_metadata().is_read_only() or
self.get_time_value_metadata().is_required()):
raise NoAccess()
self.my_osid_object_for... |
def get_image_hash(image):
'''
Returns an MD5 hash of the image file
Handles images stored locally and on AWS
I know this code is ugly.
Please don't ask.
The rabbit hole is deep.
'''
md5 = hashlib.md5()
try:
for chunk in image.file.chunks():
md5.update(chunk)
... | Returns an MD5 hash of the image file
Handles images stored locally and on AWS
I know this code is ugly.
Please don't ask.
The rabbit hole is deep. | Below is the the instruction that describes the task:
### Input:
Returns an MD5 hash of the image file
Handles images stored locally and on AWS
I know this code is ugly.
Please don't ask.
The rabbit hole is deep.
### Response:
def get_image_hash(image):
'''
Returns an MD5 hash of the imag... |
def get_vnetwork_dvpgs_output_vnetwork_dvpgs_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs")
config = get_vnetwork_dvpgs
output = ET.SubElement(get_vnetwork_dvpgs, "output")
vnetw... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_vnetwork_dvpgs_output_vnetwork_dvpgs_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs")
... |
def _find_video(self):
"""
Lookup and populate ``pybrightcove.video.Video`` object given a video
id or reference_id.
"""
data = None
if self.id:
data = self.connection.get_item(
'find_video_by_id', video_id=self.id)
elif self.reference_... | Lookup and populate ``pybrightcove.video.Video`` object given a video
id or reference_id. | Below is the the instruction that describes the task:
### Input:
Lookup and populate ``pybrightcove.video.Video`` object given a video
id or reference_id.
### Response:
def _find_video(self):
"""
Lookup and populate ``pybrightcove.video.Video`` object given a video
id or reference_i... |
def stage(draft, discard, repo_directory, release_name, release_description):
"""
Stages a release
"""
with work_in(repo_directory):
if discard:
stage_command.discard(release_name, release_description)
else:
stage_command.stage(draft, release_name, release_descrip... | Stages a release | Below is the the instruction that describes the task:
### Input:
Stages a release
### Response:
def stage(draft, discard, repo_directory, release_name, release_description):
"""
Stages a release
"""
with work_in(repo_directory):
if discard:
stage_command.discard(release_name, re... |
def get_residue_mapping(self):
'''Returns a mapping between the sequences ONLY IF there are exactly two. This restriction makes the code much simpler.'''
if len(self.sequence_ids) == 2:
if not self.alignment_output:
self.align()
assert(self.alignment_output)
... | Returns a mapping between the sequences ONLY IF there are exactly two. This restriction makes the code much simpler. | Below is the the instruction that describes the task:
### Input:
Returns a mapping between the sequences ONLY IF there are exactly two. This restriction makes the code much simpler.
### Response:
def get_residue_mapping(self):
'''Returns a mapping between the sequences ONLY IF there are exactly two. This r... |
def rename(self, oldpath, newpath):
"""
Rename a file or folder from ``oldpath`` to ``newpath``.
.. note::
This method implements 'standard' SFTP ``RENAME`` behavior; those
seeking the OpenSSH "POSIX rename" extension behavior should use
`posix_rename`.
... | Rename a file or folder from ``oldpath`` to ``newpath``.
.. note::
This method implements 'standard' SFTP ``RENAME`` behavior; those
seeking the OpenSSH "POSIX rename" extension behavior should use
`posix_rename`.
:param str oldpath:
existing name of the... | Below is the the instruction that describes the task:
### Input:
Rename a file or folder from ``oldpath`` to ``newpath``.
.. note::
This method implements 'standard' SFTP ``RENAME`` behavior; those
seeking the OpenSSH "POSIX rename" extension behavior should use
`posix_r... |
def pipeline_control_new(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None):
""" Pipeline control unit
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back o... | Pipeline control unit
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline)
stage_enable - (o) vector of enable signals, one signal per stage, that controls t... | Below is the the instruction that describes the task:
### Input:
Pipeline control unit
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline)
stage_enable ... |
def _wrapped(self):
"""
Wrap this udf with a function and attach docstring from func
"""
# It is possible for a callable instance without __name__ attribute or/and
# __module__ attribute to be wrapped here. For example, functools.partial. In this case,
# we should avoid ... | Wrap this udf with a function and attach docstring from func | Below is the the instruction that describes the task:
### Input:
Wrap this udf with a function and attach docstring from func
### Response:
def _wrapped(self):
"""
Wrap this udf with a function and attach docstring from func
"""
# It is possible for a callable instance without __na... |
def remove_mapping(agent, prefix, ip):
"""Removes a mapping with a contract.
It has high latency but gives some kind of guarantee."""
return _broadcast(agent, RemoveMappingManager,
RecordType.record_A, prefix, ip) | Removes a mapping with a contract.
It has high latency but gives some kind of guarantee. | Below is the the instruction that describes the task:
### Input:
Removes a mapping with a contract.
It has high latency but gives some kind of guarantee.
### Response:
def remove_mapping(agent, prefix, ip):
"""Removes a mapping with a contract.
It has high latency but gives some kind of guarantee."""
... |
def set_canari_mode(mode=CanariMode.Unknown):
"""
Sets the global operating mode for Canari. This is used to alter the behaviour of dangerous classes like the
CanariConfigParser.
:param mode: the numeric Canari operating mode (CanariMode.Local, CanariMode.Remote, etc.).
:return: previous operating ... | Sets the global operating mode for Canari. This is used to alter the behaviour of dangerous classes like the
CanariConfigParser.
:param mode: the numeric Canari operating mode (CanariMode.Local, CanariMode.Remote, etc.).
:return: previous operating mode. | Below is the the instruction that describes the task:
### Input:
Sets the global operating mode for Canari. This is used to alter the behaviour of dangerous classes like the
CanariConfigParser.
:param mode: the numeric Canari operating mode (CanariMode.Local, CanariMode.Remote, etc.).
:return: previous... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'intent') and self.intent is not None:
_dict['intent'] = self.intent
if hasattr(self, 'confidence') and self.confidence is not None:
_dict['confidence'] = self.... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'intent') and self.intent is not None:
_dict['... |
def get_property_value(self, name):
"""Return the value of a property.
name:
the property name in Clark notation.
return value:
may have different types, depending on the status:
- string or unicode: for standard property values.
- lxml.etree.Ele... | Return the value of a property.
name:
the property name in Clark notation.
return value:
may have different types, depending on the status:
- string or unicode: for standard property values.
- lxml.etree.Element: for complex values.
If the p... | Below is the the instruction that describes the task:
### Input:
Return the value of a property.
name:
the property name in Clark notation.
return value:
may have different types, depending on the status:
- string or unicode: for standard property values.
... |
def annual_heating_design_day_990(self):
"""A design day object representing the annual 99.0% heating design day."""
self._load_header_check()
if bool(self._heating_dict) is True:
avg_press = self.atmospheric_station_pressure.average
avg_press = None if avg_press == 99999... | A design day object representing the annual 99.0% heating design day. | Below is the the instruction that describes the task:
### Input:
A design day object representing the annual 99.0% heating design day.
### Response:
def annual_heating_design_day_990(self):
"""A design day object representing the annual 99.0% heating design day."""
self._load_header_check()
... |
def _supports(self, item):
"""Supports everything of parent class and csr, csc, bsr, and dia sparse matrices."""
if SparseParameter._is_supported_matrix(item):
return True
else:
return super(SparseResult, self)._supports(item) | Supports everything of parent class and csr, csc, bsr, and dia sparse matrices. | Below is the the instruction that describes the task:
### Input:
Supports everything of parent class and csr, csc, bsr, and dia sparse matrices.
### Response:
def _supports(self, item):
"""Supports everything of parent class and csr, csc, bsr, and dia sparse matrices."""
if SparseParameter._is_supp... |
def _transfer_output_files(self, tool_output_dir, working_dir, output_dir, patterns):
"""Transfer files created by the tool in the container to the output directory.
@param tool_output_dir: The directory under which all tool output files are created.
@param working_dir: The absolute working dire... | Transfer files created by the tool in the container to the output directory.
@param tool_output_dir: The directory under which all tool output files are created.
@param working_dir: The absolute working directory of the tool in the container.
@param output_dir: the directory where to write resul... | Below is the the instruction that describes the task:
### Input:
Transfer files created by the tool in the container to the output directory.
@param tool_output_dir: The directory under which all tool output files are created.
@param working_dir: The absolute working directory of the tool in the con... |
def fft_plan(shape, dtype=np.complex64, axes=None, fast_math=True):
"""returns an reikna plan/FFT obj of shape dshape
"""
# if not axes is None and any([a<0 for a in axes]):
# raise NotImplementedError("indices of axes have to be non negative, but are: %s"%str(axes))
axes = _convert_axes_to_abs... | returns an reikna plan/FFT obj of shape dshape | Below is the the instruction that describes the task:
### Input:
returns an reikna plan/FFT obj of shape dshape
### Response:
def fft_plan(shape, dtype=np.complex64, axes=None, fast_math=True):
"""returns an reikna plan/FFT obj of shape dshape
"""
# if not axes is None and any([a<0 for a in axes]):
... |
def surface_ras_shift(self):
"""Freesurfer uses two coordinate systems: one for volumes ("RAS") and
one for surfaces ("tkReg", "tkRAS", and "Surface RAS").
To get from surface to volume coordinates, add this numbers.
To get from volume to surface coordinates, substract this numbers.
... | Freesurfer uses two coordinate systems: one for volumes ("RAS") and
one for surfaces ("tkReg", "tkRAS", and "Surface RAS").
To get from surface to volume coordinates, add this numbers.
To get from volume to surface coordinates, substract this numbers. | Below is the the instruction that describes the task:
### Input:
Freesurfer uses two coordinate systems: one for volumes ("RAS") and
one for surfaces ("tkReg", "tkRAS", and "Surface RAS").
To get from surface to volume coordinates, add this numbers.
To get from volume to surface coordinates,... |
def camelcase_to_underline(param_dict):
"""
将驼峰命名的参数字典键转换为下划线参数
:param:
* param_dict: (dict) 请求参数字典
:return:
* temp_dict: (dict) 转换后的参数字典
举例如下::
print('--- transform_hump_to_underline demo---')
hump_param_dict = {'firstName': 'Python', 'Second_Name': 'san', 'right... | 将驼峰命名的参数字典键转换为下划线参数
:param:
* param_dict: (dict) 请求参数字典
:return:
* temp_dict: (dict) 转换后的参数字典
举例如下::
print('--- transform_hump_to_underline demo---')
hump_param_dict = {'firstName': 'Python', 'Second_Name': 'san', 'right_name': 'name'}
underline_param_dict = trans... | Below is the the instruction that describes the task:
### Input:
将驼峰命名的参数字典键转换为下划线参数
:param:
* param_dict: (dict) 请求参数字典
:return:
* temp_dict: (dict) 转换后的参数字典
举例如下::
print('--- transform_hump_to_underline demo---')
hump_param_dict = {'firstName': 'Python', 'Second_Nam... |
def additionalProperties(self):
"""Schema for all additional properties, or False."""
value = self._schema.get("additionalProperties", {})
if not isinstance(value, dict) and value is not False:
raise SchemaError(
"additionalProperties value {0!r} is neither false nor"... | Schema for all additional properties, or False. | Below is the the instruction that describes the task:
### Input:
Schema for all additional properties, or False.
### Response:
def additionalProperties(self):
"""Schema for all additional properties, or False."""
value = self._schema.get("additionalProperties", {})
if not isinstance(value, ... |
def search(self):
"""Handle the search request."""
search = self.document_class().search() # pylint: disable=not-callable
search = self.custom_filter(search)
search = self.filter_search(search)
search = self.order_search(search)
search = self.filter_permissions(search)... | Handle the search request. | Below is the the instruction that describes the task:
### Input:
Handle the search request.
### Response:
def search(self):
"""Handle the search request."""
search = self.document_class().search() # pylint: disable=not-callable
search = self.custom_filter(search)
search = self.fi... |
def dpms(self):
"""
Display a colorful state of DPMS.
"""
if "DPMS is Enabled" in self.py3.command_output("xset -q"):
_format = self.icon_on
color = self.color_on
else:
_format = self.icon_off
color = self.color_off
icon = ... | Display a colorful state of DPMS. | Below is the the instruction that describes the task:
### Input:
Display a colorful state of DPMS.
### Response:
def dpms(self):
"""
Display a colorful state of DPMS.
"""
if "DPMS is Enabled" in self.py3.command_output("xset -q"):
_format = self.icon_on
color... |
def _writeCic(self, filelike, specfile, compress):
"""Writes the ``.cic`` container entry of the specified specfile to the
``mrc_cic`` format. For details see
:func:`maspy.auxiliary.writeBinaryItemContainer()`
:param filelike: path to a file (str) or a file-like object
:param s... | Writes the ``.cic`` container entry of the specified specfile to the
``mrc_cic`` format. For details see
:func:`maspy.auxiliary.writeBinaryItemContainer()`
:param filelike: path to a file (str) or a file-like object
:param specfile: name of an ms-run file present in ``self.info``
... | Below is the the instruction that describes the task:
### Input:
Writes the ``.cic`` container entry of the specified specfile to the
``mrc_cic`` format. For details see
:func:`maspy.auxiliary.writeBinaryItemContainer()`
:param filelike: path to a file (str) or a file-like object
:... |
def get_type_name(type_name, sub_type=None):
""" Returns a go type according to a spec type
"""
if type_name in ("string", "enum"):
return "string"
if type_name == "float":
return "float64"
if type_name == "boolean":
return "bool"
if type_name == "list":
st = ... | Returns a go type according to a spec type | Below is the the instruction that describes the task:
### Input:
Returns a go type according to a spec type
### Response:
def get_type_name(type_name, sub_type=None):
""" Returns a go type according to a spec type
"""
if type_name in ("string", "enum"):
return "string"
if type_name == "fl... |
def read_large_int(self, bits, signed=True):
"""Reads a n-bits long integer value."""
return int.from_bytes(
self.read(bits // 8), byteorder='little', signed=signed) | Reads a n-bits long integer value. | Below is the the instruction that describes the task:
### Input:
Reads a n-bits long integer value.
### Response:
def read_large_int(self, bits, signed=True):
"""Reads a n-bits long integer value."""
return int.from_bytes(
self.read(bits // 8), byteorder='little', signed=signed) |
def write(self, data):
"""
write single molecule into file
"""
m = self._convert_structure(data)
self._file.write(self._format_mol(*m))
self._file.write('M END\n')
for k, v in data.meta.items():
self._file.write(f'> <{k}>\n{v}\n')
self._file... | write single molecule into file | Below is the the instruction that describes the task:
### Input:
write single molecule into file
### Response:
def write(self, data):
"""
write single molecule into file
"""
m = self._convert_structure(data)
self._file.write(self._format_mol(*m))
self._file.write('M ... |
def _create_simulated_annealing_expander(schedule):
'''
Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time.
'''
def _expander(fringe, iteration, viewer):
T = schedule(iteration)
current = frin... | Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time. | Below is the the instruction that describes the task:
### Input:
Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time.
### Response:
def _create_simulated_annealing_expander(schedule):
'''
Creates an expander that... |
def find_clusters(network, mask=[], t_labels=False):
r"""
Identify connected clusters of pores in the network. This method can
also return a list of throat cluster numbers, which correspond to the
cluster numbers of the pores to which the throat is connected. Either
site and bond percolation can b... | r"""
Identify connected clusters of pores in the network. This method can
also return a list of throat cluster numbers, which correspond to the
cluster numbers of the pores to which the throat is connected. Either
site and bond percolation can be considered, see description of input
arguments for ... | Below is the the instruction that describes the task:
### Input:
r"""
Identify connected clusters of pores in the network. This method can
also return a list of throat cluster numbers, which correspond to the
cluster numbers of the pores to which the throat is connected. Either
site and bond perco... |
def discover(self):
"""Method to send a discovery message
"""
if self.transport:
if self.discovery_countdown <= 0:
self.discovery_countdown = self.discovery_interval
msg = GetService(BROADCAST_MAC, self.source_id, seq_num=0, payload={}, ack_requested=F... | Method to send a discovery message | Below is the the instruction that describes the task:
### Input:
Method to send a discovery message
### Response:
def discover(self):
"""Method to send a discovery message
"""
if self.transport:
if self.discovery_countdown <= 0:
self.discovery_countdown = self.di... |
def shutdown(self):
""" Shuts down the daemon process.
"""
if not self._exited:
self._exited = True
# signal task runner to terminate via SIGTERM
if self._task_runner.is_alive():
self._task_runner.terminate()
# if command... | Shuts down the daemon process. | Below is the the instruction that describes the task:
### Input:
Shuts down the daemon process.
### Response:
def shutdown(self):
""" Shuts down the daemon process.
"""
if not self._exited:
self._exited = True
# signal task runner to terminate via SIGTERM
... |
def newNsPropEatName(self, ns, name, value):
"""Create a new property tagged with a namespace and carried
by a node. """
if ns is None: ns__o = None
else: ns__o = ns._o
ret = libxml2mod.xmlNewNsPropEatName(self._o, ns__o, name, value)
if ret is None:raise treeError('xm... | Create a new property tagged with a namespace and carried
by a node. | Below is the the instruction that describes the task:
### Input:
Create a new property tagged with a namespace and carried
by a node.
### Response:
def newNsPropEatName(self, ns, name, value):
"""Create a new property tagged with a namespace and carried
by a node. """
if ns is... |
def remove_accounts_from_project(accounts_query, project):
""" Remove accounts from project. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
remove_account_from_project(account, project) | Remove accounts from project. | Below is the the instruction that describes the task:
### Input:
Remove accounts from project.
### Response:
def remove_accounts_from_project(accounts_query, project):
""" Remove accounts from project. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
remove_a... |
def otsu(data, min_threshold=None, max_threshold=None,bins=256):
"""Compute a threshold using Otsu's method
data - an array of intensity values between zero and one
min_threshold - only consider thresholds above this minimum value
max_threshold - only consider thresholds below this maxi... | Compute a threshold using Otsu's method
data - an array of intensity values between zero and one
min_threshold - only consider thresholds above this minimum value
max_threshold - only consider thresholds below this maximum value
bins - we bin the data into this many equally-sp... | Below is the the instruction that describes the task:
### Input:
Compute a threshold using Otsu's method
data - an array of intensity values between zero and one
min_threshold - only consider thresholds above this minimum value
max_threshold - only consider thresholds below this maximum... |
def get_factory_context(cls):
# type: (type) -> FactoryContext
"""
Retrieves the factory context object associated to a factory. Creates it
if needed
:param cls: The factory class
:return: The factory class context
"""
context = getattr(cls, constants.IPOPO_FACTORY_CONTEXT, None)
i... | Retrieves the factory context object associated to a factory. Creates it
if needed
:param cls: The factory class
:return: The factory class context | Below is the the instruction that describes the task:
### Input:
Retrieves the factory context object associated to a factory. Creates it
if needed
:param cls: The factory class
:return: The factory class context
### Response:
def get_factory_context(cls):
# type: (type) -> FactoryContext
"""
... |
def translate_connect_args(self, names=[], **kw):
"""Translate url attributes into a dictionary of connection arguments.
Returns attributes of this url (`host`, `database`, `username`,
`password`, `port`) as a plain dictionary. The attribute names are
used as the keys by default. Unse... | Translate url attributes into a dictionary of connection arguments.
Returns attributes of this url (`host`, `database`, `username`,
`password`, `port`) as a plain dictionary. The attribute names are
used as the keys by default. Unset or false attributes are omitted
from the final dict... | Below is the the instruction that describes the task:
### Input:
Translate url attributes into a dictionary of connection arguments.
Returns attributes of this url (`host`, `database`, `username`,
`password`, `port`) as a plain dictionary. The attribute names are
used as the keys by defaul... |
def composed_deps(self):
"""Dependencies of this build target."""
if 'deps' in self.params:
param_deps = self.params['deps'] or []
deps = [self.makeaddress(dep) for dep in param_deps]
return deps
else:
return None | Dependencies of this build target. | Below is the the instruction that describes the task:
### Input:
Dependencies of this build target.
### Response:
def composed_deps(self):
"""Dependencies of this build target."""
if 'deps' in self.params:
param_deps = self.params['deps'] or []
deps = [self.makeaddress(dep) ... |
def _cnn_filter(in_file, vrn_files, data):
"""Perform CNN filtering on input VCF using pre-trained models.
"""
#tensor_type = "reference" # 1D, reference sequence
tensor_type = "read_tensor" # 2D, reads, flags, mapping quality
score_file = _cnn_score_variants(in_file, tensor_type, data)
return... | Perform CNN filtering on input VCF using pre-trained models. | Below is the the instruction that describes the task:
### Input:
Perform CNN filtering on input VCF using pre-trained models.
### Response:
def _cnn_filter(in_file, vrn_files, data):
"""Perform CNN filtering on input VCF using pre-trained models.
"""
#tensor_type = "reference" # 1D, reference sequence... |
def clear(path):
'''
Causes the all attributes on the file/directory to be removed
:param str path: The file(s) to get attributes from
:return: True if successful, otherwise False
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: ba... | Causes the all attributes on the file/directory to be removed
:param str path: The file(s) to get attributes from
:return: True if successful, otherwise False
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.de... | Below is the the instruction that describes the task:
### Input:
Causes the all attributes on the file/directory to be removed
:param str path: The file(s) to get attributes from
:return: True if successful, otherwise False
:raises: CommandExecutionError on file not found or any other unknown error
... |
def set_date(date):
'''
Set the current month, day, and year
:param str date: The date to set. Valid date formats are:
- %m:%d:%y
- %m:%d:%Y
- %m/%d/%y
- %m/%d/%Y
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Da... | Set the current month, day, and year
:param str date: The date to set. Valid date formats are:
- %m:%d:%y
- %m:%d:%Y
- %m/%d/%y
- %m/%d/%Y
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Date format
:raises: CommandEx... | Below is the the instruction that describes the task:
### Input:
Set the current month, day, and year
:param str date: The date to set. Valid date formats are:
- %m:%d:%y
- %m:%d:%Y
- %m/%d/%y
- %m/%d/%Y
:return: True if successful, False if not
:rtype: bool
:rais... |
def auto_message(self, args):
"""Try guess the message by the args passed
args: a set of args passed on the wrapper __call__ in
the definition above.
if the object already have some message (defined in __init__),
we don't change that. If the first arg is a function, so is... | Try guess the message by the args passed
args: a set of args passed on the wrapper __call__ in
the definition above.
if the object already have some message (defined in __init__),
we don't change that. If the first arg is a function, so is decorated
without argument, use ... | Below is the the instruction that describes the task:
### Input:
Try guess the message by the args passed
args: a set of args passed on the wrapper __call__ in
the definition above.
if the object already have some message (defined in __init__),
we don't change that. If the fi... |
def print_structure(self, tostring=False):
"""
## FOR DEBUGGING ONLY ##
Pretty-prints the structure of the tree.
If tostring is true, prints nothing and returns a string.
:rtype: None or str
"""
if self.top_node:
return self.top_node.print_structure(to... | ## FOR DEBUGGING ONLY ##
Pretty-prints the structure of the tree.
If tostring is true, prints nothing and returns a string.
:rtype: None or str | Below is the the instruction that describes the task:
### Input:
## FOR DEBUGGING ONLY ##
Pretty-prints the structure of the tree.
If tostring is true, prints nothing and returns a string.
:rtype: None or str
### Response:
def print_structure(self, tostring=False):
"""
## FO... |
def from_spherical_coords(theta_phi, phi=None):
"""Return the quaternion corresponding to these spherical coordinates
Assumes the spherical coordinates correspond to the quaternion R via
R = exp(phi*z/2) * exp(theta*y/2)
The angles naturally must be in radians for this to make any sense.
Not... | Return the quaternion corresponding to these spherical coordinates
Assumes the spherical coordinates correspond to the quaternion R via
R = exp(phi*z/2) * exp(theta*y/2)
The angles naturally must be in radians for this to make any sense.
Note that this quaternion rotates `z` onto the point with ... | Below is the the instruction that describes the task:
### Input:
Return the quaternion corresponding to these spherical coordinates
Assumes the spherical coordinates correspond to the quaternion R via
R = exp(phi*z/2) * exp(theta*y/2)
The angles naturally must be in radians for this to make any s... |
def _set_trunk_private_vlan_classification(self, v, load=False):
"""
Setter method for trunk_private_vlan_classification, mapped from YANG variable /interface/port_channel/switchport/trunk_private_vlan_classification (container)
If this variable is read-only (config: false) in the
source YANG file, then... | Setter method for trunk_private_vlan_classification, mapped from YANG variable /interface/port_channel/switchport/trunk_private_vlan_classification (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_trunk_private_vlan_classification is considered as a private
method... | Below is the the instruction that describes the task:
### Input:
Setter method for trunk_private_vlan_classification, mapped from YANG variable /interface/port_channel/switchport/trunk_private_vlan_classification (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tr... |
def Copy(self, name=None):
"""Returns a copy of this Cdf.
Args:
name: string name for the new Cdf
"""
if name is None:
name = self.name
return Cdf(list(self.xs), list(self.ps), name) | Returns a copy of this Cdf.
Args:
name: string name for the new Cdf | Below is the the instruction that describes the task:
### Input:
Returns a copy of this Cdf.
Args:
name: string name for the new Cdf
### Response:
def Copy(self, name=None):
"""Returns a copy of this Cdf.
Args:
name: string name for the new Cdf
"""
... |
def get_log_lookup_session(self, proxy):
"""Gets the ``OsidSession`` associated with the log lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogLookupSession) - a ``LogLookupSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationF... | Gets the ``OsidSession`` associated with the log lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogLookupSession) - a ``LogLookupSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
raise: U... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the log lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogLookupSession) - a ``LogLookupSession``
raise: NullArgument - ``proxy`` is ``null``
r... |
def accept(kind, doc=None, error_text=None, exception_handlers=empty.dict, accept_context=False):
"""Allows quick wrapping of any Python type cast function for use as a hug type annotation"""
return create(
doc,
error_text,
exception_handlers=exception_handlers,
chain=False,
... | Allows quick wrapping of any Python type cast function for use as a hug type annotation | Below is the the instruction that describes the task:
### Input:
Allows quick wrapping of any Python type cast function for use as a hug type annotation
### Response:
def accept(kind, doc=None, error_text=None, exception_handlers=empty.dict, accept_context=False):
"""Allows quick wrapping of any Python type ca... |
def inputhook_wx2():
"""Run the wx event loop, polling for stdin.
This version runs the wx eventloop for an undetermined amount of time,
during which it periodically checks to see if anything is ready on
stdin. If anything is ready on stdin, the event loop exits.
The argument to elr.Run controls ... | Run the wx event loop, polling for stdin.
This version runs the wx eventloop for an undetermined amount of time,
during which it periodically checks to see if anything is ready on
stdin. If anything is ready on stdin, the event loop exits.
The argument to elr.Run controls how often the event loop loo... | Below is the the instruction that describes the task:
### Input:
Run the wx event loop, polling for stdin.
This version runs the wx eventloop for an undetermined amount of time,
during which it periodically checks to see if anything is ready on
stdin. If anything is ready on stdin, the event loop exit... |
def cov(self, other, min_periods=None):
"""
Compute covariance with Series, excluding missing values.
Parameters
----------
other : Series
Series with which to compute the covariance.
min_periods : int, optional
Minimum number of observations need... | Compute covariance with Series, excluding missing values.
Parameters
----------
other : Series
Series with which to compute the covariance.
min_periods : int, optional
Minimum number of observations needed to have a valid result.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Compute covariance with Series, excluding missing values.
Parameters
----------
other : Series
Series with which to compute the covariance.
min_periods : int, optional
Minimum number of observat... |
def isSuperTagSetOf(self, tagSet):
"""Test type relationship against given *TagSet*
The callee is considered to be a supertype of given *TagSet*
tag-wise if all tags in *TagSet* are present in the callee and
they are in the same order.
Parameters
----------
tagS... | Test type relationship against given *TagSet*
The callee is considered to be a supertype of given *TagSet*
tag-wise if all tags in *TagSet* are present in the callee and
they are in the same order.
Parameters
----------
tagSet: :class:`~pyasn1.type.tag.TagSet`
... | Below is the the instruction that describes the task:
### Input:
Test type relationship against given *TagSet*
The callee is considered to be a supertype of given *TagSet*
tag-wise if all tags in *TagSet* are present in the callee and
they are in the same order.
Parameters
... |
def setup_types(self):
"""
The Message object has a circular reference on itself, thus we have to allow
Type referencing by name. Here we lookup any Types referenced by name and
replace with the real class.
"""
def load(t):
from TelegramBotAPI.types.type impor... | The Message object has a circular reference on itself, thus we have to allow
Type referencing by name. Here we lookup any Types referenced by name and
replace with the real class. | Below is the the instruction that describes the task:
### Input:
The Message object has a circular reference on itself, thus we have to allow
Type referencing by name. Here we lookup any Types referenced by name and
replace with the real class.
### Response:
def setup_types(self):
"""
... |
def _set_reverse_metric_info(self, v, load=False):
"""
Setter method for reverse_metric_info, mapped from YANG variable /isis_state/interface_detail/isis_intf/reverse_metric_info (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_reverse_metric_info is considere... | Setter method for reverse_metric_info, mapped from YANG variable /isis_state/interface_detail/isis_intf/reverse_metric_info (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_reverse_metric_info is considered as a private
method. Backends looking to populate this va... | Below is the the instruction that describes the task:
### Input:
Setter method for reverse_metric_info, mapped from YANG variable /isis_state/interface_detail/isis_intf/reverse_metric_info (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_reverse_metric_info is con... |
def get_prop(self, prop):
""" Calls the getter with no arguments and returns its value """
if self._parser is None:
raise ConfigurationError('Cannot call ParserProperty."get_prop" with no parser configured')
return self._parser(prop) if prop else self._parser() | Calls the getter with no arguments and returns its value | Below is the the instruction that describes the task:
### Input:
Calls the getter with no arguments and returns its value
### Response:
def get_prop(self, prop):
""" Calls the getter with no arguments and returns its value """
if self._parser is None:
raise ConfigurationError('Cannot c... |
def is_gene_list(bed_file):
"""Check if the file is only a list of genes, not a BED
"""
with utils.open_gzipsafe(bed_file) as in_handle:
for line in in_handle:
if not line.startswith("#"):
if len(line.split()) == 1:
return True
else:
... | Check if the file is only a list of genes, not a BED | Below is the the instruction that describes the task:
### Input:
Check if the file is only a list of genes, not a BED
### Response:
def is_gene_list(bed_file):
"""Check if the file is only a list of genes, not a BED
"""
with utils.open_gzipsafe(bed_file) as in_handle:
for line in in_handle:
... |
def authenticate(self, session: Session, listener):
"""
This method call the authenticate method on registered plugins to test user authentication.
User is considered authenticated if all plugins called returns True.
Plugins authenticate() method are supposed to return :
- True ... | This method call the authenticate method on registered plugins to test user authentication.
User is considered authenticated if all plugins called returns True.
Plugins authenticate() method are supposed to return :
- True if user is authentication succeed
- False if user authenticatio... | Below is the the instruction that describes the task:
### Input:
This method call the authenticate method on registered plugins to test user authentication.
User is considered authenticated if all plugins called returns True.
Plugins authenticate() method are supposed to return :
- True if ... |
def generate_random_string(cls, length):
"""
Generatesa a [length] characters alpha numeric secret
"""
# avoid things that could be mistaken ex: 'I' and '1'
letters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
return "".join([random.choice(letters) for _ in range(length)]) | Generatesa a [length] characters alpha numeric secret | Below is the the instruction that describes the task:
### Input:
Generatesa a [length] characters alpha numeric secret
### Response:
def generate_random_string(cls, length):
"""
Generatesa a [length] characters alpha numeric secret
"""
# avoid things that could be mistaken ex: 'I' a... |
def _build_default_options(self):
""""Provide the default value for all allowed fields.
Custom FactoryOptions classes should override this method
to update() its return value.
"""
return [
OptionDefault('model', None, inherit=True),
OptionDefault('abstrac... | Provide the default value for all allowed fields.
Custom FactoryOptions classes should override this method
to update() its return value. | Below is the the instruction that describes the task:
### Input:
Provide the default value for all allowed fields.
Custom FactoryOptions classes should override this method
to update() its return value.
### Response:
def _build_default_options(self):
""""Provide the default value for all a... |
def has_client_id(self, id):
"""Returns True if we have a client with a certain integer identifier"""
return self.query(Client).filter(Client.id==id).count() != 0 | Returns True if we have a client with a certain integer identifier | Below is the the instruction that describes the task:
### Input:
Returns True if we have a client with a certain integer identifier
### Response:
def has_client_id(self, id):
"""Returns True if we have a client with a certain integer identifier"""
return self.query(Client).filter(Client.id==id).count() !=... |
def detect(self):
"""Detect and return the IP address."""
if PY3: # py23
import subprocess # noqa: S404 @UnresolvedImport pylint: disable=import-error
else:
import commands as subprocess # @UnresolvedImport pylint: disable=import-error
try:
theip = ... | Detect and return the IP address. | Below is the the instruction that describes the task:
### Input:
Detect and return the IP address.
### Response:
def detect(self):
"""Detect and return the IP address."""
if PY3: # py23
import subprocess # noqa: S404 @UnresolvedImport pylint: disable=import-error
else:
... |
def set_user_method(self, user_methods, forced=False):
r'''Method to set the T, P, and composition dependent property methods
desired for consideration by the user. Can be used to exclude certain
methods which might have unacceptable accuracy.
As a side effect, the previously selected... | r'''Method to set the T, P, and composition dependent property methods
desired for consideration by the user. Can be used to exclude certain
methods which might have unacceptable accuracy.
As a side effect, the previously selected method is removed when
this method is called to ensure... | Below is the the instruction that describes the task:
### Input:
r'''Method to set the T, P, and composition dependent property methods
desired for consideration by the user. Can be used to exclude certain
methods which might have unacceptable accuracy.
As a side effect, the previously se... |
def get(package_name, pypi_server="https://pypi.python.org/pypi/"):
"""
Constructs a request to the PyPI server and returns a
:class:`yarg.package.Package`.
:param package_name: case sensitive name of the package on the PyPI server.
:param pypi_server: (option) URL to the PyPI server.
>>> ... | Constructs a request to the PyPI server and returns a
:class:`yarg.package.Package`.
:param package_name: case sensitive name of the package on the PyPI server.
:param pypi_server: (option) URL to the PyPI server.
>>> import yarg
>>> package = yarg.get('yarg')
<Package yarg> | Below is the the instruction that describes the task:
### Input:
Constructs a request to the PyPI server and returns a
:class:`yarg.package.Package`.
:param package_name: case sensitive name of the package on the PyPI server.
:param pypi_server: (option) URL to the PyPI server.
>>> import yarg... |
def _output_ret(self, ret, out, retcode=0):
'''
Print the output from a single return to the terminal
'''
import salt.output
# Handle special case commands
if self.config['fun'] == 'sys.doc' and not isinstance(ret, Exception):
self._print_docs(ret)
els... | Print the output from a single return to the terminal | Below is the the instruction that describes the task:
### Input:
Print the output from a single return to the terminal
### Response:
def _output_ret(self, ret, out, retcode=0):
'''
Print the output from a single return to the terminal
'''
import salt.output
# Handle special ... |
def secret(self, s):
"""
Parse text either a private key or a private hierarchical key.
Return a subclass of :class:`Key <pycoin.key.Key>`, or None.
"""
s = parseable_str(s)
for f in [self.private_key, self.hierarchical_key]:
v = f(s)
if v:
... | Parse text either a private key or a private hierarchical key.
Return a subclass of :class:`Key <pycoin.key.Key>`, or None. | Below is the the instruction that describes the task:
### Input:
Parse text either a private key or a private hierarchical key.
Return a subclass of :class:`Key <pycoin.key.Key>`, or None.
### Response:
def secret(self, s):
"""
Parse text either a private key or a private hierarchical key.
... |
def timedelta_to_seconds(value, with_microseconds=False):
"""
Convert datetime.timedelta to seconds
:param value: timedelta to convert
:type value: datetime.timedelta
:param with_microseconds:
:type with_microseconds: bool
:return: seconds/seconds with microseconds or None if val is None
... | Convert datetime.timedelta to seconds
:param value: timedelta to convert
:type value: datetime.timedelta
:param with_microseconds:
:type with_microseconds: bool
:return: seconds/seconds with microseconds or None if val is None
:rtype: int/float/None
:raise: TypeError when val is not timedelt... | Below is the the instruction that describes the task:
### Input:
Convert datetime.timedelta to seconds
:param value: timedelta to convert
:type value: datetime.timedelta
:param with_microseconds:
:type with_microseconds: bool
:return: seconds/seconds with microseconds or None if val is None
... |
def update(self, dictionary=None, **kwargs):
"""
Adds/overwrites all the keys and values from the dictionary.
"""
if not dictionary == None: kwargs.update(dictionary)
for k in list(kwargs.keys()): self[k] = kwargs[k] | Adds/overwrites all the keys and values from the dictionary. | Below is the the instruction that describes the task:
### Input:
Adds/overwrites all the keys and values from the dictionary.
### Response:
def update(self, dictionary=None, **kwargs):
"""
Adds/overwrites all the keys and values from the dictionary.
"""
if not dictionary == None: kw... |
def custom_conf(self, conf):
'''custom apikey and http parameters'''
if conf:
for (key, val) in conf.items():
self.__conf[key] = val
return self | custom apikey and http parameters | Below is the the instruction that describes the task:
### Input:
custom apikey and http parameters
### Response:
def custom_conf(self, conf):
'''custom apikey and http parameters'''
if conf:
for (key, val) in conf.items():
self.__conf[key] = val
return self |
def post_transaction(self, transaction, mode):
"""Submit a valid transaction to the mempool."""
if not mode or mode not in self.mode_list:
raise ValidationError('Mode must be one of the following {}.'
.format(', '.join(self.mode_list)))
tx_dict = tr... | Submit a valid transaction to the mempool. | Below is the the instruction that describes the task:
### Input:
Submit a valid transaction to the mempool.
### Response:
def post_transaction(self, transaction, mode):
"""Submit a valid transaction to the mempool."""
if not mode or mode not in self.mode_list:
raise ValidationError('Mod... |
def remove_bad_particles(st, min_rad='calc', max_rad='calc', min_edge_dist=2.0,
check_rad_cutoff=[3.5, 15], check_outside_im=True,
tries=50, im_change_frac=0.2, **kwargs):
"""
Removes improperly-featured particles from the state, based on a
combination of pa... | Removes improperly-featured particles from the state, based on a
combination of particle size and the change in error on removal.
Parameters
-----------
st : :class:`peri.states.State`
The state to remove bad particles from.
min_rad : Float, optional
All particles with radius below ... | Below is the the instruction that describes the task:
### Input:
Removes improperly-featured particles from the state, based on a
combination of particle size and the change in error on removal.
Parameters
-----------
st : :class:`peri.states.State`
The state to remove bad particles from.
... |
def l2traceroute_input_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
l2traceroute = ET.Element("l2traceroute")
config = l2traceroute
input = ET.SubElement(l2traceroute, "input")
vlan_id = ET.SubElement(input, "vlan-id")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def l2traceroute_input_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
l2traceroute = ET.Element("l2traceroute")
config = l2traceroute
... |
def extender(self, edge):
"See what edges can be extended by this edge."
(j, k, B, _, _) = edge
for (i, j, A, alpha, B1b) in self.chart[j]:
if B1b and B == B1b[0]:
self.add_edge([i, k, A, alpha + [edge], B1b[1:]]) | See what edges can be extended by this edge. | Below is the the instruction that describes the task:
### Input:
See what edges can be extended by this edge.
### Response:
def extender(self, edge):
"See what edges can be extended by this edge."
(j, k, B, _, _) = edge
for (i, j, A, alpha, B1b) in self.chart[j]:
if B1b and B ==... |
def list_instance_profiles(path_prefix='/', region=None, key=None,
keyid=None, profile=None):
'''
List all IAM instance profiles, starting at the optional path.
.. versionadded:: 2016.11.0
CLI Example:
salt-call boto_iam.list_instance_profiles
'''
p = get_al... | List all IAM instance profiles, starting at the optional path.
.. versionadded:: 2016.11.0
CLI Example:
salt-call boto_iam.list_instance_profiles | Below is the the instruction that describes the task:
### Input:
List all IAM instance profiles, starting at the optional path.
.. versionadded:: 2016.11.0
CLI Example:
salt-call boto_iam.list_instance_profiles
### Response:
def list_instance_profiles(path_prefix='/', region=None, key=None,
... |
def _get_nd_basic_indexing(self, key):
"""This function is called when key is a slice, or an integer,
or a tuple of slices or integers"""
shape = self.shape
if isinstance(key, integer_types):
if key > shape[0] - 1:
raise IndexError(
'index ... | This function is called when key is a slice, or an integer,
or a tuple of slices or integers | Below is the the instruction that describes the task:
### Input:
This function is called when key is a slice, or an integer,
or a tuple of slices or integers
### Response:
def _get_nd_basic_indexing(self, key):
"""This function is called when key is a slice, or an integer,
or a tuple of sli... |
def cmd_register(phone):
"""
Войти в приложение с помощью SMS.
"""
if phone is None:
phone = click.prompt("Номер телефона")
r = rocket.devices.register.post(data={"phone": phone})
r = handle_error(r)
id = r.json()["sms_verification"]["id"]
code = click.prompt("Введите код из SM... | Войти в приложение с помощью SMS. | Below is the the instruction that describes the task:
### Input:
Войти в приложение с помощью SMS.
### Response:
def cmd_register(phone):
"""
Войти в приложение с помощью SMS.
"""
if phone is None:
phone = click.prompt("Номер телефона")
r = rocket.devices.register.post(data={"phone": p... |
def append_delta_index(self, ts_data=None, data_delta=None, key=KEY_DATA):
"""Append columns with ∆T between rows to data."""
reasign = False
if data_delta is None:
if self.data is not None:
data_delta = self.data[key]
else:
self.printif('N... | Append columns with ∆T between rows to data. | Below is the the instruction that describes the task:
### Input:
Append columns with ∆T between rows to data.
### Response:
def append_delta_index(self, ts_data=None, data_delta=None, key=KEY_DATA):
"""Append columns with ∆T between rows to data."""
reasign = False
if data_delta is None:
... |
def get_files_map(self):
"""stub"""
files_map = {}
if self.has_files():
for label in self.my_osid_object._my_map['fileIds']:
asset_content = self._get_asset_content(
Id(self.my_osid_object._my_map['fileIds'][label]['assetId']),
... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def get_files_map(self):
"""stub"""
files_map = {}
if self.has_files():
for label in self.my_osid_object._my_map['fileIds']:
asset_content = self._get_asset_content(
... |
def bovy_ars(domain,isDomainFinite,abcissae,hx,hpx,nsamples=1,
hxparams=(),maxn=100):
"""bovy_ars: Implementation of the Adaptive-Rejection Sampling
algorithm by Gilks & Wild (1992): Adaptive Rejection Sampling
for Gibbs Sampling, Applied Statistics, 41, 337
Based on Wild & Gilks (1993), Al... | bovy_ars: Implementation of the Adaptive-Rejection Sampling
algorithm by Gilks & Wild (1992): Adaptive Rejection Sampling
for Gibbs Sampling, Applied Statistics, 41, 337
Based on Wild & Gilks (1993), Algorithm AS 287: Adaptive Rejection
Sampling from Log-concave Density Functions, Applied Statistics, 42... | Below is the the instruction that describes the task:
### Input:
bovy_ars: Implementation of the Adaptive-Rejection Sampling
algorithm by Gilks & Wild (1992): Adaptive Rejection Sampling
for Gibbs Sampling, Applied Statistics, 41, 337
Based on Wild & Gilks (1993), Algorithm AS 287: Adaptive Rejection
... |
def valid(self, inplace=False, **kwargs):
"""
Return Series without null values.
.. deprecated:: 0.23.0
Use :meth:`Series.dropna` instead.
"""
warnings.warn("Method .valid will be removed in a future version. "
"Use .dropna instead.", FutureWarn... | Return Series without null values.
.. deprecated:: 0.23.0
Use :meth:`Series.dropna` instead. | Below is the the instruction that describes the task:
### Input:
Return Series without null values.
.. deprecated:: 0.23.0
Use :meth:`Series.dropna` instead.
### Response:
def valid(self, inplace=False, **kwargs):
"""
Return Series without null values.
.. deprecated:: ... |
def get_configuration(filename):
""" Read configuration file
:type filename: str
:param filename: Path to the configuration file
"""
logger.debug('Reading configuration from {}'.format(filename))
conf = SafeConfigParser()
conf.read(filename)
if not conf:
logger.error('Configura... | Read configuration file
:type filename: str
:param filename: Path to the configuration file | Below is the the instruction that describes the task:
### Input:
Read configuration file
:type filename: str
:param filename: Path to the configuration file
### Response:
def get_configuration(filename):
""" Read configuration file
:type filename: str
:param filename: Path to the configuratio... |
def parsed_forensic_reports_to_csv(reports):
"""
Converts one or more parsed forensic reports to flat CSV format, including
headers
Args:
reports: A parsed forensic report or list of parsed forensic reports
Returns:
str: Parsed forensic report data in flat CSV format, including hea... | Converts one or more parsed forensic reports to flat CSV format, including
headers
Args:
reports: A parsed forensic report or list of parsed forensic reports
Returns:
str: Parsed forensic report data in flat CSV format, including headers | Below is the the instruction that describes the task:
### Input:
Converts one or more parsed forensic reports to flat CSV format, including
headers
Args:
reports: A parsed forensic report or list of parsed forensic reports
Returns:
str: Parsed forensic report data in flat CSV format, i... |
def get_field_keys(self, pattern=None):
"""
Builds a set of all field keys used in the pattern including nested fields.
:param pattern: The kmatch pattern to get field keys from or None to use self.pattern
:type pattern: list or None
:returns: A set object of all field keys used... | Builds a set of all field keys used in the pattern including nested fields.
:param pattern: The kmatch pattern to get field keys from or None to use self.pattern
:type pattern: list or None
:returns: A set object of all field keys used in the pattern
:rtype: set | Below is the the instruction that describes the task:
### Input:
Builds a set of all field keys used in the pattern including nested fields.
:param pattern: The kmatch pattern to get field keys from or None to use self.pattern
:type pattern: list or None
:returns: A set object of all field ... |
def split(input_file, file_1, file_2, no_in_first_file):
'''
Split a geojson in two separate files.
Args:
input_file (str): Input filename.
file_1 (str): Output file name 1.
file_2 (str): Output file name 2.
no_features (int): Number of features in input_file to go to file_1... | Split a geojson in two separate files.
Args:
input_file (str): Input filename.
file_1 (str): Output file name 1.
file_2 (str): Output file name 2.
no_features (int): Number of features in input_file to go to file_1.
output_file (str): Output file name. | Below is the the instruction that describes the task:
### Input:
Split a geojson in two separate files.
Args:
input_file (str): Input filename.
file_1 (str): Output file name 1.
file_2 (str): Output file name 2.
no_features (int): Number of features in input_file to go to file_1... |
def list_song_standby(self, song, onlyone=True):
"""try to list all valid standby
Search a song in all providers. The typical usage scenario is when a
song is not available in one provider, we can try to acquire it from other
providers.
Standby choosing strategy: search from al... | try to list all valid standby
Search a song in all providers. The typical usage scenario is when a
song is not available in one provider, we can try to acquire it from other
providers.
Standby choosing strategy: search from all providers, select two song from each provide.
Thos... | Below is the the instruction that describes the task:
### Input:
try to list all valid standby
Search a song in all providers. The typical usage scenario is when a
song is not available in one provider, we can try to acquire it from other
providers.
Standby choosing strategy: searc... |
def _compute_secondary(self):
"""Compute secondary axis min max and label positions"""
# secondary y axis support
if self.secondary_series and self._y_labels:
y_pos = list(zip(*self._y_labels))[1]
if self.include_x_axis:
ymin = min(self._secondary_min, 0)
... | Compute secondary axis min max and label positions | Below is the the instruction that describes the task:
### Input:
Compute secondary axis min max and label positions
### Response:
def _compute_secondary(self):
"""Compute secondary axis min max and label positions"""
# secondary y axis support
if self.secondary_series and self._y_labels:
... |
def as_pseudo(cls, obj):
"""
Convert obj into a pseudo. Accepts:
* Pseudo object.
* string defining a valid path.
"""
return obj if isinstance(obj, cls) else cls.from_file(obj) | Convert obj into a pseudo. Accepts:
* Pseudo object.
* string defining a valid path. | Below is the the instruction that describes the task:
### Input:
Convert obj into a pseudo. Accepts:
* Pseudo object.
* string defining a valid path.
### Response:
def as_pseudo(cls, obj):
"""
Convert obj into a pseudo. Accepts:
* Pseudo object.
* s... |
def search_registered_query_deleted_for_facet(self, facet, **kwargs): # noqa: E501
"""Lists the values of a specific facet over the customer's deleted derived metric definitions # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronou... | Lists the values of a specific facet over the customer's deleted derived metric definitions # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_registered_query_del... | Below is the the instruction that describes the task:
### Input:
Lists the values of a specific facet over the customer's deleted derived metric definitions # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pas... |
def send(self, message, envelope_from=None):
"""Verifies and sends message.
:param message: Message instance.
:param envelope_from: Email address to be used in MAIL FROM command.
"""
assert message.send_to, "No recipients have been added"
assert message.sender, (
... | Verifies and sends message.
:param message: Message instance.
:param envelope_from: Email address to be used in MAIL FROM command. | Below is the the instruction that describes the task:
### Input:
Verifies and sends message.
:param message: Message instance.
:param envelope_from: Email address to be used in MAIL FROM command.
### Response:
def send(self, message, envelope_from=None):
"""Verifies and sends message.
... |
def convert_from_file(cls, input_file=None, output_file=None, output_format='json', indent=2, compact=False):
"""Convert to json, properties or yaml
:param input_file: input file, if not specified stdin
:param output_file: output file, if not specified stdout
:param output_format: json,... | Convert to json, properties or yaml
:param input_file: input file, if not specified stdin
:param output_file: output file, if not specified stdout
:param output_format: json, properties or yaml
:return: json, properties or yaml string representation | Below is the the instruction that describes the task:
### Input:
Convert to json, properties or yaml
:param input_file: input file, if not specified stdin
:param output_file: output file, if not specified stdout
:param output_format: json, properties or yaml
:return: json, propertie... |
def _time_show(self):
"""Show the time marker window"""
if not self._time_visible:
self._time_visible = True
self._time_window = tk.Toplevel(self)
self._time_window.attributes("-topmost", True)
self._time_window.overrideredirect(True)
self._tim... | Show the time marker window | Below is the the instruction that describes the task:
### Input:
Show the time marker window
### Response:
def _time_show(self):
"""Show the time marker window"""
if not self._time_visible:
self._time_visible = True
self._time_window = tk.Toplevel(self)
self._tim... |
def open(self):
"""Turn the device ON."""
open_command = StandardSend(self._address,
COMMAND_LIGHT_ON_0X11_NONE, cmd2=0xff)
self._send_method(open_command, self._open_message_received) | Turn the device ON. | Below is the the instruction that describes the task:
### Input:
Turn the device ON.
### Response:
def open(self):
"""Turn the device ON."""
open_command = StandardSend(self._address,
COMMAND_LIGHT_ON_0X11_NONE, cmd2=0xff)
self._send_method(open_command, ... |
def load_module(self, name):
"""Load a module from a file.
"""
# Implementation inspired from pytest.rewrite and importlib
# If there is an existing module object named 'name' in
# sys.modules, the loader must use that existing module. (Otherwise,
# the reload() builtin ... | Load a module from a file. | Below is the the instruction that describes the task:
### Input:
Load a module from a file.
### Response:
def load_module(self, name):
"""Load a module from a file.
"""
# Implementation inspired from pytest.rewrite and importlib
# If there is an existing module object named 'name' ... |
def validate(style, value, vectorized=True):
"""
Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
vectorized: bool
Whether validator should allow vectorized... | Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
vectorized: bool
Whether validator should allow vectorized setting
Returns
-------
valid: boolean or N... | Below is the the instruction that describes the task:
### Input:
Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
vectorized: bool
Whether validator should allo... |
def num_gpus(): # type: () -> int
"""The number of gpus available in the current container.
Returns:
int: number of gpus available in the current container.
"""
try:
cmd = shlex.split('nvidia-smi --list-gpus')
output = subprocess.check_output(cmd).decode('utf-8')
return... | The number of gpus available in the current container.
Returns:
int: number of gpus available in the current container. | Below is the the instruction that describes the task:
### Input:
The number of gpus available in the current container.
Returns:
int: number of gpus available in the current container.
### Response:
def num_gpus(): # type: () -> int
"""The number of gpus available in the current container.
R... |
def reload(filename=None,
url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml",
loader_class=None):
u"""reload google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library."""
if loader_class is None:
loader_clas... | u"""reload google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library. | Below is the the instruction that describes the task:
### Input:
u"""reload google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library.
### Response:
def reload(filename=None,
url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml",... |
def get_homepath(self, ignore_session=False, force_cookieless=False):
"""
:param ignore_session: Ignore the cookieless session_id that should be put in the URL
:param force_cookieless: Force the cookieless session; the link will include the session_creator if needed.
"""
if not i... | :param ignore_session: Ignore the cookieless session_id that should be put in the URL
:param force_cookieless: Force the cookieless session; the link will include the session_creator if needed. | Below is the the instruction that describes the task:
### Input:
:param ignore_session: Ignore the cookieless session_id that should be put in the URL
:param force_cookieless: Force the cookieless session; the link will include the session_creator if needed.
### Response:
def get_homepath(self, ignore_sess... |
def getEndTag(self):
'''
getEndTag - returns the end tag representation as HTML string
@return - String of end tag
'''
# If this is a self-closing tag, we have no end tag (opens and closes in the start)
if self.isSelfClosing is True:
return ''
... | getEndTag - returns the end tag representation as HTML string
@return - String of end tag | Below is the the instruction that describes the task:
### Input:
getEndTag - returns the end tag representation as HTML string
@return - String of end tag
### Response:
def getEndTag(self):
'''
getEndTag - returns the end tag representation as HTML string
@return - Str... |
def getStatus(jobStoreName):
"""
Determine the status of a workflow.
If the jobstore does not exist, this returns 'QUEUED', assuming it has not been created yet.
Checks for the existence of files created in the toil.Leader.run(). In toil.Leader.run(), if a workflow completes
wi... | Determine the status of a workflow.
If the jobstore does not exist, this returns 'QUEUED', assuming it has not been created yet.
Checks for the existence of files created in the toil.Leader.run(). In toil.Leader.run(), if a workflow completes
with failed jobs, 'failed.log' is created, otherwis... | Below is the the instruction that describes the task:
### Input:
Determine the status of a workflow.
If the jobstore does not exist, this returns 'QUEUED', assuming it has not been created yet.
Checks for the existence of files created in the toil.Leader.run(). In toil.Leader.run(), if a workflow ... |
def import_model(self, source):
"""Import and return model instance."""
model = super(NonstrictImporter, self).import_model(source)
sbml.convert_sbml_model(model)
return model | Import and return model instance. | Below is the the instruction that describes the task:
### Input:
Import and return model instance.
### Response:
def import_model(self, source):
"""Import and return model instance."""
model = super(NonstrictImporter, self).import_model(source)
sbml.convert_sbml_model(model)
return ... |
def triplify(self, data, parent=None):
""" Recursively generate statements from the data supplied. """
if data is None:
return
if self.is_object:
for res in self._triplify_object(data, parent):
yield res
elif self.is_array:
for item in... | Recursively generate statements from the data supplied. | Below is the the instruction that describes the task:
### Input:
Recursively generate statements from the data supplied.
### Response:
def triplify(self, data, parent=None):
""" Recursively generate statements from the data supplied. """
if data is None:
return
if self.is_objec... |
def runlogs_policy(log_group_ref):
"""Policy needed for Empire -> Cloudwatch logs to record run output."""
p = Policy(
Statement=[
Statement(
Effect=Allow,
Resource=[
Join('', [
'arn:aws:logs:*:*:log-group:',
... | Policy needed for Empire -> Cloudwatch logs to record run output. | Below is the the instruction that describes the task:
### Input:
Policy needed for Empire -> Cloudwatch logs to record run output.
### Response:
def runlogs_policy(log_group_ref):
"""Policy needed for Empire -> Cloudwatch logs to record run output."""
p = Policy(
Statement=[
Statement(
... |
def get_tagged_tracks(self, tag, limit=None, cacheable=True):
"""Returns the tracks tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "track"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".g... | Returns the tracks tagged by a user. | Below is the the instruction that describes the task:
### Input:
Returns the tracks tagged by a user.
### Response:
def get_tagged_tracks(self, tag, limit=None, cacheable=True):
"""Returns the tracks tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.