code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_subject(self, msg):
"""Extracts the subject line from an EmailMessage object."""
text, encoding = decode_header(msg['subject'])[-1]
try:
text = text.decode(encoding)
# If it's already decoded, ignore error
except AttributeError:
pass
re... | Extracts the subject line from an EmailMessage object. | Below is the the instruction that describes the task:
### Input:
Extracts the subject line from an EmailMessage object.
### Response:
def get_subject(self, msg):
"""Extracts the subject line from an EmailMessage object."""
text, encoding = decode_header(msg['subject'])[-1]
try:
... |
def tradingStatus(symbol=None, token='', version=''):
'''The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination ... | The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons.
For non-IEX-listed securities, IE... | Below is the the instruction that describes the task:
### Input:
The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissem... |
def _get_param_names(self):
"""
Get mappable parameters from YAML.
"""
template = Template(self.yaml_string)
names = ['yaml_string'] # always include the template
for match in re.finditer(template.pattern, template.template):
name = match.group('named') or ma... | Get mappable parameters from YAML. | Below is the the instruction that describes the task:
### Input:
Get mappable parameters from YAML.
### Response:
def _get_param_names(self):
"""
Get mappable parameters from YAML.
"""
template = Template(self.yaml_string)
names = ['yaml_string'] # always include the templa... |
def acquire_hosting_device_slots(self, context, hosting_device, resource,
resource_type, resource_service, num,
exclusive=False):
"""Assign <num> slots in <hosting_device> to logical <resource>.
If exclusive is True the hosting d... | Assign <num> slots in <hosting_device> to logical <resource>.
If exclusive is True the hosting device is bound to the resource's
tenant. Otherwise it is not bound to any tenant.
Returns True if allocation was granted, False otherwise. | Below is the the instruction that describes the task:
### Input:
Assign <num> slots in <hosting_device> to logical <resource>.
If exclusive is True the hosting device is bound to the resource's
tenant. Otherwise it is not bound to any tenant.
Returns True if allocation was granted, False o... |
def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
TermDocMatrix
'''
rank_df = self.scorer.get_rank_df(term_doc_matrix)
return s... | Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
TermDocMatrix | Below is the the instruction that describes the task:
### Input:
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
TermDocMatrix
### Response:
def compact(self, term_doc_matrix):
'''
Param... |
def batch_retrieve_overrides_in_course(self, course_id, assignment_overrides_id, assignment_overrides_assignment_id):
"""
Batch retrieve overrides in a course.
Returns a list of specified overrides in this course, providing
they target sections/groups/students visible to the curren... | Batch retrieve overrides in a course.
Returns a list of specified overrides in this course, providing
they target sections/groups/students visible to the current user.
Returns null elements in the list for requests that were not found. | Below is the the instruction that describes the task:
### Input:
Batch retrieve overrides in a course.
Returns a list of specified overrides in this course, providing
they target sections/groups/students visible to the current user.
Returns null elements in the list for requests that we... |
def _set_predictor(self, predictor):
"""Set predictor for continued training.
It is not recommended for user to call this function.
Please use init_model argument in engine.train() or engine.cv() instead.
"""
if predictor is self._predictor:
return self
if se... | Set predictor for continued training.
It is not recommended for user to call this function.
Please use init_model argument in engine.train() or engine.cv() instead. | Below is the the instruction that describes the task:
### Input:
Set predictor for continued training.
It is not recommended for user to call this function.
Please use init_model argument in engine.train() or engine.cv() instead.
### Response:
def _set_predictor(self, predictor):
"""Set pr... |
def split(self, bits_count):
""" Split array into smaller parts. Each small array is fixed-length WBinArray (length of that array is
bits_count).
:param bits_count: array length
:return: list of WBinArray
"""
result = []
array = WBinArray(self.__value, self.__size)
if (len(array) % bits_count) > 0:
... | Split array into smaller parts. Each small array is fixed-length WBinArray (length of that array is
bits_count).
:param bits_count: array length
:return: list of WBinArray | Below is the the instruction that describes the task:
### Input:
Split array into smaller parts. Each small array is fixed-length WBinArray (length of that array is
bits_count).
:param bits_count: array length
:return: list of WBinArray
### Response:
def split(self, bits_count):
""" Split array into small... |
def check_differences(self):
""" In-depth check of mail differences.
Compare all mails of the duplicate set with each other, both in size
and content. Raise an error if we're not within the limits imposed by
the threshold setting.
"""
logger.info("Check that mail differe... | In-depth check of mail differences.
Compare all mails of the duplicate set with each other, both in size
and content. Raise an error if we're not within the limits imposed by
the threshold setting. | Below is the the instruction that describes the task:
### Input:
In-depth check of mail differences.
Compare all mails of the duplicate set with each other, both in size
and content. Raise an error if we're not within the limits imposed by
the threshold setting.
### Response:
def check_dif... |
def avgwave(self, wavelengths=None):
"""Calculate the :ref:`average wavelength <synphot-formula-avgwv>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be... | Calculate the :ref:`average wavelength <synphot-formula-avgwv>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, `waveset` i... | Below is the the instruction that describes the task:
### Input:
Calculate the :ref:`average wavelength <synphot-formula-avgwv>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Qu... |
def show_correlation_matrix(self, correlation_matrix):
"""Shows the given correlation matrix as image
:param correlation_matrix: Correlation matrix of features
"""
cr_plot.create_correlation_matrix_plot(
correlation_matrix, self.title, self.headers_to_test
)
... | Shows the given correlation matrix as image
:param correlation_matrix: Correlation matrix of features | Below is the the instruction that describes the task:
### Input:
Shows the given correlation matrix as image
:param correlation_matrix: Correlation matrix of features
### Response:
def show_correlation_matrix(self, correlation_matrix):
"""Shows the given correlation matrix as image
:param... |
def get_parent_of_type(typ, obj):
"""
Finds first object up the parent chain of the given type.
If no parent of the given type exists None is returned.
Args:
typ(str or python class): The type of the model object we are
looking for.
obj (model object): Python model object wh... | Finds first object up the parent chain of the given type.
If no parent of the given type exists None is returned.
Args:
typ(str or python class): The type of the model object we are
looking for.
obj (model object): Python model object which is the start of the
search pro... | Below is the the instruction that describes the task:
### Input:
Finds first object up the parent chain of the given type.
If no parent of the given type exists None is returned.
Args:
typ(str or python class): The type of the model object we are
looking for.
obj (model object):... |
def launch_job(self, job_id):
"""
Convenience method for launching a job. We use POST for actions
outside of HTTP verbs (job launch in this case).
"""
assert self.api_version.lower() in ['0.01a', '0.1'], \
'This method is only supported in BETA (0.01) and ALPHA (0.01... | Convenience method for launching a job. We use POST for actions
outside of HTTP verbs (job launch in this case). | Below is the the instruction that describes the task:
### Input:
Convenience method for launching a job. We use POST for actions
outside of HTTP verbs (job launch in this case).
### Response:
def launch_job(self, job_id):
"""
Convenience method for launching a job. We use POST for actions... |
def printed_out(self, name):
"""
Create a string representation of the action
"""
opt = self.variables().optional_namestring()
req = self.variables().required_namestring()
out = ''
out += '| |\n'
out += '| |---{}({}{})\n'.format(name, req, opt)
... | Create a string representation of the action | Below is the the instruction that describes the task:
### Input:
Create a string representation of the action
### Response:
def printed_out(self, name):
"""
Create a string representation of the action
"""
opt = self.variables().optional_namestring()
req = self.variables().r... |
def send_short_lpp_packet(self, dest_id, data):
"""
Send ultra-wide-band LPP packet to dest_id
"""
pk = CRTPPacket()
pk.port = CRTPPort.LOCALIZATION
pk.channel = self.GENERIC_CH
pk.data = struct.pack('<BB', self.LPS_SHORT_LPP_PACKET, dest_id) + data
self.... | Send ultra-wide-band LPP packet to dest_id | Below is the the instruction that describes the task:
### Input:
Send ultra-wide-band LPP packet to dest_id
### Response:
def send_short_lpp_packet(self, dest_id, data):
"""
Send ultra-wide-band LPP packet to dest_id
"""
pk = CRTPPacket()
pk.port = CRTPPort.LOCALIZATION
... |
def network_delete_event(self, network_info):
"""Process network delete event."""
net_id = network_info['network_id']
if net_id not in self.network:
LOG.error('network_delete_event: net_id %s does not exist.',
net_id)
return
segid = self.ne... | Process network delete event. | Below is the the instruction that describes the task:
### Input:
Process network delete event.
### Response:
def network_delete_event(self, network_info):
"""Process network delete event."""
net_id = network_info['network_id']
if net_id not in self.network:
LOG.error('network_d... |
def create_backed_vol(self, name, backer, _format='qcow2'):
"""
TODO(rdelinger) think about changing _format
This is a pretty specialized function.
It takes an existing volume, and creates a new volume
that is backed by the existing volume
Sadly there is no easy way to do... | TODO(rdelinger) think about changing _format
This is a pretty specialized function.
It takes an existing volume, and creates a new volume
that is backed by the existing volume
Sadly there is no easy way to do this in libvirt, the
best way I've found is to just create some xml and... | Below is the the instruction that describes the task:
### Input:
TODO(rdelinger) think about changing _format
This is a pretty specialized function.
It takes an existing volume, and creates a new volume
that is backed by the existing volume
Sadly there is no easy way to do this in li... |
def get_context_data(self, **kwargs):
""" Returns the context data to provide to the template. """
context = super().get_context_data(**kwargs)
# Insert the considered topic and the associated forum into the context
topic = self.get_topic()
context['topic'] = topic
conte... | Returns the context data to provide to the template. | Below is the the instruction that describes the task:
### Input:
Returns the context data to provide to the template.
### Response:
def get_context_data(self, **kwargs):
""" Returns the context data to provide to the template. """
context = super().get_context_data(**kwargs)
# Insert the c... |
def serverdir():
""" Get the location of the server subpackage
"""
path = join(ROOT_DIR, 'server')
path = normpath(path)
if sys.platform == 'cygwin': path = realpath(path)
return path | Get the location of the server subpackage | Below is the the instruction that describes the task:
### Input:
Get the location of the server subpackage
### Response:
def serverdir():
""" Get the location of the server subpackage
"""
path = join(ROOT_DIR, 'server')
path = normpath(path)
if sys.platform == 'cygwin': path = realpath(path)
... |
def binarize_signal(signal, treshold="auto", cut="higher"):
"""
Binarize a channel based on a continuous channel.
Parameters
----------
signal = array or list
The signal channel.
treshold = float
The treshold value by which to select the events. If "auto", takes the value betwee... | Binarize a channel based on a continuous channel.
Parameters
----------
signal = array or list
The signal channel.
treshold = float
The treshold value by which to select the events. If "auto", takes the value between the max and the min.
cut = str
"higher" or "lower", define... | Below is the the instruction that describes the task:
### Input:
Binarize a channel based on a continuous channel.
Parameters
----------
signal = array or list
The signal channel.
treshold = float
The treshold value by which to select the events. If "auto", takes the value between t... |
def permutation_entropy(time_series, order=3, delay=1, normalize=False):
"""Permutation Entropy.
Parameters
----------
time_series : list or np.array
Time series
order : int
Order of permutation entropy
delay : int
Time delay
normalize : bool
If True, divide ... | Permutation Entropy.
Parameters
----------
time_series : list or np.array
Time series
order : int
Order of permutation entropy
delay : int
Time delay
normalize : bool
If True, divide by log2(factorial(m)) to normalize the entropy
between 0 and 1. Otherwis... | Below is the the instruction that describes the task:
### Input:
Permutation Entropy.
Parameters
----------
time_series : list or np.array
Time series
order : int
Order of permutation entropy
delay : int
Time delay
normalize : bool
If True, divide by log2(fac... |
def expand_as_args(args):
"""Returns `True` if `args` should be expanded as `*args`."""
return (isinstance(args, collections.Sequence) and
not _is_namedtuple(args) and not _force_leaf(args)) | Returns `True` if `args` should be expanded as `*args`. | Below is the the instruction that describes the task:
### Input:
Returns `True` if `args` should be expanded as `*args`.
### Response:
def expand_as_args(args):
"""Returns `True` if `args` should be expanded as `*args`."""
return (isinstance(args, collections.Sequence) and
not _is_namedtuple(args) an... |
def get_startup(self, id_):
""" Get startup based on id
"""
return _get_request(_STARTUP.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,
id_=id_,
at=self.access_token)) | Get startup based on id | Below is the the instruction that describes the task:
### Input:
Get startup based on id
### Response:
def get_startup(self, id_):
""" Get startup based on id
"""
return _get_request(_STARTUP.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,
... |
def set_ifo(self,ifo):
"""
Set the ifo name to analyze. If the channel name for the job is defined,
then the name of the ifo is prepended to the channel name obtained
from the job configuration file and passed with a --channel-name option.
@param ifo: two letter ifo code (e.g. L1, H1 or H2).
"""... | Set the ifo name to analyze. If the channel name for the job is defined,
then the name of the ifo is prepended to the channel name obtained
from the job configuration file and passed with a --channel-name option.
@param ifo: two letter ifo code (e.g. L1, H1 or H2). | Below is the the instruction that describes the task:
### Input:
Set the ifo name to analyze. If the channel name for the job is defined,
then the name of the ifo is prepended to the channel name obtained
from the job configuration file and passed with a --channel-name option.
@param ifo: two letter ifo... |
def rename(self, old_name, new_name):
"""Rename key to a new name."""
try:
self.api.rename(mkey(old_name), mkey(new_name))
except ResponseError, exc:
if "no such key" in exc.args:
raise KeyError(old_name)
raise | Rename key to a new name. | Below is the the instruction that describes the task:
### Input:
Rename key to a new name.
### Response:
def rename(self, old_name, new_name):
"""Rename key to a new name."""
try:
self.api.rename(mkey(old_name), mkey(new_name))
except ResponseError, exc:
if "no such ... |
def cli(self, prt=sys.stdout):
"""Command-line interface for go_draw script."""
kws = self.objdoc.get_docargs(prt=None)
godag = get_godag(kws['obo'], prt=None, loading_bar=False, optional_attrs=['relationship'])
usrgos = GetGOs(godag, max_gos=200).get_usrgos(kws.get('GO_FILE'), prt)
... | Command-line interface for go_draw script. | Below is the the instruction that describes the task:
### Input:
Command-line interface for go_draw script.
### Response:
def cli(self, prt=sys.stdout):
"""Command-line interface for go_draw script."""
kws = self.objdoc.get_docargs(prt=None)
godag = get_godag(kws['obo'], prt=None, loading_b... |
def quick_str_input(prompt, default_value):
"""
Function to display a quick question for text input.
**Parameters:**
- **prompt:** Text / question to display
- **default_value:** Default value for no entry
**Returns:** text_type() or default_value.
"""
... | Function to display a quick question for text input.
**Parameters:**
- **prompt:** Text / question to display
- **default_value:** Default value for no entry
**Returns:** text_type() or default_value. | Below is the the instruction that describes the task:
### Input:
Function to display a quick question for text input.
**Parameters:**
- **prompt:** Text / question to display
- **default_value:** Default value for no entry
**Returns:** text_type() or default_value.
### Respons... |
def main():
"""
Main entry point for execution as a program (instead of as a module).
"""
args = parse_args()
logging.info('coursera_dl version %s', __version__)
completed_classes = []
classes_with_errors = []
mkdir_p(PATH_CACHE, 0o700)
if args.clear_cache:
shutil.rmtree(PA... | Main entry point for execution as a program (instead of as a module). | Below is the the instruction that describes the task:
### Input:
Main entry point for execution as a program (instead of as a module).
### Response:
def main():
"""
Main entry point for execution as a program (instead of as a module).
"""
args = parse_args()
logging.info('coursera_dl version %... |
def bsn(self) -> str:
"""Generate a random, but valid ``Burgerservicenummer``.
:returns: Random BSN.
:Example:
255159705
"""
def _is_valid_bsn(number: str) -> bool:
total = 0
multiplier = 9
for char in number:
mul... | Generate a random, but valid ``Burgerservicenummer``.
:returns: Random BSN.
:Example:
255159705 | Below is the the instruction that describes the task:
### Input:
Generate a random, but valid ``Burgerservicenummer``.
:returns: Random BSN.
:Example:
255159705
### Response:
def bsn(self) -> str:
"""Generate a random, but valid ``Burgerservicenummer``.
:returns: Rand... |
def eth_getBlockByNumber(self, number):
"""Get block body by block number.
:param number:
:return:
"""
block_hash = self.reader._get_block_hash(number)
block_number = _format_block_number(number)
body_key = body_prefix + block_number + block_hash
block_da... | Get block body by block number.
:param number:
:return: | Below is the the instruction that describes the task:
### Input:
Get block body by block number.
:param number:
:return:
### Response:
def eth_getBlockByNumber(self, number):
"""Get block body by block number.
:param number:
:return:
"""
block_hash = self.r... |
def execute(self, query, *args, **kwargs):
"""Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters.
"""
tornado_future = Futur... | Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters. | Below is the the instruction that describes the task:
### Input:
Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters.
### Response:
def execute(... |
def thermal_expansion_coeff(self, structure, temperature, mode="debye"):
"""
Gets thermal expansion coefficient from third-order constants.
Args:
temperature (float): Temperature in kelvin, if not specified
will return non-cv-normalized value
structure (S... | Gets thermal expansion coefficient from third-order constants.
Args:
temperature (float): Temperature in kelvin, if not specified
will return non-cv-normalized value
structure (Structure): Structure to be used in directional heat
capacity determination, o... | Below is the the instruction that describes the task:
### Input:
Gets thermal expansion coefficient from third-order constants.
Args:
temperature (float): Temperature in kelvin, if not specified
will return non-cv-normalized value
structure (Structure): Structure to ... |
def api_version(self, verbose=False):
'''
Get information about the API
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#api_version_information
'''
return self.__auth_req_get(self.rest_url, verbose=verbose) | Get information about the API
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#api_version_information | Below is the the instruction that describes the task:
### Input:
Get information about the API
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#api_version_information
### Response:
def api_version(self, verbose=False):
'''
Get information about the API
http://docs.opsview.com... |
def accepts_contributor_roles(func):
"""
Decorator that accepts only contributor roles
:param func:
:return:
"""
if inspect.isclass(func):
apply_function_to_members(func, accepts_contributor_roles)
return func
else:
@functools.wraps(func)
def decorator(*args, ... | Decorator that accepts only contributor roles
:param func:
:return: | Below is the the instruction that describes the task:
### Input:
Decorator that accepts only contributor roles
:param func:
:return:
### Response:
def accepts_contributor_roles(func):
"""
Decorator that accepts only contributor roles
:param func:
:return:
"""
if inspect.isclass(func... |
def add(self, data, overwrite=False):
"""Add given data string by guessing its format. The format must be
Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to
``True`` to allow already added data to be overwritten.
"""
if is_srec(data):
self.add_srec(data, ov... | Add given data string by guessing its format. The format must be
Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to
``True`` to allow already added data to be overwritten. | Below is the the instruction that describes the task:
### Input:
Add given data string by guessing its format. The format must be
Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to
``True`` to allow already added data to be overwritten.
### Response:
def add(self, data, overwrite=False):
... |
def calcFontScaling(self):
'''Calculates the current font size and left position for the current window.'''
self.ypx = self.figure.get_size_inches()[1]*self.figure.dpi
self.xpx = self.figure.get_size_inches()[0]*self.figure.dpi
self.fontSize = self.vertSize*(self.ypx/2.0)
self.le... | Calculates the current font size and left position for the current window. | Below is the the instruction that describes the task:
### Input:
Calculates the current font size and left position for the current window.
### Response:
def calcFontScaling(self):
'''Calculates the current font size and left position for the current window.'''
self.ypx = self.figure.get_size_inche... |
def z_angle_rotate(xy, theta):
"""
Rotated the input vector or set of vectors `xy` by the angle `theta`.
Parameters
----------
xy : array_like
The vector or array of vectors to transform. Must have shape
"""
xy = np.array(xy).T
theta = np.array(theta).T
out = np.zeros_lik... | Rotated the input vector or set of vectors `xy` by the angle `theta`.
Parameters
----------
xy : array_like
The vector or array of vectors to transform. Must have shape | Below is the the instruction that describes the task:
### Input:
Rotated the input vector or set of vectors `xy` by the angle `theta`.
Parameters
----------
xy : array_like
The vector or array of vectors to transform. Must have shape
### Response:
def z_angle_rotate(xy, theta):
"""
Rot... |
def get_portal_by_name(self, portal_name):
"""
Set active portal according to the name passed in 'portal_name'.
Returns dictionary of device 'serial_number: rid'
"""
portals = self.get_portals_list()
for p in portals:
# print("Checking {!r}".format(p... | Set active portal according to the name passed in 'portal_name'.
Returns dictionary of device 'serial_number: rid' | Below is the the instruction that describes the task:
### Input:
Set active portal according to the name passed in 'portal_name'.
Returns dictionary of device 'serial_number: rid'
### Response:
def get_portal_by_name(self, portal_name):
"""
Set active portal according to the name p... |
def pan_delta(self, dx_px, dy_px):
"""
This causes the scene to appear to translate right and up
(i.e., what really happens is the camera is translated left and down).
This is also called "panning" in some software packages.
Passing in negative delta values causes the opposite mo... | This causes the scene to appear to translate right and up
(i.e., what really happens is the camera is translated left and down).
This is also called "panning" in some software packages.
Passing in negative delta values causes the opposite motion. | Below is the the instruction that describes the task:
### Input:
This causes the scene to appear to translate right and up
(i.e., what really happens is the camera is translated left and down).
This is also called "panning" in some software packages.
Passing in negative delta values causes t... |
def hostcmd_push(base_path, project_name, engine_name, vars_files=None, config_file=None, **kwargs):
"""
Push images to a registry. Requires authenticating with the registry prior to starting
the push. If your engine's config file does not already contain an authorization for the
registry, pass username... | Push images to a registry. Requires authenticating with the registry prior to starting
the push. If your engine's config file does not already contain an authorization for the
registry, pass username and/or password. If you exclude password, you will be prompted. | Below is the the instruction that describes the task:
### Input:
Push images to a registry. Requires authenticating with the registry prior to starting
the push. If your engine's config file does not already contain an authorization for the
registry, pass username and/or password. If you exclude password, y... |
def mime(self):
"""Produce the final MIME message."""
author = self.author
sender = self.sender
if not author:
raise ValueError("You must specify an author.")
if not self.subject:
raise ValueError("You must specify a subject.")
if len(self.recipients) == 0:
raise ValueError("You must specify a... | Produce the final MIME message. | Below is the the instruction that describes the task:
### Input:
Produce the final MIME message.
### Response:
def mime(self):
"""Produce the final MIME message."""
author = self.author
sender = self.sender
if not author:
raise ValueError("You must specify an author.")
if not self.subject:
rais... |
def two_lorentzian(freq, freq0_1, freq0_2, area1, area2, hwhm1, hwhm2, phase1,
phase2, offset, drift):
"""
A two-Lorentzian model.
This is simply the sum of two lorentzian functions in some part of the
spectrum. Each individual Lorentzian has its own peak frequency, area, hwhm
and pha... | A two-Lorentzian model.
This is simply the sum of two lorentzian functions in some part of the
spectrum. Each individual Lorentzian has its own peak frequency, area, hwhm
and phase, but they share common offset and drift parameters. | Below is the the instruction that describes the task:
### Input:
A two-Lorentzian model.
This is simply the sum of two lorentzian functions in some part of the
spectrum. Each individual Lorentzian has its own peak frequency, area, hwhm
and phase, but they share common offset and drift parameters.
### Resp... |
def blend(self, blend_function=stack):
"""Blend the datasets into one scene.
.. note::
Blending is not currently optimized for generator-based
MultiScene.
"""
new_scn = Scene()
common_datasets = self.shared_dataset_ids
for ds_id in common_datase... | Blend the datasets into one scene.
.. note::
Blending is not currently optimized for generator-based
MultiScene. | Below is the the instruction that describes the task:
### Input:
Blend the datasets into one scene.
.. note::
Blending is not currently optimized for generator-based
MultiScene.
### Response:
def blend(self, blend_function=stack):
"""Blend the datasets into one scene.
... |
def normalize_modpath(modpath, hide_init=True, hide_main=False):
"""
Normalizes __init__ and __main__ paths.
Notes:
Adds __init__ if reasonable, but only removes __main__ by default
Args:
hide_init (bool): if True, always return package modules
as __init__.py files otherwise... | Normalizes __init__ and __main__ paths.
Notes:
Adds __init__ if reasonable, but only removes __main__ by default
Args:
hide_init (bool): if True, always return package modules
as __init__.py files otherwise always return the dpath.
hide_init (bool): if True, always strip awa... | Below is the the instruction that describes the task:
### Input:
Normalizes __init__ and __main__ paths.
Notes:
Adds __init__ if reasonable, but only removes __main__ by default
Args:
hide_init (bool): if True, always return package modules
as __init__.py files otherwise always ... |
def _slice_replace(code, index, old, new):
"""Replace the string *old* with *new* across *index* in *code*."""
nodes = [str(node) for node in code.get(index)]
substring = "".join(nodes).replace(old, new)
code.nodes[index] = parse_anything(substring).nodes | Replace the string *old* with *new* across *index* in *code*. | Below is the the instruction that describes the task:
### Input:
Replace the string *old* with *new* across *index* in *code*.
### Response:
def _slice_replace(code, index, old, new):
"""Replace the string *old* with *new* across *index* in *code*."""
nodes = [str(node) for node in code.get(index)]... |
def get_languages_from_item(ct_item, item):
"""
Get the languages configured for the current item
:param ct_item:
:param item:
:return:
"""
try:
item_lan = TransItemLanguage.objects.filter(content_type__pk=ct_item.id, object_id=item.id).get()
... | Get the languages configured for the current item
:param ct_item:
:param item:
:return: | Below is the the instruction that describes the task:
### Input:
Get the languages configured for the current item
:param ct_item:
:param item:
:return:
### Response:
def get_languages_from_item(ct_item, item):
"""
Get the languages configured for the current item
:p... |
def plot_blob(
sampler, blobidx=0, label=None, last_step=False, figure=None, **kwargs
):
"""
Plot a metadata blob as a fit to spectral data or value distribution
Additional ``kwargs`` are passed to `plot_fit`.
Parameters
----------
sampler : `emcee.EnsembleSampler`
Sampler with a s... | Plot a metadata blob as a fit to spectral data or value distribution
Additional ``kwargs`` are passed to `plot_fit`.
Parameters
----------
sampler : `emcee.EnsembleSampler`
Sampler with a stored chain.
blobidx : int, optional
Metadata blob index to plot.
label : str, optional
... | Below is the the instruction that describes the task:
### Input:
Plot a metadata blob as a fit to spectral data or value distribution
Additional ``kwargs`` are passed to `plot_fit`.
Parameters
----------
sampler : `emcee.EnsembleSampler`
Sampler with a stored chain.
blobidx : int, opti... |
def style_data(self):
"""Applies self.style_function to each feature of self.data."""
def recursive_get(data, keys):
if len(keys):
return recursive_get(data.get(keys[0]), keys[1:])
else:
return data
geometries = recursive_get(self.data, s... | Applies self.style_function to each feature of self.data. | Below is the the instruction that describes the task:
### Input:
Applies self.style_function to each feature of self.data.
### Response:
def style_data(self):
"""Applies self.style_function to each feature of self.data."""
def recursive_get(data, keys):
if len(keys):
re... |
def build_query_string(self, data):
"""This method occurs after dumping the data into the class.
Args:
data (dict): dictionary of all the query values
Returns:
data (dict): ordered dict of all the values
"""
query = []
keys_to_be_removed = []
... | This method occurs after dumping the data into the class.
Args:
data (dict): dictionary of all the query values
Returns:
data (dict): ordered dict of all the values | Below is the the instruction that describes the task:
### Input:
This method occurs after dumping the data into the class.
Args:
data (dict): dictionary of all the query values
Returns:
data (dict): ordered dict of all the values
### Response:
def build_query_string(self, ... |
def from_bits(self, bits):
"""
Set this person from bits (ignores the id)
:param bits: Bits representing a person
:type bits: bytearray
:rtype: Person
:raises ValueError: Bits has an unexpected length
"""
# TODO include id
if len(bits) != Person.B... | Set this person from bits (ignores the id)
:param bits: Bits representing a person
:type bits: bytearray
:rtype: Person
:raises ValueError: Bits has an unexpected length | Below is the the instruction that describes the task:
### Input:
Set this person from bits (ignores the id)
:param bits: Bits representing a person
:type bits: bytearray
:rtype: Person
:raises ValueError: Bits has an unexpected length
### Response:
def from_bits(self, bits):
... |
def create(style_dataset, content_dataset, style_feature=None,
content_feature=None, max_iterations=None, model='resnet-16',
verbose=True, batch_size = 6, **kwargs):
"""
Create a :class:`StyleTransfer` model.
Parameters
----------
style_dataset: SFrame
Input style images. Th... | Create a :class:`StyleTransfer` model.
Parameters
----------
style_dataset: SFrame
Input style images. The columns named by the ``style_feature`` parameters will
be extracted for training the model.
content_dataset : SFrame
Input content images. The columns named by the ``conte... | Below is the the instruction that describes the task:
### Input:
Create a :class:`StyleTransfer` model.
Parameters
----------
style_dataset: SFrame
Input style images. The columns named by the ``style_feature`` parameters will
be extracted for training the model.
content_dataset : ... |
def use_certificate(self, cert):
"""
Load a certificate from a X509 object
:param cert: The X509 object
:return: None
"""
if not isinstance(cert, X509):
raise TypeError("cert must be an X509 instance")
use_result = _lib.SSL_CTX_use_certificate(self._... | Load a certificate from a X509 object
:param cert: The X509 object
:return: None | Below is the the instruction that describes the task:
### Input:
Load a certificate from a X509 object
:param cert: The X509 object
:return: None
### Response:
def use_certificate(self, cert):
"""
Load a certificate from a X509 object
:param cert: The X509 object
:... |
def circles(st, layer, axis, ax=None, talpha=1.0, cedge='white', cface='white'):
"""
Plots a set of circles corresponding to a slice through the platonic
structure. Copied from twoslice_overlay with comments, standaloneness.
Inputs
------
pos : array of particle positions; [N,3]
rad... | Plots a set of circles corresponding to a slice through the platonic
structure. Copied from twoslice_overlay with comments, standaloneness.
Inputs
------
pos : array of particle positions; [N,3]
rad : array of particle radii; [N]
ax : plt.axis instance
layer : Which layer of... | Below is the the instruction that describes the task:
### Input:
Plots a set of circles corresponding to a slice through the platonic
structure. Copied from twoslice_overlay with comments, standaloneness.
Inputs
------
pos : array of particle positions; [N,3]
rad : array of particle rad... |
def visit_exact_match_value(self, node, fieldnames=None):
"""Generates a term query (exact search in ElasticSearch)."""
if not fieldnames:
fieldnames = ['_all']
else:
fieldnames = force_list(fieldnames)
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-autho... | Generates a term query (exact search in ElasticSearch). | Below is the the instruction that describes the task:
### Input:
Generates a term query (exact search in ElasticSearch).
### Response:
def visit_exact_match_value(self, node, fieldnames=None):
"""Generates a term query (exact search in ElasticSearch)."""
if not fieldnames:
fieldnames = ... |
def _handleDelete(self):
""" Handles "delete" characters """
if self.cursorPos < len(self.inputBuffer):
self.inputBuffer = self.inputBuffer[0:self.cursorPos] + self.inputBuffer[self.cursorPos+1:]
self._refreshInputPrompt(len(self.inputBuffer)+1) | Handles "delete" characters | Below is the the instruction that describes the task:
### Input:
Handles "delete" characters
### Response:
def _handleDelete(self):
""" Handles "delete" characters """
if self.cursorPos < len(self.inputBuffer):
self.inputBuffer = self.inputBuffer[0:self.cursorPos] + self.inputBuffer[sel... |
def verify_sc_url(url: str) -> bool:
"""Verify signature certificate URL against Amazon Alexa requirements.
Each call of Agent passes incoming utterances batch through skills filter,
agent skills, skills processor. Batch of dialog IDs can be provided, in
other case utterances indexes in incoming batch ... | Verify signature certificate URL against Amazon Alexa requirements.
Each call of Agent passes incoming utterances batch through skills filter,
agent skills, skills processor. Batch of dialog IDs can be provided, in
other case utterances indexes in incoming batch are used as dialog IDs.
Args:
u... | Below is the the instruction that describes the task:
### Input:
Verify signature certificate URL against Amazon Alexa requirements.
Each call of Agent passes incoming utterances batch through skills filter,
agent skills, skills processor. Batch of dialog IDs can be provided, in
other case utterances i... |
def write(self, handle):
'''Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
if not self._frames... | Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. | Below is the the instruction that describes the task:
### Input:
Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
### Re... |
def sort_values(self, by=None, axis=0, ascending=True, inplace=False,
kind='quicksort', na_position='last'):
"""
Sort by the values along either axis.
Parameters
----------%(optional_by)s
axis : %(axes_single_arg)s, default 0
Axis to be sorted.
... | Sort by the values along either axis.
Parameters
----------%(optional_by)s
axis : %(axes_single_arg)s, default 0
Axis to be sorted.
ascending : bool or list of bool, default True
Sort ascending vs. descending. Specify list for multiple sort
orders.... | Below is the the instruction that describes the task:
### Input:
Sort by the values along either axis.
Parameters
----------%(optional_by)s
axis : %(axes_single_arg)s, default 0
Axis to be sorted.
ascending : bool or list of bool, default True
Sort ascendin... |
def send(self, request, **kwargs):
"""Send a given PreparedRequest."""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify... | Send a given PreparedRequest. | Below is the the instruction that describes the task:
### Input:
Send a given PreparedRequest.
### Response:
def send(self, request, **kwargs):
"""Send a given PreparedRequest."""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the ... |
def grouper_nofill_str(n, iterable):
"""
Take a sequence and break it up into chunks of the specified size.
The last chunk may be smaller than size.
This works very similar to grouper_nofill, except
it works with strings as well.
>>> tuple(grouper_nofill_str(3, 'foobarbaz'))
('foo', 'bar', 'baz')
You can sti... | Take a sequence and break it up into chunks of the specified size.
The last chunk may be smaller than size.
This works very similar to grouper_nofill, except
it works with strings as well.
>>> tuple(grouper_nofill_str(3, 'foobarbaz'))
('foo', 'bar', 'baz')
You can still use it on non-strings too if you like.
... | Below is the the instruction that describes the task:
### Input:
Take a sequence and break it up into chunks of the specified size.
The last chunk may be smaller than size.
This works very similar to grouper_nofill, except
it works with strings as well.
>>> tuple(grouper_nofill_str(3, 'foobarbaz'))
('foo', '... |
def GetForwardedIps(self, interface, interface_ip=None):
"""Retrieve the list of configured forwarded IP addresses.
Args:
interface: string, the output device to query.
interface_ip: string, current interface ip address.
Returns:
list, the IP address strings.
"""
try:
ips =... | Retrieve the list of configured forwarded IP addresses.
Args:
interface: string, the output device to query.
interface_ip: string, current interface ip address.
Returns:
list, the IP address strings. | Below is the the instruction that describes the task:
### Input:
Retrieve the list of configured forwarded IP addresses.
Args:
interface: string, the output device to query.
interface_ip: string, current interface ip address.
Returns:
list, the IP address strings.
### Response:
def GetF... |
def eval_genome(genome, config):
"""
This function will be run in parallel by ParallelEvaluator. It takes two
arguments (a single genome and the genome class configuration data) and
should return one float (that genome's fitness).
Note that this function needs to be in module scope for multiproces... | This function will be run in parallel by ParallelEvaluator. It takes two
arguments (a single genome and the genome class configuration data) and
should return one float (that genome's fitness).
Note that this function needs to be in module scope for multiprocessing.Pool
(which is what ParallelEvaluato... | Below is the the instruction that describes the task:
### Input:
This function will be run in parallel by ParallelEvaluator. It takes two
arguments (a single genome and the genome class configuration data) and
should return one float (that genome's fitness).
Note that this function needs to be in modu... |
def quantize_model(sym, arg_params, aux_params,
data_names=('data',), label_names=('softmax_label',),
ctx=cpu(), excluded_sym_names=None, calib_mode='entropy',
calib_data=None, num_calib_examples=None, calib_layer=None,
quantized_dtype='int8', ... | User-level API for generating a quantized model from a FP32 model w/ or w/o calibration.
The backend quantized operators are only enabled for Linux systems. Please do not run
inference using the quantized models on Windows for now.
The quantization implementation adopts the TensorFlow's approach:
https:... | Below is the the instruction that describes the task:
### Input:
User-level API for generating a quantized model from a FP32 model w/ or w/o calibration.
The backend quantized operators are only enabled for Linux systems. Please do not run
inference using the quantized models on Windows for now.
The qua... |
def make_venv(self, dj_version):
"""Creates a virtual environment for a given Django version.
:param str dj_version:
:rtype: str
:return: path to created virtual env
"""
venv_path = self._get_venv_path(dj_version)
self.logger.info('Creating virtual environment fo... | Creates a virtual environment for a given Django version.
:param str dj_version:
:rtype: str
:return: path to created virtual env | Below is the the instruction that describes the task:
### Input:
Creates a virtual environment for a given Django version.
:param str dj_version:
:rtype: str
:return: path to created virtual env
### Response:
def make_venv(self, dj_version):
"""Creates a virtual environment for a g... |
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, 'rindex'):
raise ValueError("'package' not set to a string")
dot = len(package)
for x in xrange(level, 1, -1):
try:
dot = package.rindex('.', 0, dot)
... | Return the absolute name of the module to be imported. | Below is the the instruction that describes the task:
### Input:
Return the absolute name of the module to be imported.
### Response:
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, 'rindex'):
raise ValueError("'package' ... |
def readPattern(self):
"""Read the entire color pattern
:return List of pattern line tuples
"""
if ( self.dev == None ): return ''
pattern=[]
for i in range(0,16): # FIXME: adjustable for diff blink(1) models
pattern.append( self.readPatternLine(i) )
... | Read the entire color pattern
:return List of pattern line tuples | Below is the the instruction that describes the task:
### Input:
Read the entire color pattern
:return List of pattern line tuples
### Response:
def readPattern(self):
"""Read the entire color pattern
:return List of pattern line tuples
"""
if ( self.dev == None ): return ''... |
def mark_flags_as_mutual_exclusive(flag_names, required=False,
flag_values=_flagvalues.FLAGS):
"""Ensures that only one flag among flag_names is not None.
Important note: This validator checks if flag values are None, and it does not
distinguish between default and explicit val... | Ensures that only one flag among flag_names is not None.
Important note: This validator checks if flag values are None, and it does not
distinguish between default and explicit values. Therefore, this validator
does not make sense when applied to flags with default values other than None,
including other false... | Below is the the instruction that describes the task:
### Input:
Ensures that only one flag among flag_names is not None.
Important note: This validator checks if flag values are None, and it does not
distinguish between default and explicit values. Therefore, this validator
does not make sense when applied ... |
def _set_allowed_services_and_actions(self, services):
"""Expect services to be a list of service dictionaries, each with `name` and `actions` keys."""
for service in services:
self.services[service['name']] = {}
for action in service['actions']:
name = action.po... | Expect services to be a list of service dictionaries, each with `name` and `actions` keys. | Below is the the instruction that describes the task:
### Input:
Expect services to be a list of service dictionaries, each with `name` and `actions` keys.
### Response:
def _set_allowed_services_and_actions(self, services):
"""Expect services to be a list of service dictionaries, each with `name` and `act... |
def _read_parsed(self, lines):
"""
Read text fragments from a parsed format text file.
:param list lines: the lines of the parsed text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings)
"""
self.l... | Read text fragments from a parsed format text file.
:param list lines: the lines of the parsed text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings) | Below is the the instruction that describes the task:
### Input:
Read text fragments from a parsed format text file.
:param list lines: the lines of the parsed text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings)
### Resp... |
def addmsg(self, msg_p):
"""
Push encoded message as a new frame. Message takes ownership of
submessage, so the original is destroyed in this call. Returns 0 on
success, -1 on error.
"""
return lib.zmsg_addmsg(self._as_parameter_, byref(zmsg_p.from_param(msg_p))) | Push encoded message as a new frame. Message takes ownership of
submessage, so the original is destroyed in this call. Returns 0 on
success, -1 on error. | Below is the the instruction that describes the task:
### Input:
Push encoded message as a new frame. Message takes ownership of
submessage, so the original is destroyed in this call. Returns 0 on
success, -1 on error.
### Response:
def addmsg(self, msg_p):
"""
Push encoded message as a new frame. ... |
def check_timers(self):
""" Awake process if timer has expired """
if self._current is None:
# Advance the clocks. Go to future!!
advance = min([self.clocks] + [x for x in self.timers if x is not None]) + 1
logger.debug(f"Advancing the clock from {self.clocks} to {adv... | Awake process if timer has expired | Below is the the instruction that describes the task:
### Input:
Awake process if timer has expired
### Response:
def check_timers(self):
""" Awake process if timer has expired """
if self._current is None:
# Advance the clocks. Go to future!!
advance = min([self.clocks] + [... |
def triangle_area(point1, point2, point3):
"""
Uses Heron's formula to find the area of a triangle
based on the coordinates of three points.
Args:
point1: list or tuple, the x y coordinate of point one.
point2: list or tuple, the x y coordinate of point two.
point3: list or tu... | Uses Heron's formula to find the area of a triangle
based on the coordinates of three points.
Args:
point1: list or tuple, the x y coordinate of point one.
point2: list or tuple, the x y coordinate of point two.
point3: list or tuple, the x y coordinate of point three.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Uses Heron's formula to find the area of a triangle
based on the coordinates of three points.
Args:
point1: list or tuple, the x y coordinate of point one.
point2: list or tuple, the x y coordinate of point two.
poin... |
def _get_role_arn(name, **conn_params):
'''
Helper function to turn a name into an arn string,
returns None if not able to resolve
'''
if name.startswith('arn:aws:iam'):
return name
role = __salt__['boto_iam.describe_role'](name, **conn_params)
rolearn = role.get('arn') if role else ... | Helper function to turn a name into an arn string,
returns None if not able to resolve | Below is the the instruction that describes the task:
### Input:
Helper function to turn a name into an arn string,
returns None if not able to resolve
### Response:
def _get_role_arn(name, **conn_params):
'''
Helper function to turn a name into an arn string,
returns None if not able to resolve
... |
def value_str(sc):
"""
Returns the value part ("[*]", "<M>", "(foo)" etc.) of a menu entry.
sc: Symbol or Choice.
"""
if sc.type in (STRING, INT, HEX):
return "({})".format(sc.str_value)
# BOOL or TRISTATE
# The choice mode is an upper bound on the visibility of choice symbols, so... | Returns the value part ("[*]", "<M>", "(foo)" etc.) of a menu entry.
sc: Symbol or Choice. | Below is the the instruction that describes the task:
### Input:
Returns the value part ("[*]", "<M>", "(foo)" etc.) of a menu entry.
sc: Symbol or Choice.
### Response:
def value_str(sc):
"""
Returns the value part ("[*]", "<M>", "(foo)" etc.) of a menu entry.
sc: Symbol or Choice.
"""
i... |
def load_mod_from_file(self, fpath):
"""Loads modules from a .py file into ShutIt if there are no modules from
this file already.
We expect to have a callable 'module/0' which returns one or more module
objects.
If this doesn't exist we assume that the .py file works in the old style
(automatically insertin... | Loads modules from a .py file into ShutIt if there are no modules from
this file already.
We expect to have a callable 'module/0' which returns one or more module
objects.
If this doesn't exist we assume that the .py file works in the old style
(automatically inserting the module into shutit_global) or it's n... | Below is the the instruction that describes the task:
### Input:
Loads modules from a .py file into ShutIt if there are no modules from
this file already.
We expect to have a callable 'module/0' which returns one or more module
objects.
If this doesn't exist we assume that the .py file works in the old styl... |
def NewFromJSON(data):
"""
Create a new User instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a user.
Returns:
A User instance.
"""
if data.get('shakes', None):
shakes = [Shake.NewFromJSON(shk) for shk in dat... | Create a new User instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a user.
Returns:
A User instance. | Below is the the instruction that describes the task:
### Input:
Create a new User instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a user.
Returns:
A User instance.
### Response:
def NewFromJSON(data):
"""
Create a new User instan... |
def _estimate_label_shape(self):
"""Helper function to estimate label shape"""
max_count = 0
self.reset()
try:
while True:
label, _ = self.next_sample()
label = self._parse_label(label)
max_count = max(max_count, label.shape[0])... | Helper function to estimate label shape | Below is the the instruction that describes the task:
### Input:
Helper function to estimate label shape
### Response:
def _estimate_label_shape(self):
"""Helper function to estimate label shape"""
max_count = 0
self.reset()
try:
while True:
label, _ = se... |
def stretch_weber_fechner(self, k, s0):
"""Stretch according to the Weber-Fechner law.
p = k.ln(S/S0)
p is perception, S is the stimulus, S0 is the stimulus threshold (the
highest unpercieved stimulus), and k is the factor.
"""
attrs = self.data.attrs
self.data =... | Stretch according to the Weber-Fechner law.
p = k.ln(S/S0)
p is perception, S is the stimulus, S0 is the stimulus threshold (the
highest unpercieved stimulus), and k is the factor. | Below is the the instruction that describes the task:
### Input:
Stretch according to the Weber-Fechner law.
p = k.ln(S/S0)
p is perception, S is the stimulus, S0 is the stimulus threshold (the
highest unpercieved stimulus), and k is the factor.
### Response:
def stretch_weber_fechner(self... |
def read(path, encoding="utf-8"):
"""Read the content of the file.
Args:
path (str): Path to the file
encoding (str): File encoding. Default: utf-8
Returns:
str: File content or empty string if there was an error
"""
try:
with io.open(path, encoding=encoding) as f:
... | Read the content of the file.
Args:
path (str): Path to the file
encoding (str): File encoding. Default: utf-8
Returns:
str: File content or empty string if there was an error | Below is the the instruction that describes the task:
### Input:
Read the content of the file.
Args:
path (str): Path to the file
encoding (str): File encoding. Default: utf-8
Returns:
str: File content or empty string if there was an error
### Response:
def read(path, encoding="u... |
def send_zipfile(request, fileList):
"""
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files.... | Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files. | Below is the the instruction that describes the task:
### Input:
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files.
### Response:
def send_zipfile(request, fileList):
... |
def cmd(send, msg, args):
"""Converts text to morse code.
Syntax: {command} [text]
"""
if not msg:
msg = gen_word()
morse = gen_morse(msg)
if len(morse) > 100:
send("Your morse is too long. Have you considered Western Union?")
else:
send(morse) | Converts text to morse code.
Syntax: {command} [text] | Below is the the instruction that describes the task:
### Input:
Converts text to morse code.
Syntax: {command} [text]
### Response:
def cmd(send, msg, args):
"""Converts text to morse code.
Syntax: {command} [text]
"""
if not msg:
msg = gen_word()
morse = gen_morse(msg)
if l... |
def is_multicast(text):
"""Is the textual-form network address a multicast address?
@param text: the textual address
@raises ValueError: the address family cannot be determined from the input.
@rtype: bool
"""
try:
first = ord(dns.ipv4.inet_aton(text)[0])
return (first >= 224 an... | Is the textual-form network address a multicast address?
@param text: the textual address
@raises ValueError: the address family cannot be determined from the input.
@rtype: bool | Below is the the instruction that describes the task:
### Input:
Is the textual-form network address a multicast address?
@param text: the textual address
@raises ValueError: the address family cannot be determined from the input.
@rtype: bool
### Response:
def is_multicast(text):
"""Is the textua... |
def toTypeURIs(namespace_map, alias_list_s):
"""Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_map: openid.messa... | Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_map: openid.message.NamespaceMap
@param alias_list_s: The string... | Below is the the instruction that describes the task:
### Input:
Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_... |
def __query_spec(self):
"""Get the spec to use for a query.
"""
operators = self.__modifiers.copy()
if self.__ordering:
operators["$orderby"] = self.__ordering
if self.__explain:
operators["$explain"] = True
if self.__hint:
operators["$... | Get the spec to use for a query. | Below is the the instruction that describes the task:
### Input:
Get the spec to use for a query.
### Response:
def __query_spec(self):
"""Get the spec to use for a query.
"""
operators = self.__modifiers.copy()
if self.__ordering:
operators["$orderby"] = self.__ordering... |
def followed_topic_num(self):
"""获取用户关注的话题数
:return: 关注的话题数
:rtype: int
"""
if self.url is not None:
tag = self.soup.find('div', class_='zm-profile-side-topics')
if tag is not None:
return int(re_get_number.match(
tag.p... | 获取用户关注的话题数
:return: 关注的话题数
:rtype: int | Below is the the instruction that describes the task:
### Input:
获取用户关注的话题数
:return: 关注的话题数
:rtype: int
### Response:
def followed_topic_num(self):
"""获取用户关注的话题数
:return: 关注的话题数
:rtype: int
"""
if self.url is not None:
tag = self.soup.find('div'... |
def response_to_json_dict(response, **kwargs):
"""
Standard place to convert responses to JSON.
:param response: requests response object
:param **kwargs: arguments accepted by json.loads
:returns: dict of JSON response
"""
if response.encoding is None:
response.encoding = 'utf-8'
... | Standard place to convert responses to JSON.
:param response: requests response object
:param **kwargs: arguments accepted by json.loads
:returns: dict of JSON response | Below is the the instruction that describes the task:
### Input:
Standard place to convert responses to JSON.
:param response: requests response object
:param **kwargs: arguments accepted by json.loads
:returns: dict of JSON response
### Response:
def response_to_json_dict(response, **kwargs):
""... |
def get_dates(raw_table) -> "list of dates":
"""
Goes through the first column of input table and
returns the first sequence of dates it finds.
"""
dates = []
found_first = False
for i, dstr in enumerate([raw_table[i][0] for i in range(0, len(raw_table))])... | Goes through the first column of input table and
returns the first sequence of dates it finds. | Below is the the instruction that describes the task:
### Input:
Goes through the first column of input table and
returns the first sequence of dates it finds.
### Response:
def get_dates(raw_table) -> "list of dates":
"""
Goes through the first column of input table and
... |
def write_url (self, url_data):
"""Write url_data.base_url."""
self.writeln(u"<tr>")
self.writeln(u'<td class="url">%s</td>' % self.part("url"))
self.write(u'<td class="url">')
self.write(u"`%s'" % cgi.escape(url_data.base_url))
self.writeln(u"</td></tr>") | Write url_data.base_url. | Below is the the instruction that describes the task:
### Input:
Write url_data.base_url.
### Response:
def write_url (self, url_data):
"""Write url_data.base_url."""
self.writeln(u"<tr>")
self.writeln(u'<td class="url">%s</td>' % self.part("url"))
self.write(u'<td class="url">')
... |
def _set_token(self):
"""Set the Cerberus token based on auth type"""
try:
self.token = os.environ['CERBERUS_TOKEN']
if self.verbose:
print("Overriding Cerberus token with environment variable.", file=sys.stderr)
logger.info("Overriding Cerberus token ... | Set the Cerberus token based on auth type | Below is the the instruction that describes the task:
### Input:
Set the Cerberus token based on auth type
### Response:
def _set_token(self):
"""Set the Cerberus token based on auth type"""
try:
self.token = os.environ['CERBERUS_TOKEN']
if self.verbose:
prin... |
async def renew(self, session, *, dc=None):
"""Renews a TTL-based session
Parameters:
session (ObjectID): Session ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
ObjectMeta: where val... | Renews a TTL-based session
Parameters:
session (ObjectID): Session ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
ObjectMeta: where value is session
Raises:
NotFound: ses... | Below is the the instruction that describes the task:
### Input:
Renews a TTL-based session
Parameters:
session (ObjectID): Session ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
ObjectM... |
def reduce(source, func, initializer=None):
"""Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default when ... | Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty. | Below is the the instruction that describes the task:
### Input:
Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves ... |
def create_init(self, path): # type: (str) -> None
"""
Create a minimal __init__ file with enough boiler plate to not add to lint messages
:param path:
:return:
"""
source = """# coding=utf-8
\"\"\"
Version
\"\"\"
__version__ = \"0.0.0\"
"""
with io.open(path, "w... | Create a minimal __init__ file with enough boiler plate to not add to lint messages
:param path:
:return: | Below is the the instruction that describes the task:
### Input:
Create a minimal __init__ file with enough boiler plate to not add to lint messages
:param path:
:return:
### Response:
def create_init(self, path): # type: (str) -> None
"""
Create a minimal __init__ file with enough... |
def gene_to_panels(self, case_obj):
"""Fetch all gene panels and group them by gene
Args:
case_obj(scout.models.Case)
Returns:
gene_dict(dict): A dictionary with gene as keys and a set of
panel names as value
"""
... | Fetch all gene panels and group them by gene
Args:
case_obj(scout.models.Case)
Returns:
gene_dict(dict): A dictionary with gene as keys and a set of
panel names as value | Below is the the instruction that describes the task:
### Input:
Fetch all gene panels and group them by gene
Args:
case_obj(scout.models.Case)
Returns:
gene_dict(dict): A dictionary with gene as keys and a set of
panel names ... |
def get_count(self, prefix=''):
"""Return the total count of errors and warnings."""
return sum([self.counters[key]
for key in self.messages if key.startswith(prefix)]) | Return the total count of errors and warnings. | Below is the the instruction that describes the task:
### Input:
Return the total count of errors and warnings.
### Response:
def get_count(self, prefix=''):
"""Return the total count of errors and warnings."""
return sum([self.counters[key]
for key in self.messages if key.start... |
def load_watch():
'''
Loads some of the 6-axis inertial sensor data from my smartwatch project. The sensor data was
recorded as study subjects performed sets of 20 shoulder exercise repetitions while wearing a
smartwatch. It is a multivariate time series.
The study can be found here: https://arxiv.... | Loads some of the 6-axis inertial sensor data from my smartwatch project. The sensor data was
recorded as study subjects performed sets of 20 shoulder exercise repetitions while wearing a
smartwatch. It is a multivariate time series.
The study can be found here: https://arxiv.org/abs/1802.01489
Return... | Below is the the instruction that describes the task:
### Input:
Loads some of the 6-axis inertial sensor data from my smartwatch project. The sensor data was
recorded as study subjects performed sets of 20 shoulder exercise repetitions while wearing a
smartwatch. It is a multivariate time series.
The ... |
def add_filter(self, ftype, func):
''' Register a new output filter. Whenever bottle hits a handler output
matching `ftype`, `func` is applyed to it. '''
if not isinstance(ftype, type):
raise TypeError("Expected type object, got %s" % type(ftype))
self.castfilter = [(t, f... | Register a new output filter. Whenever bottle hits a handler output
matching `ftype`, `func` is applyed to it. | Below is the the instruction that describes the task:
### Input:
Register a new output filter. Whenever bottle hits a handler output
matching `ftype`, `func` is applyed to it.
### Response:
def add_filter(self, ftype, func):
''' Register a new output filter. Whenever bottle hits a handler outpu... |
def vgcreate(vgname, devices, **kwargs):
'''
Create an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y
'''
if not vgname or not devices:
return 'Error: vgn... | Create an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y | Below is the the instruction that describes the task:
### Input:
Create an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y
### Response:
def vgcreate(vgname, devices, **kwarg... |
def stop_instance(self, instance_id):
"""Stops the instance gracefully.
:param str instance_id: instance identifier
:raises: `InstanceError` if instance can not be stopped
"""
if not instance_id:
log.info("Instance to stop has no instance id")
return
... | Stops the instance gracefully.
:param str instance_id: instance identifier
:raises: `InstanceError` if instance can not be stopped | Below is the the instruction that describes the task:
### Input:
Stops the instance gracefully.
:param str instance_id: instance identifier
:raises: `InstanceError` if instance can not be stopped
### Response:
def stop_instance(self, instance_id):
"""Stops the instance gracefully.
... |
def connect(self, hostkey=None, username='', password=None, pkey=None):
"""
Negotiate an SSH2 session, and optionally verify the server's host key
and authenticate using a password or private key. This is a shortcut
for L{start_client}, L{get_remote_server_key}, and
L{Transport.... | Negotiate an SSH2 session, and optionally verify the server's host key
and authenticate using a password or private key. This is a shortcut
for L{start_client}, L{get_remote_server_key}, and
L{Transport.auth_password} or L{Transport.auth_publickey}. Use those
methods if you want more c... | Below is the the instruction that describes the task:
### Input:
Negotiate an SSH2 session, and optionally verify the server's host key
and authenticate using a password or private key. This is a shortcut
for L{start_client}, L{get_remote_server_key}, and
L{Transport.auth_password} or L{Tra... |
def overview():
"""
Function to create an overview of the services.
Will print a list of ports found an the number of times the port was seen.
"""
search = Service.search()
search = search.filter("term", state='open')
search.aggs.bucket('port_count', 'terms', field='port', order={'_c... | Function to create an overview of the services.
Will print a list of ports found an the number of times the port was seen. | Below is the the instruction that describes the task:
### Input:
Function to create an overview of the services.
Will print a list of ports found an the number of times the port was seen.
### Response:
def overview():
"""
Function to create an overview of the services.
Will print a list... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.