code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def remove_empty_dirs(path):
""" removes empty dirs under a given path """
for root, dirs, files in os.walk(path):
for d in dirs:
dir_path = os.path.join(root, d)
if not os.listdir(dir_path):
os.rmdir(dir_path) | removes empty dirs under a given path | Below is the the instruction that describes the task:
### Input:
removes empty dirs under a given path
### Response:
def remove_empty_dirs(path):
""" removes empty dirs under a given path """
for root, dirs, files in os.walk(path):
for d in dirs:
dir_path = os.path.join(root, d)
... |
def _at_block_start(tc, line):
"""
Improve QTextCursor.atBlockStart to ignore spaces
"""
if tc.atBlockStart():
return True
column = tc.columnNumber()
indentation = len(line) - len(line.lstrip())
return column <= indentation | Improve QTextCursor.atBlockStart to ignore spaces | Below is the the instruction that describes the task:
### Input:
Improve QTextCursor.atBlockStart to ignore spaces
### Response:
def _at_block_start(tc, line):
"""
Improve QTextCursor.atBlockStart to ignore spaces
"""
if tc.atBlockStart():
return True
column = tc... |
def interpretAsOpenMath(x):
"""tries to convert a Python object into an OpenMath object
this is not a replacement for using a Converter for exporting Python objects
instead, it is used conveniently building OM objects in DSL embedded in Python
inparticular, it converts Python functions into OMBinding ob... | tries to convert a Python object into an OpenMath object
this is not a replacement for using a Converter for exporting Python objects
instead, it is used conveniently building OM objects in DSL embedded in Python
inparticular, it converts Python functions into OMBinding objects using lambdaOM as the binder | Below is the the instruction that describes the task:
### Input:
tries to convert a Python object into an OpenMath object
this is not a replacement for using a Converter for exporting Python objects
instead, it is used conveniently building OM objects in DSL embedded in Python
inparticular, it converts ... |
def adjust_all_to_360(dictionary):
"""
Take a dictionary and check each key/value pair.
If this key is of type: declination/longitude/azimuth/direction,
adjust it to be within 0-360 as required by the MagIC data model
"""
for key in dictionary:
dictionary[key] = adjust_to_360(dictionary[... | Take a dictionary and check each key/value pair.
If this key is of type: declination/longitude/azimuth/direction,
adjust it to be within 0-360 as required by the MagIC data model | Below is the the instruction that describes the task:
### Input:
Take a dictionary and check each key/value pair.
If this key is of type: declination/longitude/azimuth/direction,
adjust it to be within 0-360 as required by the MagIC data model
### Response:
def adjust_all_to_360(dictionary):
"""
Ta... |
def show_one(request, post_process_fun, object_class, id, template='common_json.html'):
"""
Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
h... | Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
html
turn on the HTML version of the API | Below is the the instruction that describes the task:
### Input:
Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
html
turn on the HTML ve... |
def features(self):
"""All available features"""
mycols = []
for col in dfn.feature_names:
if col in self:
mycols.append(col)
mycols.sort()
return mycols | All available features | Below is the the instruction that describes the task:
### Input:
All available features
### Response:
def features(self):
"""All available features"""
mycols = []
for col in dfn.feature_names:
if col in self:
mycols.append(col)
mycols.sort()
retur... |
def text2labels(text, sents):
'''
Marks all characters in given `text`, that doesn't exists within any
element of `sents` with `1` character, other characters (within sentences)
will be marked with `0`
Used in training process
>>> text = 'привет. меня зовут аня.'
>>> sents = ['привет.', 'мен... | Marks all characters in given `text`, that doesn't exists within any
element of `sents` with `1` character, other characters (within sentences)
will be marked with `0`
Used in training process
>>> text = 'привет. меня зовут аня.'
>>> sents = ['привет.', 'меня зовут аня.']
>>> labels = text2label... | Below is the the instruction that describes the task:
### Input:
Marks all characters in given `text`, that doesn't exists within any
element of `sents` with `1` character, other characters (within sentences)
will be marked with `0`
Used in training process
>>> text = 'привет. меня зовут аня.'
>... |
def _recurse(self, inputs, output):
'''internal recursion routine called by the run method that generates
all input combinations'''
if inputs:
my_input = inputs[0]
name = my_input.name
if my_input.state:
my_options = my_input.options(self.state... | internal recursion routine called by the run method that generates
all input combinations | Below is the the instruction that describes the task:
### Input:
internal recursion routine called by the run method that generates
all input combinations
### Response:
def _recurse(self, inputs, output):
'''internal recursion routine called by the run method that generates
all input combin... |
def get_source(self, objtxt):
"""Get object source"""
from spyder_kernels.utils.dochelpers import getsource
obj, valid = self._eval(objtxt)
if valid:
return getsource(obj) | Get object source | Below is the the instruction that describes the task:
### Input:
Get object source
### Response:
def get_source(self, objtxt):
"""Get object source"""
from spyder_kernels.utils.dochelpers import getsource
obj, valid = self._eval(objtxt)
if valid:
return getsource(obj) |
def description(self):
""" Get the textual description of the category """
if self._meta and self._meta.get_payload():
return utils.TrueCallableProxy(self._description)
return utils.CallableProxy(None) | Get the textual description of the category | Below is the the instruction that describes the task:
### Input:
Get the textual description of the category
### Response:
def description(self):
""" Get the textual description of the category """
if self._meta and self._meta.get_payload():
return utils.TrueCallableProxy(self._descript... |
def gradient(self, mu, dist):
"""
derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n
"""
return dist.levels/(mu*(dist.le... | derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n | Below is the the instruction that describes the task:
### Input:
derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n
### Response:
def gradient(self... |
def read(self, queue):
"""
Read complete DSMR telegram's from the serial interface and parse it
into CosemObject's and MbusObject's.
Instead of being a generator, values are pushed to provided queue for
asynchronous processing.
:rtype: None
"""
# create ... | Read complete DSMR telegram's from the serial interface and parse it
into CosemObject's and MbusObject's.
Instead of being a generator, values are pushed to provided queue for
asynchronous processing.
:rtype: None | Below is the the instruction that describes the task:
### Input:
Read complete DSMR telegram's from the serial interface and parse it
into CosemObject's and MbusObject's.
Instead of being a generator, values are pushed to provided queue for
asynchronous processing.
:rtype: None
###... |
def handle(self, *args, **options):
"""
dump fields permissions for a user
"""
def get_user(username):
try:
return User.objects.get(username=username)
except ObjectDoesNotExist as e:
raise CommandError("This user doesn't exist in t... | dump fields permissions for a user | Below is the the instruction that describes the task:
### Input:
dump fields permissions for a user
### Response:
def handle(self, *args, **options):
"""
dump fields permissions for a user
"""
def get_user(username):
try:
return User.objects.get(username... |
def PrintAllTables(self):
""" Prints contents of every table. """
goodlogging.Log.Info("DB", "Database contents:\n")
for table in self._tableDict.keys():
self._PrintDatabaseTable(table) | Prints contents of every table. | Below is the the instruction that describes the task:
### Input:
Prints contents of every table.
### Response:
def PrintAllTables(self):
""" Prints contents of every table. """
goodlogging.Log.Info("DB", "Database contents:\n")
for table in self._tableDict.keys():
self._PrintDatabaseTable(table) |
def _get_baseline_from_tag(config, tag):
'''
Returns the last created baseline snapshot marked with `tag`
'''
last_snapshot = None
for snapshot in __salt__['snapper.list_snapshots'](config):
if tag == snapshot['userdata'].get("baseline_tag"):
if not last_snapshot or last_snapshot... | Returns the last created baseline snapshot marked with `tag` | Below is the the instruction that describes the task:
### Input:
Returns the last created baseline snapshot marked with `tag`
### Response:
def _get_baseline_from_tag(config, tag):
'''
Returns the last created baseline snapshot marked with `tag`
'''
last_snapshot = None
for snapshot in __salt__... |
def assign_power_curve(self, wake_losses_model='power_efficiency_curve',
smoothing=False, block_width=0.5,
standard_deviation_method='turbulence_intensity',
smoothing_order='wind_farm_power_curves',
turbulence_in... | r"""
Calculates the power curve of a wind turbine cluster.
The turbine cluster power curve is calculated by aggregating the wind
farm power curves of wind farms within the turbine cluster. Depending
on the parameters the power curves are smoothed (before or after the
aggregation... | Below is the the instruction that describes the task:
### Input:
r"""
Calculates the power curve of a wind turbine cluster.
The turbine cluster power curve is calculated by aggregating the wind
farm power curves of wind farms within the turbine cluster. Depending
on the parameters t... |
def get_states(self):
"""
Add outcome to variables of XMLBIF
Return
------
dict: dict of type {variable: outcome tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_states()
{'dog-out': [<Element OUTCOME at 0x7ffbabfcd... | Add outcome to variables of XMLBIF
Return
------
dict: dict of type {variable: outcome tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_states()
{'dog-out': [<Element OUTCOME at 0x7ffbabfcdec8>, <Element OUTCOME at 0x7ffbabfcdf08>]... | Below is the the instruction that describes the task:
### Input:
Add outcome to variables of XMLBIF
Return
------
dict: dict of type {variable: outcome tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_states()
{'dog-out': [<Ele... |
def user(username, password, all):
"""Create admin users (BasicAuth only)."""
if current_app.config['AUTH_PROVIDER'] != 'basic':
raise click.UsageError('Not required for {} admin users'.format(current_app.config['AUTH_PROVIDER']))
if username and username not in current_app.config['ADMIN_USERS']:
... | Create admin users (BasicAuth only). | Below is the the instruction that describes the task:
### Input:
Create admin users (BasicAuth only).
### Response:
def user(username, password, all):
"""Create admin users (BasicAuth only)."""
if current_app.config['AUTH_PROVIDER'] != 'basic':
raise click.UsageError('Not required for {} admin user... |
def _GetNormalizedTimestamp(self):
"""Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cann... | Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cannot be
determined. | Below is the the instruction that describes the task:
### Input:
Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if th... |
def set_cache_buster(redis, path, hash):
"""Sets the cache buster value for a given file path"""
redis.hset("cache-buster:{}:v3".format(oz.settings["s3_bucket"]), path, hash) | Sets the cache buster value for a given file path | Below is the the instruction that describes the task:
### Input:
Sets the cache buster value for a given file path
### Response:
def set_cache_buster(redis, path, hash):
"""Sets the cache buster value for a given file path"""
redis.hset("cache-buster:{}:v3".format(oz.settings["s3_bucket"]), path, hash) |
def get_narrow_url(self, instance):
"""
Return a link suitable for narrowing on the current item.
"""
text = instance[0]
request = self.context["request"]
query_params = request.GET.copy()
# Never keep the page query parameter in narrowing urls.
# It will... | Return a link suitable for narrowing on the current item. | Below is the the instruction that describes the task:
### Input:
Return a link suitable for narrowing on the current item.
### Response:
def get_narrow_url(self, instance):
"""
Return a link suitable for narrowing on the current item.
"""
text = instance[0]
request = self.co... |
def matplotlib_scraper(block, block_vars, gallery_conf, **kwargs):
"""Scrape Matplotlib images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains ... | Scrape Matplotlib images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
**kwargs : dict
Additional... | Below is the the instruction that describes the task:
### Input:
Scrape Matplotlib images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the c... |
def dl_full_file(url, save_file_name):
"""
Download a file. No checks are performed.
Parameters
----------
url : str
The url of the file to download
save_file_name : str
The name to save the file as
"""
response = requests.get(url)
with open(save_file_name, 'wb') as... | Download a file. No checks are performed.
Parameters
----------
url : str
The url of the file to download
save_file_name : str
The name to save the file as | Below is the the instruction that describes the task:
### Input:
Download a file. No checks are performed.
Parameters
----------
url : str
The url of the file to download
save_file_name : str
The name to save the file as
### Response:
def dl_full_file(url, save_file_name):
"""
... |
def _new_conn(self):
""" Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
"""
extra_kw = {}
if self.source_address:
extra_kw['source_address'] = self.source_address
if self.socket_options:
extra_kw['so... | Establish a socket connection and set nodelay settings on it.
:return: New socket connection. | Below is the the instruction that describes the task:
### Input:
Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
### Response:
def _new_conn(self):
""" Establish a socket connection and set nodelay settings on it.
:return: New socket connectio... |
def get_user_autocompletions(ctx, args, incomplete, cmd_param):
"""
:param ctx: context associated with the parsed command
:param args: full list of args
:param incomplete: the incomplete text to autocomplete
:param cmd_param: command definition
:return: all the possible user-specified completio... | :param ctx: context associated with the parsed command
:param args: full list of args
:param incomplete: the incomplete text to autocomplete
:param cmd_param: command definition
:return: all the possible user-specified completions for the param | Below is the the instruction that describes the task:
### Input:
:param ctx: context associated with the parsed command
:param args: full list of args
:param incomplete: the incomplete text to autocomplete
:param cmd_param: command definition
:return: all the possible user-specified completions for ... |
def assignEditor(self):
"""
Assigns the editor for this entry based on the plugin.
"""
plugin = self.currentPlugin()
column = self.currentColumn()
value = self.currentValue()
if not plugin:
self.setEditor(None)
return
... | Assigns the editor for this entry based on the plugin. | Below is the the instruction that describes the task:
### Input:
Assigns the editor for this entry based on the plugin.
### Response:
def assignEditor(self):
"""
Assigns the editor for this entry based on the plugin.
"""
plugin = self.currentPlugin()
column = self.curre... |
def extract_names(sender):
"""Tries to extract sender's names from `From:` header.
It could extract not only the actual names but e.g.
the name of the company, parts of email, etc.
>>> extract_names('Sergey N. Obukhov <serobnic@mail.ru>')
['Sergey', 'Obukhov', 'serobnic']
>>> extract_names(''... | Tries to extract sender's names from `From:` header.
It could extract not only the actual names but e.g.
the name of the company, parts of email, etc.
>>> extract_names('Sergey N. Obukhov <serobnic@mail.ru>')
['Sergey', 'Obukhov', 'serobnic']
>>> extract_names('')
[] | Below is the the instruction that describes the task:
### Input:
Tries to extract sender's names from `From:` header.
It could extract not only the actual names but e.g.
the name of the company, parts of email, etc.
>>> extract_names('Sergey N. Obukhov <serobnic@mail.ru>')
['Sergey', 'Obukhov', '... |
def filter(self, query, output_fields=None):
"""Query the database and return subject information for those
who match the query logic
Parameters
----------
query: Query or QueryGroup
Query(Group) object to process
output_fields: list
The fields de... | Query the database and return subject information for those
who match the query logic
Parameters
----------
query: Query or QueryGroup
Query(Group) object to process
output_fields: list
The fields desired for matching subjects
Returns
---... | Below is the the instruction that describes the task:
### Input:
Query the database and return subject information for those
who match the query logic
Parameters
----------
query: Query or QueryGroup
Query(Group) object to process
output_fields: list
... |
def reset_full(self, force=False, _meta=None):
""" Remove all accounts which can be recalculated based on Z, Y, F, FY
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. Default: False
_met... | Remove all accounts which can be recalculated based on Z, Y, F, FY
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. Default: False
_meta: MRIOMetaData, optional
Metadata handler for ... | Below is the the instruction that describes the task:
### Input:
Remove all accounts which can be recalculated based on Z, Y, F, FY
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. Default: False
... |
def is_unprocessed_local_replica(pid):
"""Is local replica with status "queued"."""
return d1_gmn.app.models.LocalReplica.objects.filter(
pid__did=pid, info__status__status='queued'
).exists() | Is local replica with status "queued". | Below is the the instruction that describes the task:
### Input:
Is local replica with status "queued".
### Response:
def is_unprocessed_local_replica(pid):
"""Is local replica with status "queued"."""
return d1_gmn.app.models.LocalReplica.objects.filter(
pid__did=pid, info__status__status='queued'... |
def assumed_state(self):
# pylint: disable=protected-access
"""Return whether the data is from an online vehicle."""
return (not self._controller.car_online[self.id()] and
(self._controller._last_update_time[self.id()] -
self._controller._last_wake_up_time[self.i... | Return whether the data is from an online vehicle. | Below is the the instruction that describes the task:
### Input:
Return whether the data is from an online vehicle.
### Response:
def assumed_state(self):
# pylint: disable=protected-access
"""Return whether the data is from an online vehicle."""
return (not self._controller.car_online[self... |
def _std_err(self):
"""Standard error of the estimate (SEE). A scalar.
For standard errors of parameters, see _se_all, se_alpha, and se_beta.
"""
return np.sqrt(np.sum(np.square(self._resids), axis=1) / self._df_err) | Standard error of the estimate (SEE). A scalar.
For standard errors of parameters, see _se_all, se_alpha, and se_beta. | Below is the the instruction that describes the task:
### Input:
Standard error of the estimate (SEE). A scalar.
For standard errors of parameters, see _se_all, se_alpha, and se_beta.
### Response:
def _std_err(self):
"""Standard error of the estimate (SEE). A scalar.
For standard ... |
def get_charge(chebi_id):
'''Returns charge'''
if len(__CHARGES) == 0:
__parse_chemical_data()
return __CHARGES[chebi_id] if chebi_id in __CHARGES else float('NaN') | Returns charge | Below is the the instruction that describes the task:
### Input:
Returns charge
### Response:
def get_charge(chebi_id):
'''Returns charge'''
if len(__CHARGES) == 0:
__parse_chemical_data()
return __CHARGES[chebi_id] if chebi_id in __CHARGES else float('NaN') |
def run_simulation(wdir, arp=True, **kwargs):
"""
Example
-------
100-nm silica sphere with 10-nm thick Ag coating,
embedded in water; arprec 20 digits; illuminated with YAG (1064nm);
scan xz plane (21x21, +-200nm)
bhfield-arp-db.exe mpdigit wl r_core r_coat
n_grid_x ... | Example
-------
100-nm silica sphere with 10-nm thick Ag coating,
embedded in water; arprec 20 digits; illuminated with YAG (1064nm);
scan xz plane (21x21, +-200nm)
bhfield-arp-db.exe mpdigit wl r_core r_coat
n_grid_x xspan_min xspan_max
n_grid_y yspan_... | Below is the the instruction that describes the task:
### Input:
Example
-------
100-nm silica sphere with 10-nm thick Ag coating,
embedded in water; arprec 20 digits; illuminated with YAG (1064nm);
scan xz plane (21x21, +-200nm)
bhfield-arp-db.exe mpdigit wl r_core r_coat
... |
def load(self: T, **kwargs) -> T:
"""Manually trigger loading of this dataset's data from disk or a
remote source into memory and return this dataset.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data ... | Manually trigger loading of this dataset's data from disk or a
remote source into memory and return this dataset.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically. However, ... | Below is the the instruction that describes the task:
### Input:
Manually trigger loading of this dataset's data from disk or a
remote source into memory and return this dataset.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should eithe... |
def use_kwargs(args, locations=None, inherit=None, apply=None, **kwargs):
"""Inject keyword arguments from the specified webargs arguments into the
decorated view function.
Usage:
.. code-block:: python
from marshmallow import fields
@use_kwargs({'name': fields.Str(), 'category': fie... | Inject keyword arguments from the specified webargs arguments into the
decorated view function.
Usage:
.. code-block:: python
from marshmallow import fields
@use_kwargs({'name': fields.Str(), 'category': fields.Str()})
def get_pets(**kwargs):
return Pet.query.filter_b... | Below is the the instruction that describes the task:
### Input:
Inject keyword arguments from the specified webargs arguments into the
decorated view function.
Usage:
.. code-block:: python
from marshmallow import fields
@use_kwargs({'name': fields.Str(), 'category': fields.Str()})
... |
def _register(self, session, url):
"""
Register a package to a repository.
"""
dist = self._poetry.file.parent / "dist"
file = dist / "{}-{}.tar.gz".format(
self._package.name, normalize_version(self._package.version.text)
)
if not file.exists():
... | Register a package to a repository. | Below is the the instruction that describes the task:
### Input:
Register a package to a repository.
### Response:
def _register(self, session, url):
"""
Register a package to a repository.
"""
dist = self._poetry.file.parent / "dist"
file = dist / "{}-{}.tar.gz".format(
... |
def set_description(self):
"""
Set the node description
"""
if self.device_info['type'] == 'Router':
self.node['description'] = '%s %s' % (self.device_info['type'],
self.device_info['model'])
else:
self.nod... | Set the node description | Below is the the instruction that describes the task:
### Input:
Set the node description
### Response:
def set_description(self):
"""
Set the node description
"""
if self.device_info['type'] == 'Router':
self.node['description'] = '%s %s' % (self.device_info['type'],
... |
def json_request(endpoint, verb='GET', session_options=None, **options):
"""Like :func:`molotov.request` but extracts json from the response.
"""
req = functools.partial(_request, endpoint, verb, session_options,
json=True, **options)
return _run_in_fresh_loop(req) | Like :func:`molotov.request` but extracts json from the response. | Below is the the instruction that describes the task:
### Input:
Like :func:`molotov.request` but extracts json from the response.
### Response:
def json_request(endpoint, verb='GET', session_options=None, **options):
"""Like :func:`molotov.request` but extracts json from the response.
"""
req = functo... |
def trace_to_next_plane(self):
"""Trace the positions to the next plane."""
return list(map(lambda positions, deflections: np.subtract(positions, deflections),
self.positions, self.deflections)) | Trace the positions to the next plane. | Below is the the instruction that describes the task:
### Input:
Trace the positions to the next plane.
### Response:
def trace_to_next_plane(self):
"""Trace the positions to the next plane."""
return list(map(lambda positions, deflections: np.subtract(positions, deflections),
... |
def check_if_username_exists(self, username):
'''
Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleError`... | Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleError`
:return: True. If it does not exist, an exception is rais... | Below is the the instruction that describes the task:
### Input:
Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleErr... |
def is_correct(self):
"""Check if this object configuration is correct ::
* Check our own specific properties
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool
"""
state = True
# Inter... | Check if this object configuration is correct ::
* Check our own specific properties
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if this object configuration is correct ::
* Check our own specific properties
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool
### Response:... |
def AddMethod(self, function, name=None):
"""
Adds the specified function as a method of this construction
environment with the specified name. If the name is omitted,
the default name is the name of the function itself.
"""
method = MethodWrapper(self, function, name)
... | Adds the specified function as a method of this construction
environment with the specified name. If the name is omitted,
the default name is the name of the function itself. | Below is the the instruction that describes the task:
### Input:
Adds the specified function as a method of this construction
environment with the specified name. If the name is omitted,
the default name is the name of the function itself.
### Response:
def AddMethod(self, function, name=None):
... |
def fd(self):
""":return: file descriptor used to create the underlying mapping.
**Note:** it is not required to be valid anymore
:raise ValueError: if the mapping was not created by a file descriptor"""
if isinstance(self._rlist.path_or_fd(), string_types()):
raise ValueErr... | :return: file descriptor used to create the underlying mapping.
**Note:** it is not required to be valid anymore
:raise ValueError: if the mapping was not created by a file descriptor | Below is the the instruction that describes the task:
### Input:
:return: file descriptor used to create the underlying mapping.
**Note:** it is not required to be valid anymore
:raise ValueError: if the mapping was not created by a file descriptor
### Response:
def fd(self):
""":return: f... |
def get_version():
"""
Retrieves the version of the GLFW library.
Wrapper for:
void glfwGetVersion(int* major, int* minor, int* rev);
"""
major_value = ctypes.c_int(0)
major = ctypes.pointer(major_value)
minor_value = ctypes.c_int(0)
minor = ctypes.pointer(minor_value)
rev_v... | Retrieves the version of the GLFW library.
Wrapper for:
void glfwGetVersion(int* major, int* minor, int* rev); | Below is the the instruction that describes the task:
### Input:
Retrieves the version of the GLFW library.
Wrapper for:
void glfwGetVersion(int* major, int* minor, int* rev);
### Response:
def get_version():
"""
Retrieves the version of the GLFW library.
Wrapper for:
void glfwGet... |
def _explore_storage(self):
"""Generator of all files contained in media storage."""
path = ''
dirs = [path]
while dirs:
path = dirs.pop()
subdirs, files = self.media_storage.listdir(path)
for media_filename in files:
yield os.path.join... | Generator of all files contained in media storage. | Below is the the instruction that describes the task:
### Input:
Generator of all files contained in media storage.
### Response:
def _explore_storage(self):
"""Generator of all files contained in media storage."""
path = ''
dirs = [path]
while dirs:
path = dirs.pop()
... |
def status(self):
"""
The current status of the event (started, finished or pending).
"""
myNow = timezone.localtime(timezone=self.tz)
daysDelta = dt.timedelta(days=self.num_days - 1)
# NB: postponements can be created after the until date
# so ignore that
... | The current status of the event (started, finished or pending). | Below is the the instruction that describes the task:
### Input:
The current status of the event (started, finished or pending).
### Response:
def status(self):
"""
The current status of the event (started, finished or pending).
"""
myNow = timezone.localtime(timezone=self.tz)
... |
def setbit(self, key, offset, value):
"""Sets or clears the bit at offset in the string value stored at key.
:raises TypeError: if offset is not int
:raises ValueError: if offset is less than 0 or value is not 0 or 1
"""
if not isinstance(offset, int):
raise TypeErro... | Sets or clears the bit at offset in the string value stored at key.
:raises TypeError: if offset is not int
:raises ValueError: if offset is less than 0 or value is not 0 or 1 | Below is the the instruction that describes the task:
### Input:
Sets or clears the bit at offset in the string value stored at key.
:raises TypeError: if offset is not int
:raises ValueError: if offset is less than 0 or value is not 0 or 1
### Response:
def setbit(self, key, offset, value):
... |
def parse_map_Ka(self):
"""Ambient map"""
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_ambient(Kd) | Ambient map | Below is the the instruction that describes the task:
### Input:
Ambient map
### Response:
def parse_map_Ka(self):
"""Ambient map"""
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_ambient(Kd) |
def get_parent_vault_ids(self, vault_id):
"""Gets the parent ``Ids`` of the given vault.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (osid.id.IdList) - the parent ``Ids`` of the vault
raise: NotFound - ``vault_id`` is not found
raise: NullArgument - ``vault_id`` is `... | Gets the parent ``Ids`` of the given vault.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (osid.id.IdList) - the parent ``Ids`` of the vault
raise: NotFound - ``vault_id`` is not found
raise: NullArgument - ``vault_id`` is ``null``
raise: OperationFailed - unable to c... | Below is the the instruction that describes the task:
### Input:
Gets the parent ``Ids`` of the given vault.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (osid.id.IdList) - the parent ``Ids`` of the vault
raise: NotFound - ``vault_id`` is not found
raise: NullArgument - `... |
def load(self, filename="temp.pkl"):
"""
Save TM in the filename specified above
"""
inputFile = open(filename, 'rb')
self.tm = cPickle.load(inputFile) | Save TM in the filename specified above | Below is the the instruction that describes the task:
### Input:
Save TM in the filename specified above
### Response:
def load(self, filename="temp.pkl"):
"""
Save TM in the filename specified above
"""
inputFile = open(filename, 'rb')
self.tm = cPickle.load(inputFile) |
def list_connection_channels(self, name):
"""
List of all channels for a given connection.
:param name: The connection name
:type name: str
"""
return self._api_get('/api/connections/{0}/channels'.format(
urllib.parse.quote_plus(name)
)) | List of all channels for a given connection.
:param name: The connection name
:type name: str | Below is the the instruction that describes the task:
### Input:
List of all channels for a given connection.
:param name: The connection name
:type name: str
### Response:
def list_connection_channels(self, name):
"""
List of all channels for a given connection.
:param na... |
def _get_object(data, position, obj_end, opts, dummy):
"""Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef."""
obj_size = _UNPACK_INT(data[position:position + 4])[0]
end = position + obj_size - 1
if data[end:position + obj_size] != b"\x00":
raise InvalidBSON("bad eoo")
if... | Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef. | Below is the the instruction that describes the task:
### Input:
Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef.
### Response:
def _get_object(data, position, obj_end, opts, dummy):
"""Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef."""
obj_size = _UNPACK_INT(data... |
def build(env, ciprcfg, console):
"""
Build the current project for distribution
"""
os.putenv('CIPR_PACKAGES', env.package_dir)
os.putenv('CIPR_PROJECT', env.project_directory)
build_settings = path.join(env.project_directory, 'build.settings')
with open(build_settings, 'r') as f:
... | Build the current project for distribution | Below is the the instruction that describes the task:
### Input:
Build the current project for distribution
### Response:
def build(env, ciprcfg, console):
"""
Build the current project for distribution
"""
os.putenv('CIPR_PACKAGES', env.package_dir)
os.putenv('CIPR_PROJECT', env.project_direct... |
def amchar_to_int(amchar, hij=False):
'''Convert an angular momentum integer to a character
The return value is a list of integers (to handle sp, spd, ... orbitals)
For example, converts 'p' to [1] and 'sp' to [0,1]
If hij is True, the ordering spdfghijkl is used. Otherwise, the
ordering will be ... | Convert an angular momentum integer to a character
The return value is a list of integers (to handle sp, spd, ... orbitals)
For example, converts 'p' to [1] and 'sp' to [0,1]
If hij is True, the ordering spdfghijkl is used. Otherwise, the
ordering will be spdfghikl (skipping j) | Below is the the instruction that describes the task:
### Input:
Convert an angular momentum integer to a character
The return value is a list of integers (to handle sp, spd, ... orbitals)
For example, converts 'p' to [1] and 'sp' to [0,1]
If hij is True, the ordering spdfghijkl is used. Otherwise, t... |
def draw_tree_grid(self,
nrows=None,
ncols=None,
start=0,
fixed_order=False,
shared_axis=False,
**kwargs):
"""
Draw a slice of x*y trees into a x,y grid non-overlapping.
Parameters:
-----------
x (int):
N... | Draw a slice of x*y trees into a x,y grid non-overlapping.
Parameters:
-----------
x (int):
Number of grid cells in x dimension. Default=automatically set.
y (int):
Number of grid cells in y dimension. Default=automatically set.
start (int):
... | Below is the the instruction that describes the task:
### Input:
Draw a slice of x*y trees into a x,y grid non-overlapping.
Parameters:
-----------
x (int):
Number of grid cells in x dimension. Default=automatically set.
y (int):
Number of grid cells in y di... |
def main(config, host, port, logfile, debug, daemon, uid, gid, pidfile, umask, rundir):
"""
Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whe... | Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whether deamon mode was specified or not,
the process may be forked (or not) and the server will b... | Below is the the instruction that describes the task:
### Input:
Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whether deamon mode was specified ... |
def stopped(name, connection=None, username=None, password=None):
'''
Stops a VM by shutting it down nicely.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
... | Stops a VM by shutting it down nicely.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect w... | Below is the the instruction that describes the task:
### Input:
Stops a VM by shutting it down nicely.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
... |
def _create_table_and_update_context(node, context):
"""Create an aliased table for a SqlNode.
Updates the relevant Selectable global context.
Args:
node: SqlNode, the current node.
context: CompilationContext, global compilation state and metadata.
Returns:
Table, the newly a... | Create an aliased table for a SqlNode.
Updates the relevant Selectable global context.
Args:
node: SqlNode, the current node.
context: CompilationContext, global compilation state and metadata.
Returns:
Table, the newly aliased SQLAlchemy table. | Below is the the instruction that describes the task:
### Input:
Create an aliased table for a SqlNode.
Updates the relevant Selectable global context.
Args:
node: SqlNode, the current node.
context: CompilationContext, global compilation state and metadata.
Returns:
Table, th... |
def attributes(self, **kwargs): # pragma: no cover
"""Retrieve the attribute configuration object.
Retrieves a mapping that identifies the custom directory
attributes configured for the Directory SyncService instance,
and the mapping of the custom attributes to standard directory
... | Retrieve the attribute configuration object.
Retrieves a mapping that identifies the custom directory
attributes configured for the Directory SyncService instance,
and the mapping of the custom attributes to standard directory
attributes.
Args:
**kwargs: Supported :... | Below is the the instruction that describes the task:
### Input:
Retrieve the attribute configuration object.
Retrieves a mapping that identifies the custom directory
attributes configured for the Directory SyncService instance,
and the mapping of the custom attributes to standard directory... |
def code_deparse_around_offset(name, offset, co, out=StringIO(),
version=None, is_pypy=None,
debug_opts=DEFAULT_DEBUG_OPTS):
"""
Like deparse_code(), but given a function/module name and
offset, finds the node closest to offset. If offset is not... | Like deparse_code(), but given a function/module name and
offset, finds the node closest to offset. If offset is not an instruction boundary,
we raise an IndexError. | Below is the the instruction that describes the task:
### Input:
Like deparse_code(), but given a function/module name and
offset, finds the node closest to offset. If offset is not an instruction boundary,
we raise an IndexError.
### Response:
def code_deparse_around_offset(name, offset, co, out=StringIO... |
def dpss_windows(N, NW, Kmax, interp_from=None, interp_kind='linear'):
"""
Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1]
for a given frequency-spacing multiple NW and sequence length N.
Parameters
----------
N : int
sequence length
NW : float, unitless
... | Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1]
for a given frequency-spacing multiple NW and sequence length N.
Parameters
----------
N : int
sequence length
NW : float, unitless
standardized half bandwidth corresponding to 2NW = BW/f0 = BW*N*dt
but w... | Below is the the instruction that describes the task:
### Input:
Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1]
for a given frequency-spacing multiple NW and sequence length N.
Parameters
----------
N : int
sequence length
NW : float, unitless
standardize... |
def _convertNonNumericData(self, spatialOutput, temporalOutput, output):
"""
Converts all of the non-numeric fields from spatialOutput and temporalOutput
into their scalar equivalents and records them in the output dictionary.
:param spatialOutput: The results of topDownCompute() for the spatial input.... | Converts all of the non-numeric fields from spatialOutput and temporalOutput
into their scalar equivalents and records them in the output dictionary.
:param spatialOutput: The results of topDownCompute() for the spatial input.
:param temporalOutput: The results of topDownCompute() for the temporal
in... | Below is the the instruction that describes the task:
### Input:
Converts all of the non-numeric fields from spatialOutput and temporalOutput
into their scalar equivalents and records them in the output dictionary.
:param spatialOutput: The results of topDownCompute() for the spatial input.
:param temp... |
def getOntology(self, id_):
"""
Returns the ontology with the specified ID.
"""
if id_ not in self._ontologyIdMap:
raise exceptions.OntologyNotFoundException(id_)
return self._ontologyIdMap[id_] | Returns the ontology with the specified ID. | Below is the the instruction that describes the task:
### Input:
Returns the ontology with the specified ID.
### Response:
def getOntology(self, id_):
"""
Returns the ontology with the specified ID.
"""
if id_ not in self._ontologyIdMap:
raise exceptions.OntologyNotFound... |
def parse_subprotocol_item(
header: str, pos: int, header_name: str
) -> Tuple[Subprotocol, int]:
"""
Parse a subprotocol from ``header`` at the given position.
Return the subprotocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
"""
... | Parse a subprotocol from ``header`` at the given position.
Return the subprotocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. | Below is the the instruction that describes the task:
### Input:
Parse a subprotocol from ``header`` at the given position.
Return the subprotocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
### Response:
def parse_subprotocol_item(
header: s... |
def organization_requests(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests#list-requests"
api_path = "/api/v2/organizations/{id}/requests.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/requests#list-requests | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/requests#list-requests
### Response:
def organization_requests(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests#list-requests"
api_path = "/api/v2/organiz... |
def add_libravatar (generator, metadata):
"""Article generator connector for the Libravatar plugin"""
missing = generator.settings.get ('LIBRAVATAR_MISSING')
size = generator.settings.get ('LIBRAVATAR_SIZE')
## Check the presence of the Email header
if 'email' not in metadata.keys ():
try:
... | Article generator connector for the Libravatar plugin | Below is the the instruction that describes the task:
### Input:
Article generator connector for the Libravatar plugin
### Response:
def add_libravatar (generator, metadata):
"""Article generator connector for the Libravatar plugin"""
missing = generator.settings.get ('LIBRAVATAR_MISSING')
size = gener... |
def add_material(self, material):
"""Add a material to the mesh, IF it's not already present."""
if self.has_material(material):
return
self.materials.append(material) | Add a material to the mesh, IF it's not already present. | Below is the the instruction that describes the task:
### Input:
Add a material to the mesh, IF it's not already present.
### Response:
def add_material(self, material):
"""Add a material to the mesh, IF it's not already present."""
if self.has_material(material):
return
self.m... |
def add_image_history(self, data):
"""Add arbitrary string to ImageHistory tag."""
self._ef['0th'][piexif.ImageIFD.ImageHistory] = json.dumps(data) | Add arbitrary string to ImageHistory tag. | Below is the the instruction that describes the task:
### Input:
Add arbitrary string to ImageHistory tag.
### Response:
def add_image_history(self, data):
"""Add arbitrary string to ImageHistory tag."""
self._ef['0th'][piexif.ImageIFD.ImageHistory] = json.dumps(data) |
def clazz(clazz, parent_clazz, description, link, params_string, init_super_args=None):
"""
Live template for pycharm:
y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$description$", link="$lnk$", params_string="$first_param$")
"""
variables_needed = []
variables_optional = []
... | Live template for pycharm:
y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$description$", link="$lnk$", params_string="$first_param$") | Below is the the instruction that describes the task:
### Input:
Live template for pycharm:
y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$description$", link="$lnk$", params_string="$first_param$")
### Response:
def clazz(clazz, parent_clazz, description, link, params_string, init_super_ar... |
def transplant_func(func, module):
"""
Make a function imported from module A appear as if it is located
in module B.
>>> from pprint import pprint
>>> pprint.__module__
'pprint'
>>> pp = transplant_func(pprint, __name__)
>>> pp.__module__
'nose.util'
The original function is n... | Make a function imported from module A appear as if it is located
in module B.
>>> from pprint import pprint
>>> pprint.__module__
'pprint'
>>> pp = transplant_func(pprint, __name__)
>>> pp.__module__
'nose.util'
The original function is not modified.
>>> pprint.__module__
'pp... | Below is the the instruction that describes the task:
### Input:
Make a function imported from module A appear as if it is located
in module B.
>>> from pprint import pprint
>>> pprint.__module__
'pprint'
>>> pp = transplant_func(pprint, __name__)
>>> pp.__module__
'nose.util'
The ... |
def random_outdir(): # type: () -> Text
""" Return the random directory name chosen to use for tool / workflow output """
# compute this once and store it as a function attribute - each subsequent call will return the same value
if not hasattr(random_outdir, 'outdir'):
random_outdir.outdir = '/' + ... | Return the random directory name chosen to use for tool / workflow output | Below is the the instruction that describes the task:
### Input:
Return the random directory name chosen to use for tool / workflow output
### Response:
def random_outdir(): # type: () -> Text
""" Return the random directory name chosen to use for tool / workflow output """
# compute this once and store i... |
def from_dict(cls, d):
"""
Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using
the as_dict method.
:param d: dict representation of the VoronoiContainer object
:return: VoronoiContainer object
"""
structure = S... | Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using
the as_dict method.
:param d: dict representation of the VoronoiContainer object
:return: VoronoiContainer object | Below is the the instruction that describes the task:
### Input:
Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using
the as_dict method.
:param d: dict representation of the VoronoiContainer object
:return: VoronoiContainer object
### Res... |
def storage_update(self, name, config, timeout=10):
"""
Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
... | Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
required attributes and definitions.
:param timeout: int
... | Below is the the instruction that describes the task:
### Input:
Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
... |
def parse_http_accept_header(header):
"""
Return a list of content types listed in the HTTP Accept header
ordered by quality.
:param header: A string describing the contents of the HTTP Accept header.
"""
components = [item.strip() for item in header.split(',')]
l = []
for component in... | Return a list of content types listed in the HTTP Accept header
ordered by quality.
:param header: A string describing the contents of the HTTP Accept header. | Below is the the instruction that describes the task:
### Input:
Return a list of content types listed in the HTTP Accept header
ordered by quality.
:param header: A string describing the contents of the HTTP Accept header.
### Response:
def parse_http_accept_header(header):
"""
Return a list of c... |
def import_fx_rates(self, rates: List[PriceModel]):
""" Imports the given prices into database. Write operation! """
have_new_rates = False
base_currency = self.get_default_currency()
for rate in rates:
assert isinstance(rate, PriceModel)
currency = self.get_by... | Imports the given prices into database. Write operation! | Below is the the instruction that describes the task:
### Input:
Imports the given prices into database. Write operation!
### Response:
def import_fx_rates(self, rates: List[PriceModel]):
""" Imports the given prices into database. Write operation! """
have_new_rates = False
base_currency ... |
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ("alpha", "beta", "rc", "final")
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub =... | Derives a PEP386-compliant version number from VERSION. | Below is the the instruction that describes the task:
### Input:
Derives a PEP386-compliant version number from VERSION.
### Response:
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
... |
def check_bottleneck(text):
"""Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61
"""
err = "mixed_metaphors.misc.bottleneck"
msg = u"Mixed metaphor — bottles with big necks are easy to pass through."
list = [
"bigge... | Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61 | Below is the the instruction that describes the task:
### Input:
Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61
### Response:
def check_bottleneck(text):
"""Avoid mixing metaphors about bottles and their necks.
source: Sir... |
def to_xml(self, name="address"):
'''
Returns a DOM Element containing the XML representation of the
address.
@return:Element
'''
for n, v in {"street_address": self.street_address, "city": self.city,
"country": self.country}.items():
if i... | Returns a DOM Element containing the XML representation of the
address.
@return:Element | Below is the the instruction that describes the task:
### Input:
Returns a DOM Element containing the XML representation of the
address.
@return:Element
### Response:
def to_xml(self, name="address"):
'''
Returns a DOM Element containing the XML representation of the
address... |
def StartGdb(self):
"""Hands control over to a new gdb process."""
if self.inferior.is_running:
self.inferior.ShutDownGdb()
program_arg = 'program %d ' % self.inferior.pid
else:
program_arg = ''
os.system('gdb ' + program_arg + ' '.join(self.gdb_args))
reset_position = raw_input('R... | Hands control over to a new gdb process. | Below is the the instruction that describes the task:
### Input:
Hands control over to a new gdb process.
### Response:
def StartGdb(self):
"""Hands control over to a new gdb process."""
if self.inferior.is_running:
self.inferior.ShutDownGdb()
program_arg = 'program %d ' % self.inferior.pid
... |
def ArcSin(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Takes the inverse sin of a vertex, Arcsin(vertex)
:param input_vertex: the vertex
"""
return Double(context.jvm_view().ArcSinVertex, label, cast_to_double_vertex(input_vertex)) | Takes the inverse sin of a vertex, Arcsin(vertex)
:param input_vertex: the vertex | Below is the the instruction that describes the task:
### Input:
Takes the inverse sin of a vertex, Arcsin(vertex)
:param input_vertex: the vertex
### Response:
def ArcSin(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Takes the inverse sin of a vertex, Arc... |
def kullback_leibler(p, q) :
"""Discrete Kullback-Leibler divergence D(P||Q)"""
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
if p.shape != q.shape :
raise ValueError("p and q must be of the same dimensions")
return np.sum(np.where(p > 0, np.log(p / q) * p, 0)) | Discrete Kullback-Leibler divergence D(P||Q) | Below is the the instruction that describes the task:
### Input:
Discrete Kullback-Leibler divergence D(P||Q)
### Response:
def kullback_leibler(p, q) :
"""Discrete Kullback-Leibler divergence D(P||Q)"""
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
if p.shape != q.shape :
raise ValueE... |
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='Ca... | Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg | Below is the the instruction that describes the task:
### Input:
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
### Response:
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile... |
def JCXZ(cpu, target):
"""
Jumps short if CX register is 0.
:param cpu: current CPU.
:param target: destination operand.
"""
cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CX == 0, target.read(), cpu.PC) | Jumps short if CX register is 0.
:param cpu: current CPU.
:param target: destination operand. | Below is the the instruction that describes the task:
### Input:
Jumps short if CX register is 0.
:param cpu: current CPU.
:param target: destination operand.
### Response:
def JCXZ(cpu, target):
"""
Jumps short if CX register is 0.
:param cpu: current CPU.
:param ... |
def get_as_dataframe(worksheet,
evaluate_formulas=False,
**options):
"""
Returns the worksheet contents as a DataFrame.
:param worksheet: the worksheet.
:param evaluate_formulas: if True, get the value of a cell after
formula evaluation; otherwise g... | Returns the worksheet contents as a DataFrame.
:param worksheet: the worksheet.
:param evaluate_formulas: if True, get the value of a cell after
formula evaluation; otherwise get the formula itself if present.
Defaults to False.
:param \*\*options: all the options for pandas.io.pars... | Below is the the instruction that describes the task:
### Input:
Returns the worksheet contents as a DataFrame.
:param worksheet: the worksheet.
:param evaluate_formulas: if True, get the value of a cell after
formula evaluation; otherwise get the formula itself if present.
Defaults... |
def ratio(value, decimal_places=0, failure_string='N/A'):
"""
Converts a floating point value a X:1 ratio.
Number of decimal places set by the `precision` kwarg. Default is one.
"""
try:
f = float(value)
except ValueError:
return failure_string
return _saferound(f, decim... | Converts a floating point value a X:1 ratio.
Number of decimal places set by the `precision` kwarg. Default is one. | Below is the the instruction that describes the task:
### Input:
Converts a floating point value a X:1 ratio.
Number of decimal places set by the `precision` kwarg. Default is one.
### Response:
def ratio(value, decimal_places=0, failure_string='N/A'):
"""
Converts a floating point value a X:1 rat... |
def limit_update(db, key, limits):
"""
Safely updates the list of limits in the database.
:param db: The database handle.
:param key: The key the limits are stored under.
:param limits: A list or sequence of limit objects, each
understanding the dehydrate() method.
The limit... | Safely updates the list of limits in the database.
:param db: The database handle.
:param key: The key the limits are stored under.
:param limits: A list or sequence of limit objects, each
understanding the dehydrate() method.
The limits list currently in the database will be atomic... | Below is the the instruction that describes the task:
### Input:
Safely updates the list of limits in the database.
:param db: The database handle.
:param key: The key the limits are stored under.
:param limits: A list or sequence of limit objects, each
understanding the dehydrate() ... |
def get_name(self, name):
"""Return name `PyName` defined in this scope"""
if name not in self.get_names():
raise exceptions.NameNotFoundError('name %s not found' % name)
return self.get_names()[name] | Return name `PyName` defined in this scope | Below is the the instruction that describes the task:
### Input:
Return name `PyName` defined in this scope
### Response:
def get_name(self, name):
"""Return name `PyName` defined in this scope"""
if name not in self.get_names():
raise exceptions.NameNotFoundError('name %s not found' % ... |
def send(self, stat, value, backend=None):
"""Send stat to backend."""
client = yield from self.client(backend)
if not client:
return False
client.send(stat, value)
client.disconnect() | Send stat to backend. | Below is the the instruction that describes the task:
### Input:
Send stat to backend.
### Response:
def send(self, stat, value, backend=None):
"""Send stat to backend."""
client = yield from self.client(backend)
if not client:
return False
client.send(stat, value)
... |
def daffpa():
"""
Find the previous (backward) array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/daffpa_c.html
:return: True if an array was found.
:rtype: bool
"""
found = ctypes.c_int()
libspice.daffpa_c(ctypes.byref(found))
return bool(found.value... | Find the previous (backward) array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/daffpa_c.html
:return: True if an array was found.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Find the previous (backward) array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/daffpa_c.html
:return: True if an array was found.
:rtype: bool
### Response:
def daffpa():
"""
Find the previous (ba... |
def _write_hex_long(self, data, pos, value):
"""
Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the value to write
:type... | Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the value to write
:type value: unsigned long | Below is the the instruction that describes the task:
### Input:
Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the value to write
:... |
def recv(self, filename, dest_file, timeout=None):
"""Retrieve a file from the device into the file-like dest_file."""
transport = DataFilesyncTransport(self.stream)
transport.write_data('RECV', filename, timeout)
for data_msg in transport.read_until_done('DATA', timeout):
dest_file.write(data_msg... | Retrieve a file from the device into the file-like dest_file. | Below is the the instruction that describes the task:
### Input:
Retrieve a file from the device into the file-like dest_file.
### Response:
def recv(self, filename, dest_file, timeout=None):
"""Retrieve a file from the device into the file-like dest_file."""
transport = DataFilesyncTransport(self.stream)
... |
def Range(min=None, max=None, min_message="Must be at least {min}", max_message="Must be at most {max}"):
"""
Creates a validator that checks if the given numeric value is in the
specified range, inclusive.
Accepts values specified by ``numbers.Number`` only, excluding booleans.
The error messages... | Creates a validator that checks if the given numeric value is in the
specified range, inclusive.
Accepts values specified by ``numbers.Number`` only, excluding booleans.
The error messages raised can be customized with ``min_message`` and
``max_message``. The ``min`` and ``max`` arguments are formatte... | Below is the the instruction that describes the task:
### Input:
Creates a validator that checks if the given numeric value is in the
specified range, inclusive.
Accepts values specified by ``numbers.Number`` only, excluding booleans.
The error messages raised can be customized with ``min_message`` an... |
def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True):
"""
Reset scores for a specific student on a specific problem.
Note: this does *not* delete `Score` models from the database,
since these are immutable. It simply creates a new score with
the "reset" flag set to ... | Reset scores for a specific student on a specific problem.
Note: this does *not* delete `Score` models from the database,
since these are immutable. It simply creates a new score with
the "reset" flag set to True.
Args:
student_id (unicode): The ID of the student for whom to reset scores.
... | Below is the the instruction that describes the task:
### Input:
Reset scores for a specific student on a specific problem.
Note: this does *not* delete `Score` models from the database,
since these are immutable. It simply creates a new score with
the "reset" flag set to True.
Args:
stud... |
def tasks_missing_predicate(
service_name,
old_task_ids,
task_predicate=None
):
""" Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by g... | Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searchin... | Below is the the instruction that describes the task:
### Input:
Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_... |
def span(self, name='child_span'):
"""Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.span.Span`
:returns: A child Span to be added to ... | Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.span.Span`
:returns: A child Span to be added to the current span. | Below is the the instruction that describes the task:
### Input:
Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.span.Span`
:returns: A chi... |
def _get_data(self, read_size):
"""Get data from the character device."""
if NIX:
return super(Mouse, self)._get_data(read_size)
return self._pipe.recv_bytes() | Get data from the character device. | Below is the the instruction that describes the task:
### Input:
Get data from the character device.
### Response:
def _get_data(self, read_size):
"""Get data from the character device."""
if NIX:
return super(Mouse, self)._get_data(read_size)
return self._pipe.recv_bytes() |
def SerializeFaultDetail(self, val, info):
""" Serialize an object """
self._SerializeDataObject(val, info, ' xsi:typ="{1}"'.format(val._wsdlName), self.defaultNS) | Serialize an object | Below is the the instruction that describes the task:
### Input:
Serialize an object
### Response:
def SerializeFaultDetail(self, val, info):
""" Serialize an object """
self._SerializeDataObject(val, info, ' xsi:typ="{1}"'.format(val._wsdlName), self.defaultNS) |
def update(self, repo_dir, **kwargs):
"""This function updates an existing checkout of source code."""
del kwargs
rev = self._args.get("revision")
if rev:
return [{"args": ["git", "checkout", rev], "cwd": repo_dir}] + _ff_command(
rev, repo_dir
)
... | This function updates an existing checkout of source code. | Below is the the instruction that describes the task:
### Input:
This function updates an existing checkout of source code.
### Response:
def update(self, repo_dir, **kwargs):
"""This function updates an existing checkout of source code."""
del kwargs
rev = self._args.get("revision")
... |
def enum_sigma_cubic(cutoff, r_axis):
"""
Find all possible sigma values and corresponding rotation angles
within a sigma value cutoff with known rotation axis in cubic system.
The algorithm for this code is from reference, Acta Cryst, A40,108(1984)
Args:
cutoff (inte... | Find all possible sigma values and corresponding rotation angles
within a sigma value cutoff with known rotation axis in cubic system.
The algorithm for this code is from reference, Acta Cryst, A40,108(1984)
Args:
cutoff (integer): the cutoff of sigma values.
r_axis (list... | Below is the the instruction that describes the task:
### Input:
Find all possible sigma values and corresponding rotation angles
within a sigma value cutoff with known rotation axis in cubic system.
The algorithm for this code is from reference, Acta Cryst, A40,108(1984)
Args:
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.