code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def acceptmergerequest(self, project_id, mergerequest_id, merge_commit_message=None):
"""
Update an existing merge request.
:param project_id: ID of the project originating the merge request
:param mergerequest_id: ID of the merge request to accept
:param merge_commit_message: C... | Update an existing merge request.
:param project_id: ID of the project originating the merge request
:param mergerequest_id: ID of the merge request to accept
:param merge_commit_message: Custom merge commit message
:return: dict of the modified merge request | Below is the the instruction that describes the task:
### Input:
Update an existing merge request.
:param project_id: ID of the project originating the merge request
:param mergerequest_id: ID of the merge request to accept
:param merge_commit_message: Custom merge commit message
:r... |
def username_matches_request_user(view_fn):
"""Checks if the username matches the request user, and if so replaces
username with the actual user object.
Returns 404 if the username does not exist, and 403 if it doesn't match.
"""
@wraps(view_fn)
def wrapper(request, username, *args, **kwargs):
... | Checks if the username matches the request user, and if so replaces
username with the actual user object.
Returns 404 if the username does not exist, and 403 if it doesn't match. | Below is the the instruction that describes the task:
### Input:
Checks if the username matches the request user, and if so replaces
username with the actual user object.
Returns 404 if the username does not exist, and 403 if it doesn't match.
### Response:
def username_matches_request_user(view_fn):
"... |
def app_view(name, **kwargs):
"""
Show manifest content for an application.
If application is not uploaded, an error will be displayed.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | Show manifest content for an application.
If application is not uploaded, an error will be displayed. | Below is the the instruction that describes the task:
### Input:
Show manifest content for an application.
If application is not uploaded, an error will be displayed.
### Response:
def app_view(name, **kwargs):
"""
Show manifest content for an application.
If application is not uploaded, an error... |
def volume(self, volume):
"""See `volume`."""
# max 100
volume = int(volume)
self._volume = max(0, min(volume, 100)) | See `volume`. | Below is the the instruction that describes the task:
### Input:
See `volume`.
### Response:
def volume(self, volume):
"""See `volume`."""
# max 100
volume = int(volume)
self._volume = max(0, min(volume, 100)) |
def validate(cls, keystr):
""" raises cls.Bad if keys has errors """
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
for k in keys:
cls.validate_one(cls.extract(k))
else:
# plain keys str
... | raises cls.Bad if keys has errors | Below is the the instruction that describes the task:
### Input:
raises cls.Bad if keys has errors
### Response:
def validate(cls, keystr):
""" raises cls.Bad if keys has errors """
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
... |
def visit_unload_from_select(element, compiler, **kw):
"""Returns the actual sql query for the UnloadFromSelect class."""
template = """
UNLOAD (:select) TO :unload_location
CREDENTIALS :credentials
{manifest}
{header}
{delimiter}
{encrypted}
{fixed_width}
... | Returns the actual sql query for the UnloadFromSelect class. | Below is the the instruction that describes the task:
### Input:
Returns the actual sql query for the UnloadFromSelect class.
### Response:
def visit_unload_from_select(element, compiler, **kw):
"""Returns the actual sql query for the UnloadFromSelect class."""
template = """
UNLOAD (:select) TO :u... |
def has_document(self, doc_url):
""" Check if the content of the given document is present
in the cache
If the max_age attribute of this Cache is set to a nonzero value,
entries older than the value of max_age in seconds will be ignored
:type doc_url: String or Document
... | Check if the content of the given document is present
in the cache
If the max_age attribute of this Cache is set to a nonzero value,
entries older than the value of max_age in seconds will be ignored
:type doc_url: String or Document
:param doc_url: the URL of the document, or ... | Below is the the instruction that describes the task:
### Input:
Check if the content of the given document is present
in the cache
If the max_age attribute of this Cache is set to a nonzero value,
entries older than the value of max_age in seconds will be ignored
:type doc_url: St... |
def rm(i):
"""
Input: {
(repo_uoa) - repo UOA ; can be wild cards
module_uoa - module UOA ; can be wild cards
data_uoa - data UOA ; can be wild cards
(force) - if 'yes', force deleting without questions
or... | Input: {
(repo_uoa) - repo UOA ; can be wild cards
module_uoa - module UOA ; can be wild cards
data_uoa - data UOA ; can be wild cards
(force) - if 'yes', force deleting without questions
or
(f) ... | Below is the the instruction that describes the task:
### Input:
Input: {
(repo_uoa) - repo UOA ; can be wild cards
module_uoa - module UOA ; can be wild cards
data_uoa - data UOA ; can be wild cards
(force) - if 'yes', force ... |
def parse_operations(ops_string):
"""Takes a string of operations written with a handy DSL
"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG"
And returns a list of functions, each of which take and return ndarrays
"""
band_lookup = {"r": 1, "g": 2, "b": 3}
count = len(band_lookup)
... | Takes a string of operations written with a handy DSL
"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG"
And returns a list of functions, each of which take and return ndarrays | Below is the the instruction that describes the task:
### Input:
Takes a string of operations written with a handy DSL
"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG"
And returns a list of functions, each of which take and return ndarrays
### Response:
def parse_operations(ops_string):
"""T... |
def _annotate_groups(self):
"""
Annotate the objects belonging to separate (non-connected) graphs with
individual indices.
"""
g = {}
for x in self.metadata:
g[x.id] = x
idx = 0
for x in self.metadata:
if not hasattr(x, 'group'):
... | Annotate the objects belonging to separate (non-connected) graphs with
individual indices. | Below is the the instruction that describes the task:
### Input:
Annotate the objects belonging to separate (non-connected) graphs with
individual indices.
### Response:
def _annotate_groups(self):
"""
Annotate the objects belonging to separate (non-connected) graphs with
individual... |
def update(self, distributor_id, grade_id, session, trade_type=None):
'''taobao.fenxiao.cooperation.update 更新合作关系等级
供应商更新合作的分销商等级'''
request = TOPRequest('taobao.fenxiao.cooperation.update')
request['distributor_id'] = distributor_id
request['grade_id'] = grade_id
... | taobao.fenxiao.cooperation.update 更新合作关系等级
供应商更新合作的分销商等级 | Below is the the instruction that describes the task:
### Input:
taobao.fenxiao.cooperation.update 更新合作关系等级
供应商更新合作的分销商等级
### Response:
def update(self, distributor_id, grade_id, session, trade_type=None):
'''taobao.fenxiao.cooperation.update 更新合作关系等级
供应商更新合作的分销商等级'''
... |
def execute_prebuild_script(self):
"""
Parse and execute the prebuild_script from the zappa_settings.
"""
(pb_mod_path, pb_func) = self.prebuild_script.rsplit('.', 1)
try: # Prefer prebuild script in working directory
if pb_mod_path.count('.') >= 1: # Prebuild sc... | Parse and execute the prebuild_script from the zappa_settings. | Below is the the instruction that describes the task:
### Input:
Parse and execute the prebuild_script from the zappa_settings.
### Response:
def execute_prebuild_script(self):
"""
Parse and execute the prebuild_script from the zappa_settings.
"""
(pb_mod_path, pb_func) = self.pre... |
def unconsumed_ranges(self):
"""Return an IntervalTree of unconsumed ranges, of the format
(start, end] with the end value not being included
"""
res = IntervalTree()
prev = None
# normal iteration is not in a predictable order
ranges = sorted([x for x in self.r... | Return an IntervalTree of unconsumed ranges, of the format
(start, end] with the end value not being included | Below is the the instruction that describes the task:
### Input:
Return an IntervalTree of unconsumed ranges, of the format
(start, end] with the end value not being included
### Response:
def unconsumed_ranges(self):
"""Return an IntervalTree of unconsumed ranges, of the format
(start, end... |
def can_handle(self, cls):
"""
this will theoretically be compatible with everything,
as cattrs can handle many basic types as well.
"""
# cattrs uses a Singledispatch like function
# under the hood.
f = self._cattrs_converter._structure_func.dispatch(cls)
... | this will theoretically be compatible with everything,
as cattrs can handle many basic types as well. | Below is the the instruction that describes the task:
### Input:
this will theoretically be compatible with everything,
as cattrs can handle many basic types as well.
### Response:
def can_handle(self, cls):
"""
this will theoretically be compatible with everything,
as cattrs can ha... |
def DownloadReportToFile(self, report_job_id, export_format, outfile,
include_report_properties=False,
include_totals_row=None, use_gzip_compression=True):
"""Downloads report data and writes it to a file.
The report job must be completed before calling thi... | Downloads report data and writes it to a file.
The report job must be completed before calling this function.
Args:
report_job_id: The ID of the report job to wait for, as a string.
export_format: The export format for the report file, as a string.
outfile: A writeable, file-like object to w... | Below is the the instruction that describes the task:
### Input:
Downloads report data and writes it to a file.
The report job must be completed before calling this function.
Args:
report_job_id: The ID of the report job to wait for, as a string.
export_format: The export format for the report... |
def to_fmt(self) -> str:
"""
Provide a useful representation of the register.
"""
infos = fmt.end(";\n", [])
s = fmt.sep(', ', [])
for ids in sorted(self.states.keys()):
s.lsdata.append(str(ids))
infos.lsdata.append(fmt.block('(', ')', [s]))
in... | Provide a useful representation of the register. | Below is the the instruction that describes the task:
### Input:
Provide a useful representation of the register.
### Response:
def to_fmt(self) -> str:
"""
Provide a useful representation of the register.
"""
infos = fmt.end(";\n", [])
s = fmt.sep(', ', [])
for ids ... |
def flow(self)->FlowField:
"Access the flow-field grid after applying queued affine and coord transforms."
if self._affine_mat is not None:
self._flow = _affine_inv_mult(self._flow, self._affine_mat)
self._affine_mat = None
self.transformed = True
if len(self.... | Access the flow-field grid after applying queued affine and coord transforms. | Below is the the instruction that describes the task:
### Input:
Access the flow-field grid after applying queued affine and coord transforms.
### Response:
def flow(self)->FlowField:
"Access the flow-field grid after applying queued affine and coord transforms."
if self._affine_mat is not None:
... |
def getFilepaths(self, filename):
"""
Get home and mackup filepaths for given file
Args:
filename (str)
Returns:
home_filepath, mackup_filepath (str, str)
"""
return (os.path.join(os.environ['HOME'], filename),
os.path.join(self.m... | Get home and mackup filepaths for given file
Args:
filename (str)
Returns:
home_filepath, mackup_filepath (str, str) | Below is the the instruction that describes the task:
### Input:
Get home and mackup filepaths for given file
Args:
filename (str)
Returns:
home_filepath, mackup_filepath (str, str)
### Response:
def getFilepaths(self, filename):
"""
Get home and mackup fil... |
def syslog(server, enable=True):
'''
Configure syslog remote logging, by default syslog will automatically be
enabled if a server is specified. However, if you want to disable syslog
you will need to specify a server followed by False
CLI Example:
.. code-block:: bash
salt dell drac.s... | Configure syslog remote logging, by default syslog will automatically be
enabled if a server is specified. However, if you want to disable syslog
you will need to specify a server followed by False
CLI Example:
.. code-block:: bash
salt dell drac.syslog [SYSLOG IP] [ENABLE/DISABLE]
sa... | Below is the the instruction that describes the task:
### Input:
Configure syslog remote logging, by default syslog will automatically be
enabled if a server is specified. However, if you want to disable syslog
you will need to specify a server followed by False
CLI Example:
.. code-block:: bash
... |
def sents(self: object, fileids: str):
"""
Tokenizes documents in the corpus by sentence
"""
for para in self.paras(fileids):
for sent in sent_tokenize(para):
yield sent | Tokenizes documents in the corpus by sentence | Below is the the instruction that describes the task:
### Input:
Tokenizes documents in the corpus by sentence
### Response:
def sents(self: object, fileids: str):
"""
Tokenizes documents in the corpus by sentence
"""
for para in self.paras(fileids):
for sent in sent_to... |
def get_range_info(array, component):
"""Get the data range of the array's component"""
r = array.GetRange(component)
comp_range = {}
comp_range['min'] = r[0]
comp_range['max'] = r[1]
comp_range['component'] = array.GetComponentName(component)
return comp_range | Get the data range of the array's component | Below is the the instruction that describes the task:
### Input:
Get the data range of the array's component
### Response:
def get_range_info(array, component):
"""Get the data range of the array's component"""
r = array.GetRange(component)
comp_range = {}
comp_range['min'] = r[0]
comp_range['m... |
def call(self, methodname, *args, **kwargs):
"""Call a common method on all the plugins, if it exists."""
for plugin in self._plugins:
method = getattr(plugin, methodname, None)
if method is None:
continue
yield method(*args, **kwargs) | Call a common method on all the plugins, if it exists. | Below is the the instruction that describes the task:
### Input:
Call a common method on all the plugins, if it exists.
### Response:
def call(self, methodname, *args, **kwargs):
"""Call a common method on all the plugins, if it exists."""
for plugin in self._plugins:
method = getattr(... |
def unpack_version(version):
"""Unpack a single version integer into the two major and minor
components."""
minor_version = version % VERSION_MULTIPLIER
major_version = (version - minor_version) / VERSION_MULTIPLIER
return (major_version, minor_version) | Unpack a single version integer into the two major and minor
components. | Below is the the instruction that describes the task:
### Input:
Unpack a single version integer into the two major and minor
components.
### Response:
def unpack_version(version):
"""Unpack a single version integer into the two major and minor
components."""
minor_version = version % VERSION_MULTI... |
def translateprotocolmask(protocol):
"""Translate CardConnection protocol mask into PCSC protocol mask."""
pcscprotocol = 0
if None != protocol:
if CardConnection.T0_protocol & protocol:
pcscprotocol |= SCARD_PROTOCOL_T0
if CardConnection.T1_protocol & protocol:
pcscp... | Translate CardConnection protocol mask into PCSC protocol mask. | Below is the the instruction that describes the task:
### Input:
Translate CardConnection protocol mask into PCSC protocol mask.
### Response:
def translateprotocolmask(protocol):
"""Translate CardConnection protocol mask into PCSC protocol mask."""
pcscprotocol = 0
if None != protocol:
if Card... |
def change_object_content_type(self, container, obj, new_ctype,
guess=False, extra_info=None):
"""
Copies object to itself, but applies a new content-type. The guess
feature requires the container to be CDN-enabled. If not then the
content-type must be supplied. If using gues... | Copies object to itself, but applies a new content-type. The guess
feature requires the container to be CDN-enabled. If not then the
content-type must be supplied. If using guess with a CDN-enabled
container, new_ctype can be set to None. Failure during the put will
result in a swift exc... | Below is the the instruction that describes the task:
### Input:
Copies object to itself, but applies a new content-type. The guess
feature requires the container to be CDN-enabled. If not then the
content-type must be supplied. If using guess with a CDN-enabled
container, new_ctype can be s... |
def add_vnic_template(self, vlan_id, ucsm_ip, vnic_template, physnet):
"""Adds an entry for a vlan_id on a SP template to the table."""
if not self.get_vnic_template_vlan_entry(vlan_id, vnic_template,
ucsm_ip, physnet):
vnic_t = ucsm_model.VnicTemplate(vlan_id=vlan_id,
... | Adds an entry for a vlan_id on a SP template to the table. | Below is the the instruction that describes the task:
### Input:
Adds an entry for a vlan_id on a SP template to the table.
### Response:
def add_vnic_template(self, vlan_id, ucsm_ip, vnic_template, physnet):
"""Adds an entry for a vlan_id on a SP template to the table."""
if not self.get_vnic_temp... |
def _iter_candidate_groups(self, init_match, edges0, edges1):
"""Divide the edges into groups"""
# collect all end vertices0 and end vertices1 that belong to the same
# group.
sources = {}
for start_vertex0, end_vertex0 in edges0:
l = sources.setdefault(start_vertex0,... | Divide the edges into groups | Below is the the instruction that describes the task:
### Input:
Divide the edges into groups
### Response:
def _iter_candidate_groups(self, init_match, edges0, edges1):
"""Divide the edges into groups"""
# collect all end vertices0 and end vertices1 that belong to the same
# group.
... |
def open_connection(ip, username, password, function, args, write=False,
conn_timeout=5, sess_timeout=300, port=22):
""" Open a Jaide session with the device.
To open a Jaide session to the device, and run the appropriate function
against the device. Arguments for the downstream functio... | Open a Jaide session with the device.
To open a Jaide session to the device, and run the appropriate function
against the device. Arguments for the downstream function are passed
through.
@param ip: String of the IP or hostname of the device to connect to.
@type ip: str
@param username: The st... | Below is the the instruction that describes the task:
### Input:
Open a Jaide session with the device.
To open a Jaide session to the device, and run the appropriate function
against the device. Arguments for the downstream function are passed
through.
@param ip: String of the IP or hostname of th... |
def __build_sign_query(saml_data, relay_state, algorithm, saml_type, lowercase_urlencoding=False):
"""
Build sign query
:param saml_data: The Request data
:type saml_data: str
:param relay_state: The Relay State
:type relay_state: str
:param algorithm: The Sign... | Build sign query
:param saml_data: The Request data
:type saml_data: str
:param relay_state: The Relay State
:type relay_state: str
:param algorithm: The Signature Algorithm
:type algorithm: str
:param saml_type: The target URL the user should be redirected to... | Below is the the instruction that describes the task:
### Input:
Build sign query
:param saml_data: The Request data
:type saml_data: str
:param relay_state: The Relay State
:type relay_state: str
:param algorithm: The Signature Algorithm
:type algorithm: str
... |
def get_sequence_rules(self):
"""Gets all ``SequenceRules``.
return: (osid.assessment.authoring.SequenceRuleList) - the
returned ``SequenceRule`` list
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*complianc... | Gets all ``SequenceRules``.
return: (osid.assessment.authoring.SequenceRuleList) - the
returned ``SequenceRule`` list
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be imple... | Below is the the instruction that describes the task:
### Input:
Gets all ``SequenceRules``.
return: (osid.assessment.authoring.SequenceRuleList) - the
returned ``SequenceRule`` list
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorizatio... |
def resolve(self, requirement_set):
# type: (RequirementSet) -> None
"""Resolve what operations need to be done
As a side-effect of this method, the packages (and their dependencies)
are downloaded, unpacked and prepared for installation. This
preparation is done by ``pip.operat... | Resolve what operations need to be done
As a side-effect of this method, the packages (and their dependencies)
are downloaded, unpacked and prepared for installation. This
preparation is done by ``pip.operations.prepare``.
Once PyPI has static dependency metadata available, it would be... | Below is the the instruction that describes the task:
### Input:
Resolve what operations need to be done
As a side-effect of this method, the packages (and their dependencies)
are downloaded, unpacked and prepared for installation. This
preparation is done by ``pip.operations.prepare``.
... |
def _filter_vcf(out_file):
"""Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference.
"""
in_file = out_file.replace(".vcf", "-ori.vcf")
FILTER_line = ('##FILTER=<ID=SBIAS,Description="Due to bias">\n'
'##FILTER=<ID=5BP,Description="Due to 5BP">\n'
... | Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference. | Below is the the instruction that describes the task:
### Input:
Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference.
### Response:
def _filter_vcf(out_file):
"""Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference.
"""
in_file = out_file.repla... |
def bindings_exist(name, jboss_config, bindings, profile=None):
'''
Ensures that given JNDI binding are present on the server.
If a binding doesn't exist on the server it will be created.
If it already exists its value will be changed.
jboss_config:
Dict with connection properties (see stat... | Ensures that given JNDI binding are present on the server.
If a binding doesn't exist on the server it will be created.
If it already exists its value will be changed.
jboss_config:
Dict with connection properties (see state description)
bindings:
Dict with bindings to set.
profile:... | Below is the the instruction that describes the task:
### Input:
Ensures that given JNDI binding are present on the server.
If a binding doesn't exist on the server it will be created.
If it already exists its value will be changed.
jboss_config:
Dict with connection properties (see state descr... |
def run_all(logdir, verbose=False):
"""Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins
"""
run_box_to_gaussian(logdir, verbose=verbose)
run_sobel(logdir, verbose=verbose... | Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins | Below is the the instruction that describes the task:
### Input:
Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins
### Response:
def run_all(logdir, verbose=False):
"""Run ... |
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
... | Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None. | Below is the the instruction that describes the task:
### Input:
Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't ma... |
def process_bulk_queue(self, es_bulk_kwargs=None):
"""Process bulk indexing queue.
:param dict es_bulk_kwargs: Passed to
:func:`elasticsearch:elasticsearch.helpers.bulk`.
"""
with current_celery_app.pool.acquire(block=True) as conn:
consumer = Consumer(
... | Process bulk indexing queue.
:param dict es_bulk_kwargs: Passed to
:func:`elasticsearch:elasticsearch.helpers.bulk`. | Below is the the instruction that describes the task:
### Input:
Process bulk indexing queue.
:param dict es_bulk_kwargs: Passed to
:func:`elasticsearch:elasticsearch.helpers.bulk`.
### Response:
def process_bulk_queue(self, es_bulk_kwargs=None):
"""Process bulk indexing queue.
... |
def make_parser(self, ctx):
"""Creates the underlying option parser for this command."""
parser = OptionParser(ctx)
parser.allow_interspersed_args = ctx.allow_interspersed_args
parser.ignore_unknown_options = ctx.ignore_unknown_options
for param in self.get_params(ctx):
... | Creates the underlying option parser for this command. | Below is the the instruction that describes the task:
### Input:
Creates the underlying option parser for this command.
### Response:
def make_parser(self, ctx):
"""Creates the underlying option parser for this command."""
parser = OptionParser(ctx)
parser.allow_interspersed_args = ctx.allo... |
def create_module_docs():
"""
Create documentation for modules.
"""
data = core_module_docstrings(format="rst")
# get screenshot data
screenshots_data = {}
samples = get_samples()
for sample in samples.keys():
module = sample.split("-")[0]
if module not in screenshots_dat... | Create documentation for modules. | Below is the the instruction that describes the task:
### Input:
Create documentation for modules.
### Response:
def create_module_docs():
"""
Create documentation for modules.
"""
data = core_module_docstrings(format="rst")
# get screenshot data
screenshots_data = {}
samples = get_samp... |
def parallel_part(data, parallel):
"""parallel_part(data, parallel) -> part
Splits off samples from the the given data list and the given number of parallel jobs based on the ``SGE_TASK_ID`` environment variable.
**Parameters:**
``data`` : [object]
A list of data that should be split up into ``parallel``... | parallel_part(data, parallel) -> part
Splits off samples from the the given data list and the given number of parallel jobs based on the ``SGE_TASK_ID`` environment variable.
**Parameters:**
``data`` : [object]
A list of data that should be split up into ``parallel`` parts
``parallel`` : int or ``None``... | Below is the the instruction that describes the task:
### Input:
parallel_part(data, parallel) -> part
Splits off samples from the the given data list and the given number of parallel jobs based on the ``SGE_TASK_ID`` environment variable.
**Parameters:**
``data`` : [object]
A list of data that should ... |
def convert_to_xml(cls, degrees):
"""Convert signed angle float like -427.42 to int 60000 per degree.
Value is normalized to a positive value less than 360 degrees.
"""
if degrees < 0.0:
degrees %= -360
degrees += 360
elif degrees > 0.0:
degre... | Convert signed angle float like -427.42 to int 60000 per degree.
Value is normalized to a positive value less than 360 degrees. | Below is the the instruction that describes the task:
### Input:
Convert signed angle float like -427.42 to int 60000 per degree.
Value is normalized to a positive value less than 360 degrees.
### Response:
def convert_to_xml(cls, degrees):
"""Convert signed angle float like -427.42 to int 60000 p... |
def add_skip_ci_to_commit_msg(message: str) -> str:
"""
Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message
:param message: commit message
:type message: str
:return: edited commit message
:rtype: str
"""
first_line_index = message... | Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message
:param message: commit message
:type message: str
:return: edited commit message
:rtype: str | Below is the the instruction that describes the task:
### Input:
Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message
:param message: commit message
:type message: str
:return: edited commit message
:rtype: str
### Response:
def add_skip_ci_to_commit_msg(mess... |
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
mtype = m.get_type()
if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']:
if self.wp_op is None:
self.console.error("No waypoint load started")
else:
self.wploader.clear()
... | handle an incoming mavlink packet | Below is the the instruction that describes the task:
### Input:
handle an incoming mavlink packet
### Response:
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
mtype = m.get_type()
if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']:
if self.wp_op is None:
... |
def bubble_at_T(zs, Psats, fugacities=None, gammas=None):
'''
>>> bubble_at_T([0.5, 0.5], [1400, 7000])
4200.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75])
3395.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75], fugacities=[.995, 0.98])
3452.440775305097
'''
... | >>> bubble_at_T([0.5, 0.5], [1400, 7000])
4200.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75])
3395.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75], fugacities=[.995, 0.98])
3452.440775305097 | Below is the the instruction that describes the task:
### Input:
>>> bubble_at_T([0.5, 0.5], [1400, 7000])
4200.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75])
3395.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75], fugacities=[.995, 0.98])
3452.440775305097
### Respon... |
def init_storage():
"""
Initialize the local dictionnaries cache in ~/.crosswords/dicts.
"""
# http://stackoverflow.com/a/600612/735926
try:
os.makedirs(DICTS_PATH)
except OSError as ex:
if ex.errno != errno.EEXIST or not os.path.isdir(DICTS_PATH):
raise | Initialize the local dictionnaries cache in ~/.crosswords/dicts. | Below is the the instruction that describes the task:
### Input:
Initialize the local dictionnaries cache in ~/.crosswords/dicts.
### Response:
def init_storage():
"""
Initialize the local dictionnaries cache in ~/.crosswords/dicts.
"""
# http://stackoverflow.com/a/600612/735926
try:
os... |
def set_elements_tail(parent_to_parse, element_path=None, tail_values=None):
"""
Assigns an array of tail values to each of the elements parsed from the parent. The
tail values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; b... | Assigns an array of tail values to each of the elements parsed from the parent. The
tail values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; but if
there are more, new elements will be inserted for each with the remaining tail ... | Below is the the instruction that describes the task:
### Input:
Assigns an array of tail values to each of the elements parsed from the parent. The
tail values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; but if
there are ... |
def get_domain(url):
""" Returns domain name portion of a URL """
if 'http' not in url.lower():
url = 'http://{}'.format(url)
return urllib.parse.urlparse(url).hostname | Returns domain name portion of a URL | Below is the the instruction that describes the task:
### Input:
Returns domain name portion of a URL
### Response:
def get_domain(url):
""" Returns domain name portion of a URL """
if 'http' not in url.lower():
url = 'http://{}'.format(url)
return urllib.parse.urlparse(url).hostname |
def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str:
"""
From a consistent list of dictionaries mapping fieldnames to values,
make a TSV file.
"""
if not dictlist:
return ""
fieldnames = dictlist[0].keys()
tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n"
for d i... | From a consistent list of dictionaries mapping fieldnames to values,
make a TSV file. | Below is the the instruction that describes the task:
### Input:
From a consistent list of dictionaries mapping fieldnames to values,
make a TSV file.
### Response:
def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str:
"""
From a consistent list of dictionaries mapping fieldnames to values,
m... |
def convert_surrogate_pair(match):
"""
Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
"""
pair = match.group(0)
codept = 0x10000 + (ord(pair[0]) - 0xd800) * ... | Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates | Below is the the instruction that describes the task:
### Input:
Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
### Response:
def convert_surrogate_pair(match):
"""
... |
def init(name, subnames, dest, skeleton, description, project_type, skip_core):
"""Creates a standalone, subprojects or submodules script sctrucure"""
dest = dest or CUR_DIR
skeleton = join(skeleton or SKEL_PATH, project_type)
project = join(dest, name)
script = join(project, name + '.py')
core ... | Creates a standalone, subprojects or submodules script sctrucure | Below is the the instruction that describes the task:
### Input:
Creates a standalone, subprojects or submodules script sctrucure
### Response:
def init(name, subnames, dest, skeleton, description, project_type, skip_core):
"""Creates a standalone, subprojects or submodules script sctrucure"""
dest = dest ... |
def unpack(self, s):
"""Parse bytes and return a namedtuple."""
return self._create(super(DictStruct, self).unpack(s)) | Parse bytes and return a namedtuple. | Below is the the instruction that describes the task:
### Input:
Parse bytes and return a namedtuple.
### Response:
def unpack(self, s):
"""Parse bytes and return a namedtuple."""
return self._create(super(DictStruct, self).unpack(s)) |
def detach_session(self):
"""Allow the session to be discarded and don't get change notifications from it anymore"""
if self._session is not None:
self._session.unsubscribe(self)
self._session = None | Allow the session to be discarded and don't get change notifications from it anymore | Below is the the instruction that describes the task:
### Input:
Allow the session to be discarded and don't get change notifications from it anymore
### Response:
def detach_session(self):
"""Allow the session to be discarded and don't get change notifications from it anymore"""
if self._session i... |
def wait_socks(sock_events, inmask=1, outmask=2, timeout=None):
"""wait on a combination of zeromq sockets, normal sockets, and fds
.. note:: this method can block
it will return once there is relevant activity on any of the
descriptors or sockets, or the timeout expires
:param sock_event... | wait on a combination of zeromq sockets, normal sockets, and fds
.. note:: this method can block
it will return once there is relevant activity on any of the
descriptors or sockets, or the timeout expires
:param sock_events:
two-tuples, the first item is either a zeromq socket, a sock... | Below is the the instruction that describes the task:
### Input:
wait on a combination of zeromq sockets, normal sockets, and fds
.. note:: this method can block
it will return once there is relevant activity on any of the
descriptors or sockets, or the timeout expires
:param sock_events:... |
def isNonNull(requestContext, seriesList):
"""
Takes a metric or wild card seriesList and counts up how many
non-null values are specified. This is useful for understanding
which metrics have data at a given point in time (ie, to count
which servers are alive).
Example::
&target=isNonN... | Takes a metric or wild card seriesList and counts up how many
non-null values are specified. This is useful for understanding
which metrics have data at a given point in time (ie, to count
which servers are alive).
Example::
&target=isNonNull(webapp.pages.*.views)
Returns a seriesList whe... | Below is the the instruction that describes the task:
### Input:
Takes a metric or wild card seriesList and counts up how many
non-null values are specified. This is useful for understanding
which metrics have data at a given point in time (ie, to count
which servers are alive).
Example::
... |
def format(self):
"""Format of the (string) object."""
value = self._schema.get("format", None)
if value is None:
return
if not isinstance(value, basestring):
raise SchemaError(
"format value {0!r} is not a string".format(value))
if value i... | Format of the (string) object. | Below is the the instruction that describes the task:
### Input:
Format of the (string) object.
### Response:
def format(self):
"""Format of the (string) object."""
value = self._schema.get("format", None)
if value is None:
return
if not isinstance(value, basestring):
... |
def _cleanly_slice_encoded_string(encoded_string, length_limit):
"""
Takes a byte string (a UTF-8 encoded string) and splits it into two pieces such that the first slice is no
longer than argument `length_limit`, then returns a tuple containing the first slice and remainder of the
byte s... | Takes a byte string (a UTF-8 encoded string) and splits it into two pieces such that the first slice is no
longer than argument `length_limit`, then returns a tuple containing the first slice and remainder of the
byte string, respectively. The first slice may actually be shorter than `length_limit`, bec... | Below is the the instruction that describes the task:
### Input:
Takes a byte string (a UTF-8 encoded string) and splits it into two pieces such that the first slice is no
longer than argument `length_limit`, then returns a tuple containing the first slice and remainder of the
byte string, respectiv... |
def parse_xml(data, handle_units):
"""Parse XML data returned by NCSS."""
root = ET.fromstring(data)
return squish(parse_xml_dataset(root, handle_units)) | Parse XML data returned by NCSS. | Below is the the instruction that describes the task:
### Input:
Parse XML data returned by NCSS.
### Response:
def parse_xml(data, handle_units):
"""Parse XML data returned by NCSS."""
root = ET.fromstring(data)
return squish(parse_xml_dataset(root, handle_units)) |
def high_cli(repo_name, login, with_blog, as_list, role):
"""Extract mails from stargazers, collaborators and people involved with issues of given
repository.
"""
passw = getpass.getpass()
github = gh_login(login, passw)
repo = github.repository(login, repo_name)
role = [ROLES[k] for k in ro... | Extract mails from stargazers, collaborators and people involved with issues of given
repository. | Below is the the instruction that describes the task:
### Input:
Extract mails from stargazers, collaborators and people involved with issues of given
repository.
### Response:
def high_cli(repo_name, login, with_blog, as_list, role):
"""Extract mails from stargazers, collaborators and people involved with... |
def get_eqsl_users(**kwargs):
"""Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_.
Args:
url (str, optional): Download URL
Returns:
list: List containing the callsigns of EQSL users (unicode)
Raises:
IOError: ... | Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_.
Args:
url (str, optional): Download URL
Returns:
list: List containing the callsigns of EQSL users (unicode)
Raises:
IOError: When network is unavailable, file can... | Below is the the instruction that describes the task:
### Input:
Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_.
Args:
url (str, optional): Download URL
Returns:
list: List containing the callsigns of EQSL users (unicode)
... |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | Below is the the instruction that describes the task:
### Input:
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to c... |
def commit(self, container, repository=None, tag=None, message=None,
author=None, changes=None, conf=None):
"""
Commit a container to an image. Similar to the ``docker commit``
command.
Args:
container (str): The image hash of the container
reposit... | Commit a container to an image. Similar to the ``docker commit``
command.
Args:
container (str): The image hash of the container
repository (str): The repository to push the image to
tag (str): The tag to push
message (str): A commit message
a... | Below is the the instruction that describes the task:
### Input:
Commit a container to an image. Similar to the ``docker commit``
command.
Args:
container (str): The image hash of the container
repository (str): The repository to push the image to
tag (str): The ... |
def get_qseq_dir(fc_dir):
"""Retrieve the qseq directory within Solexa flowcell output.
"""
machine_bc = os.path.join(fc_dir, "Data", "Intensities", "BaseCalls")
if os.path.exists(machine_bc):
return machine_bc
# otherwise assume we are in the qseq directory
# XXX What other cases can we... | Retrieve the qseq directory within Solexa flowcell output. | Below is the the instruction that describes the task:
### Input:
Retrieve the qseq directory within Solexa flowcell output.
### Response:
def get_qseq_dir(fc_dir):
"""Retrieve the qseq directory within Solexa flowcell output.
"""
machine_bc = os.path.join(fc_dir, "Data", "Intensities", "BaseCalls")
... |
def get_rlzs_by_gsim(self, trt_or_grp_id, sm_id=None):
"""
:param trt_or_grp_id: a tectonic region type or a source group ID
:param sm_id: source model ordinal (or None)
:returns: a dictionary gsim -> rlzs
"""
if isinstance(trt_or_grp_id, (int, U16, U32)): # grp_id
... | :param trt_or_grp_id: a tectonic region type or a source group ID
:param sm_id: source model ordinal (or None)
:returns: a dictionary gsim -> rlzs | Below is the the instruction that describes the task:
### Input:
:param trt_or_grp_id: a tectonic region type or a source group ID
:param sm_id: source model ordinal (or None)
:returns: a dictionary gsim -> rlzs
### Response:
def get_rlzs_by_gsim(self, trt_or_grp_id, sm_id=None):
"""
... |
def itemsbyscore(self, min='-inf', max='+inf', start=None, num=None,
reverse=None):
""" Return a range of |(member, score)| pairs from the sorted set name
with scores between @min and @max.
If @start and @num are specified, then return a slice
of the ran... | Return a range of |(member, score)| pairs from the sorted set name
with scores between @min and @max.
If @start and @num are specified, then return a slice
of the range.
@min: #int minimum score, or #str '-inf'
@max: #int minimum score, or #str '+inf'
... | Below is the the instruction that describes the task:
### Input:
Return a range of |(member, score)| pairs from the sorted set name
with scores between @min and @max.
If @start and @num are specified, then return a slice
of the range.
@min: #int minimum score, or #s... |
def pstdev(data):
"""Calculates the population standard deviation."""
#: http://stackoverflow.com/a/27758326
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/n # the population variance
return pvar**0.5 | Calculates the population standard deviation. | Below is the the instruction that describes the task:
### Input:
Calculates the population standard deviation.
### Response:
def pstdev(data):
"""Calculates the population standard deviation."""
#: http://stackoverflow.com/a/27758326
n = len(data)
if n < 2:
raise ValueError('variance requir... |
def apply_poisson_noise(data, random_state=None):
"""
Apply Poisson noise to an array, where the value of each element in
the input array represents the expected number of counts.
Each pixel in the output array is generated by drawing a random
sample from a Poisson distribution whose expectation va... | Apply Poisson noise to an array, where the value of each element in
the input array represents the expected number of counts.
Each pixel in the output array is generated by drawing a random
sample from a Poisson distribution whose expectation value is given
by the pixel value in the input array.
P... | Below is the the instruction that describes the task:
### Input:
Apply Poisson noise to an array, where the value of each element in
the input array represents the expected number of counts.
Each pixel in the output array is generated by drawing a random
sample from a Poisson distribution whose expecta... |
def collect(self):
"""Yields metrics from the collectors in the registry."""
collectors = None
with self._lock:
collectors = copy.copy(self._collector_to_names)
for collector in collectors:
for metric in collector.collect():
yield metric | Yields metrics from the collectors in the registry. | Below is the the instruction that describes the task:
### Input:
Yields metrics from the collectors in the registry.
### Response:
def collect(self):
"""Yields metrics from the collectors in the registry."""
collectors = None
with self._lock:
collectors = copy.copy(self._collect... |
def add_task_group(self, task_group, project):
"""AddTaskGroup.
[Preview API] Create a task group.
:param :class:`<TaskGroupCreateParameter> <azure.devops.v5_0.task_agent.models.TaskGroupCreateParameter>` task_group: Task group object to create.
:param str project: Project ID or project ... | AddTaskGroup.
[Preview API] Create a task group.
:param :class:`<TaskGroupCreateParameter> <azure.devops.v5_0.task_agent.models.TaskGroupCreateParameter>` task_group: Task group object to create.
:param str project: Project ID or project name
:rtype: :class:`<TaskGroup> <azure.devops.v5_... | Below is the the instruction that describes the task:
### Input:
AddTaskGroup.
[Preview API] Create a task group.
:param :class:`<TaskGroupCreateParameter> <azure.devops.v5_0.task_agent.models.TaskGroupCreateParameter>` task_group: Task group object to create.
:param str project: Project ID ... |
def _screen_buffer(self):
"""Setup the screen buffer from the C++ code."""
# get the address of the screen
address = _LIB.Screen(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(SCREEN_TENSOR)).contents
#... | Setup the screen buffer from the C++ code. | Below is the the instruction that describes the task:
### Input:
Setup the screen buffer from the C++ code.
### Response:
def _screen_buffer(self):
"""Setup the screen buffer from the C++ code."""
# get the address of the screen
address = _LIB.Screen(self._env)
# create a buffer fro... |
def parse_timestr(timestr):
"""
Parse a string describing a point in time.
"""
timedelta_secs = parse_timedelta(timestr)
sync_start = datetime.now()
if timedelta_secs:
target = datetime.now() + timedelta(seconds=timedelta_secs)
elif timestr.isdigit():
target = datetime.now()... | Parse a string describing a point in time. | Below is the the instruction that describes the task:
### Input:
Parse a string describing a point in time.
### Response:
def parse_timestr(timestr):
"""
Parse a string describing a point in time.
"""
timedelta_secs = parse_timedelta(timestr)
sync_start = datetime.now()
if timedelta_secs:
... |
def memoize_method(method):
"""Simple caching decorator."""
cache = {}
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""Caching wrapper."""
key = (args, tuple(sorted(kwargs.items())))
if key in cache:
return cache[key]
else:
result ... | Simple caching decorator. | Below is the the instruction that describes the task:
### Input:
Simple caching decorator.
### Response:
def memoize_method(method):
"""Simple caching decorator."""
cache = {}
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""Caching wrapper."""
key = (args, tuple(sor... |
def updateObj(self,event):
"""Put this object in the search box"""
name=w.objList.get("active")
w.SearchVar.set(name)
w.ObjInfo.set(objInfoDict[name])
return | Put this object in the search box | Below is the the instruction that describes the task:
### Input:
Put this object in the search box
### Response:
def updateObj(self,event):
"""Put this object in the search box"""
name=w.objList.get("active")
w.SearchVar.set(name)
w.ObjInfo.set(objInfoDict[name])
re... |
def get_pyof_obj_new_version(name, obj, new_version):
r"""Return a class attribute on a different pyof version.
This method receives the name of a class attribute, the class attribute
itself (object) and an openflow version.
The attribute will be evaluated and from it we will recover it... | r"""Return a class attribute on a different pyof version.
This method receives the name of a class attribute, the class attribute
itself (object) and an openflow version.
The attribute will be evaluated and from it we will recover its class
and the module where the class was defined.
... | Below is the the instruction that describes the task:
### Input:
r"""Return a class attribute on a different pyof version.
This method receives the name of a class attribute, the class attribute
itself (object) and an openflow version.
The attribute will be evaluated and from it we will rec... |
def astra_projection_geometry(geometry):
"""Create an ASTRA projection geometry from an ODL geometry object.
As of ASTRA version 1.7, the length values are not required any more to be
rescaled for 3D geometries and non-unit (but isotropic) voxel sizes.
Parameters
----------
geometry : `Geometr... | Create an ASTRA projection geometry from an ODL geometry object.
As of ASTRA version 1.7, the length values are not required any more to be
rescaled for 3D geometries and non-unit (but isotropic) voxel sizes.
Parameters
----------
geometry : `Geometry`
ODL projection geometry from which to... | Below is the the instruction that describes the task:
### Input:
Create an ASTRA projection geometry from an ODL geometry object.
As of ASTRA version 1.7, the length values are not required any more to be
rescaled for 3D geometries and non-unit (but isotropic) voxel sizes.
Parameters
----------
... |
def feature_path_unset(self):
"""Copy features to memory and remove the association of the feature file."""
if not self.feature_file:
raise IOError('No feature file to unset')
with open(self.feature_path) as handle:
feats = list(GFF.parse(handle))
if len(feat... | Copy features to memory and remove the association of the feature file. | Below is the the instruction that describes the task:
### Input:
Copy features to memory and remove the association of the feature file.
### Response:
def feature_path_unset(self):
"""Copy features to memory and remove the association of the feature file."""
if not self.feature_file:
ra... |
def p_duration_number_duration_unit(self, p):
'duration : NUMBER DURATION_UNIT'
logger.debug('duration = number %s, duration unit %s', p[1], p[2])
p[0] = Duration.from_quantity_unit(p[1], p[2]) | duration : NUMBER DURATION_UNIT | Below is the the instruction that describes the task:
### Input:
duration : NUMBER DURATION_UNIT
### Response:
def p_duration_number_duration_unit(self, p):
'duration : NUMBER DURATION_UNIT'
logger.debug('duration = number %s, duration unit %s', p[1], p[2])
p[0] = Duration.from_quantity_uni... |
def parse(value):
"""Parse the string date.
This supports the subset of ISO8601 used by xsd:time, but is lenient
with what is accepted, handling most reasonable syntax.
@param value: A time string.
@type value: str
@return: A time object.
@rtype: B{datetime}.I{t... | Parse the string date.
This supports the subset of ISO8601 used by xsd:time, but is lenient
with what is accepted, handling most reasonable syntax.
@param value: A time string.
@type value: str
@return: A time object.
@rtype: B{datetime}.I{time} | Below is the the instruction that describes the task:
### Input:
Parse the string date.
This supports the subset of ISO8601 used by xsd:time, but is lenient
with what is accepted, handling most reasonable syntax.
@param value: A time string.
@type value: str
@return: A time... |
def update_status_with_media(self, **params): # pragma: no cover
"""Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-referen... | Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update_with_media | Below is the the instruction that describes the task:
### Input:
Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-... |
def journals(self):
"""
Retrieve journals attribute for this very Issue
"""
try:
target = self._item_path
json_data = self._redmine.get(target % str(self.id),
parms={'include': 'journals'})
data = self._redmine... | Retrieve journals attribute for this very Issue | Below is the the instruction that describes the task:
### Input:
Retrieve journals attribute for this very Issue
### Response:
def journals(self):
"""
Retrieve journals attribute for this very Issue
"""
try:
target = self._item_path
json_data = self._redmine.... |
def read_file(self, changeset_file):
"""Download the replication changeset file or read it directly from the
filesystem (to test purposes).
"""
if isfile(changeset_file):
self.filename = changeset_file
else:
self.path = mkdtemp()
self.filename ... | Download the replication changeset file or read it directly from the
filesystem (to test purposes). | Below is the the instruction that describes the task:
### Input:
Download the replication changeset file or read it directly from the
filesystem (to test purposes).
### Response:
def read_file(self, changeset_file):
"""Download the replication changeset file or read it directly from the
fil... |
def load(self, ymlfile=None):
"""Load and process the YAML file"""
if ymlfile is not None:
self.ymlfile = ymlfile
try:
# If yaml should be 'cleaned' of document references
if self._clean:
self.data = self.process(self.ymlfile)
else... | Load and process the YAML file | Below is the the instruction that describes the task:
### Input:
Load and process the YAML file
### Response:
def load(self, ymlfile=None):
"""Load and process the YAML file"""
if ymlfile is not None:
self.ymlfile = ymlfile
try:
# If yaml should be 'cleaned' of docu... |
def remove(self, option):
"""
Removes an option from a Config instance
IN: option (type: Option)
"""
if option.__class__ == Option:
if option in self.options:
del self.options[self.options.index(option)]
else:
raise OptionNotFoundError(option.name)
else:
raise TypeError("invalid type suppli... | Removes an option from a Config instance
IN: option (type: Option) | Below is the the instruction that describes the task:
### Input:
Removes an option from a Config instance
IN: option (type: Option)
### Response:
def remove(self, option):
"""
Removes an option from a Config instance
IN: option (type: Option)
"""
if option.__class__ == Option:
if option in self.opti... |
def get(self, name):
"""
Get an asset from the ZIP archive.
Parameters
-------------
name : str
Name of the asset
Returns
-------------
data : bytes
Loaded data from asset
"""
# not much we can do with that
if ... | Get an asset from the ZIP archive.
Parameters
-------------
name : str
Name of the asset
Returns
-------------
data : bytes
Loaded data from asset | Below is the the instruction that describes the task:
### Input:
Get an asset from the ZIP archive.
Parameters
-------------
name : str
Name of the asset
Returns
-------------
data : bytes
Loaded data from asset
### Response:
def get(self, name)... |
def line_items(self):
"""Apply a datetime filter against the contributors's line item queryset."""
if self._line_items is None:
self._line_items = self.contributor.line_items.filter(
payment_date__range=(self.start, self.end)
)
return self._line_items | Apply a datetime filter against the contributors's line item queryset. | Below is the the instruction that describes the task:
### Input:
Apply a datetime filter against the contributors's line item queryset.
### Response:
def line_items(self):
"""Apply a datetime filter against the contributors's line item queryset."""
if self._line_items is None:
self._lin... |
def update_qos_aggregated_configuration(self, qos_configuration, timeout=-1):
"""
Updates the QoS aggregated configuration for the logical interconnect.
Args:
qos_configuration:
QOS configuration.
timeout:
Timeout in seconds. Wait for task... | Updates the QoS aggregated configuration for the logical interconnect.
Args:
qos_configuration:
QOS configuration.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
OneView, just ... | Below is the the instruction that describes the task:
### Input:
Updates the QoS aggregated configuration for the logical interconnect.
Args:
qos_configuration:
QOS configuration.
timeout:
Timeout in seconds. Wait for task completion by default. The t... |
def commit(self):
"""
As in DBAPI2.0:
Commit any pending transaction to the database. Note that
if the database supports an auto-commit feature, this must
be initially off. An interface method may be provided to
turn it back on.
Database modules that do not suppo... | As in DBAPI2.0:
Commit any pending transaction to the database. Note that
if the database supports an auto-commit feature, this must
be initially off. An interface method may be provided to
turn it back on.
Database modules that do not support transactions should
impleme... | Below is the the instruction that describes the task:
### Input:
As in DBAPI2.0:
Commit any pending transaction to the database. Note that
if the database supports an auto-commit feature, this must
be initially off. An interface method may be provided to
turn it back on.
Dat... |
def long_description():
"""Generate .rst document for PyPi."""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--doc', dest="doc",
action="store_true", default=False)
args, sys.argv = parser.parse_known_args(sys.argv)
if args.doc:
import doc2md, pypand... | Generate .rst document for PyPi. | Below is the the instruction that describes the task:
### Input:
Generate .rst document for PyPi.
### Response:
def long_description():
"""Generate .rst document for PyPi."""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--doc', dest="doc",
action="store_true",... |
def run_flag_maf_zero(in_prefix, in_type, out_prefix, base_dir, options):
"""Runs step11 (flag MAF zero).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: th... | Runs step11 (flag MAF zero).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: the options needed.
:type in_prefix: str
:type in_type: str
:type out_... | Below is the the instruction that describes the task:
### Input:
Runs step11 (flag MAF zero).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: the options ne... |
def preprocess(string):
"""
Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string
"""
split = string.split('${')
rval = [split[0]]
for candidate... | Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string | Below is the the instruction that describes the task:
### Input:
Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string
### Response:
def preprocess(string):
"""
... |
def assign(self, droplet_id):
"""
Assign a FloatingIP to a Droplet.
Args:
droplet_id: int - droplet id
"""
return self.get_data(
"floating_ips/%s/actions/" % self.ip,
type=POST,
params={"type": "assign", "droplet_id": d... | Assign a FloatingIP to a Droplet.
Args:
droplet_id: int - droplet id | Below is the the instruction that describes the task:
### Input:
Assign a FloatingIP to a Droplet.
Args:
droplet_id: int - droplet id
### Response:
def assign(self, droplet_id):
"""
Assign a FloatingIP to a Droplet.
Args:
droplet_id: int... |
def generate_about_table(extra_info={}):
"""
Make a table with information about FlowCal and the current analysis.
Parameters
----------
extra_info : dict, optional
Additional keyword:value pairs to include in the table.
Returns
-------
about_table : DataFrame
Table wit... | Make a table with information about FlowCal and the current analysis.
Parameters
----------
extra_info : dict, optional
Additional keyword:value pairs to include in the table.
Returns
-------
about_table : DataFrame
Table with information about FlowCal and the current analysis,... | Below is the the instruction that describes the task:
### Input:
Make a table with information about FlowCal and the current analysis.
Parameters
----------
extra_info : dict, optional
Additional keyword:value pairs to include in the table.
Returns
-------
about_table : DataFrame
... |
def remove_label(self, name):
"""Removes label ``name`` from this issue.
:param str name: (required), name of the label to remove
:returns: bool
"""
url = self._build_url('labels', name, base_url=self._api)
# Docs say it should be a list of strings returned, practice say... | Removes label ``name`` from this issue.
:param str name: (required), name of the label to remove
:returns: bool | Below is the the instruction that describes the task:
### Input:
Removes label ``name`` from this issue.
:param str name: (required), name of the label to remove
:returns: bool
### Response:
def remove_label(self, name):
"""Removes label ``name`` from this issue.
:param str name: ... |
def _draw_placeholder(self):
"""To be used in QTreeView"""
if self.model().rowCount() == 0:
painter = QPainter(self.viewport())
painter.setFont(_custom_font(is_italic=True))
painter.drawText(self.rect().adjusted(0, 0, -5, -5), Qt.AlignCenter | Qt.TextWordWrap,
... | To be used in QTreeView | Below is the the instruction that describes the task:
### Input:
To be used in QTreeView
### Response:
def _draw_placeholder(self):
"""To be used in QTreeView"""
if self.model().rowCount() == 0:
painter = QPainter(self.viewport())
painter.setFont(_custom_font(is_italic=True)... |
def get_file_path(self, digest):
"""Retrieve the absolute path to the file with the given digest
Args:
digest -- digest of the file
Returns:
String rapresenting the absolute path of the file
"""
relPath = Fsdb.generate_tree_path(digest, self._conf['de... | Retrieve the absolute path to the file with the given digest
Args:
digest -- digest of the file
Returns:
String rapresenting the absolute path of the file | Below is the the instruction that describes the task:
### Input:
Retrieve the absolute path to the file with the given digest
Args:
digest -- digest of the file
Returns:
String rapresenting the absolute path of the file
### Response:
def get_file_path(self, digest):
... |
def ifind_first_object(self, ObjectClass, **kwargs):
""" Retrieve the first object of type ``ObjectClass``,
matching the specified filters in ``**kwargs`` -- case insensitive.
| If USER_IFIND_MODE is 'nocase_collation' this method maps to find_first_object().
| If USER_IFIND_MODE is 'if... | Retrieve the first object of type ``ObjectClass``,
matching the specified filters in ``**kwargs`` -- case insensitive.
| If USER_IFIND_MODE is 'nocase_collation' this method maps to find_first_object().
| If USER_IFIND_MODE is 'ifind' this method performs a case insensitive find. | Below is the the instruction that describes the task:
### Input:
Retrieve the first object of type ``ObjectClass``,
matching the specified filters in ``**kwargs`` -- case insensitive.
| If USER_IFIND_MODE is 'nocase_collation' this method maps to find_first_object().
| If USER_IFIND_MODE is... |
def errors(self):
"""
Returns a TupleErrorList for this field. This overloaded method adds additional error lists
to the errors as detected by the form validator.
"""
if not hasattr(self, '_errors_cache'):
self._errors_cache = self.form.get_field_errors(self)
... | Returns a TupleErrorList for this field. This overloaded method adds additional error lists
to the errors as detected by the form validator. | Below is the the instruction that describes the task:
### Input:
Returns a TupleErrorList for this field. This overloaded method adds additional error lists
to the errors as detected by the form validator.
### Response:
def errors(self):
"""
Returns a TupleErrorList for this field. This ove... |
def request_data(self):
'''在调用dialog.run()之前先调用这个函数来获取数据'''
def on_tasks_received(info, error=None):
if error or not info:
logger.error('BTBrowserDialog.on_tasks_received: %s, %s.' %
(info, error))
return
if 'magnet_inf... | 在调用dialog.run()之前先调用这个函数来获取数据 | Below is the the instruction that describes the task:
### Input:
在调用dialog.run()之前先调用这个函数来获取数据
### Response:
def request_data(self):
'''在调用dialog.run()之前先调用这个函数来获取数据'''
def on_tasks_received(info, error=None):
if error or not info:
logger.error('BTBrowserDialog.on_tasks_... |
def compile(self, csdl):
""" Compile the given CSDL.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/compile
Raises a DataSiftApiException for any error given by the REST API, including CSDL compilation.
:param csdl: CSDL to compile
:... | Compile the given CSDL.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/compile
Raises a DataSiftApiException for any error given by the REST API, including CSDL compilation.
:param csdl: CSDL to compile
:type csdl: str
:returns: ... | Below is the the instruction that describes the task:
### Input:
Compile the given CSDL.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/compile
Raises a DataSiftApiException for any error given by the REST API, including CSDL compilation.
:param csd... |
def write(self, values):
"""
Write values to the targeted documents
Values need to be a dict as : {document_id: value}
"""
# Insert only for docs targeted by the target
filtered = {_id: value for _id, value in values.items() if _id in self._document_ids}
if not f... | Write values to the targeted documents
Values need to be a dict as : {document_id: value} | Below is the the instruction that describes the task:
### Input:
Write values to the targeted documents
Values need to be a dict as : {document_id: value}
### Response:
def write(self, values):
"""
Write values to the targeted documents
Values need to be a dict as : {document_id: va... |
def find_output_without_tag(self, tag):
"""
Find all files who do not have tag in self.tags
"""
# Enforce upper case
tag = tag.upper()
return FileList([i for i in self if tag not in i.tags]) | Find all files who do not have tag in self.tags | Below is the the instruction that describes the task:
### Input:
Find all files who do not have tag in self.tags
### Response:
def find_output_without_tag(self, tag):
"""
Find all files who do not have tag in self.tags
"""
# Enforce upper case
tag = tag.upper()
retur... |
def delete(self, path=None, method='DELETE', **options):
""" Equals :meth:`route` with a ``DELETE`` method parameter. """
return self.route(path, method, **options) | Equals :meth:`route` with a ``DELETE`` method parameter. | Below is the the instruction that describes the task:
### Input:
Equals :meth:`route` with a ``DELETE`` method parameter.
### Response:
def delete(self, path=None, method='DELETE', **options):
""" Equals :meth:`route` with a ``DELETE`` method parameter. """
return self.route(path, method, **options... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.