code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def system_generate_batch_inputs(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/generateBatchInputs API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method:-/system/generateBatchInputs
"""
return DXHTTPRequest('/system/generateBat... | Invokes the /system/generateBatchInputs API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method:-/system/generateBatchInputs | Below is the the instruction that describes the task:
### Input:
Invokes the /system/generateBatchInputs API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method:-/system/generateBatchInputs
### Response:
def system_generate_batch_inputs(input_params={}, always_retr... |
def create_dagrun(self,
run_id,
state,
execution_date,
start_date=None,
external_trigger=False,
conf=None,
session=None):
"""
Creates a dag run from t... | Creates a dag run from this dag including the tasks associated with this dag.
Returns the dag run.
:param run_id: defines the the run id for this dag run
:type run_id: str
:param execution_date: the execution date of this dag run
:type execution_date: datetime.datetime
:... | Below is the the instruction that describes the task:
### Input:
Creates a dag run from this dag including the tasks associated with this dag.
Returns the dag run.
:param run_id: defines the the run id for this dag run
:type run_id: str
:param execution_date: the execution date of t... |
def resolved_packages(self):
"""Return a list of PackageVariant objects, or None if the resolve did
not complete or was unsuccessful.
"""
if (self.status != SolverStatus.solved):
return None
final_phase = self.phase_stack[-1]
return final_phase._get_solved_va... | Return a list of PackageVariant objects, or None if the resolve did
not complete or was unsuccessful. | Below is the the instruction that describes the task:
### Input:
Return a list of PackageVariant objects, or None if the resolve did
not complete or was unsuccessful.
### Response:
def resolved_packages(self):
"""Return a list of PackageVariant objects, or None if the resolve did
not comple... |
def _advapi32_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False):
"""
Encrypts a value using an RSA public key via CryptoAPI
:param certificate_or_public_key:
A Certificate or PublicKey instance to encrypt with
:param data:
A byte string of the data to encrypt
:param... | Encrypts a value using an RSA public key via CryptoAPI
:param certificate_or_public_key:
A Certificate or PublicKey instance to encrypt with
:param data:
A byte string of the data to encrypt
:param rsa_oaep_padding:
If OAEP padding should be used instead of PKCS#1 v1.5
:raise... | Below is the the instruction that describes the task:
### Input:
Encrypts a value using an RSA public key via CryptoAPI
:param certificate_or_public_key:
A Certificate or PublicKey instance to encrypt with
:param data:
A byte string of the data to encrypt
:param rsa_oaep_padding:
... |
def add(request, kind, method, *args):
"""
add(request, "mixpanel", "track", "purchase", {order: "1234", amount: "100"})
add(request, "google", "push", ["_addTrans", "1234", "Gondor", "100"])
"""
request.session.setdefault(_key_name(kind), []).append({
"method": method,
"args": args
... | add(request, "mixpanel", "track", "purchase", {order: "1234", amount: "100"})
add(request, "google", "push", ["_addTrans", "1234", "Gondor", "100"]) | Below is the the instruction that describes the task:
### Input:
add(request, "mixpanel", "track", "purchase", {order: "1234", amount: "100"})
add(request, "google", "push", ["_addTrans", "1234", "Gondor", "100"])
### Response:
def add(request, kind, method, *args):
"""
add(request, "mixpanel", "track"... |
def main(bot):
"""
Entry point for the command line launcher.
:param bot: the IRC bot to run
:type bot: :class:`fatbotslim.irc.bot.IRC`
"""
greenlet = spawn(bot.run)
try:
greenlet.join()
except KeyboardInterrupt:
print '' # cosmetics matters
log.info("Killed by ... | Entry point for the command line launcher.
:param bot: the IRC bot to run
:type bot: :class:`fatbotslim.irc.bot.IRC` | Below is the the instruction that describes the task:
### Input:
Entry point for the command line launcher.
:param bot: the IRC bot to run
:type bot: :class:`fatbotslim.irc.bot.IRC`
### Response:
def main(bot):
"""
Entry point for the command line launcher.
:param bot: the IRC bot to run
... |
def text(what="sentence", *args, **kwargs):
"""An aggregator for all above defined public methods."""
if what == "character":
return character(*args, **kwargs)
elif what == "characters":
return characters(*args, **kwargs)
elif what == "word":
return word(*args, **kwargs)
eli... | An aggregator for all above defined public methods. | Below is the the instruction that describes the task:
### Input:
An aggregator for all above defined public methods.
### Response:
def text(what="sentence", *args, **kwargs):
"""An aggregator for all above defined public methods."""
if what == "character":
return character(*args, **kwargs)
eli... |
def repair_broken_bonds(self, slab, bonds):
"""
This method will find undercoordinated atoms due to slab
cleaving specified by the bonds parameter and move them
to the other surface to make sure the bond is kept intact.
In a future release of surface.py, the ghost_sites will be
... | This method will find undercoordinated atoms due to slab
cleaving specified by the bonds parameter and move them
to the other surface to make sure the bond is kept intact.
In a future release of surface.py, the ghost_sites will be
used to tell us how the repair bonds should look like.
... | Below is the the instruction that describes the task:
### Input:
This method will find undercoordinated atoms due to slab
cleaving specified by the bonds parameter and move them
to the other surface to make sure the bond is kept intact.
In a future release of surface.py, the ghost_sites will... |
def get_account(self, account):
'''
check the account whether in the protfolio dict or not
:param account: QA_Account
:return: QA_Account if in dict
None not in list
'''
try:
return self.get_account_by_cookie(account.account_cookie)
e... | check the account whether in the protfolio dict or not
:param account: QA_Account
:return: QA_Account if in dict
None not in list | Below is the the instruction that describes the task:
### Input:
check the account whether in the protfolio dict or not
:param account: QA_Account
:return: QA_Account if in dict
None not in list
### Response:
def get_account(self, account):
'''
check the account wh... |
def _await_descriptor_upload(tor_protocol, onion, progress, await_all_uploads):
"""
Internal helper.
:param tor_protocol: ITorControlProtocol instance
:param onion: IOnionService instance
:param progress: a progess callback, or None
:returns: a Deferred that fires once we've detected at leas... | Internal helper.
:param tor_protocol: ITorControlProtocol instance
:param onion: IOnionService instance
:param progress: a progess callback, or None
:returns: a Deferred that fires once we've detected at least one
descriptor upload for the service (as detected by listening for
HS_DES... | Below is the the instruction that describes the task:
### Input:
Internal helper.
:param tor_protocol: ITorControlProtocol instance
:param onion: IOnionService instance
:param progress: a progess callback, or None
:returns: a Deferred that fires once we've detected at least one
descripto... |
def eval_nonagg_call(self, exp):
"helper for eval_callx; evaluator for CallX that consume a single value"
# todo: get more concrete about argument counts
args=self.eval(exp.args)
if exp.f=='coalesce':
a,b=args # todo: does coalesce take more than 2 args?
return b if a is None else a
elif... | helper for eval_callx; evaluator for CallX that consume a single value | Below is the the instruction that describes the task:
### Input:
helper for eval_callx; evaluator for CallX that consume a single value
### Response:
def eval_nonagg_call(self, exp):
"helper for eval_callx; evaluator for CallX that consume a single value"
# todo: get more concrete about argument counts
... |
def _add_spin_magnitudes(self, structure):
"""
Replaces Spin.up/Spin.down with spin magnitudes specified
by mag_species_spin.
:param structure:
:return:
"""
for idx, site in enumerate(structure):
if getattr(site.specie, '_properties', None):
... | Replaces Spin.up/Spin.down with spin magnitudes specified
by mag_species_spin.
:param structure:
:return: | Below is the the instruction that describes the task:
### Input:
Replaces Spin.up/Spin.down with spin magnitudes specified
by mag_species_spin.
:param structure:
:return:
### Response:
def _add_spin_magnitudes(self, structure):
"""
Replaces Spin.up/Spin.down with spin magnit... |
def _migrate_subresource(subresource, parent, migrations):
"""
Migrate a resource's subresource
:param subresource: the perch.SubResource instance
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource
"""
for key, doc in getattr(parent, subresour... | Migrate a resource's subresource
:param subresource: the perch.SubResource instance
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource | Below is the the instruction that describes the task:
### Input:
Migrate a resource's subresource
:param subresource: the perch.SubResource instance
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource
### Response:
def _migrate_subresource(subresource, pa... |
def gen_age(output, ascii_props=False, append=False, prefix=""):
"""Generate `age` property."""
obj = {}
all_chars = ALL_ASCII if ascii_props else ALL_CHARS
with codecs.open(os.path.join(HOME, 'unicodedata', UNIVERSION, 'DerivedAge.txt'), 'r', 'utf-8') as uf:
for line in uf:
if not ... | Generate `age` property. | Below is the the instruction that describes the task:
### Input:
Generate `age` property.
### Response:
def gen_age(output, ascii_props=False, append=False, prefix=""):
"""Generate `age` property."""
obj = {}
all_chars = ALL_ASCII if ascii_props else ALL_CHARS
with codecs.open(os.path.join(HOME, '... |
def make_success_redirect(self):
""" Return a Django ``HttpResponseRedirect`` describing the request success.
The custom authorization endpoint should return the result of this method
when the user grants the Client's authorization request. The request is
assumed to have successfully been vetted by the... | Return a Django ``HttpResponseRedirect`` describing the request success.
The custom authorization endpoint should return the result of this method
when the user grants the Client's authorization request. The request is
assumed to have successfully been vetted by the :py:meth:`validate` method. | Below is the the instruction that describes the task:
### Input:
Return a Django ``HttpResponseRedirect`` describing the request success.
The custom authorization endpoint should return the result of this method
when the user grants the Client's authorization request. The request is
assumed to have suc... |
def short_dask_repr(array, show_dtype=True):
"""Similar to dask.array.DataArray.__repr__, but without
redundant information that's already printed by the repr
function of the xarray wrapper.
"""
chunksize = tuple(c[0] for c in array.chunks)
if show_dtype:
return 'dask.array<shape={}, dty... | Similar to dask.array.DataArray.__repr__, but without
redundant information that's already printed by the repr
function of the xarray wrapper. | Below is the the instruction that describes the task:
### Input:
Similar to dask.array.DataArray.__repr__, but without
redundant information that's already printed by the repr
function of the xarray wrapper.
### Response:
def short_dask_repr(array, show_dtype=True):
"""Similar to dask.array.DataArray._... |
def add(repo, args, targetdir,
execute=False, generator=False,
includes=[], script=False,
source=None):
"""
Add files to the repository by explicitly specifying them or by
specifying a pattern over files accessed during execution of an
executable.
Parameters
----------
... | Add files to the repository by explicitly specifying them or by
specifying a pattern over files accessed during execution of an
executable.
Parameters
----------
repo: Repository
args: files or command line
(a) If simply adding files, then the list of files that must
be adde... | Below is the the instruction that describes the task:
### Input:
Add files to the repository by explicitly specifying them or by
specifying a pattern over files accessed during execution of an
executable.
Parameters
----------
repo: Repository
args: files or command line
(a) If s... |
def build_ast_schema(
document_ast: DocumentNode,
assume_valid: bool = False,
assume_valid_sdl: bool = False,
) -> GraphQLSchema:
"""Build a GraphQL Schema from a given AST.
This takes the ast of a schema document produced by the parse function in
src/language/parser.py.
If no schema defin... | Build a GraphQL Schema from a given AST.
This takes the ast of a schema document produced by the parse function in
src/language/parser.py.
If no schema definition is provided, then it will look for types named Query
and Mutation.
Given that AST it constructs a GraphQLSchema. The resulting schema ... | Below is the the instruction that describes the task:
### Input:
Build a GraphQL Schema from a given AST.
This takes the ast of a schema document produced by the parse function in
src/language/parser.py.
If no schema definition is provided, then it will look for types named Query
and Mutation.
... |
def variable_declaration(self):
"""
variable_declaration: 'let' assignment ';'
"""
self._process(Nature.LET)
node = VariableDeclaration(assignment=self.assignment())
self._process(Nature.SEMI)
return node | variable_declaration: 'let' assignment ';' | Below is the the instruction that describes the task:
### Input:
variable_declaration: 'let' assignment ';'
### Response:
def variable_declaration(self):
"""
variable_declaration: 'let' assignment ';'
"""
self._process(Nature.LET)
node = VariableDeclaration(assignment=self.a... |
def DEBUG(msg, *args, **kwargs):
"""temporary logger during development that is always on"""
logger = getLogger("DEBUG")
if len(logger.handlers) == 0:
logger.addHandler(StreamHandler())
logger.propagate = False
logger.setLevel(logging.DEBUG)
logger.DEV(msg, *args, **kwargs) | temporary logger during development that is always on | Below is the the instruction that describes the task:
### Input:
temporary logger during development that is always on
### Response:
def DEBUG(msg, *args, **kwargs):
"""temporary logger during development that is always on"""
logger = getLogger("DEBUG")
if len(logger.handlers) == 0:
logger.addH... |
def AddProperty(self, interface, name, value):
'''Add property to this object
interface: D-Bus interface to add this to. For convenience you can
specify '' here to add the property to the object's main
interface (as specified on construction).
name: Propert... | Add property to this object
interface: D-Bus interface to add this to. For convenience you can
specify '' here to add the property to the object's main
interface (as specified on construction).
name: Property name.
value: Property value. | Below is the the instruction that describes the task:
### Input:
Add property to this object
interface: D-Bus interface to add this to. For convenience you can
specify '' here to add the property to the object's main
interface (as specified on construction).
na... |
def ensure_table_strings(table):
"""
Force each cell in the table to be a string
Parameters
----------
table : list of lists
Returns
-------
table : list of lists of str
"""
for row in range(len(table)):
for column in range(len(table[row])):
table[row][colum... | Force each cell in the table to be a string
Parameters
----------
table : list of lists
Returns
-------
table : list of lists of str | Below is the the instruction that describes the task:
### Input:
Force each cell in the table to be a string
Parameters
----------
table : list of lists
Returns
-------
table : list of lists of str
### Response:
def ensure_table_strings(table):
"""
Force each cell in the table to ... |
def verbose(self):
"""
Make it the verbose log.
A verbose log can be only shown when user want to see more logs.
It works as::
log.verbose.warn('this is a verbose warn')
log.verbose.info('this is a verbose info')
"""
log = copy.copy(self)
... | Make it the verbose log.
A verbose log can be only shown when user want to see more logs.
It works as::
log.verbose.warn('this is a verbose warn')
log.verbose.info('this is a verbose info') | Below is the the instruction that describes the task:
### Input:
Make it the verbose log.
A verbose log can be only shown when user want to see more logs.
It works as::
log.verbose.warn('this is a verbose warn')
log.verbose.info('this is a verbose info')
### Response:
def ... |
def GET_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ
""" Edit a task """
if not id_checker(taskid):
raise Exception("Invalid task id")
self.get_course_and_check_rights(courseid, allow_all_staff=False)
request = web.input()
if request.get("action... | Edit a task | Below is the the instruction that describes the task:
### Input:
Edit a task
### Response:
def GET_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ
""" Edit a task """
if not id_checker(taskid):
raise Exception("Invalid task id")
self.get_course_and_check_right... |
def latitude(self, dms: bool = False) -> Union[str, float]:
"""Generate a random value of latitude.
:param dms: DMS format.
:return: Value of longitude.
"""
return self._get_fs('lt', dms) | Generate a random value of latitude.
:param dms: DMS format.
:return: Value of longitude. | Below is the the instruction that describes the task:
### Input:
Generate a random value of latitude.
:param dms: DMS format.
:return: Value of longitude.
### Response:
def latitude(self, dms: bool = False) -> Union[str, float]:
"""Generate a random value of latitude.
:param dms: ... |
def parse_package_string(path):
"""
Parse the effect package string.
Can contain the package python path or path to effect class in an effect package.
Examples::
# Path to effect pacakge
examples.cubes
# Path to effect class
examples.cubes.Cubes
Args:
path... | Parse the effect package string.
Can contain the package python path or path to effect class in an effect package.
Examples::
# Path to effect pacakge
examples.cubes
# Path to effect class
examples.cubes.Cubes
Args:
path: python path to effect package. May also in... | Below is the the instruction that describes the task:
### Input:
Parse the effect package string.
Can contain the package python path or path to effect class in an effect package.
Examples::
# Path to effect pacakge
examples.cubes
# Path to effect class
examples.cubes.Cube... |
def visit_pass(self, node, parent):
"""visit a Pass node by returning a fresh instance of it"""
return nodes.Pass(node.lineno, node.col_offset, parent) | visit a Pass node by returning a fresh instance of it | Below is the the instruction that describes the task:
### Input:
visit a Pass node by returning a fresh instance of it
### Response:
def visit_pass(self, node, parent):
"""visit a Pass node by returning a fresh instance of it"""
return nodes.Pass(node.lineno, node.col_offset, parent) |
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
for ufo in ufos:
font_name = self._font_name(ufo)
logger.info("Removing overlaps for " + font_name... | Remove overlaps in UFOs' glyphs' contours. | Below is the the instruction that describes the task:
### Input:
Remove overlaps in UFOs' glyphs' contours.
### Response:
def remove_overlaps(self, ufos, glyph_filter=lambda g: len(g)):
"""Remove overlaps in UFOs' glyphs' contours."""
from booleanOperations import union, BooleanOperationsError
... |
def run(arguments: List[str], execution_directory: str=None, execution_environment: Dict=None) -> str:
"""
Runs the given arguments from the given directory (if given, else resorts to the (undefined) current directory).
:param arguments: the CLI arguments to run
:param execution_directory: the directory... | Runs the given arguments from the given directory (if given, else resorts to the (undefined) current directory).
:param arguments: the CLI arguments to run
:param execution_directory: the directory to execute the arguments in
:param execution_environment: the environment to execute in
:return: what is w... | Below is the the instruction that describes the task:
### Input:
Runs the given arguments from the given directory (if given, else resorts to the (undefined) current directory).
:param arguments: the CLI arguments to run
:param execution_directory: the directory to execute the arguments in
:param execut... |
def get_pmap_from_nrml(oqparam, fname):
"""
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param fname:
an XML file containing hazard curves
:returns:
site mesh, curve array
"""
hcurves_by_imt = {}
oqparam.hazard_imtls = imtls = {}
... | :param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param fname:
an XML file containing hazard curves
:returns:
site mesh, curve array | Below is the the instruction that describes the task:
### Input:
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param fname:
an XML file containing hazard curves
:returns:
site mesh, curve array
### Response:
def get_pmap_from_nrml(oqparam, fname):
... |
def tell(self):
"""Returns the current position of read head.
"""
pos = ctypes.c_size_t()
check_call(_LIB.MXRecordIOReaderTell(self.handle, ctypes.byref(pos)))
return pos.value | Returns the current position of read head. | Below is the the instruction that describes the task:
### Input:
Returns the current position of read head.
### Response:
def tell(self):
"""Returns the current position of read head.
"""
pos = ctypes.c_size_t()
check_call(_LIB.MXRecordIOReaderTell(self.handle, ctypes.byref(pos)))
... |
def _add_post_data(self, request: Request):
'''Add data to the payload.'''
if self._item_session.url_record.post_data:
data = wpull.string.to_bytes(self._item_session.url_record.post_data)
else:
data = wpull.string.to_bytes(
self._processor.fetch_params.po... | Add data to the payload. | Below is the the instruction that describes the task:
### Input:
Add data to the payload.
### Response:
def _add_post_data(self, request: Request):
'''Add data to the payload.'''
if self._item_session.url_record.post_data:
data = wpull.string.to_bytes(self._item_session.url_record.post_... |
def scan_processes_fast(self):
"""
Populates the snapshot with running processes.
Only the PID is retrieved for each process.
Dead processes are removed.
Threads and modules of living processes are ignored.
Tipically you don't need to call this method directly, if unsur... | Populates the snapshot with running processes.
Only the PID is retrieved for each process.
Dead processes are removed.
Threads and modules of living processes are ignored.
Tipically you don't need to call this method directly, if unsure use
L{scan} instead.
@note: This... | Below is the the instruction that describes the task:
### Input:
Populates the snapshot with running processes.
Only the PID is retrieved for each process.
Dead processes are removed.
Threads and modules of living processes are ignored.
Tipically you don't need to call this method ... |
def get_uvec(vec):
""" Gets a unit vector parallel to input vector"""
l = np.linalg.norm(vec)
if l < 1e-8:
return vec
return vec / l | Gets a unit vector parallel to input vector | Below is the the instruction that describes the task:
### Input:
Gets a unit vector parallel to input vector
### Response:
def get_uvec(vec):
""" Gets a unit vector parallel to input vector"""
l = np.linalg.norm(vec)
if l < 1e-8:
return vec
return vec / l |
def add_ne(self, ne):
"""
Parameters
----------
ne : etree.Element
etree representation of a <ne> element
(marks a text span -- (one or more <node> or <word> elements) as a named entity)
Example
-------
<ne xml:id="ne_23" type="PER">
... | Parameters
----------
ne : etree.Element
etree representation of a <ne> element
(marks a text span -- (one or more <node> or <word> elements) as a named entity)
Example
-------
<ne xml:id="ne_23" type="PER">
<word xml:id="s3_2" form="Ute"... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
ne : etree.Element
etree representation of a <ne> element
(marks a text span -- (one or more <node> or <word> elements) as a named entity)
Example
-------
<ne x... |
def delete(self, id, **kwargs):
"""
Deletes an existing License
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function... | Deletes an existing License
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
... | Below is the the instruction that describes the task:
### Input:
Deletes an existing License
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def ... |
def _in_version(self, *versions):
"Returns true if this frame is in any of the specified versions of ID3."
for version in versions:
if (self._version == version
or (isinstance(self._version, collections.Container)
and version in self._version)):
... | Returns true if this frame is in any of the specified versions of ID3. | Below is the the instruction that describes the task:
### Input:
Returns true if this frame is in any of the specified versions of ID3.
### Response:
def _in_version(self, *versions):
"Returns true if this frame is in any of the specified versions of ID3."
for version in versions:
if (s... |
def generous_parse_uri(uri):
"""Return a urlparse.ParseResult object with the results of parsing the
given URI. This has the same properties as the result of parse_uri.
When passed a relative path, it determines the absolute path, sets the
scheme to file, the netloc to localhost and returns a parse of ... | Return a urlparse.ParseResult object with the results of parsing the
given URI. This has the same properties as the result of parse_uri.
When passed a relative path, it determines the absolute path, sets the
scheme to file, the netloc to localhost and returns a parse of the result. | Below is the the instruction that describes the task:
### Input:
Return a urlparse.ParseResult object with the results of parsing the
given URI. This has the same properties as the result of parse_uri.
When passed a relative path, it determines the absolute path, sets the
scheme to file, the netloc to ... |
def reconstruct_interval(experiment_id):
"""
Reverse the construct_experiment_id operation
:param experiment_id: The experiment id
:return: time interval
"""
start, end = map(lambda x: udatetime.utcfromtimestamp(x / 1000.0), map(float, experiment_id.split("-")))
from ..time_interval import T... | Reverse the construct_experiment_id operation
:param experiment_id: The experiment id
:return: time interval | Below is the the instruction that describes the task:
### Input:
Reverse the construct_experiment_id operation
:param experiment_id: The experiment id
:return: time interval
### Response:
def reconstruct_interval(experiment_id):
"""
Reverse the construct_experiment_id operation
:param experimen... |
def html(theme_name='readthedocs'):
# disable Flask RSTPAGES due to sphinx incompatibility
os.environ['RSTPAGES'] = 'FALSE'
theme(theme_name)
api()
man()
"""build the doc locally and view"""
clean()
local("cd docs; make html")
local("fab security.check")
local("touch docs/build/h... | build the doc locally and view | Below is the the instruction that describes the task:
### Input:
build the doc locally and view
### Response:
def html(theme_name='readthedocs'):
# disable Flask RSTPAGES due to sphinx incompatibility
os.environ['RSTPAGES'] = 'FALSE'
theme(theme_name)
api()
man()
"""build the doc locally an... |
def bulk_call(self, call_params):
"""REST BulkCalls Helper
"""
path = '/' + self.api_version + '/BulkCall/'
method = 'POST'
return self.request(path, method, call_params) | REST BulkCalls Helper | Below is the the instruction that describes the task:
### Input:
REST BulkCalls Helper
### Response:
def bulk_call(self, call_params):
"""REST BulkCalls Helper
"""
path = '/' + self.api_version + '/BulkCall/'
method = 'POST'
return self.request(path, method, call_params) |
def predict(self, X):
"""Rank samples according to survival times
Lower ranks indicate shorter survival, higher ranks longer survival.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Returns
-------
y... | Rank samples according to survival times
Lower ranks indicate shorter survival, higher ranks longer survival.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape = (n_samples,)
... | Below is the the instruction that describes the task:
### Input:
Rank samples according to survival times
Lower ranks indicate shorter survival, higher ranks longer survival.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
... |
def items(self):
"""Get the items fetched by the jobs."""
# Get and remove queued items in an atomic transaction
pipe = self.conn.pipeline()
pipe.lrange(Q_STORAGE_ITEMS, 0, -1)
pipe.ltrim(Q_STORAGE_ITEMS, 1, 0)
items = pipe.execute()[0]
for item in items:
... | Get the items fetched by the jobs. | Below is the the instruction that describes the task:
### Input:
Get the items fetched by the jobs.
### Response:
def items(self):
"""Get the items fetched by the jobs."""
# Get and remove queued items in an atomic transaction
pipe = self.conn.pipeline()
pipe.lrange(Q_STORAGE_ITEMS... |
async def dump_blob(elem, elem_type=None):
"""
Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_is_blob = isinstance(elem, x.BlobType)
data = getattr(elem, x.BlobType.DATA_ATTR) if elem_is_bl... | Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return: | Below is the the instruction that describes the task:
### Input:
Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
### Response:
async def dump_blob(elem, elem_type=None):
"""
Dumps blob message.
Supports... |
def from_shapefile(cls, shapefile, *args, **kwargs):
"""
Loads a shapefile from disk and optionally merges
it with a dataset. See ``from_records`` for full
signature.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator contain... | Loads a shapefile from disk and optionally merges
it with a dataset. See ``from_records`` for full
signature.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator containing Records.
dataset: holoviews.Dataset
Any HoloViews ... | Below is the the instruction that describes the task:
### Input:
Loads a shapefile from disk and optionally merges
it with a dataset. See ``from_records`` for full
signature.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator containing ... |
def similar(self, **kwargs):
"""
Get the similar TV series for a specific TV series id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any TV metho... | Get the similar TV series for a specific TV series id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any TV method.
Returns:
A dict respresen... | Below is the the instruction that describes the task:
### Input:
Get the similar TV series for a specific TV series id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma sep... |
def _apply_dvs_capability(capability_spec, capability_dict):
'''
Applies the values of the capability_dict dictionary to a DVS capability
object (vim.vim.DVSCapability)
'''
if 'operation_supported' in capability_dict:
capability_spec.dvsOperationSupported = \
capability_dict[... | Applies the values of the capability_dict dictionary to a DVS capability
object (vim.vim.DVSCapability) | Below is the the instruction that describes the task:
### Input:
Applies the values of the capability_dict dictionary to a DVS capability
object (vim.vim.DVSCapability)
### Response:
def _apply_dvs_capability(capability_spec, capability_dict):
'''
Applies the values of the capability_dict dictionary to... |
def parse_manifest(path_to_manifest):
"""
Parses manifest file for Toil Germline Pipeline
:param str path_to_manifest: Path to sample manifest file
:return: List of GermlineSample namedtuples
:rtype: list[GermlineSample]
"""
bam_re = r"^(?P<uuid>\S+)\s(?P<url>\S+[bsc][r]?am)"
fq_re = r"... | Parses manifest file for Toil Germline Pipeline
:param str path_to_manifest: Path to sample manifest file
:return: List of GermlineSample namedtuples
:rtype: list[GermlineSample] | Below is the the instruction that describes the task:
### Input:
Parses manifest file for Toil Germline Pipeline
:param str path_to_manifest: Path to sample manifest file
:return: List of GermlineSample namedtuples
:rtype: list[GermlineSample]
### Response:
def parse_manifest(path_to_manifest):
""... |
def rnd_date(start=date(1970, 1, 1), end=None, **kwargs):
"""
Generate a random date between ``start`` to ``end``.
:param start: Left bound
:type start: string or datetime.date, (default date(1970, 1, 1))
:param end: Right bound
:type end: string or datetime.date, (default date.today())
:re... | Generate a random date between ``start`` to ``end``.
:param start: Left bound
:type start: string or datetime.date, (default date(1970, 1, 1))
:param end: Right bound
:type end: string or datetime.date, (default date.today())
:return: a datetime.date object
**中文文档**
随机生成一个位于 ``start`` 和 `... | Below is the the instruction that describes the task:
### Input:
Generate a random date between ``start`` to ``end``.
:param start: Left bound
:type start: string or datetime.date, (default date(1970, 1, 1))
:param end: Right bound
:type end: string or datetime.date, (default date.today())
:ret... |
def close(self):
"""
Close service client and its plugins.
"""
self._execute_plugin_hooks_sync(hook='close')
if not self.session.closed:
ensure_future(self.session.close(), loop=self.loop) | Close service client and its plugins. | Below is the the instruction that describes the task:
### Input:
Close service client and its plugins.
### Response:
def close(self):
"""
Close service client and its plugins.
"""
self._execute_plugin_hooks_sync(hook='close')
if not self.session.closed:
ensure_f... |
def xcom_pull(
self,
task_ids=None,
dag_id=None,
key=XCOM_RETURN_KEY,
include_prior_dates=False):
"""
Pull XComs that optionally meet certain criteria.
The default value for `key` limits the search to XComs
that were returned b... | Pull XComs that optionally meet certain criteria.
The default value for `key` limits the search to XComs
that were returned by other tasks (as opposed to those that were pushed
manually). To remove this filter, pass key=None (or any desired value).
If a single task_id string is provide... | Below is the the instruction that describes the task:
### Input:
Pull XComs that optionally meet certain criteria.
The default value for `key` limits the search to XComs
that were returned by other tasks (as opposed to those that were pushed
manually). To remove this filter, pass key=None (... |
def getAnalystName(self):
""" Returns the name of the currently assigned analyst
"""
mtool = getToolByName(self, 'portal_membership')
analyst = self.getAnalyst().strip()
analyst_member = mtool.getMemberById(analyst)
if analyst_member is not None:
return analys... | Returns the name of the currently assigned analyst | Below is the the instruction that describes the task:
### Input:
Returns the name of the currently assigned analyst
### Response:
def getAnalystName(self):
""" Returns the name of the currently assigned analyst
"""
mtool = getToolByName(self, 'portal_membership')
analyst = self.getA... |
def seek(self, pos):
""" Move to new input file position. If position is negative or out of file, raise Exception. """
if (pos > self.file_size) or (pos < 0):
raise Exception("Unable to seek - position out of file!")
self.file.seek(pos) | Move to new input file position. If position is negative or out of file, raise Exception. | Below is the the instruction that describes the task:
### Input:
Move to new input file position. If position is negative or out of file, raise Exception.
### Response:
def seek(self, pos):
""" Move to new input file position. If position is negative or out of file, raise Exception. """
if (pos > s... |
def to_list(self):
"""Converts the GeneSet object to a flat list of strings.
Note: see also :meth:`from_list`.
Parameters
----------
Returns
-------
list of str
The data from the GeneSet object as a flat list.
"""
src = self._source ... | Converts the GeneSet object to a flat list of strings.
Note: see also :meth:`from_list`.
Parameters
----------
Returns
-------
list of str
The data from the GeneSet object as a flat list. | Below is the the instruction that describes the task:
### Input:
Converts the GeneSet object to a flat list of strings.
Note: see also :meth:`from_list`.
Parameters
----------
Returns
-------
list of str
The data from the GeneSet object as a flat list.
... |
def spectral_registration(data, target, initial_guess=(0.0, 0.0), frequency_range=None):
"""
Performs the spectral registration method to calculate the frequency and
phase shifts between the input data and the reference spectrum target. The
frequency range over which the two spectra are compared can be ... | Performs the spectral registration method to calculate the frequency and
phase shifts between the input data and the reference spectrum target. The
frequency range over which the two spectra are compared can be specified to
exclude regions where the spectra differ.
:param data:
:param target:
:... | Below is the the instruction that describes the task:
### Input:
Performs the spectral registration method to calculate the frequency and
phase shifts between the input data and the reference spectrum target. The
frequency range over which the two spectra are compared can be specified to
exclude regions... |
def callback(self, request, **kwargs):
"""
Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template
"""
access_token = request.session['oauth_token'] + "#... | Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template | Below is the the instruction that describes the task:
### Input:
Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template
### Response:
def callback(self, request, **kwargs):
""... |
def custom_object_prefix_lax(instance):
"""Ensure custom objects follow lenient naming style conventions
for forward-compatibility.
"""
if (instance['type'] not in enums.TYPES and
instance['type'] not in enums.RESERVED_OBJECTS and
not CUSTOM_TYPE_LAX_PREFIX_RE.match(instance['typ... | Ensure custom objects follow lenient naming style conventions
for forward-compatibility. | Below is the the instruction that describes the task:
### Input:
Ensure custom objects follow lenient naming style conventions
for forward-compatibility.
### Response:
def custom_object_prefix_lax(instance):
"""Ensure custom objects follow lenient naming style conventions
for forward-compatibility.
... |
def enable_key(self):
"""Enable an existing API Key."""
print("This command will enable a disabled key.")
apiKeyID = input("API Key ID: ")
try:
key = self._curl_bitmex("/apiKey/enable",
postdict={"apiKeyID": apiKeyID})
print("Ke... | Enable an existing API Key. | Below is the the instruction that describes the task:
### Input:
Enable an existing API Key.
### Response:
def enable_key(self):
"""Enable an existing API Key."""
print("This command will enable a disabled key.")
apiKeyID = input("API Key ID: ")
try:
key = self._curl_bit... |
def split_path(path) :
"convenience routine for splitting a path into a list of components."
if isinstance(path, (tuple, list)) :
result = path # assume already split
elif path == "/" :
result = []
else :
if not path.startswith("/") or path.endswith("/") :
raise DBusE... | convenience routine for splitting a path into a list of components. | Below is the the instruction that describes the task:
### Input:
convenience routine for splitting a path into a list of components.
### Response:
def split_path(path) :
"convenience routine for splitting a path into a list of components."
if isinstance(path, (tuple, list)) :
result = path # assume... |
def replyToComment(self, repo_user, repo_name, pull_number,
body, in_reply_to):
"""
POST /repos/:owner/:repo/pulls/:number/comments
Like create, but reply to an existing comment.
:param body: The text of the comment.
:param in_reply_to: The comment ID to ... | POST /repos/:owner/:repo/pulls/:number/comments
Like create, but reply to an existing comment.
:param body: The text of the comment.
:param in_reply_to: The comment ID to reply to. | Below is the the instruction that describes the task:
### Input:
POST /repos/:owner/:repo/pulls/:number/comments
Like create, but reply to an existing comment.
:param body: The text of the comment.
:param in_reply_to: The comment ID to reply to.
### Response:
def replyToComment(self, repo... |
def _produce_return(self, cursor):
""" Calls callback once with generator.
:rtype: None
"""
self.callback(self._row_generator(cursor), *self.cb_args)
return None | Calls callback once with generator.
:rtype: None | Below is the the instruction that describes the task:
### Input:
Calls callback once with generator.
:rtype: None
### Response:
def _produce_return(self, cursor):
""" Calls callback once with generator.
:rtype: None
"""
self.callback(self._row_generator(cursor), *sel... |
def init(banner, hidden, backup):
"""Initialize a manage shell in current directory
$ manage init --banner="My awesome app shell"
initializing manage...
creating manage.yml
"""
manage_file = HIDDEN_MANAGE_FILE if hidden else MANAGE_FILE
if os.path.exists(manage_file):
if ... | Initialize a manage shell in current directory
$ manage init --banner="My awesome app shell"
initializing manage...
creating manage.yml | Below is the the instruction that describes the task:
### Input:
Initialize a manage shell in current directory
$ manage init --banner="My awesome app shell"
initializing manage...
creating manage.yml
### Response:
def init(banner, hidden, backup):
"""Initialize a manage shell in curren... |
def rc_params(usetex=None):
"""Returns a new `matplotlib.RcParams` with updated GWpy parameters
The updated parameters are globally stored as
`gwpy.plot.rc.GWPY_RCPARAMS`, with the updated TeX parameters as
`gwpy.plot.rc.GWPY_TEX_RCPARAMS`.
.. note::
This function doesn't apply the new `Rc... | Returns a new `matplotlib.RcParams` with updated GWpy parameters
The updated parameters are globally stored as
`gwpy.plot.rc.GWPY_RCPARAMS`, with the updated TeX parameters as
`gwpy.plot.rc.GWPY_TEX_RCPARAMS`.
.. note::
This function doesn't apply the new `RcParams` in any way, just
cre... | Below is the the instruction that describes the task:
### Input:
Returns a new `matplotlib.RcParams` with updated GWpy parameters
The updated parameters are globally stored as
`gwpy.plot.rc.GWPY_RCPARAMS`, with the updated TeX parameters as
`gwpy.plot.rc.GWPY_TEX_RCPARAMS`.
.. note::
This ... |
def calc_allowedremoterelieve_v1(self):
"""Get the allowed remote relieve of the last simulation step.
Required log sequence:
|LoggedAllowedRemoteRelieve|
Calculated flux sequence:
|AllowedRemoteRelieve|
Basic equation:
:math:`AllowedRemoteRelieve = LoggedAllowedRemoteRelieve`
... | Get the allowed remote relieve of the last simulation step.
Required log sequence:
|LoggedAllowedRemoteRelieve|
Calculated flux sequence:
|AllowedRemoteRelieve|
Basic equation:
:math:`AllowedRemoteRelieve = LoggedAllowedRemoteRelieve`
Example:
>>> from hydpy.models.dam imp... | Below is the the instruction that describes the task:
### Input:
Get the allowed remote relieve of the last simulation step.
Required log sequence:
|LoggedAllowedRemoteRelieve|
Calculated flux sequence:
|AllowedRemoteRelieve|
Basic equation:
:math:`AllowedRemoteRelieve = LoggedAllow... |
def validate(self, generator, axesToMove=None, **kwargs):
# type: (AGenerator, AAxesToMove, **Any) -> AConfigureParams
"""Validate configuration parameters and return validated parameters.
Doesn't take device state into account so can be run in any state
"""
iterations = 10
... | Validate configuration parameters and return validated parameters.
Doesn't take device state into account so can be run in any state | Below is the the instruction that describes the task:
### Input:
Validate configuration parameters and return validated parameters.
Doesn't take device state into account so can be run in any state
### Response:
def validate(self, generator, axesToMove=None, **kwargs):
# type: (AGenerator, AAxesTo... |
def get_current_cmus():
"""
Get the current song from cmus.
"""
result = subprocess.run('cmus-remote -Q'.split(' '), check=True,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
info = {}
for line in result.stdout.decode().split('\n'):
line = line.split(' ')... | Get the current song from cmus. | Below is the the instruction that describes the task:
### Input:
Get the current song from cmus.
### Response:
def get_current_cmus():
"""
Get the current song from cmus.
"""
result = subprocess.run('cmus-remote -Q'.split(' '), check=True,
stdout=subprocess.PIPE, stderr=... |
def validate_unique_items(value, **kwargs):
"""
Validator for ARRAY types to enforce that all array items must be unique.
"""
# we can't just look at the items themselves since 0 and False are treated
# the same as dictionary keys, and objects aren't hashable.
counter = collections.Counter((
... | Validator for ARRAY types to enforce that all array items must be unique. | Below is the the instruction that describes the task:
### Input:
Validator for ARRAY types to enforce that all array items must be unique.
### Response:
def validate_unique_items(value, **kwargs):
"""
Validator for ARRAY types to enforce that all array items must be unique.
"""
# we can't just look... |
def _extract_inner_match(self, candidate, offset):
"""Attempts to extract a match from candidate if the whole candidate
does not qualify as a match.
Arguments:
candidate -- The candidate text that might contain a phone number
offset -- The current offset of candidate within text... | Attempts to extract a match from candidate if the whole candidate
does not qualify as a match.
Arguments:
candidate -- The candidate text that might contain a phone number
offset -- The current offset of candidate within text
Returns the match found, None if none can be found | Below is the the instruction that describes the task:
### Input:
Attempts to extract a match from candidate if the whole candidate
does not qualify as a match.
Arguments:
candidate -- The candidate text that might contain a phone number
offset -- The current offset of candidate with... |
def _send_rpc_response(self, *packets):
"""Send an RPC response.
It is executed in the baBLE working thread: should not be blocking.
The RPC response is notified in one or two packets depending on whether or not
response data is included. If there is a temporary error sending one of the... | Send an RPC response.
It is executed in the baBLE working thread: should not be blocking.
The RPC response is notified in one or two packets depending on whether or not
response data is included. If there is a temporary error sending one of the packets
it is retried automatically. If th... | Below is the the instruction that describes the task:
### Input:
Send an RPC response.
It is executed in the baBLE working thread: should not be blocking.
The RPC response is notified in one or two packets depending on whether or not
response data is included. If there is a temporary error ... |
def stat(path, user=None):
"""
Performs the equivalent of :func:`os.stat` on ``path``, returning a
:class:`StatResult` object.
"""
host, port, path_ = split(path, user)
fs = hdfs_fs.hdfs(host, port, user)
retval = StatResult(fs.get_path_info(path_))
if not host:
_update_stat(retv... | Performs the equivalent of :func:`os.stat` on ``path``, returning a
:class:`StatResult` object. | Below is the the instruction that describes the task:
### Input:
Performs the equivalent of :func:`os.stat` on ``path``, returning a
:class:`StatResult` object.
### Response:
def stat(path, user=None):
"""
Performs the equivalent of :func:`os.stat` on ``path``, returning a
:class:`StatResult` objec... |
def _merge_keys(kwargs):
'''
The log_config is a mixture of the CLI options --log-driver and --log-opt
(which we support in Salt as log_driver and log_opt, respectively), but it
must be submitted to the host config in the format {'Type': log_driver,
'Config': log_opt}. So, we need to construct this ... | The log_config is a mixture of the CLI options --log-driver and --log-opt
(which we support in Salt as log_driver and log_opt, respectively), but it
must be submitted to the host config in the format {'Type': log_driver,
'Config': log_opt}. So, we need to construct this argument to be passed to
the API ... | Below is the the instruction that describes the task:
### Input:
The log_config is a mixture of the CLI options --log-driver and --log-opt
(which we support in Salt as log_driver and log_opt, respectively), but it
must be submitted to the host config in the format {'Type': log_driver,
'Config': log_opt}... |
def _priority(s):
"""Return priority for a given object."""
if type(s) in (list, tuple, set, frozenset):
return ITERABLE
if type(s) is dict:
return DICT
if issubclass(type(s), type):
return TYPE
if hasattr(s, "validate"):
return VALIDATOR
if callable(s):
r... | Return priority for a given object. | Below is the the instruction that describes the task:
### Input:
Return priority for a given object.
### Response:
def _priority(s):
"""Return priority for a given object."""
if type(s) in (list, tuple, set, frozenset):
return ITERABLE
if type(s) is dict:
return DICT
if issubclass(t... |
def permuted_copy(self, partition=None):
""" Return a copy of the collection with all alignment columns permuted
"""
def take(n, iterable):
return [next(iterable) for _ in range(n)]
if partition is None:
partition = Partition([1] * len(self))
index_tuple... | Return a copy of the collection with all alignment columns permuted | Below is the the instruction that describes the task:
### Input:
Return a copy of the collection with all alignment columns permuted
### Response:
def permuted_copy(self, partition=None):
""" Return a copy of the collection with all alignment columns permuted
"""
def take(n, iterable):
... |
def bounds(self, thr=0):
""" Gets the bounds of this segment
Returns:
(float, float, float, float): Bounds, with min latitude, min longitude,
max latitude and max longitude
"""
min_lat = float("inf")
min_lon = float("inf")
max_lat = -float("in... | Gets the bounds of this segment
Returns:
(float, float, float, float): Bounds, with min latitude, min longitude,
max latitude and max longitude | Below is the the instruction that describes the task:
### Input:
Gets the bounds of this segment
Returns:
(float, float, float, float): Bounds, with min latitude, min longitude,
max latitude and max longitude
### Response:
def bounds(self, thr=0):
""" Gets the bounds of... |
def getRoutes(self):
"""Get routing table.
@return: List of routes.
"""
routes = []
try:
out = subprocess.Popen([routeCmd, "-n"],
stdout=subprocess.PIPE).communicate()[0]
except:
raise Exception... | Get routing table.
@return: List of routes. | Below is the the instruction that describes the task:
### Input:
Get routing table.
@return: List of routes.
### Response:
def getRoutes(self):
"""Get routing table.
@return: List of routes.
"""
routes = []
try:
out = subprocess... |
def verify_multi(self, otp_list, max_time_window=DEFAULT_MAX_TIME_WINDOW,
sl=None, timeout=None):
"""
Verify a provided list of OTPs.
:param max_time_window: Maximum number of seconds which can pass
between the first and last OTP generation f... | Verify a provided list of OTPs.
:param max_time_window: Maximum number of seconds which can pass
between the first and last OTP generation for
the OTP to still be considered valid.
:type max_time_window: ``int`` | Below is the the instruction that describes the task:
### Input:
Verify a provided list of OTPs.
:param max_time_window: Maximum number of seconds which can pass
between the first and last OTP generation for
the OTP to still be considered vali... |
def mount_share_at_path(share_path, mount_path):
"""Mounts a share at the specified path
Args:
share_path: String URL with all auth info to connect to file share.
mount_path: Path to mount share on.
Returns:
The mount point or raises an error
"""
sh_url = CFURLCreateWithStr... | Mounts a share at the specified path
Args:
share_path: String URL with all auth info to connect to file share.
mount_path: Path to mount share on.
Returns:
The mount point or raises an error | Below is the the instruction that describes the task:
### Input:
Mounts a share at the specified path
Args:
share_path: String URL with all auth info to connect to file share.
mount_path: Path to mount share on.
Returns:
The mount point or raises an error
### Response:
def mount_s... |
def get_syllable_count(self, syllables: List[str]) -> int:
"""
Counts the number of syllable groups that would occur after ellision.
Often we will want preserve the position and separation of syllables so that they
can be used to reconstitute a line, and apply stresses to the original w... | Counts the number of syllable groups that would occur after ellision.
Often we will want preserve the position and separation of syllables so that they
can be used to reconstitute a line, and apply stresses to the original word positions.
However, we also want to be able to count the number of ... | Below is the the instruction that describes the task:
### Input:
Counts the number of syllable groups that would occur after ellision.
Often we will want preserve the position and separation of syllables so that they
can be used to reconstitute a line, and apply stresses to the original word positi... |
def signFix(val, width):
"""
Convert negative int to positive int which has same bits set
"""
if val > 0:
msb = 1 << (width - 1)
if val & msb:
val -= mask(width) + 1
return val | Convert negative int to positive int which has same bits set | Below is the the instruction that describes the task:
### Input:
Convert negative int to positive int which has same bits set
### Response:
def signFix(val, width):
"""
Convert negative int to positive int which has same bits set
"""
if val > 0:
msb = 1 << (width - 1)
if val & msb:
... |
def update(self, modelID, modelParams, modelParamsHash, metricResult,
completed, completionReason, matured, numRecords):
""" Insert a new entry or update an existing one. If this is an update
of an existing entry, then modelParams will be None
Parameters:
----------------------------------... | Insert a new entry or update an existing one. If this is an update
of an existing entry, then modelParams will be None
Parameters:
--------------------------------------------------------------------
modelID: globally unique modelID of this model
modelParams: params dict for this model, or... | Below is the the instruction that describes the task:
### Input:
Insert a new entry or update an existing one. If this is an update
of an existing entry, then modelParams will be None
Parameters:
--------------------------------------------------------------------
modelID: globally unique mod... |
def check_email_status(mx_resolver, recipient_address, sender_address, smtp_timeout=10, helo_hostname=None):
"""
Checks if an email might be valid by getting the status from the SMTP server.
:param mx_resolver: MXResolver
:param recipient_address: string
:param sender_address: string
:param smt... | Checks if an email might be valid by getting the status from the SMTP server.
:param mx_resolver: MXResolver
:param recipient_address: string
:param sender_address: string
:param smtp_timeout: integer
:param helo_hostname: string
:return: dict | Below is the the instruction that describes the task:
### Input:
Checks if an email might be valid by getting the status from the SMTP server.
:param mx_resolver: MXResolver
:param recipient_address: string
:param sender_address: string
:param smtp_timeout: integer
:param helo_hostname: string
... |
def run_breiman2():
"""Run Breiman's other sample problem."""
x, y = build_sample_ace_problem_breiman2(500)
ace_solver = ace.ACESolver()
ace_solver.specify_data_set(x, y)
ace_solver.solve()
try:
plt = ace.plot_transforms(ace_solver, None)
except ImportError:
pass
plt.sub... | Run Breiman's other sample problem. | Below is the the instruction that describes the task:
### Input:
Run Breiman's other sample problem.
### Response:
def run_breiman2():
"""Run Breiman's other sample problem."""
x, y = build_sample_ace_problem_breiman2(500)
ace_solver = ace.ACESolver()
ace_solver.specify_data_set(x, y)
ace_solve... |
def lstm_seq2seq_internal_attention_bid_encoder(inputs, targets, hparams,
train):
"""LSTM seq2seq model with attention, main step used for training."""
with tf.variable_scope("lstm_seq2seq_attention_bid_encoder"):
inputs_length = common_layers.length_from_embeddin... | LSTM seq2seq model with attention, main step used for training. | Below is the the instruction that describes the task:
### Input:
LSTM seq2seq model with attention, main step used for training.
### Response:
def lstm_seq2seq_internal_attention_bid_encoder(inputs, targets, hparams,
train):
"""LSTM seq2seq model with attention, ma... |
def get_keyboard_mapping_unchecked(conn):
"""
Return an unchecked keyboard mapping cookie that can be used to fetch the
table of keysyms in the current X environment.
:rtype: xcb.xproto.GetKeyboardMappingCookie
"""
mn, mx = get_min_max_keycode()
return conn.core.GetKeyboardMappingUnchecked... | Return an unchecked keyboard mapping cookie that can be used to fetch the
table of keysyms in the current X environment.
:rtype: xcb.xproto.GetKeyboardMappingCookie | Below is the the instruction that describes the task:
### Input:
Return an unchecked keyboard mapping cookie that can be used to fetch the
table of keysyms in the current X environment.
:rtype: xcb.xproto.GetKeyboardMappingCookie
### Response:
def get_keyboard_mapping_unchecked(conn):
"""
Return a... |
def tempo_account_get_customers(self, query=None, count_accounts=None):
"""
Gets all or some Attribute whose key or name contain a specific substring.
Attributes can be a Category or Customer.
:param query: OPTIONAL: query for search
:param count_accounts: bool OPTIONAL: provide ... | Gets all or some Attribute whose key or name contain a specific substring.
Attributes can be a Category or Customer.
:param query: OPTIONAL: query for search
:param count_accounts: bool OPTIONAL: provide how many associated Accounts with Customer
:return: list of customers | Below is the the instruction that describes the task:
### Input:
Gets all or some Attribute whose key or name contain a specific substring.
Attributes can be a Category or Customer.
:param query: OPTIONAL: query for search
:param count_accounts: bool OPTIONAL: provide how many associated Acc... |
def line_intersection_2D(abarg, cdarg):
'''
line_intersection((a, b), (c, d)) yields the intersection point between the lines that pass
through the given pairs of points. If any lines are parallel, (numpy.nan, numpy.nan) is
returned; note that a, b, c, and d can all be 2 x n matrices of x and y coordina... | line_intersection((a, b), (c, d)) yields the intersection point between the lines that pass
through the given pairs of points. If any lines are parallel, (numpy.nan, numpy.nan) is
returned; note that a, b, c, and d can all be 2 x n matrices of x and y coordinate row-vectors. | Below is the the instruction that describes the task:
### Input:
line_intersection((a, b), (c, d)) yields the intersection point between the lines that pass
through the given pairs of points. If any lines are parallel, (numpy.nan, numpy.nan) is
returned; note that a, b, c, and d can all be 2 x n matrices of... |
def pexpect_monkeypatch():
"""Patch pexpect to prevent unhandled exceptions at VM teardown.
Calling this function will monkeypatch the pexpect.spawn class and modify
its __del__ method to make it more robust in the face of failures that can
occur if it is called when the Python VM is shutting down.
... | Patch pexpect to prevent unhandled exceptions at VM teardown.
Calling this function will monkeypatch the pexpect.spawn class and modify
its __del__ method to make it more robust in the face of failures that can
occur if it is called when the Python VM is shutting down.
Since Python may fire __del__ me... | Below is the the instruction that describes the task:
### Input:
Patch pexpect to prevent unhandled exceptions at VM teardown.
Calling this function will monkeypatch the pexpect.spawn class and modify
its __del__ method to make it more robust in the face of failures that can
occur if it is called when ... |
def get(self):
"""Get a task from the queue."""
tasks = self._get_avaliable_tasks()
if not tasks:
return None
name, data = tasks[0]
self._client.kv.delete(name)
return data | Get a task from the queue. | Below is the the instruction that describes the task:
### Input:
Get a task from the queue.
### Response:
def get(self):
"""Get a task from the queue."""
tasks = self._get_avaliable_tasks()
if not tasks:
return None
name, data = tasks[0]
self._client.kv.delete(na... |
def do_alias(self, arg):
"""alias [name [command [parameter parameter ...] ]]
Create an alias called 'name' that executes 'command'. The
command must *not* be enclosed in quotes. Replaceable
parameters can be indicated by %1, %2, and so on, while %* is
replaced by all the param... | alias [name [command [parameter parameter ...] ]]
Create an alias called 'name' that executes 'command'. The
command must *not* be enclosed in quotes. Replaceable
parameters can be indicated by %1, %2, and so on, while %* is
replaced by all the parameters. If no command is given, the
... | Below is the the instruction that describes the task:
### Input:
alias [name [command [parameter parameter ...] ]]
Create an alias called 'name' that executes 'command'. The
command must *not* be enclosed in quotes. Replaceable
parameters can be indicated by %1, %2, and so on, while %* is
... |
def _set_datapath(self, datapath):
""" Set a datapath.
"""
if datapath:
self._datapath = datapath.rstrip(os.sep)
self._fifo = int(stat.S_ISFIFO(os.stat(self.datapath).st_mode))
else:
self._datapath = None
self._fifo = False | Set a datapath. | Below is the the instruction that describes the task:
### Input:
Set a datapath.
### Response:
def _set_datapath(self, datapath):
""" Set a datapath.
"""
if datapath:
self._datapath = datapath.rstrip(os.sep)
self._fifo = int(stat.S_ISFIFO(os.stat(self.datapath).st_mo... |
def count_snps(mat):
"""
get dstats from the count array and return as a float tuple
"""
## get [aabb, baba, abba, aaab]
snps = np.zeros(4, dtype=np.uint32)
## get concordant (aabb) pis sites
snps[0] = np.uint32(\
mat[0, 5] + mat[0, 10] + mat[0, 15] + \
mat[5, 0] +... | get dstats from the count array and return as a float tuple | Below is the the instruction that describes the task:
### Input:
get dstats from the count array and return as a float tuple
### Response:
def count_snps(mat):
"""
get dstats from the count array and return as a float tuple
"""
## get [aabb, baba, abba, aaab]
snps = np.zeros(4, dtype=np.uin... |
def lhistogram (inlist,numbins=10,defaultreallimits=None,printextras=0):
"""
Returns (i) a list of histogram bin counts, (ii) the smallest value
of the histogram binning, and (iii) the bin width (the last 2 are not
necessarily integers). Default number of bins is 10. If no sequence object
is given for defaultreal... | Returns (i) a list of histogram bin counts, (ii) the smallest value
of the histogram binning, and (iii) the bin width (the last 2 are not
necessarily integers). Default number of bins is 10. If no sequence object
is given for defaultreallimits, the routine picks (usually non-pretty) bins
spanning all the numbers in t... | Below is the the instruction that describes the task:
### Input:
Returns (i) a list of histogram bin counts, (ii) the smallest value
of the histogram binning, and (iii) the bin width (the last 2 are not
necessarily integers). Default number of bins is 10. If no sequence object
is given for defaultreallimits, the ... |
def get_pip(mov=None, api=None, name=None):
"""get value of pip"""
# ~ check args
if mov is None and api is None:
logger.error("need at least one of those")
raise ValueError()
elif mov is not None and api is not None:
logger.error("mov and api are exclusive")
raise ValueE... | get value of pip | Below is the the instruction that describes the task:
### Input:
get value of pip
### Response:
def get_pip(mov=None, api=None, name=None):
"""get value of pip"""
# ~ check args
if mov is None and api is None:
logger.error("need at least one of those")
raise ValueError()
elif mov is... |
def _dict_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
if _debug: Object._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
... | Return the contents of an object as a dict. | Below is the the instruction that describes the task:
### Input:
Return the contents of an object as a dict.
### Response:
def _dict_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
if _debug: Object._debug("dict_contents use_dict=%r as_class=%r", use_... |
def strip_docstrings(tokens):
"""Replace docstring tokens with NL tokens in a `tokenize` stream.
Any STRING token not part of an expression is deemed a docstring.
Indented docstrings are not yet recognised.
"""
stack = []
state = 'wait_string'
for t in tokens:
typ = t[0]
if ... | Replace docstring tokens with NL tokens in a `tokenize` stream.
Any STRING token not part of an expression is deemed a docstring.
Indented docstrings are not yet recognised. | Below is the the instruction that describes the task:
### Input:
Replace docstring tokens with NL tokens in a `tokenize` stream.
Any STRING token not part of an expression is deemed a docstring.
Indented docstrings are not yet recognised.
### Response:
def strip_docstrings(tokens):
"""Replace docstrin... |
def get_brandings(self):
"""
Get all account brandings
@return List of brandings
"""
connection = Connection(self.token)
connection.set_url(self.production, self.BRANDINGS_URL)
return connection.get_request() | Get all account brandings
@return List of brandings | Below is the the instruction that describes the task:
### Input:
Get all account brandings
@return List of brandings
### Response:
def get_brandings(self):
"""
Get all account brandings
@return List of brandings
"""
connection = Connection(self.token)
connec... |
def CopyVcardFields(new_vcard, auth_vcard, field_names):
"""Copy vCard field values from an authoritative vCard into a new one."""
for field in field_names:
value_list = auth_vcard.contents.get(field)
new_vcard = SetVcardField(new_vcard, field, value_list)
return new_vcard | Copy vCard field values from an authoritative vCard into a new one. | Below is the the instruction that describes the task:
### Input:
Copy vCard field values from an authoritative vCard into a new one.
### Response:
def CopyVcardFields(new_vcard, auth_vcard, field_names):
"""Copy vCard field values from an authoritative vCard into a new one."""
for field in field_names:
... |
def F_(self, X):
"""
computes h()
:param X:
:return:
"""
if self._interpol:
if not hasattr(self, '_F_interp'):
if self._lookup:
x = self._x_lookup
F_x = self._f_lookup
else:
... | computes h()
:param X:
:return: | Below is the the instruction that describes the task:
### Input:
computes h()
:param X:
:return:
### Response:
def F_(self, X):
"""
computes h()
:param X:
:return:
"""
if self._interpol:
if not hasattr(self, '_F_interp'):
... |
def write_info (self, url_data):
"""Write url_data.info."""
sep = u"<br/>"+os.linesep
text = sep.join(cgi.escape(x) for x in url_data.info)
self.writeln(u'<tr><td valign="top">' + self.part("info")+
u"</td><td>"+text+u"</td></tr>") | Write url_data.info. | Below is the the instruction that describes the task:
### Input:
Write url_data.info.
### Response:
def write_info (self, url_data):
"""Write url_data.info."""
sep = u"<br/>"+os.linesep
text = sep.join(cgi.escape(x) for x in url_data.info)
self.writeln(u'<tr><td valign="top">' + sel... |
def status(deps=DEPENDENCIES, linesep=os.linesep):
"""Return a status of dependencies"""
maxwidth = 0
col1 = []
col2 = []
for dependency in deps:
title1 = dependency.modname
title1 += ' ' + dependency.required_version
col1.append(title1)
maxwidth = max([maxwi... | Return a status of dependencies | Below is the the instruction that describes the task:
### Input:
Return a status of dependencies
### Response:
def status(deps=DEPENDENCIES, linesep=os.linesep):
"""Return a status of dependencies"""
maxwidth = 0
col1 = []
col2 = []
for dependency in deps:
title1 = dependency.modn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.