code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _lint():
"""Run lint and return an exit code."""
# Flake8 doesn't have an easy way to run checks using a Python function, so
# just fork off another process to do it.
# Python 3 compat:
# - The result of subprocess call outputs are byte strings, meaning we need
# to pass a byte string to ... | Run lint and return an exit code. | Below is the the instruction that describes the task:
### Input:
Run lint and return an exit code.
### Response:
def _lint():
"""Run lint and return an exit code."""
# Flake8 doesn't have an easy way to run checks using a Python function, so
# just fork off another process to do it.
# Python 3 com... |
def _got_sol_payload(self, payload):
"""SOL payload callback
"""
# TODO(jbjohnso) test cases to throw some likely scenarios at functions
# for example, retry with new data, retry with no new data
# retry with unexpected sequence number
if type(payload) == dict: # we rece... | SOL payload callback | Below is the the instruction that describes the task:
### Input:
SOL payload callback
### Response:
def _got_sol_payload(self, payload):
"""SOL payload callback
"""
# TODO(jbjohnso) test cases to throw some likely scenarios at functions
# for example, retry with new data, retry with... |
def lnlike(self, model, refactor=False, pos_tol=2.5, neg_tol=50.,
full_output=False):
r"""
Return the likelihood of the astrophysical model `model`.
Returns the likelihood of `model` marginalized over the PLD model.
:param ndarray model: A vector of the same shape as `se... | r"""
Return the likelihood of the astrophysical model `model`.
Returns the likelihood of `model` marginalized over the PLD model.
:param ndarray model: A vector of the same shape as `self.time` \
corresponding to the astrophysical model.
:param bool refactor: Re-compute ... | Below is the the instruction that describes the task:
### Input:
r"""
Return the likelihood of the astrophysical model `model`.
Returns the likelihood of `model` marginalized over the PLD model.
:param ndarray model: A vector of the same shape as `self.time` \
corresponding ... |
def form_valid(self,form):
'''
Even if this form is valid, the handlers for this form may have added messages
to the request. In that case, then the page should be handled as if the form
were invalid. Otherwise, update the session data with the form data and then
move to the ne... | Even if this form is valid, the handlers for this form may have added messages
to the request. In that case, then the page should be handled as if the form
were invalid. Otherwise, update the session data with the form data and then
move to the next view | Below is the the instruction that describes the task:
### Input:
Even if this form is valid, the handlers for this form may have added messages
to the request. In that case, then the page should be handled as if the form
were invalid. Otherwise, update the session data with the form data and then
... |
def validate_identifier(self, field):
"""Validate field identifier."""
if field.data:
field.data = field.data.lower()
if Community.get(field.data, with_deleted=True):
raise validators.ValidationError(
_('The identifier already exists. '
... | Validate field identifier. | Below is the the instruction that describes the task:
### Input:
Validate field identifier.
### Response:
def validate_identifier(self, field):
"""Validate field identifier."""
if field.data:
field.data = field.data.lower()
if Community.get(field.data, with_deleted=True):
... |
def get_logview_address(self, hours=None):
"""
Get logview address of the instance object by hours.
:param hours:
:return: logview address
:rtype: str
"""
hours = hours or options.log_view_hours
project = self.project
url = '%s/authorization' % p... | Get logview address of the instance object by hours.
:param hours:
:return: logview address
:rtype: str | Below is the the instruction that describes the task:
### Input:
Get logview address of the instance object by hours.
:param hours:
:return: logview address
:rtype: str
### Response:
def get_logview_address(self, hours=None):
"""
Get logview address of the instance object b... |
def _get_xml_doc(self, endpoint, query, is_post=False):
"""
Return False if connection could not be made.
Otherwise, return a minidom Document.
"""
response = self._get_response(endpoint, query, is_post=is_post)
return minidom.parse(response.text) | Return False if connection could not be made.
Otherwise, return a minidom Document. | Below is the the instruction that describes the task:
### Input:
Return False if connection could not be made.
Otherwise, return a minidom Document.
### Response:
def _get_xml_doc(self, endpoint, query, is_post=False):
"""
Return False if connection could not be made.
Otherwise, ret... |
def reboot(self):
"""Reboots the device.
Generally one should use this method to reboot the device instead of
directly calling `adb.reboot`. Because this method gracefully handles
the teardown and restoration of running services.
This method is blocking and only returns when th... | Reboots the device.
Generally one should use this method to reboot the device instead of
directly calling `adb.reboot`. Because this method gracefully handles
the teardown and restoration of running services.
This method is blocking and only returns when the reboot has completed
... | Below is the the instruction that describes the task:
### Input:
Reboots the device.
Generally one should use this method to reboot the device instead of
directly calling `adb.reboot`. Because this method gracefully handles
the teardown and restoration of running services.
This met... |
def make_initstr(modname, import_tuples, verbose=False):
"""
Just creates the string representation. Does no importing.
"""
imports = [tup[0] for tup in import_tuples]
from_imports = __get_from_imports(import_tuples)
inject_execstr = _inject_execstr(modname, import_tuples)
return _initstr(mo... | Just creates the string representation. Does no importing. | Below is the the instruction that describes the task:
### Input:
Just creates the string representation. Does no importing.
### Response:
def make_initstr(modname, import_tuples, verbose=False):
"""
Just creates the string representation. Does no importing.
"""
imports = [tup[0] for tup in import_t... |
def register(self, device, callback):
"""Register a callback.
device: device to be updated by subscription
callback: callback for notification of changes
"""
if not device:
logger.error("Received an invalid device: %r", device)
return
logger.debu... | Register a callback.
device: device to be updated by subscription
callback: callback for notification of changes | Below is the the instruction that describes the task:
### Input:
Register a callback.
device: device to be updated by subscription
callback: callback for notification of changes
### Response:
def register(self, device, callback):
"""Register a callback.
device: device to be update... |
def lats(self, degrees=True):
"""
Return the latitudes of each row of the gridded data.
Usage
-----
lats = x.lats([degrees])
Returns
-------
lats : ndarray, shape (nlat)
1-D numpy array of size nlat containing the latitude of each row
... | Return the latitudes of each row of the gridded data.
Usage
-----
lats = x.lats([degrees])
Returns
-------
lats : ndarray, shape (nlat)
1-D numpy array of size nlat containing the latitude of each row
of the gridded data.
Parameters
... | Below is the the instruction that describes the task:
### Input:
Return the latitudes of each row of the gridded data.
Usage
-----
lats = x.lats([degrees])
Returns
-------
lats : ndarray, shape (nlat)
1-D numpy array of size nlat containing the latitude ... |
def db(self, connection_string=None):
"""Gets the SQLALchemy session for this request"""
connection_string = connection_string or self.settings["db"]
if not hasattr(self, "_db_conns"):
self._db_conns = {}
if not connection_string in self._db_conns:
self._db_conn... | Gets the SQLALchemy session for this request | Below is the the instruction that describes the task:
### Input:
Gets the SQLALchemy session for this request
### Response:
def db(self, connection_string=None):
"""Gets the SQLALchemy session for this request"""
connection_string = connection_string or self.settings["db"]
if not hasattr(... |
def run_spyder(app, options, args):
"""
Create and show Spyder's main window
Start QApplication event loop
"""
#TODO: insert here
# Main window
main = MainWindow(options)
try:
main.setup()
except BaseException:
if main.console is not None:
try:... | Create and show Spyder's main window
Start QApplication event loop | Below is the the instruction that describes the task:
### Input:
Create and show Spyder's main window
Start QApplication event loop
### Response:
def run_spyder(app, options, args):
"""
Create and show Spyder's main window
Start QApplication event loop
"""
#TODO: insert here
# Ma... |
def validate(self, value, model=None, context=None):
""" Perform validation """
from boiler.user.services import user_service
self_id = None
if model:
if isinstance(model, dict):
self_id = model.get('id')
else:
self_id = getattr(mo... | Perform validation | Below is the the instruction that describes the task:
### Input:
Perform validation
### Response:
def validate(self, value, model=None, context=None):
""" Perform validation """
from boiler.user.services import user_service
self_id = None
if model:
if isinstance(model, ... |
def frange(start, stop, step=1.0):
""" Implementation of Python's ``range()`` function which works with floats.
Reference to this implementation: https://stackoverflow.com/a/36091634
:param start: start value
:type start: float
:param stop: end value
:type stop: float
:param step: incremen... | Implementation of Python's ``range()`` function which works with floats.
Reference to this implementation: https://stackoverflow.com/a/36091634
:param start: start value
:type start: float
:param stop: end value
:type stop: float
:param step: increment
:type step: float
:return: float
... | Below is the the instruction that describes the task:
### Input:
Implementation of Python's ``range()`` function which works with floats.
Reference to this implementation: https://stackoverflow.com/a/36091634
:param start: start value
:type start: float
:param stop: end value
:type stop: float... |
def _prepare_source(selector, source):
"""Normalize source rows and selectors."""
tablename, fields = get_data_specifier(selector)
if len(fields) != 1:
raise ItsdbError(
'Selector must specify exactly one data column: {}'
.format(selector)
)
if isinstance(source, ... | Normalize source rows and selectors. | Below is the the instruction that describes the task:
### Input:
Normalize source rows and selectors.
### Response:
def _prepare_source(selector, source):
"""Normalize source rows and selectors."""
tablename, fields = get_data_specifier(selector)
if len(fields) != 1:
raise ItsdbError(
... |
def bits(self):
"""
The target architecture word size. One of :class:`Target.Bits`.
"""
if self._bits is None:
value = self._DEFAULT_BITS.get(self.arch)
if value is None:
raise NotImplementedError('Could not determine the default word size of %s ar... | The target architecture word size. One of :class:`Target.Bits`. | Below is the the instruction that describes the task:
### Input:
The target architecture word size. One of :class:`Target.Bits`.
### Response:
def bits(self):
"""
The target architecture word size. One of :class:`Target.Bits`.
"""
if self._bits is None:
value = self._DEF... |
def get_wallet_addresses(wallet_name, api_key, is_hd_wallet=False,
zero_balance=None, used=None, omit_addresses=False, coin_symbol='btc'):
'''
Returns a list of wallet addresses as well as some meta-data
'''
assert is_valid_coin_symbol(coin_symbol)
assert api_key
assert len(wallet_name) ... | Returns a list of wallet addresses as well as some meta-data | Below is the the instruction that describes the task:
### Input:
Returns a list of wallet addresses as well as some meta-data
### Response:
def get_wallet_addresses(wallet_name, api_key, is_hd_wallet=False,
zero_balance=None, used=None, omit_addresses=False, coin_symbol='btc'):
'''
Returns a list o... |
def QA_util_datetime_to_strdatetime(dt):
"""
:param dt: pythone datetime.datetime
:return: 1999-02-01 09:30:91 string type
"""
strdatetime = "%04d-%02d-%02d %02d:%02d:%02d" % (
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second
)
return... | :param dt: pythone datetime.datetime
:return: 1999-02-01 09:30:91 string type | Below is the the instruction that describes the task:
### Input:
:param dt: pythone datetime.datetime
:return: 1999-02-01 09:30:91 string type
### Response:
def QA_util_datetime_to_strdatetime(dt):
"""
:param dt: pythone datetime.datetime
:return: 1999-02-01 09:30:91 string type
"""
str... |
def generate_doc(self, dir_name, vasprun_files):
"""
Process aflow style runs, where each run is actually a combination of
two vasp runs.
"""
try:
fullpath = os.path.abspath(dir_name)
# Defensively copy the additional fields first. This is a MUST.
... | Process aflow style runs, where each run is actually a combination of
two vasp runs. | Below is the the instruction that describes the task:
### Input:
Process aflow style runs, where each run is actually a combination of
two vasp runs.
### Response:
def generate_doc(self, dir_name, vasprun_files):
"""
Process aflow style runs, where each run is actually a combination of
... |
def _magic(header, footer, mime, ext=None):
""" Discover what type of file it is based on the incoming string """
if not header:
raise ValueError("Input was empty")
info = _identify_all(header, footer, ext)[0]
if mime:
return info.mime_type
return info.extension if not \
isin... | Discover what type of file it is based on the incoming string | Below is the the instruction that describes the task:
### Input:
Discover what type of file it is based on the incoming string
### Response:
def _magic(header, footer, mime, ext=None):
""" Discover what type of file it is based on the incoming string """
if not header:
raise ValueError("Input was e... |
def read_namespaced_replica_set(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replica_set # noqa: E501
read the specified ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=T... | read_namespaced_replica_set # noqa: E501
read the specified ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replica_set(name, namespace, async_req=True)
... | Below is the the instruction that describes the task:
### Input:
read_namespaced_replica_set # noqa: E501
read the specified ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread... |
def _round(self, **kwargs):
"""
Subclasses may override this method.
"""
mathInfo = self._toMathInfo(guidelines=False)
mathInfo = mathInfo.round()
self._fromMathInfo(mathInfo, guidelines=False) | Subclasses may override this method. | Below is the the instruction that describes the task:
### Input:
Subclasses may override this method.
### Response:
def _round(self, **kwargs):
"""
Subclasses may override this method.
"""
mathInfo = self._toMathInfo(guidelines=False)
mathInfo = mathInfo.round()
self... |
def uri_to_iri_parts(path, query, fragment):
r"""
Converts a URI parts to corresponding IRI parts in a given charset.
Examples for URI versus IRI:
:param path: The path of URI to convert.
:param query: The query string of URI to convert.
:param fragment: The fragment of URI to convert.
"""... | r"""
Converts a URI parts to corresponding IRI parts in a given charset.
Examples for URI versus IRI:
:param path: The path of URI to convert.
:param query: The query string of URI to convert.
:param fragment: The fragment of URI to convert. | Below is the the instruction that describes the task:
### Input:
r"""
Converts a URI parts to corresponding IRI parts in a given charset.
Examples for URI versus IRI:
:param path: The path of URI to convert.
:param query: The query string of URI to convert.
:param fragment: The fragment of URI... |
def process(self):
"""Periodic nonblocking processes"""
super(NativeBLEVirtualInterface, self).process()
if (not self._stream_sm_running) and (not self.reports.empty()):
self._stream_data()
if (not self._trace_sm_running) and (not self.traces.empty()):
self._se... | Periodic nonblocking processes | Below is the the instruction that describes the task:
### Input:
Periodic nonblocking processes
### Response:
def process(self):
"""Periodic nonblocking processes"""
super(NativeBLEVirtualInterface, self).process()
if (not self._stream_sm_running) and (not self.reports.empty()):
... |
def get(self, request):
"""
Render a form to collect user input about data sharing consent.
"""
enterprise_customer_uuid = request.GET.get('enterprise_customer_uuid')
success_url = request.GET.get('next')
failure_url = request.GET.get('failure_url')
course_id = re... | Render a form to collect user input about data sharing consent. | Below is the the instruction that describes the task:
### Input:
Render a form to collect user input about data sharing consent.
### Response:
def get(self, request):
"""
Render a form to collect user input about data sharing consent.
"""
enterprise_customer_uuid = request.GET.get('... |
def timedelta_to_string(timedelta):
"""
Utility that converts a pandas.Timedelta to a string representation
compatible with pandas.Timedelta constructor format
Parameters
----------
timedelta: pd.Timedelta
Returns
-------
string
string representation of 'timedelta'
"""
... | Utility that converts a pandas.Timedelta to a string representation
compatible with pandas.Timedelta constructor format
Parameters
----------
timedelta: pd.Timedelta
Returns
-------
string
string representation of 'timedelta' | Below is the the instruction that describes the task:
### Input:
Utility that converts a pandas.Timedelta to a string representation
compatible with pandas.Timedelta constructor format
Parameters
----------
timedelta: pd.Timedelta
Returns
-------
string
string representation of... |
def prepareToCalcEndOfPrdvP(self):
'''
Prepare to calculate end-of-period marginal value by creating an array
of market resources that the agent could have next period, considering
the grid of end-of-period assets and the distribution of shocks he might
experience next period. T... | Prepare to calculate end-of-period marginal value by creating an array
of market resources that the agent could have next period, considering
the grid of end-of-period assets and the distribution of shocks he might
experience next period. This differs from the baseline case because
diff... | Below is the the instruction that describes the task:
### Input:
Prepare to calculate end-of-period marginal value by creating an array
of market resources that the agent could have next period, considering
the grid of end-of-period assets and the distribution of shocks he might
experience n... |
def file():
""" Grammar for files found in the overall input files. """
return (
Optional(Word(alphanums).setResultsName('alias') +
Suppress(Literal('.'))) + Suppress(White()) +
Word(approved_printables).setResultsName('filename')
) | Grammar for files found in the overall input files. | Below is the the instruction that describes the task:
### Input:
Grammar for files found in the overall input files.
### Response:
def file():
""" Grammar for files found in the overall input files. """
return (
Optional(Word(alphanums).setResultsName('alias') +
Suppress... |
def _node_isomorphic(a, b, check_varprops=True):
"""
Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds.
"""
# first some quick checks
a_var_refs = sorted(len(vd['refs']) for vd in a._vars.values())
b_var_refs = sorted(len(vd['ref... | Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds. | Below is the the instruction that describes the task:
### Input:
Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds.
### Response:
def _node_isomorphic(a, b, check_varprops=True):
"""
Two Xmrs objects are isomorphic if they have the same str... |
def draw_markers(self, data, coordinates, style, label, mplobj=None):
"""
Draw a set of markers. By default, this is done by repeatedly
calling draw_path(), but renderers should generally overload
this method to provide a more efficient implementation.
In matplotlib, markers are... | Draw a set of markers. By default, this is done by repeatedly
calling draw_path(), but renderers should generally overload
this method to provide a more efficient implementation.
In matplotlib, markers are created using the plt.plot() command.
Parameters
----------
data... | Below is the the instruction that describes the task:
### Input:
Draw a set of markers. By default, this is done by repeatedly
calling draw_path(), but renderers should generally overload
this method to provide a more efficient implementation.
In matplotlib, markers are created using the pl... |
def get(obj):
"""
Determines file format and picks suitable file types, extensions and MIME types
Takes:
obj (bytes) -> byte sequence (128 bytes are enough)
Returns:
(<class 'fleep.Info'>) -> Class instance
"""
if not isinstance(obj, bytes):
raise TypeError("object typ... | Determines file format and picks suitable file types, extensions and MIME types
Takes:
obj (bytes) -> byte sequence (128 bytes are enough)
Returns:
(<class 'fleep.Info'>) -> Class instance | Below is the the instruction that describes the task:
### Input:
Determines file format and picks suitable file types, extensions and MIME types
Takes:
obj (bytes) -> byte sequence (128 bytes are enough)
Returns:
(<class 'fleep.Info'>) -> Class instance
### Response:
def get(obj):
"""... |
def generate(env):
"""Add Builders and construction variables for ar to an Environment."""
as_module.generate(env)
env['AS'] = '386asm'
env['ASFLAGS'] = SCons.Util.CLVar('')
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASCOM'] = '$AS $ASFLAGS $SOURCES -o $TARGET'
env['ASPPCOM'] = '$CC ... | Add Builders and construction variables for ar to an Environment. | Below is the the instruction that describes the task:
### Input:
Add Builders and construction variables for ar to an Environment.
### Response:
def generate(env):
"""Add Builders and construction variables for ar to an Environment."""
as_module.generate(env)
env['AS'] = '386asm'
env['ASFLA... |
def update(self):
""" Update all the switch values """
self.states = [bool(int(x)) for x in self.get('port list') or '0000'] | Update all the switch values | Below is the the instruction that describes the task:
### Input:
Update all the switch values
### Response:
def update(self):
""" Update all the switch values """
self.states = [bool(int(x)) for x in self.get('port list') or '0000'] |
def get_type(mime=None, ext=None):
"""
Returns the file type instance searching by
MIME type or file extension.
Args:
ext: file extension string. E.g: jpg, png, mp4, mp3
mime: MIME string. E.g: image/jpeg, video/mpeg
Returns:
The matched file type instance. Otherwise None.
... | Returns the file type instance searching by
MIME type or file extension.
Args:
ext: file extension string. E.g: jpg, png, mp4, mp3
mime: MIME string. E.g: image/jpeg, video/mpeg
Returns:
The matched file type instance. Otherwise None. | Below is the the instruction that describes the task:
### Input:
Returns the file type instance searching by
MIME type or file extension.
Args:
ext: file extension string. E.g: jpg, png, mp4, mp3
mime: MIME string. E.g: image/jpeg, video/mpeg
Returns:
The matched file type inst... |
def handle_prepared_selection_of_core_class_elements(self, core_class, models):
"""Handles the selection for TreeStore widgets maintaining lists of a specific `core_class` elements
If widgets hold a TreeStore with elements of a specific `core_class`, the local selection of that element
type is ... | Handles the selection for TreeStore widgets maintaining lists of a specific `core_class` elements
If widgets hold a TreeStore with elements of a specific `core_class`, the local selection of that element
type is handled by that widget. This method is called to integrate the local selection with the ove... | Below is the the instruction that describes the task:
### Input:
Handles the selection for TreeStore widgets maintaining lists of a specific `core_class` elements
If widgets hold a TreeStore with elements of a specific `core_class`, the local selection of that element
type is handled by that widget... |
def select(self, df, args, inplace=False):
"""
After joining, selects a subset of arguments
df: the result of a call to self.join(left)
args: a collcetion of arguments to select, as accepted by drain.util.list_expand:
- a tuple corresponding to concat_args,
e.... | After joining, selects a subset of arguments
df: the result of a call to self.join(left)
args: a collcetion of arguments to select, as accepted by drain.util.list_expand:
- a tuple corresponding to concat_args,
e.g. [('District', '12h'), ('Distict', '24h')]
- a di... | Below is the the instruction that describes the task:
### Input:
After joining, selects a subset of arguments
df: the result of a call to self.join(left)
args: a collcetion of arguments to select, as accepted by drain.util.list_expand:
- a tuple corresponding to concat_args,
... |
async def connect(self):
"""
Create new asynchronous connection to the RabbitMQ instance.
This will connect, declare exchange and bind itself to the configured queue.
After that, client is ready to publish or consume messages.
:return: Does not return anything.
"""
... | Create new asynchronous connection to the RabbitMQ instance.
This will connect, declare exchange and bind itself to the configured queue.
After that, client is ready to publish or consume messages.
:return: Does not return anything. | Below is the the instruction that describes the task:
### Input:
Create new asynchronous connection to the RabbitMQ instance.
This will connect, declare exchange and bind itself to the configured queue.
After that, client is ready to publish or consume messages.
:return: Does not return an... |
def color_validator(input_str):
"""
A filter allowing only the particular colors used by the Google Calendar
API
Raises ValidationError otherwise.
"""
try:
assert input_str in VALID_OVERRIDE_COLORS + ['']
return input_str
except AssertionError:
raise ValidationError(... | A filter allowing only the particular colors used by the Google Calendar
API
Raises ValidationError otherwise. | Below is the the instruction that describes the task:
### Input:
A filter allowing only the particular colors used by the Google Calendar
API
Raises ValidationError otherwise.
### Response:
def color_validator(input_str):
"""
A filter allowing only the particular colors used by the Google Calendar... |
def ecdsa_recover_compact(msg32, sig):
"""
Takes the a message and a parsed recoverable signature
Returns the serialized public key from the private key in the sign function
"""
assert isinstance(msg32, bytes)
assert len(msg32) == 32
_check_signature(sig)
# Check that recid is of... | Takes the a message and a parsed recoverable signature
Returns the serialized public key from the private key in the sign function | Below is the the instruction that describes the task:
### Input:
Takes the a message and a parsed recoverable signature
Returns the serialized public key from the private key in the sign function
### Response:
def ecdsa_recover_compact(msg32, sig):
"""
Takes the a message and a parsed recoverab... |
def elements_as_text(self, elems, indent=2):
""" Returns the elems dictionary as formatted plain text. """
assert elems
text = ""
for elename, eledesc in elems.items():
if isinstance(eledesc, dict):
desc_txt = self.elements_as_text(eledesc, indent + 2)
... | Returns the elems dictionary as formatted plain text. | Below is the the instruction that describes the task:
### Input:
Returns the elems dictionary as formatted plain text.
### Response:
def elements_as_text(self, elems, indent=2):
""" Returns the elems dictionary as formatted plain text. """
assert elems
text = ""
for elename, eledesc... |
def get_nagios_unit_name(relation_name='nrpe-external-master'):
"""
Return the nagios unit name prepended with host_context if needed
:param str relation_name: Name of relation nrpe sub joined to
"""
host_context = get_nagios_hostcontext(relation_name)
if host_context:
unit = "%s:%s" % ... | Return the nagios unit name prepended with host_context if needed
:param str relation_name: Name of relation nrpe sub joined to | Below is the the instruction that describes the task:
### Input:
Return the nagios unit name prepended with host_context if needed
:param str relation_name: Name of relation nrpe sub joined to
### Response:
def get_nagios_unit_name(relation_name='nrpe-external-master'):
"""
Return the nagios unit name... |
def set_permission(self, path, **kwargs):
"""Set permission of a path.
:param permission: The permission of a file/directory. Any radix-8 integer (leading zeros
may be omitted.)
:type permission: octal
"""
response = self._put(path, 'SETPERMISSION', **kwargs)
... | Set permission of a path.
:param permission: The permission of a file/directory. Any radix-8 integer (leading zeros
may be omitted.)
:type permission: octal | Below is the the instruction that describes the task:
### Input:
Set permission of a path.
:param permission: The permission of a file/directory. Any radix-8 integer (leading zeros
may be omitted.)
:type permission: octal
### Response:
def set_permission(self, path, **kwargs):
... |
def clear(self):
"""
Cleans up the manager. The manager can't be used after this method has
been called
"""
self.services.clear()
self.services = None
self._future_value = None
super(AggregateDependency, self).clear() | Cleans up the manager. The manager can't be used after this method has
been called | Below is the the instruction that describes the task:
### Input:
Cleans up the manager. The manager can't be used after this method has
been called
### Response:
def clear(self):
"""
Cleans up the manager. The manager can't be used after this method has
been called
"""
... |
def delete_offline_reports(self):
"""
Delete all stored offline reports
:return: List of reports that still require submission
"""
reports = self.get_offline_reports()
remaining_reports = reports[:]
for report in reports:
with open(report, 'r') as _f:
... | Delete all stored offline reports
:return: List of reports that still require submission | Below is the the instruction that describes the task:
### Input:
Delete all stored offline reports
:return: List of reports that still require submission
### Response:
def delete_offline_reports(self):
"""
Delete all stored offline reports
:return: List of reports that still require... |
def create_server(self, server):
"""
Create a server and its storages based on a (locally created) Server object.
Populates the given Server instance with the API response.
0.3.0: also supports giving the entire POST body as a dict that is directly
serialised into JSON. Refer t... | Create a server and its storages based on a (locally created) Server object.
Populates the given Server instance with the API response.
0.3.0: also supports giving the entire POST body as a dict that is directly
serialised into JSON. Refer to the REST API documentation for correct format.
... | Below is the the instruction that describes the task:
### Input:
Create a server and its storages based on a (locally created) Server object.
Populates the given Server instance with the API response.
0.3.0: also supports giving the entire POST body as a dict that is directly
serialised in... |
def Contains(self, other):
"""Checks if the passed parameter is in the range of this object.
"""
if other is None:
raise ValueError("other is None.")
if isinstance(other, Range):
if other.low >= self.low and other.high <= self.high:
return True
... | Checks if the passed parameter is in the range of this object. | Below is the the instruction that describes the task:
### Input:
Checks if the passed parameter is in the range of this object.
### Response:
def Contains(self, other):
"""Checks if the passed parameter is in the range of this object.
"""
if other is None:
raise ValueError("othe... |
async def Restore(self, backup_id):
'''
backup_id : str
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Backups',
request='Restore',
version=1,
params=_params)
_par... | backup_id : str
Returns -> None | Below is the the instruction that describes the task:
### Input:
backup_id : str
Returns -> None
### Response:
async def Restore(self, backup_id):
'''
backup_id : str
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='B... |
def thumbnail_url(source, alias):
"""
Return the thumbnail url for a source file using an aliased set of
thumbnail options.
If no matching alias is found, returns an empty string.
Example usage::
<img src="{{ person.photo|thumbnail_url:'small' }}" alt="">
"""
try:
thumb = ... | Return the thumbnail url for a source file using an aliased set of
thumbnail options.
If no matching alias is found, returns an empty string.
Example usage::
<img src="{{ person.photo|thumbnail_url:'small' }}" alt=""> | Below is the the instruction that describes the task:
### Input:
Return the thumbnail url for a source file using an aliased set of
thumbnail options.
If no matching alias is found, returns an empty string.
Example usage::
<img src="{{ person.photo|thumbnail_url:'small' }}" alt="">
### Respon... |
def getParams(self):
""" get params """
rv = np.array([])
if self.n_terms>0:
rv = np.concatenate([np.reshape(self.B[term_i],self.B[term_i].size, order='F') for term_i in range(self.n_terms)])
return rv | get params | Below is the the instruction that describes the task:
### Input:
get params
### Response:
def getParams(self):
""" get params """
rv = np.array([])
if self.n_terms>0:
rv = np.concatenate([np.reshape(self.B[term_i],self.B[term_i].size, order='F') for term_i in range(self.n_terms)... |
def get_shm_volumes():
"""
Mount an tmpfs volume to /dev/shm.
This will set /dev/shm size to half of the RAM of node.
By default, /dev/shm is very small, only 64MB.
Some experiments will fail due to lack of share memory,
such as some experiments running on Pytorch.
"""
volumes, volume_mo... | Mount an tmpfs volume to /dev/shm.
This will set /dev/shm size to half of the RAM of node.
By default, /dev/shm is very small, only 64MB.
Some experiments will fail due to lack of share memory,
such as some experiments running on Pytorch. | Below is the the instruction that describes the task:
### Input:
Mount an tmpfs volume to /dev/shm.
This will set /dev/shm size to half of the RAM of node.
By default, /dev/shm is very small, only 64MB.
Some experiments will fail due to lack of share memory,
such as some experiments running on Pytor... |
def char(self):
""" Read one character from the stream or queue if available. Return
EOF when EOF is reached.
"""
# Read a new chunk from the input stream if necessary
if self.chunkOffset >= self.chunkSize:
if not self.readChunk():
return EOF
... | Read one character from the stream or queue if available. Return
EOF when EOF is reached. | Below is the the instruction that describes the task:
### Input:
Read one character from the stream or queue if available. Return
EOF when EOF is reached.
### Response:
def char(self):
""" Read one character from the stream or queue if available. Return
EOF when EOF is reached.
... |
def to_python(self, value):
"""
Validates that the input can be converted to a time. Returns a
Python datetime.time object.
"""
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value.time()
if... | Validates that the input can be converted to a time. Returns a
Python datetime.time object. | Below is the the instruction that describes the task:
### Input:
Validates that the input can be converted to a time. Returns a
Python datetime.time object.
### Response:
def to_python(self, value):
"""
Validates that the input can be converted to a time. Returns a
Python datetime.t... |
def get_languages(self, include_main=False):
"""
Get all the languages except the main.
Try to get in order:
1.- item languages
2.- model languages
3.- application model languages
# 4.- default languages
:param master:
:param incl... | Get all the languages except the main.
Try to get in order:
1.- item languages
2.- model languages
3.- application model languages
# 4.- default languages
:param master:
:param include_main:
:return: | Below is the the instruction that describes the task:
### Input:
Get all the languages except the main.
Try to get in order:
1.- item languages
2.- model languages
3.- application model languages
# 4.- default languages
:param master:
:param ... |
def requests_for_variant(self, request, variant_id=None):
"""Get all the requests for a single variant
"""
requests = ProductRequest.objects.filter(variant__id=variant_id)
serializer = self.serializer_class(requests, many=True)
return Response(data=serializer.data, status=status.... | Get all the requests for a single variant | Below is the the instruction that describes the task:
### Input:
Get all the requests for a single variant
### Response:
def requests_for_variant(self, request, variant_id=None):
"""Get all the requests for a single variant
"""
requests = ProductRequest.objects.filter(variant__id=variant_id... |
def _slider_changed(self, n):
"""
updates the colormap / plot
"""
self._button_save.setEnabled(True)
self.modify_colorpoint(n, self._sliders[n].value()*0.001, self._colorpoint_list[n][1], self._colorpoint_list[n][2]) | updates the colormap / plot | Below is the the instruction that describes the task:
### Input:
updates the colormap / plot
### Response:
def _slider_changed(self, n):
"""
updates the colormap / plot
"""
self._button_save.setEnabled(True)
self.modify_colorpoint(n, self._sliders[n].value()*0.001, self._co... |
def where(self, code):
"""Adds a $where clause to this query.
The `code` argument must be an instance of :class:`basestring`
(:class:`str` in python 3) or :class:`~bson.code.Code`
containing a JavaScript expression. This expression will be
evaluated for each document scanned. On... | Adds a $where clause to this query.
The `code` argument must be an instance of :class:`basestring`
(:class:`str` in python 3) or :class:`~bson.code.Code`
containing a JavaScript expression. This expression will be
evaluated for each document scanned. Only those documents
for whi... | Below is the the instruction that describes the task:
### Input:
Adds a $where clause to this query.
The `code` argument must be an instance of :class:`basestring`
(:class:`str` in python 3) or :class:`~bson.code.Code`
containing a JavaScript expression. This expression will be
eval... |
def add_left_space(self, nspace=1):
"""elem_add n cols of spaces before the first col.
(for texttable 0.8.3)"""
sp = ' ' * nspace
for item in self._rows:
item[0] = sp + item[0] | elem_add n cols of spaces before the first col.
(for texttable 0.8.3) | Below is the the instruction that describes the task:
### Input:
elem_add n cols of spaces before the first col.
(for texttable 0.8.3)
### Response:
def add_left_space(self, nspace=1):
"""elem_add n cols of spaces before the first col.
(for texttable 0.8.3)"""
sp = ' ' * nspac... |
def admin_keywords_submit(request):
"""
Adds any new given keywords from the custom keywords field in the
admin, and returns their IDs for use when saving a model with a
keywords field.
"""
keyword_ids, titles = [], []
remove = punctuation.replace("-", "") # Strip punctuation, allow dashes.... | Adds any new given keywords from the custom keywords field in the
admin, and returns their IDs for use when saving a model with a
keywords field. | Below is the the instruction that describes the task:
### Input:
Adds any new given keywords from the custom keywords field in the
admin, and returns their IDs for use when saving a model with a
keywords field.
### Response:
def admin_keywords_submit(request):
"""
Adds any new given keywords from t... |
def fasta2bed(fastafile):
"""
Alternative BED generation from FASTA file. Used for sanity check.
"""
dustfasta = fastafile.rsplit(".", 1)[0] + ".dust.fasta"
for name, seq in parse_fasta(dustfasta):
for islower, ss in groupby(enumerate(seq), key=lambda x: x[-1].islower()):
if not ... | Alternative BED generation from FASTA file. Used for sanity check. | Below is the the instruction that describes the task:
### Input:
Alternative BED generation from FASTA file. Used for sanity check.
### Response:
def fasta2bed(fastafile):
"""
Alternative BED generation from FASTA file. Used for sanity check.
"""
dustfasta = fastafile.rsplit(".", 1)[0] + ".dust.fas... |
def get_words(self, include_freq=False, on_unicode_error='strict'):
"""
Get the entire list of words of the dictionary optionally
including the frequency of the individual words. This
does not include any subwords. For that please consult
the function get_subwords.
"""
... | Get the entire list of words of the dictionary optionally
including the frequency of the individual words. This
does not include any subwords. For that please consult
the function get_subwords. | Below is the the instruction that describes the task:
### Input:
Get the entire list of words of the dictionary optionally
including the frequency of the individual words. This
does not include any subwords. For that please consult
the function get_subwords.
### Response:
def get_words(self... |
def reload(self):
"""
allow to refresh the document, so after using update(), it could reload
its value from the database.
Be carreful : reload() will erase all unsaved values.
If no _id is set in the document, a KeyError is raised.
"""
old_doc = self.mongokat... | allow to refresh the document, so after using update(), it could reload
its value from the database.
Be carreful : reload() will erase all unsaved values.
If no _id is set in the document, a KeyError is raised. | Below is the the instruction that describes the task:
### Input:
allow to refresh the document, so after using update(), it could reload
its value from the database.
Be carreful : reload() will erase all unsaved values.
If no _id is set in the document, a KeyError is raised.
### Response: ... |
def run_as(self, identifiers):
"""
:type identifiers: subject_abcs.IdentifierCollection
"""
if (not self.has_identifiers):
msg = ("This subject does not yet have an identity. Assuming the "
"identity of another Subject is only allowed for Subjects "
... | :type identifiers: subject_abcs.IdentifierCollection | Below is the the instruction that describes the task:
### Input:
:type identifiers: subject_abcs.IdentifierCollection
### Response:
def run_as(self, identifiers):
"""
:type identifiers: subject_abcs.IdentifierCollection
"""
if (not self.has_identifiers):
msg = ("This s... |
def _board_from_game_image(self, game_image):
"""Return a board object matching the board in the game image.
Return None if any tiles are not identified.
"""
# board image
board_rect = self._board_tools['board_region'].region_in(game_image)
t, l, b, r = board_rect
... | Return a board object matching the board in the game image.
Return None if any tiles are not identified. | Below is the the instruction that describes the task:
### Input:
Return a board object matching the board in the game image.
Return None if any tiles are not identified.
### Response:
def _board_from_game_image(self, game_image):
"""Return a board object matching the board in the game image.
... |
def get_all_objects(self):
"Return pointers to all GC tracked objects"
for i, generation in enumerate(self.gc_generations):
generation_head_ptr = pygc_head_ptr = generation.head.get_pointer()
generation_head_addr = generation_head_ptr._value
while True:
... | Return pointers to all GC tracked objects | Below is the the instruction that describes the task:
### Input:
Return pointers to all GC tracked objects
### Response:
def get_all_objects(self):
"Return pointers to all GC tracked objects"
for i, generation in enumerate(self.gc_generations):
generation_head_ptr = pygc_head_ptr = gene... |
def fit_transform(self, X, y=None, **fit_params):
"""Fit all transformers, transform the data and concatenate results.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data to be transformed.
y : array-like, shape (n_samples, ...), o... | Fit all transformers, transform the data and concatenate results.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data to be transformed.
y : array-like, shape (n_samples, ...), optional
Targets for supervised learning.
... | Below is the the instruction that describes the task:
### Input:
Fit all transformers, transform the data and concatenate results.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data to be transformed.
y : array-like, shape (n_samples,... |
def on_get(resc, req, resp):
""" Get the models identified by query parameters
We return an empty list if no models are found.
"""
signals.pre_req.send(resc.model)
signals.pre_req_search.send(resc.model)
models = goldman.sess.store.search(resc.rtype, **{
'filters': req.filters,
... | Get the models identified by query parameters
We return an empty list if no models are found. | Below is the the instruction that describes the task:
### Input:
Get the models identified by query parameters
We return an empty list if no models are found.
### Response:
def on_get(resc, req, resp):
""" Get the models identified by query parameters
We return an empty list if no models are found.
... |
def create_entity_class(self):
'''
Creates a class-based entity with fixed values, using all of the supported data types.
'''
entity = Entity()
# Partition key and row key must be strings and are required
entity.PartitionKey = 'pk{}'.format(str(uuid.uuid4()).replace('-',... | Creates a class-based entity with fixed values, using all of the supported data types. | Below is the the instruction that describes the task:
### Input:
Creates a class-based entity with fixed values, using all of the supported data types.
### Response:
def create_entity_class(self):
'''
Creates a class-based entity with fixed values, using all of the supported data types.
'''... |
def touch(self, eventType=adbclient.DOWN_AND_UP, deltaX=0, deltaY=0):
'''
Touches the center of this C{View}. The touch can be displaced from the center by
using C{deltaX} and C{deltaY} values.
@param eventType: The event type
@type eventType: L{adbclient.DOWN}, L{adbclient.UP} ... | Touches the center of this C{View}. The touch can be displaced from the center by
using C{deltaX} and C{deltaY} values.
@param eventType: The event type
@type eventType: L{adbclient.DOWN}, L{adbclient.UP} or L{adbclient.DOWN_AND_UP}
@param deltaX: Displacement from center (X axis)
... | Below is the the instruction that describes the task:
### Input:
Touches the center of this C{View}. The touch can be displaced from the center by
using C{deltaX} and C{deltaY} values.
@param eventType: The event type
@type eventType: L{adbclient.DOWN}, L{adbclient.UP} or L{adbclient.DOWN_A... |
def _get_object_key(self, p_object):
"""Get key from object"""
matched_key = None
matched_index = None
if hasattr(p_object, self._searchNames[0]):
return getattr(p_object, self._searchNames[0])
for x in xrange(len(self._searchNames)):
key = self._searchN... | Get key from object | Below is the the instruction that describes the task:
### Input:
Get key from object
### Response:
def _get_object_key(self, p_object):
"""Get key from object"""
matched_key = None
matched_index = None
if hasattr(p_object, self._searchNames[0]):
return getattr(p_object,... |
def get_python(cls):
"""
returns the python and pip version
:return: python version, pip version
"""
python_version = sys.version_info[:3]
v_string = [str(i) for i in python_version]
python_version_s = '.'.join(v_string)
# pip_version = pip.__version__
... | returns the python and pip version
:return: python version, pip version | Below is the the instruction that describes the task:
### Input:
returns the python and pip version
:return: python version, pip version
### Response:
def get_python(cls):
"""
returns the python and pip version
:return: python version, pip version
"""
python_version ... |
def send(self, data):
"""Send `data' to the server.
``data`` can be a string object, a bytes object, an array object, a
file-like object that supports a .read() method, or an iterable object.
"""
if self.sock is None:
if self.auto_open:
self.connect()... | Send `data' to the server.
``data`` can be a string object, a bytes object, an array object, a
file-like object that supports a .read() method, or an iterable object. | Below is the the instruction that describes the task:
### Input:
Send `data' to the server.
``data`` can be a string object, a bytes object, an array object, a
file-like object that supports a .read() method, or an iterable object.
### Response:
def send(self, data):
"""Send `data' to the s... |
def connect_timeout(self):
""" Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
... | Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None | Below is the the instruction that describes the task:
### Input:
Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Tim... |
def _flatten_location_translations(location_translations):
"""If location A translates to B, and B to C, then make A translate directly to C.
Args:
location_translations: dict of Location -> Location, where the key translates to the value.
Mutated in place for efficiency ... | If location A translates to B, and B to C, then make A translate directly to C.
Args:
location_translations: dict of Location -> Location, where the key translates to the value.
Mutated in place for efficiency and simplicity of implementation. | Below is the the instruction that describes the task:
### Input:
If location A translates to B, and B to C, then make A translate directly to C.
Args:
location_translations: dict of Location -> Location, where the key translates to the value.
Mutated in place for efficien... |
def spawn(self, monitor, kind=None, **params):
'''Spawn a new :class:`Actor` and return its
:class:`.ActorProxyMonitor`.
'''
proxy = _spawn_actor(kind, monitor, **params)
# Add to the list of managed actors if this is a remote actor
if isinstance(proxy, Actor):
... | Spawn a new :class:`Actor` and return its
:class:`.ActorProxyMonitor`. | Below is the the instruction that describes the task:
### Input:
Spawn a new :class:`Actor` and return its
:class:`.ActorProxyMonitor`.
### Response:
def spawn(self, monitor, kind=None, **params):
'''Spawn a new :class:`Actor` and return its
:class:`.ActorProxyMonitor`.
'''
... |
def Run(self, args):
"""Lists a directory."""
try:
directory = vfs.VFSOpen(args.pathspec, progress_callback=self.Progress)
except (IOError, OSError) as e:
self.SetStatus(rdf_flows.GrrStatus.ReturnedStatus.IOERROR, e)
return
files = list(directory.ListFiles())
files.sort(key=lambda... | Lists a directory. | Below is the the instruction that describes the task:
### Input:
Lists a directory.
### Response:
def Run(self, args):
"""Lists a directory."""
try:
directory = vfs.VFSOpen(args.pathspec, progress_callback=self.Progress)
except (IOError, OSError) as e:
self.SetStatus(rdf_flows.GrrStatus.Ret... |
def ndvi(self):
""" Normalized difference vegetation index.
:return: NDVI
"""
red, nir = self.reflectance(3), self.reflectance(4)
ndvi = self._divide_zero((nir - red), (nir + red), nan)
return ndvi | Normalized difference vegetation index.
:return: NDVI | Below is the the instruction that describes the task:
### Input:
Normalized difference vegetation index.
:return: NDVI
### Response:
def ndvi(self):
""" Normalized difference vegetation index.
:return: NDVI
"""
red, nir = self.reflectance(3), self.reflectance(4)
ndvi... |
def set_sub_stream_format(self, format, callback=None):
'''
Set the stream fromat of sub stream????
'''
params = {'format': format}
return self.execute_command('setSubStreamFormat',
params, callback=callback) | Set the stream fromat of sub stream???? | Below is the the instruction that describes the task:
### Input:
Set the stream fromat of sub stream????
### Response:
def set_sub_stream_format(self, format, callback=None):
'''
Set the stream fromat of sub stream????
'''
params = {'format': format}
return self.execute_comm... |
def set_generation_type(self, num_processors=-1, num_splits=1000, verbose=-1):
"""Change generation type.
Choose weather to generate the data in parallel or on a single processor.
Args:
num_processors (int or None, optional): Number of parallel processors to use.
If... | Change generation type.
Choose weather to generate the data in parallel or on a single processor.
Args:
num_processors (int or None, optional): Number of parallel processors to use.
If ``num_processors==-1``, this will use multiprocessing module and use
avai... | Below is the the instruction that describes the task:
### Input:
Change generation type.
Choose weather to generate the data in parallel or on a single processor.
Args:
num_processors (int or None, optional): Number of parallel processors to use.
If ``num_processors==-1... |
def OMSymbol(self, module, name):
r"""
Helper function to build an OMS object
EXAMPLES::
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMSymbol(module="foo.bar", name="baz"); o
... | r"""
Helper function to build an OMS object
EXAMPLES::
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMSymbol(module="foo.bar", name="baz"); o
OMSymbol(name='baz', cd='foo.bar', id=Non... | Below is the the instruction that describes the task:
### Input:
r"""
Helper function to build an OMS object
EXAMPLES::
>>> from openmath.convert_pickle import PickleConverter
>>> converter = PickleConverter()
>>> o = converter.OMSymbol(module="foo.bar",... |
def recordbatch(self, auth, resource, entries, defer=False):
""" Records a list of historical entries to the resource specified.
Calls a function that bulids a request that writes a list of historical entries to the
specified resource.
Args:
auth: Takes the device cik
... | Records a list of historical entries to the resource specified.
Calls a function that bulids a request that writes a list of historical entries to the
specified resource.
Args:
auth: Takes the device cik
resource: Takes the dataport alias or rid.
entries: A ... | Below is the the instruction that describes the task:
### Input:
Records a list of historical entries to the resource specified.
Calls a function that bulids a request that writes a list of historical entries to the
specified resource.
Args:
auth: Takes the device cik
... |
def format(self, record: logging.LogRecord) -> str:
"""
Formats a record and serializes it as a JSON str. If record message isnt
already a dict, initializes a new dict and uses `default_msg_fieldname`
as a key as the record msg as the value.
"""
msg: Union[str, dict] = re... | Formats a record and serializes it as a JSON str. If record message isnt
already a dict, initializes a new dict and uses `default_msg_fieldname`
as a key as the record msg as the value. | Below is the the instruction that describes the task:
### Input:
Formats a record and serializes it as a JSON str. If record message isnt
already a dict, initializes a new dict and uses `default_msg_fieldname`
as a key as the record msg as the value.
### Response:
def format(self, record: logging.L... |
def _get_token_create_url(config):
'''
Create Vault url for token creation
'''
role_name = config.get('role_name', None)
auth_path = '/v1/auth/token/create'
base_url = config['url']
return '/'.join(x.strip('/') for x in (base_url, auth_path, role_name) if x) | Create Vault url for token creation | Below is the the instruction that describes the task:
### Input:
Create Vault url for token creation
### Response:
def _get_token_create_url(config):
'''
Create Vault url for token creation
'''
role_name = config.get('role_name', None)
auth_path = '/v1/auth/token/create'
base_url = config['... |
def main():
""" Build a standalone dql executable """
venv_dir = tempfile.mkdtemp()
try:
make_virtualenv(venv_dir)
print("Downloading dependencies")
pip = os.path.join(venv_dir, "bin", "pip")
subprocess.check_call([pip, "install", "pex"])
print("Building executable"... | Build a standalone dql executable | Below is the the instruction that describes the task:
### Input:
Build a standalone dql executable
### Response:
def main():
""" Build a standalone dql executable """
venv_dir = tempfile.mkdtemp()
try:
make_virtualenv(venv_dir)
print("Downloading dependencies")
pip = os.path.jo... |
def clean():
"""
Clean documentation generated files.
"""
shutil.rmtree(BUILD_PATH, ignore_errors=True)
shutil.rmtree(os.path.join(SOURCE_PATH, 'reference', 'api'),
ignore_errors=True) | Clean documentation generated files. | Below is the the instruction that describes the task:
### Input:
Clean documentation generated files.
### Response:
def clean():
"""
Clean documentation generated files.
"""
shutil.rmtree(BUILD_PATH, ignore_errors=True)
shutil.rmtree(os.path.join(SOURCE_PATH, 'reference', 'a... |
def run(self, result):
"""Run tests in suite inside of suite fixtures.
"""
# proxy the result for myself
log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests)
#import pdb
#pdb.set_trace()
if self.resultProxy:
result, orig = self... | Run tests in suite inside of suite fixtures. | Below is the the instruction that describes the task:
### Input:
Run tests in suite inside of suite fixtures.
### Response:
def run(self, result):
"""Run tests in suite inside of suite fixtures.
"""
# proxy the result for myself
log.debug("suite %s (%s) run called, tests: %s", id(se... |
def configure_app(config_path=None, project=None, default_config_path=None,
default_settings=None, settings_initializer=None,
settings_envvar=None, initializer=None, allow_extras=True,
config_module_name=None, runner_name=None, on_configure=None):
"""
:param... | :param project: should represent the canonical name for the project, generally
the same name it assigned in distutils.
:param default_config_path: the default location for the configuration file.
:param default_settings: default settings to load (think inheritence).
:param settings_initializer: a ca... | Below is the the instruction that describes the task:
### Input:
:param project: should represent the canonical name for the project, generally
the same name it assigned in distutils.
:param default_config_path: the default location for the configuration file.
:param default_settings: default settin... |
def as_search_action(self, *, index, action):
"""
Return an object as represented in a bulk api operation.
Bulk API operations have a very specific format. This function will
call the standard `as_search_document` method on the object and then
wrap that up in the correct format ... | Return an object as represented in a bulk api operation.
Bulk API operations have a very specific format. This function will
call the standard `as_search_document` method on the object and then
wrap that up in the correct format for the action specified.
https://www.elastic.co/guide/en... | Below is the the instruction that describes the task:
### Input:
Return an object as represented in a bulk api operation.
Bulk API operations have a very specific format. This function will
call the standard `as_search_document` method on the object and then
wrap that up in the correct form... |
def get_all_subnets(self, subnet_ids=None, filters=None):
"""
Retrieve information about your Subnets. You can filter results to
return information only about those Subnets that match your search
parameters. Otherwise, all Subnets associated with your account
are returned.
... | Retrieve information about your Subnets. You can filter results to
return information only about those Subnets that match your search
parameters. Otherwise, all Subnets associated with your account
are returned.
:type subnet_ids: list
:param subnet_ids: A list of strings with ... | Below is the the instruction that describes the task:
### Input:
Retrieve information about your Subnets. You can filter results to
return information only about those Subnets that match your search
parameters. Otherwise, all Subnets associated with your account
are returned.
:typ... |
def get_listing_api(self, resource):
""" Generates the meta descriptor for the resource listing api. """
get_all_params = self.get_listing_parameters(resource)
get_all_api = {
'path': '/%s/' % resource.get_api_name(),
'description': 'Operations on %s' % resource.model._... | Generates the meta descriptor for the resource listing api. | Below is the the instruction that describes the task:
### Input:
Generates the meta descriptor for the resource listing api.
### Response:
def get_listing_api(self, resource):
""" Generates the meta descriptor for the resource listing api. """
get_all_params = self.get_listing_parameters(resource)... |
def LeaseFlowForProcessing(self,
client_id,
flow_id,
processing_time,
cursor=None):
"""Marks a flow as being processed on this worker and returns it."""
query = ("SELECT " + self.FLOW_DB_FIELDS +
... | Marks a flow as being processed on this worker and returns it. | Below is the the instruction that describes the task:
### Input:
Marks a flow as being processed on this worker and returns it.
### Response:
def LeaseFlowForProcessing(self,
client_id,
flow_id,
processing_time,
... |
def __get_conn(**kwargs):
'''
Detects what type of dom this node is and attempts to connect to the
correct hypervisor via libvirt.
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect w... | Detects what type of dom this node is and attempts to connect to the
correct hypervisor via libvirt.
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect with, overriding defaults | Below is the the instruction that describes the task:
### Input:
Detects what type of dom this node is and attempts to connect to the
correct hypervisor via libvirt.
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param ... |
def parse_checkM_tables(tables):
"""
convert checkM genome info tables to dictionary
"""
g2info = {}
for table in tables:
for line in open(table):
line = line.strip().split('\t')
if line[0].startswith('Bin Id'):
header = line
header[8] ... | convert checkM genome info tables to dictionary | Below is the the instruction that describes the task:
### Input:
convert checkM genome info tables to dictionary
### Response:
def parse_checkM_tables(tables):
"""
convert checkM genome info tables to dictionary
"""
g2info = {}
for table in tables:
for line in open(table):
l... |
def insertFile(self, qInserts=False):
"""
API to insert a list of file into DBS in DBS. Up to 10 files can be inserted in one request.
:param qInserts: True means that inserts will be queued instead of done immediately. INSERT QUEUE Manager will perform the inserts, within few minutes.
... | API to insert a list of file into DBS in DBS. Up to 10 files can be inserted in one request.
:param qInserts: True means that inserts will be queued instead of done immediately. INSERT QUEUE Manager will perform the inserts, within few minutes.
:type qInserts: bool
:param filesList: List of dic... | Below is the the instruction that describes the task:
### Input:
API to insert a list of file into DBS in DBS. Up to 10 files can be inserted in one request.
:param qInserts: True means that inserts will be queued instead of done immediately. INSERT QUEUE Manager will perform the inserts, within few minute... |
def result(self, result, functionality):
"""
For the final result of the scan.
@param result: as returned by BasePluginInternal.url_scan
@param functionality: functionality as returned by
BasePluginInternal._general_init
"""
for enumerate in result:
... | For the final result of the scan.
@param result: as returned by BasePluginInternal.url_scan
@param functionality: functionality as returned by
BasePluginInternal._general_init | Below is the the instruction that describes the task:
### Input:
For the final result of the scan.
@param result: as returned by BasePluginInternal.url_scan
@param functionality: functionality as returned by
BasePluginInternal._general_init
### Response:
def result(self, result, functio... |
def marvcli_undiscard(datasets):
"""Undiscard DATASETS previously discarded."""
create_app()
setids = parse_setids(datasets, discarded=True)
dataset = Dataset.__table__
stmt = dataset.update()\
.where(dataset.c.setid.in_(setids))\
.values(discarded=False)
db.... | Undiscard DATASETS previously discarded. | Below is the the instruction that describes the task:
### Input:
Undiscard DATASETS previously discarded.
### Response:
def marvcli_undiscard(datasets):
"""Undiscard DATASETS previously discarded."""
create_app()
setids = parse_setids(datasets, discarded=True)
dataset = Dataset.__table__
stmt ... |
def scale(data, scale = (1.,1.,1.), interpolation = "linear"):
"""
returns a interpolated, scaled version of data
the output shape is scaled too.
Parameters
----------
data: ndarray
3d input array
scale: float, tuple
scaling factor along each axis (x,y,z)
inter... | returns a interpolated, scaled version of data
the output shape is scaled too.
Parameters
----------
data: ndarray
3d input array
scale: float, tuple
scaling factor along each axis (x,y,z)
interpolation: str
either "nearest" or "linear"
Returns
-------... | Below is the the instruction that describes the task:
### Input:
returns a interpolated, scaled version of data
the output shape is scaled too.
Parameters
----------
data: ndarray
3d input array
scale: float, tuple
scaling factor along each axis (x,y,z)
interpolati... |
def get_message_handler(self, message_handlers):
"""
Create a MessageHandler for the configured Encoder
:param message_handlers: a dictionart of MessageHandler keyed by encoder
:return: a MessageHandler
"""
encoder = self.options.encoder
try:
return me... | Create a MessageHandler for the configured Encoder
:param message_handlers: a dictionart of MessageHandler keyed by encoder
:return: a MessageHandler | Below is the the instruction that describes the task:
### Input:
Create a MessageHandler for the configured Encoder
:param message_handlers: a dictionart of MessageHandler keyed by encoder
:return: a MessageHandler
### Response:
def get_message_handler(self, message_handlers):
"""
C... |
def pair(self, array, stats):
"""
:return (array, array_stats) if stats, else (array, None)
"""
if len(self.weights) > 1 and stats:
statnames, statfuncs = zip(*stats)
array_stats = compute_stats2(array, statfuncs, self.weights)
else:
array_stat... | :return (array, array_stats) if stats, else (array, None) | Below is the the instruction that describes the task:
### Input:
:return (array, array_stats) if stats, else (array, None)
### Response:
def pair(self, array, stats):
"""
:return (array, array_stats) if stats, else (array, None)
"""
if len(self.weights) > 1 and stats:
st... |
def memoize(func):
"""Simple caching decorator."""
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Caching wrapper."""
key = (args, tuple(sorted(kwargs.items())))
if key in cache:
return cache[key]
else:
result = func(*args, **k... | Simple caching decorator. | Below is the the instruction that describes the task:
### Input:
Simple caching decorator.
### Response:
def memoize(func):
"""Simple caching decorator."""
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Caching wrapper."""
key = (args, tuple(sorted(kwargs.items(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.