code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _update_uncompressed(collection_name, upsert, multi, spec,
doc, safe, last_error_args, check_keys, opts):
"""Internal update message helper."""
op_update, max_bson_size = _update(
collection_name, upsert, multi, spec, doc, check_keys, opts)
rid, msg = __pack_message(2001... | Internal update message helper. | Below is the the instruction that describes the task:
### Input:
Internal update message helper.
### Response:
def _update_uncompressed(collection_name, upsert, multi, spec,
doc, safe, last_error_args, check_keys, opts):
"""Internal update message helper."""
op_update, max_bson_siz... |
def should_trigger(self, dt):
"""
Composes the two rules with a lazy composer.
"""
return self.composer(
self.first.should_trigger,
self.second.should_trigger,
dt
) | Composes the two rules with a lazy composer. | Below is the the instruction that describes the task:
### Input:
Composes the two rules with a lazy composer.
### Response:
def should_trigger(self, dt):
"""
Composes the two rules with a lazy composer.
"""
return self.composer(
self.first.should_trigger,
sel... |
def matern_function(Xi, Xj, *args):
r"""Matern covariance function of arbitrary dimension, for use with :py:class:`ArbitraryKernel`.
The Matern kernel has the following hyperparameters, always referenced in
the order listed:
= ===== ====================================
0 sigma prefactor
... | r"""Matern covariance function of arbitrary dimension, for use with :py:class:`ArbitraryKernel`.
The Matern kernel has the following hyperparameters, always referenced in
the order listed:
= ===== ====================================
0 sigma prefactor
1 nu order of kernel
2 l1 le... | Below is the the instruction that describes the task:
### Input:
r"""Matern covariance function of arbitrary dimension, for use with :py:class:`ArbitraryKernel`.
The Matern kernel has the following hyperparameters, always referenced in
the order listed:
= ===== ================================... |
def estimate_augmented_markov_model(dtrajs, ftrajs, lag, m, sigmas,
count_mode='sliding', connectivity='largest',
dt_traj='1 step', maxiter=1000000, eps=0.05, maxcache=3000):
r""" Estimates an Augmented Markov model from discrete trajectories and experimental dat... | r""" Estimates an Augmented Markov model from discrete trajectories and experimental data
Returns a :class:`AugmentedMarkovModel` that
contains the estimated transition matrix and allows to compute a
large number of quantities related to Markov models.
Parameters
----------
dtrajs : list conta... | Below is the the instruction that describes the task:
### Input:
r""" Estimates an Augmented Markov model from discrete trajectories and experimental data
Returns a :class:`AugmentedMarkovModel` that
contains the estimated transition matrix and allows to compute a
large number of quantities related to ... |
def init(self):
"""Init the connection to the Cassandra server."""
if not self.export_enable:
return None
# if username and/or password are not set the connection will try to connect with no auth
auth_provider = PlainTextAuthProvider(
username=self.username, pass... | Init the connection to the Cassandra server. | Below is the the instruction that describes the task:
### Input:
Init the connection to the Cassandra server.
### Response:
def init(self):
"""Init the connection to the Cassandra server."""
if not self.export_enable:
return None
# if username and/or password are not set the co... |
def ParseBookmarkAnnotationRow(
self, parser_mediator, query, row, **unused_kwargs):
"""Parses a bookmark annotation row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created th... | Parses a bookmark annotation row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | Below is the the instruction that describes the task:
### Input:
Parses a bookmark annotation row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row... |
def _route(self, action, method):
"""
Given an action method, generates a route for it.
"""
# First thing, determine the path for the method
path = method._wsgi_path
methods = None
if path is None:
map_rule = self.wsgi_method_map.get(method.__name__)
... | Given an action method, generates a route for it. | Below is the the instruction that describes the task:
### Input:
Given an action method, generates a route for it.
### Response:
def _route(self, action, method):
"""
Given an action method, generates a route for it.
"""
# First thing, determine the path for the method
path... |
def register_tool(self, tool, name=None):
"""Check tool and see if it is installed in the local cpp toolchain.
All cpp tasks should request their tools using this method. Tools are validated
and cached for quick lookup.
:param string tool: Name or path of program tool, eg 'g++'
:param string name:... | Check tool and see if it is installed in the local cpp toolchain.
All cpp tasks should request their tools using this method. Tools are validated
and cached for quick lookup.
:param string tool: Name or path of program tool, eg 'g++'
:param string name: Logical name of tool, eg 'compiler'. If not supp... | Below is the the instruction that describes the task:
### Input:
Check tool and see if it is installed in the local cpp toolchain.
All cpp tasks should request their tools using this method. Tools are validated
and cached for quick lookup.
:param string tool: Name or path of program tool, eg 'g++'
... |
def setExpertLevel(self):
"""
Set expert level
"""
g = get_root(self).globals
level = g.cpars['expert_level']
# first define which buttons are visible
if level == 0:
# simple layout
for button in self.all_buttons:
button.gr... | Set expert level | Below is the the instruction that describes the task:
### Input:
Set expert level
### Response:
def setExpertLevel(self):
"""
Set expert level
"""
g = get_root(self).globals
level = g.cpars['expert_level']
# first define which buttons are visible
if level ==... |
def find_contexts(self, in_request=None, in_resolve=None):
"""Find contexts in the suite based on search criteria.
Args:
in_request (str): Match contexts that contain the given package in
their request.
in_resolve (str or `Requirement`): Match contexts that conta... | Find contexts in the suite based on search criteria.
Args:
in_request (str): Match contexts that contain the given package in
their request.
in_resolve (str or `Requirement`): Match contexts that contain the
given package in their resolve. You can also su... | Below is the the instruction that describes the task:
### Input:
Find contexts in the suite based on search criteria.
Args:
in_request (str): Match contexts that contain the given package in
their request.
in_resolve (str or `Requirement`): Match contexts that contai... |
def clear_children(parent_to_parse, element_path=None):
"""
Clears only children (not text or attributes) from the parsed parent
or named element.
"""
element = get_element(parent_to_parse, element_path)
if element is None:
return parent_to_parse
else:
elem_txt = element.te... | Clears only children (not text or attributes) from the parsed parent
or named element. | Below is the the instruction that describes the task:
### Input:
Clears only children (not text or attributes) from the parsed parent
or named element.
### Response:
def clear_children(parent_to_parse, element_path=None):
"""
Clears only children (not text or attributes) from the parsed parent
or n... |
def build(self, client,
nobuild=False,
usecache=True,
pull=False):
"""
Drives the build of the final image - get the list of steps and execute them.
Args:
client (docker.Client): docker client object that will build the image
nob... | Drives the build of the final image - get the list of steps and execute them.
Args:
client (docker.Client): docker client object that will build the image
nobuild (bool): just create dockerfiles, don't actually build the image
usecache (bool): use docker cache, or rebuild ev... | Below is the the instruction that describes the task:
### Input:
Drives the build of the final image - get the list of steps and execute them.
Args:
client (docker.Client): docker client object that will build the image
nobuild (bool): just create dockerfiles, don't actually build t... |
def ansi_split(text, _re=re.compile(u"(\x1b\\[(\\d*;?)*\\S)")):
"""Yields (is_ansi, text)"""
for part in _re.split(text):
if part:
yield (bool(_re.match(part)), part) | Yields (is_ansi, text) | Below is the the instruction that describes the task:
### Input:
Yields (is_ansi, text)
### Response:
def ansi_split(text, _re=re.compile(u"(\x1b\\[(\\d*;?)*\\S)")):
"""Yields (is_ansi, text)"""
for part in _re.split(text):
if part:
yield (bool(_re.match(part)), part) |
def _check_completion(task, mark_incomplete, clear, stats, visited, to_clear):
"""Core recursion function for :func:`check_completion`, see there for more documentation
Args:
task (luigi.Task): task instance
mark_incomplete (bool): see :func:`check_completion`
clear (bool): see :func:... | Core recursion function for :func:`check_completion`, see there for more documentation
Args:
task (luigi.Task): task instance
mark_incomplete (bool): see :func:`check_completion`
clear (bool): see :func:`check_completion`
stats (dict): task checking statistics (counts of incomple... | Below is the the instruction that describes the task:
### Input:
Core recursion function for :func:`check_completion`, see there for more documentation
Args:
task (luigi.Task): task instance
mark_incomplete (bool): see :func:`check_completion`
clear (bool): see :func:`check_completion... |
def get_profile(fqa):
""" Given a fully-qualified username (username.namespace)
get the data associated with that fqu.
Return cached entries, if possible.
"""
profile_expired_grace = False
fqa = fqa.lower()
try:
try:
res = blockstack.lib.client.resolve_profile(... | Given a fully-qualified username (username.namespace)
get the data associated with that fqu.
Return cached entries, if possible. | Below is the the instruction that describes the task:
### Input:
Given a fully-qualified username (username.namespace)
get the data associated with that fqu.
Return cached entries, if possible.
### Response:
def get_profile(fqa):
""" Given a fully-qualified username (username.namespace)
... |
def frequency2fractional(frequency, mean_frequency=-1):
""" Convert frequency in Hz to fractional frequency
Parameters
----------
frequency: np.array
Data array of frequency in Hz
mean_frequency: float
(optional) The nominal mean frequency, in Hz
if omitted, defaults to mean... | Convert frequency in Hz to fractional frequency
Parameters
----------
frequency: np.array
Data array of frequency in Hz
mean_frequency: float
(optional) The nominal mean frequency, in Hz
if omitted, defaults to mean frequency=np.mean(frequency)
Returns
-------
y:
... | Below is the the instruction that describes the task:
### Input:
Convert frequency in Hz to fractional frequency
Parameters
----------
frequency: np.array
Data array of frequency in Hz
mean_frequency: float
(optional) The nominal mean frequency, in Hz
if omitted, defaults to... |
def get_default_assets_zip_provider():
"""Opens stock TensorBoard web assets collection.
Returns:
Returns function that returns a newly opened file handle to zip file
containing static assets for stock TensorBoard, or None if webfiles.zip
could not be found. The value the callback returns must be close... | Opens stock TensorBoard web assets collection.
Returns:
Returns function that returns a newly opened file handle to zip file
containing static assets for stock TensorBoard, or None if webfiles.zip
could not be found. The value the callback returns must be closed. The
paths inside the zip file are con... | Below is the the instruction that describes the task:
### Input:
Opens stock TensorBoard web assets collection.
Returns:
Returns function that returns a newly opened file handle to zip file
containing static assets for stock TensorBoard, or None if webfiles.zip
could not be found. The value the callb... |
def calculate(self, T, P, zs, ws, method):
r'''Method to calculate molar volume of a gas mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for that.
... | r'''Method to calculate molar volume of a gas mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for that.
Parameters
----------
T : float
... | Below is the the instruction that describes the task:
### Input:
r'''Method to calculate molar volume of a gas mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
... |
def set_void_declension(self, number_type, case_type):
"""
>>> decl = DeclinableOneGender("armr", Gender.masculine)
>>> decl.declension
[]
>>> decl.set_void_declension(Number, Case)
>>> decl.declension
[['', '', '', ''], ['', '', '', '']]
:param number_ty... | >>> decl = DeclinableOneGender("armr", Gender.masculine)
>>> decl.declension
[]
>>> decl.set_void_declension(Number, Case)
>>> decl.declension
[['', '', '', ''], ['', '', '', '']]
:param number_type:
:param case_type:
:return: | Below is the the instruction that describes the task:
### Input:
>>> decl = DeclinableOneGender("armr", Gender.masculine)
>>> decl.declension
[]
>>> decl.set_void_declension(Number, Case)
>>> decl.declension
[['', '', '', ''], ['', '', '', '']]
:param number_type:
... |
def _log_enabled_protocols(self, flags, protocols):
"""Given a list of single character strings of 1's and 0's and a list
of protocol names. Log the status of each protocol where ``"1"`` is
enabled and ``"0"`` is disabled. The order of the lists here is
important as they need to be zippe... | Given a list of single character strings of 1's and 0's and a list
of protocol names. Log the status of each protocol where ``"1"`` is
enabled and ``"0"`` is disabled. The order of the lists here is
important as they need to be zipped together to create the mapping.
Then return a tuple o... | Below is the the instruction that describes the task:
### Input:
Given a list of single character strings of 1's and 0's and a list
of protocol names. Log the status of each protocol where ``"1"`` is
enabled and ``"0"`` is disabled. The order of the lists here is
important as they need to be... |
def use_comparative_bin_view(self):
"""Pass through to provider ResourceBinSession.use_comparative_bin_view"""
self._bin_view = COMPARATIVE
# self._get_provider_session('resource_bin_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
... | Pass through to provider ResourceBinSession.use_comparative_bin_view | Below is the the instruction that describes the task:
### Input:
Pass through to provider ResourceBinSession.use_comparative_bin_view
### Response:
def use_comparative_bin_view(self):
"""Pass through to provider ResourceBinSession.use_comparative_bin_view"""
self._bin_view = COMPARATIVE
# s... |
def _contents(self):
"""Define the contents of new Infos.
transmit() -> _what() -> create_information() -> _contents().
"""
stories = [
"ghosts.md",
"cricket.md",
"moochi.md",
"outwit.md",
"raid.md",
"species.md",
... | Define the contents of new Infos.
transmit() -> _what() -> create_information() -> _contents(). | Below is the the instruction that describes the task:
### Input:
Define the contents of new Infos.
transmit() -> _what() -> create_information() -> _contents().
### Response:
def _contents(self):
"""Define the contents of new Infos.
transmit() -> _what() -> create_information() -> _conten... |
def check_file(self, filename):
# type: (str) -> bool
"""
Overrides :py:meth:`.Config.check_file`
"""
can_read = super(SecuredConfig, self).check_file(filename)
if not can_read:
return False
mode = get_stat(filename).st_mode
if (mode & stat.S_... | Overrides :py:meth:`.Config.check_file` | Below is the the instruction that describes the task:
### Input:
Overrides :py:meth:`.Config.check_file`
### Response:
def check_file(self, filename):
# type: (str) -> bool
"""
Overrides :py:meth:`.Config.check_file`
"""
can_read = super(SecuredConfig, self).check_file(filen... |
def from_hdf(cls, fp, template_hash, root=None, load_to_memory=True,
load_now=False):
"""Load a compressed waveform from the given hdf file handler.
The waveform is retrieved from:
`fp['[{root}/]compressed_waveforms/{template_hash}/{param}']`,
where `param` is the `samp... | Load a compressed waveform from the given hdf file handler.
The waveform is retrieved from:
`fp['[{root}/]compressed_waveforms/{template_hash}/{param}']`,
where `param` is the `sample_points`, `amplitude`, and `phase`.
Parameters
----------
fp : h5py.File
An... | Below is the the instruction that describes the task:
### Input:
Load a compressed waveform from the given hdf file handler.
The waveform is retrieved from:
`fp['[{root}/]compressed_waveforms/{template_hash}/{param}']`,
where `param` is the `sample_points`, `amplitude`, and `phase`.
... |
def get_point(self, *position):
"""Return the noise value of a specific position.
Example usage: value = noise.getPoint(x, y, z)
Args:
position (Tuple[float, ...]): The point to sample at.
Returns:
float: The noise value at position.
This will ... | Return the noise value of a specific position.
Example usage: value = noise.getPoint(x, y, z)
Args:
position (Tuple[float, ...]): The point to sample at.
Returns:
float: The noise value at position.
This will be a floating point in the 0.0-1.0 range. | Below is the the instruction that describes the task:
### Input:
Return the noise value of a specific position.
Example usage: value = noise.getPoint(x, y, z)
Args:
position (Tuple[float, ...]): The point to sample at.
Returns:
float: The noise value at position.
... |
def _stop_processes(paths):
""" Scans process list trying to terminate processes matching paths
specified. Uses checksums to identify processes that are duplicates of
those specified to terminate.
`paths`
List of full paths to executables for processes to terminate.
"""
... | Scans process list trying to terminate processes matching paths
specified. Uses checksums to identify processes that are duplicates of
those specified to terminate.
`paths`
List of full paths to executables for processes to terminate. | Below is the the instruction that describes the task:
### Input:
Scans process list trying to terminate processes matching paths
specified. Uses checksums to identify processes that are duplicates of
those specified to terminate.
`paths`
List of full paths to executables for pro... |
def set_coords(self, names, inplace=None):
"""Given names of one or more variables, set them as coordinates
Parameters
----------
names : str or list of str
Name(s) of variables in this dataset to convert into coordinates.
inplace : bool, optional
If True... | Given names of one or more variables, set them as coordinates
Parameters
----------
names : str or list of str
Name(s) of variables in this dataset to convert into coordinates.
inplace : bool, optional
If True, modify this dataset inplace. Otherwise, create a new... | Below is the the instruction that describes the task:
### Input:
Given names of one or more variables, set them as coordinates
Parameters
----------
names : str or list of str
Name(s) of variables in this dataset to convert into coordinates.
inplace : bool, optional
... |
def get_delimited_message_bytes(byte_stream, nr=4):
''' Parse a delimited protobuf message. This is done by first getting a protobuf varint from
the stream that represents the length of the message, then reading that amount of
from the message and then parse it.
Since the int can be represented as max 4... | Parse a delimited protobuf message. This is done by first getting a protobuf varint from
the stream that represents the length of the message, then reading that amount of
from the message and then parse it.
Since the int can be represented as max 4 bytes, first get 4 bytes and try to decode.
The decoder... | Below is the the instruction that describes the task:
### Input:
Parse a delimited protobuf message. This is done by first getting a protobuf varint from
the stream that represents the length of the message, then reading that amount of
from the message and then parse it.
Since the int can be represented... |
def EncodeMultipartFormData(fields, files):
"""Encode form fields for multipart/form-data.
Args:
fields: A sequence of (name, value) elements for regular form fields.
files: A sequence of (name, filename, value) elements for data to be
uploaded as files.
Returns:
(content_type, body) ready for httplib.HT... | Encode form fields for multipart/form-data.
Args:
fields: A sequence of (name, value) elements for regular form fields.
files: A sequence of (name, filename, value) elements for data to be
uploaded as files.
Returns:
(content_type, body) ready for httplib.HTTP instance.
Source:
http://aspn.activestate... | Below is the the instruction that describes the task:
### Input:
Encode form fields for multipart/form-data.
Args:
fields: A sequence of (name, value) elements for regular form fields.
files: A sequence of (name, filename, value) elements for data to be
uploaded as files.
Returns:
(content_type, body)... |
def verify_checksum(self, progress_callback=None, chunk_size=None,
throws=True, checksum_kwargs=None, **kwargs):
"""Verify checksum of file instance.
:param bool throws: If `True`, exceptions raised during checksum
calculation will be re-raised after logging. If set ... | Verify checksum of file instance.
:param bool throws: If `True`, exceptions raised during checksum
calculation will be re-raised after logging. If set to `False`, and
an exception occurs, the `last_check` field is set to `None`
(`last_check_at` of course is updated), since n... | Below is the the instruction that describes the task:
### Input:
Verify checksum of file instance.
:param bool throws: If `True`, exceptions raised during checksum
calculation will be re-raised after logging. If set to `False`, and
an exception occurs, the `last_check` field is set ... |
def _start_lock_renewer(self):
"""
Starts the lock refresher thread.
"""
if self._lock_renewal_thread is not None:
raise AlreadyStarted("Lock refresh thread already started")
logger.debug(
"Starting thread to refresh lock every %s seconds",
se... | Starts the lock refresher thread. | Below is the the instruction that describes the task:
### Input:
Starts the lock refresher thread.
### Response:
def _start_lock_renewer(self):
"""
Starts the lock refresher thread.
"""
if self._lock_renewal_thread is not None:
raise AlreadyStarted("Lock refresh thread a... |
def render(self, context):
"""Render markdown."""
import markdown
content = self.get_content_from_context(context)
return markdown.markdown(content) | Render markdown. | Below is the the instruction that describes the task:
### Input:
Render markdown.
### Response:
def render(self, context):
"""Render markdown."""
import markdown
content = self.get_content_from_context(context)
return markdown.markdown(content) |
def user_agent(self):
"""
its a user agent string!
"""
version = ""
project_root = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(project_root, 'VERSION')) as version_file:
version = version_file.read().strip()
return "Python Snow A... | its a user agent string! | Below is the the instruction that describes the task:
### Input:
its a user agent string!
### Response:
def user_agent(self):
"""
its a user agent string!
"""
version = ""
project_root = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(project_root, ... |
def save_models(self, models_file):
"""
Saves model parameters at each iteration of the optimization
:param models_file: name of the file or a file buffer, in which the results are saved.
"""
if self.model_parameters_iterations is None:
raise ValueError("No iteration... | Saves model parameters at each iteration of the optimization
:param models_file: name of the file or a file buffer, in which the results are saved. | Below is the the instruction that describes the task:
### Input:
Saves model parameters at each iteration of the optimization
:param models_file: name of the file or a file buffer, in which the results are saved.
### Response:
def save_models(self, models_file):
"""
Saves model parameters ... |
def output_clusters(labels, cluster_centers_indices):
"""Write in tab-separated files the vectors of cluster identities and
of indices of cluster centers.
"""
here = os.getcwd()
try:
output_directory = os.path.join(here, 'concurrent_AP_output')
os.makedirs(output_dir... | Write in tab-separated files the vectors of cluster identities and
of indices of cluster centers. | Below is the the instruction that describes the task:
### Input:
Write in tab-separated files the vectors of cluster identities and
of indices of cluster centers.
### Response:
def output_clusters(labels, cluster_centers_indices):
"""Write in tab-separated files the vectors of cluster identities and
... |
def data(self):
"""Get the data, after performing post-processing if necessary."""
data = super(DynamicListSerializer, self).data
processed_data = ReturnDict(
SideloadingProcessor(self, data).data,
serializer=self
) if self.child.envelope else ReturnList(
... | Get the data, after performing post-processing if necessary. | Below is the the instruction that describes the task:
### Input:
Get the data, after performing post-processing if necessary.
### Response:
def data(self):
"""Get the data, after performing post-processing if necessary."""
data = super(DynamicListSerializer, self).data
processed_data = Retu... |
def _get_path_pattern_tornado45(self, router=None):
"""Return the path pattern used when routing a request. (Tornado>=4.5)
:param tornado.routing.Router router: (Optional) The router to scan.
Defaults to the application's router.
:rtype: str
"""
if router is None:
... | Return the path pattern used when routing a request. (Tornado>=4.5)
:param tornado.routing.Router router: (Optional) The router to scan.
Defaults to the application's router.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Return the path pattern used when routing a request. (Tornado>=4.5)
:param tornado.routing.Router router: (Optional) The router to scan.
Defaults to the application's router.
:rtype: str
### Response:
def _get_path_patte... |
def _update_advertised(self, advertised):
"""Called when advertisement data is received."""
# Advertisement data was received, pull out advertised service UUIDs and
# name from advertisement data.
if 'kCBAdvDataServiceUUIDs' in advertised:
self._advertised = self._advertised ... | Called when advertisement data is received. | Below is the the instruction that describes the task:
### Input:
Called when advertisement data is received.
### Response:
def _update_advertised(self, advertised):
"""Called when advertisement data is received."""
# Advertisement data was received, pull out advertised service UUIDs and
# n... |
def get_tokens(max_value):
"""Defines tokens.
Args:
max_value: the maximum numeric range for the token.
Returns:
list of string tokens in vocabulary.
"""
vocab = [str(i) for i in range(max_value)]
vocab = set(vocab)
vocab.update(CodeOp.LITERALS)
vocab.update(CodeOp.KEYWORDS)
vocab |= set("".... | Defines tokens.
Args:
max_value: the maximum numeric range for the token.
Returns:
list of string tokens in vocabulary. | Below is the the instruction that describes the task:
### Input:
Defines tokens.
Args:
max_value: the maximum numeric range for the token.
Returns:
list of string tokens in vocabulary.
### Response:
def get_tokens(max_value):
"""Defines tokens.
Args:
max_value: the maximum numeric range for ... |
def readACTIONRECORD(self):
""" Read a SWFActionRecord """
action = None
actionCode = self.readUI8()
if actionCode != 0:
actionLength = self.readUI16() if actionCode >= 0x80 else 0
#print "0x%x"%actionCode, actionLength
action = SWFActionFactory.create... | Read a SWFActionRecord | Below is the the instruction that describes the task:
### Input:
Read a SWFActionRecord
### Response:
def readACTIONRECORD(self):
""" Read a SWFActionRecord """
action = None
actionCode = self.readUI8()
if actionCode != 0:
actionLength = self.readUI16() if actionCode >= ... |
def update_index(entries):
"""find the last 10 entries in the database and create the main
page.
Each entry in has an doc_id, so we only get the last 10 doc_ids.
This method also updates the ATOM feed.
"""
context = GLOBAL_TEMPLATE_CONTEXT.copy()
context['entries'] = entries
context['la... | find the last 10 entries in the database and create the main
page.
Each entry in has an doc_id, so we only get the last 10 doc_ids.
This method also updates the ATOM feed. | Below is the the instruction that describes the task:
### Input:
find the last 10 entries in the database and create the main
page.
Each entry in has an doc_id, so we only get the last 10 doc_ids.
This method also updates the ATOM feed.
### Response:
def update_index(entries):
"""find the last 10 ... |
def func_accepts_var_args(func):
"""
Return True if function 'func' accepts positional arguments *args.
"""
if six.PY2:
return inspect.getargspec(func)[1] is not None
return any(
p for p in inspect.signature(func).parameters.values()
if p.kind == p.VAR_POSITIONAL
) | Return True if function 'func' accepts positional arguments *args. | Below is the the instruction that describes the task:
### Input:
Return True if function 'func' accepts positional arguments *args.
### Response:
def func_accepts_var_args(func):
"""
Return True if function 'func' accepts positional arguments *args.
"""
if six.PY2:
return inspect.getargspec... |
def GetOutputDir(self, base_dir, config_filename):
"""Add the repack config filename onto the base output directory.
This allows us to repack lots of different configs to the same installer
name and still be able to distinguish them.
Args:
base_dir: output directory string
config_filename:... | Add the repack config filename onto the base output directory.
This allows us to repack lots of different configs to the same installer
name and still be able to distinguish them.
Args:
base_dir: output directory string
config_filename: the secondary config filename string
Returns:
... | Below is the the instruction that describes the task:
### Input:
Add the repack config filename onto the base output directory.
This allows us to repack lots of different configs to the same installer
name and still be able to distinguish them.
Args:
base_dir: output directory string
confi... |
def getBeamline(self, beamlineKw):
""" get beamline definition from all_elements, return as a list
:param beamlineKw: keyword of beamline
"""
lattice_string = list(self.all_elements.get(beamlineKw.upper()).values())[0].get('lattice')
return lattice_string[1:-1].split() | get beamline definition from all_elements, return as a list
:param beamlineKw: keyword of beamline | Below is the the instruction that describes the task:
### Input:
get beamline definition from all_elements, return as a list
:param beamlineKw: keyword of beamline
### Response:
def getBeamline(self, beamlineKw):
""" get beamline definition from all_elements, return as a list
:param beamlin... |
def semester_feature(catalog, soup):
"""The year and semester information that this xml file hold courses for.
"""
raw = soup.coursedb['semesternumber']
catalog.year = int(raw[:4])
month_mapping = {1: 'Spring', 5: 'Summer', 9: 'Fall'}
catalog.month = int(raw[4:])
catalog.semester = month_ma... | The year and semester information that this xml file hold courses for. | Below is the the instruction that describes the task:
### Input:
The year and semester information that this xml file hold courses for.
### Response:
def semester_feature(catalog, soup):
"""The year and semester information that this xml file hold courses for.
"""
raw = soup.coursedb['semesternumber']
... |
def url(self):
"""
Convert self into a url
This function should more or less round-trip with :func:`.parse_url`. The
returned url may not be exactly the same as the url inputted to
:func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls
with a blank port w... | Convert self into a url
This function should more or less round-trip with :func:`.parse_url`. The
returned url may not be exactly the same as the url inputted to
:func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls
with a blank port will have : removed).
Examp... | Below is the the instruction that describes the task:
### Input:
Convert self into a url
This function should more or less round-trip with :func:`.parse_url`. The
returned url may not be exactly the same as the url inputted to
:func:`.parse_url`, but it should be equivalent by the RFC (e.g.... |
def run(args):
"""Process command line arguments and walk inputs."""
raw_arguments = get_arguments(args[1:])
process_arguments(raw_arguments)
walk.run()
return True | Process command line arguments and walk inputs. | Below is the the instruction that describes the task:
### Input:
Process command line arguments and walk inputs.
### Response:
def run(args):
"""Process command line arguments and walk inputs."""
raw_arguments = get_arguments(args[1:])
process_arguments(raw_arguments)
walk.run()
return True |
def split_comp_info(self, catalog_name, split_ver, split_key):
""" Return the info for a particular split key """
return self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)][split_key] | Return the info for a particular split key | Below is the the instruction that describes the task:
### Input:
Return the info for a particular split key
### Response:
def split_comp_info(self, catalog_name, split_ver, split_key):
""" Return the info for a particular split key """
return self._split_comp_info_dicts["%s_%s" % (catalog_name, spl... |
def _normalize_name(name):
"""Returns a normalized element tag or attribute name. A tag name or attribute name can be given
either as a string, or as a 2-tuple. If a 2-tuple, it is interpreted as (namespace, name) and is
returned joined by a colon ":"
:name: a string or a 2-tuple of strings
"""
if isinstan... | Returns a normalized element tag or attribute name. A tag name or attribute name can be given
either as a string, or as a 2-tuple. If a 2-tuple, it is interpreted as (namespace, name) and is
returned joined by a colon ":"
:name: a string or a 2-tuple of strings | Below is the the instruction that describes the task:
### Input:
Returns a normalized element tag or attribute name. A tag name or attribute name can be given
either as a string, or as a 2-tuple. If a 2-tuple, it is interpreted as (namespace, name) and is
returned joined by a colon ":"
:name: a string or a 2... |
def file_close(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /file-xxxx/close API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Files#API-method%3A-%2Ffile-xxxx%2Fclose
"""
return DXHTTPRequest('/%s/close' % object_id, input_params, alway... | Invokes the /file-xxxx/close API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Files#API-method%3A-%2Ffile-xxxx%2Fclose | Below is the the instruction that describes the task:
### Input:
Invokes the /file-xxxx/close API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Files#API-method%3A-%2Ffile-xxxx%2Fclose
### Response:
def file_close(object_id, input_params={}, always_retry=True, **kwargs):
"... |
def optimise(args, **kwargs):
"""
Optimise the model parameters.
"""
expected_output_files = kwargs.pop("expected_output_files", None)
if not expected_output_files:
expected_output_files = ["optimised.pkl"]
if args.plotting:
expected_output_files.extend([
... | Optimise the model parameters. | Below is the the instruction that describes the task:
### Input:
Optimise the model parameters.
### Response:
def optimise(args, **kwargs):
"""
Optimise the model parameters.
"""
expected_output_files = kwargs.pop("expected_output_files", None)
if not expected_output_files:
expected_ou... |
def to_cloudformation(self, **kwargs):
"""Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed
policy to the function's execution role, if such a role is provided.
:param dict kwargs: a dict containing the execution role generated for the func... | Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed
policy to the function's execution role, if such a role is provided.
:param dict kwargs: a dict containing the execution role generated for the function
:returns: a list of vanilla CloudForm... | Below is the the instruction that describes the task:
### Input:
Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed
policy to the function's execution role, if such a role is provided.
:param dict kwargs: a dict containing the execution role gen... |
def _get_base_interface_info(interface):
'''
return base details about given interface
'''
blacklist = {
'tcpip': {
'name': [],
'type': [],
'additional_protocol': False
},
'disabled': {
'name': ['eth0'],
'type': ['gadget... | return base details about given interface | Below is the the instruction that describes the task:
### Input:
return base details about given interface
### Response:
def _get_base_interface_info(interface):
'''
return base details about given interface
'''
blacklist = {
'tcpip': {
'name': [],
'type': [],
... |
def append_fallback(model, fields):
"""
If translated field is encountered, add also all its fallback fields.
Returns tuple: (set_of_new_fields_to_use, set_of_translated_field_names)
"""
fields = set(fields)
trans = set()
from modeltranslation.translator import translator
opts = translat... | If translated field is encountered, add also all its fallback fields.
Returns tuple: (set_of_new_fields_to_use, set_of_translated_field_names) | Below is the the instruction that describes the task:
### Input:
If translated field is encountered, add also all its fallback fields.
Returns tuple: (set_of_new_fields_to_use, set_of_translated_field_names)
### Response:
def append_fallback(model, fields):
"""
If translated field is encountered, add a... |
def insert_element_to_dict_of_dicts_of_list(dict_of_dict_of_list, first_key, second_key, parser):
"""
Utility method
:param dict_of_dict_of_list:
:param first_key:
:param second_key:
:param parser:
:return:
"""
list_to_insert = parser if isinstance(parser, list) else [parser]
i... | Utility method
:param dict_of_dict_of_list:
:param first_key:
:param second_key:
:param parser:
:return: | Below is the the instruction that describes the task:
### Input:
Utility method
:param dict_of_dict_of_list:
:param first_key:
:param second_key:
:param parser:
:return:
### Response:
def insert_element_to_dict_of_dicts_of_list(dict_of_dict_of_list, first_key, second_key, parser):
"""
... |
def p_block(self, p):
""" block_decl : block_open declaration_list brace_close
"""
p[0] = Block(list(p)[1:-1], p.lineno(3))
self.scope.pop()
self.scope.add_block(p[0]) | block_decl : block_open declaration_list brace_close | Below is the the instruction that describes the task:
### Input:
block_decl : block_open declaration_list brace_close
### Response:
def p_block(self, p):
""" block_decl : block_open declaration_list brace_close
"""
p[0] = Block(list(p)[1:-1], p.lineno(3))
... |
def viewit(self, post_id):
'''
View the link.
'''
rec = MLink.get_by_uid(post_id)
if not rec:
kwd = {'info': '您要找的分类不存在。'}
self.render('misc/html/404.html', kwd=kwd)
return False
kwd = {
'pager': '',
'editable... | View the link. | Below is the the instruction that describes the task:
### Input:
View the link.
### Response:
def viewit(self, post_id):
'''
View the link.
'''
rec = MLink.get_by_uid(post_id)
if not rec:
kwd = {'info': '您要找的分类不存在。'}
self.render('misc/html/404.html'... |
def setParameter(self, parameterName, index, parameterValue):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are ex... | Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are explicitly handled here. | Below is the the instruction that describes the task:
### Input:
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are explici... |
def sort(words, context="", strict=True, relative=True, service=YAHOO_SEARCH,
wait=10, asynchronous=False, cached=False):
"""Performs a Yahoo sort on the given list.
Sorts the items in the list according to
the result count Yahoo yields on an item.
Setting a context sorts the it... | Performs a Yahoo sort on the given list.
Sorts the items in the list according to
the result count Yahoo yields on an item.
Setting a context sorts the items according
to their relation to this context;
for example sorting [red, green, blue] by "love"
yields red as the highest results... | Below is the the instruction that describes the task:
### Input:
Performs a Yahoo sort on the given list.
Sorts the items in the list according to
the result count Yahoo yields on an item.
Setting a context sorts the items according
to their relation to this context;
for example sorti... |
def QA_util_add_months(dt, months):
"""
#返回dt隔months个月后的日期,months相当于步长
"""
dt = datetime.datetime.strptime(
dt, "%Y-%m-%d") + relativedelta(months=months)
return(dt) | #返回dt隔months个月后的日期,months相当于步长 | Below is the the instruction that describes the task:
### Input:
#返回dt隔months个月后的日期,months相当于步长
### Response:
def QA_util_add_months(dt, months):
"""
#返回dt隔months个月后的日期,months相当于步长
"""
dt = datetime.datetime.strptime(
dt, "%Y-%m-%d") + relativedelta(months=months)
return(dt) |
def copy(self):
"""
Return a shallow copy of a pqdict.
"""
return self.__class__(self, key=self._keyfn, precedes=self._precedes) | Return a shallow copy of a pqdict. | Below is the the instruction that describes the task:
### Input:
Return a shallow copy of a pqdict.
### Response:
def copy(self):
"""
Return a shallow copy of a pqdict.
"""
return self.__class__(self, key=self._keyfn, precedes=self._precedes) |
def prettylist(list_):
"""
Filter out duplicate values while keeping order.
"""
if not list_:
return ''
values = set()
uniqueList = []
for entry in list_:
if not entry in values:
values.add(entry)
uniqueList.append(entry)
return uniqueList[0] if... | Filter out duplicate values while keeping order. | Below is the the instruction that describes the task:
### Input:
Filter out duplicate values while keeping order.
### Response:
def prettylist(list_):
"""
Filter out duplicate values while keeping order.
"""
if not list_:
return ''
values = set()
uniqueList = []
for entry in l... |
def get_settings(self):
"""
Returns current settings.
Only accessible if authenticated as the user.
"""
url = self._imgur._base_url + "/3/account/{0}/settings".format(self.name)
return self._imgur._send_request(url) | Returns current settings.
Only accessible if authenticated as the user. | Below is the the instruction that describes the task:
### Input:
Returns current settings.
Only accessible if authenticated as the user.
### Response:
def get_settings(self):
"""
Returns current settings.
Only accessible if authenticated as the user.
"""
url = self... |
def delete_container_instance_group(access_token, subscription_id, resource_group,
container_group_name):
'''Delete a container group from a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscriptio... | Delete a container group from a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
container_group_name (str): Name of container instance group.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Delete a container group from a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
container... |
def get_configuration_dict(self, secret_attrs=False):
"""Overrides superclass method and renames some properties"""
cd = super(TreeCollectionsShard, self).get_configuration_dict(secret_attrs=secret_attrs)
# "rename" some keys in the dict provided
cd['number of collections'] = cd.pop('num... | Overrides superclass method and renames some properties | Below is the the instruction that describes the task:
### Input:
Overrides superclass method and renames some properties
### Response:
def get_configuration_dict(self, secret_attrs=False):
"""Overrides superclass method and renames some properties"""
cd = super(TreeCollectionsShard, self).get_confi... |
def fit(self, X, y, **kwargs):
"""
Fits the learning curve with the wrapped model to the specified data.
Draws training and test score curves and saves the scores to the
estimator.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Tr... | Fits the learning curve with the wrapped model to the specified data.
Draws training and test score curves and saves the scores to the
estimator.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of sam... | Below is the the instruction that describes the task:
### Input:
Fits the learning curve with the wrapped model to the specified data.
Draws training and test score curves and saves the scores to the
estimator.
Parameters
----------
X : array-like, shape (n_samples, n_featur... |
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs) | Perform all actions on a given attribute dict. | Below is the the instruction that describes the task:
### Input:
Perform all actions on a given attribute dict.
### Response:
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs... |
def store_oui(self, port_uuid, oui_type, oui_data):
"""Function for storing the OUI.
param uuid: UUID of the vNIC
param oui_type: OUI ID
param oui_data: OUI Opaque Data
"""
self.oui_vif_map[port_uuid] = {'oui_id': oui_type,
'oui_dat... | Function for storing the OUI.
param uuid: UUID of the vNIC
param oui_type: OUI ID
param oui_data: OUI Opaque Data | Below is the the instruction that describes the task:
### Input:
Function for storing the OUI.
param uuid: UUID of the vNIC
param oui_type: OUI ID
param oui_data: OUI Opaque Data
### Response:
def store_oui(self, port_uuid, oui_type, oui_data):
"""Function for storing the OUI.
... |
def getAll(self):
"""Get all objects
Returns:
List: list of all objects
"""
objs = []
for obj in self.model.db:
objs.append(self._cast_model(obj))
return objs | Get all objects
Returns:
List: list of all objects | Below is the the instruction that describes the task:
### Input:
Get all objects
Returns:
List: list of all objects
### Response:
def getAll(self):
"""Get all objects
Returns:
List: list of all objects
"""
objs = []
for obj in ... |
def arange(start, stop=None, step=1.0, repeat=1, infer_range=None, ctx=None, dtype=mx_real_t):
"""Returns evenly spaced values within a given interval.
Values are generated within the half-open interval [`start`, `stop`). In other
words, the interval includes `start` but excludes `stop`. The function is
... | Returns evenly spaced values within a given interval.
Values are generated within the half-open interval [`start`, `stop`). In other
words, the interval includes `start` but excludes `stop`. The function is
similar to the built-in Python function `range` and to `numpy.arange`,
but returns an `NDArray`.... | Below is the the instruction that describes the task:
### Input:
Returns evenly spaced values within a given interval.
Values are generated within the half-open interval [`start`, `stop`). In other
words, the interval includes `start` but excludes `stop`. The function is
similar to the built-in Python ... |
def __normalize(self,text):
"""
Substitute words in the string, according to the specified Normal,
e.g. "I'm" -> "I am"
:type str: str
:param str: The string to be mapped
:rtype: str
"""
return self._normalizer_regex.sub(lambda mo:
self._n... | Substitute words in the string, according to the specified Normal,
e.g. "I'm" -> "I am"
:type str: str
:param str: The string to be mapped
:rtype: str | Below is the the instruction that describes the task:
### Input:
Substitute words in the string, according to the specified Normal,
e.g. "I'm" -> "I am"
:type str: str
:param str: The string to be mapped
:rtype: str
### Response:
def __normalize(self,text):
"""
Subs... |
def _draw_rectangle(data, obj, draw_options):
"""Return the PGFPlots code for rectangles.
"""
# Objects with labels are plot objects (from bar charts, etc). Even those without
# labels explicitly set have a label of "_nolegend_". Everything else should be
# skipped because they likely correspong t... | Return the PGFPlots code for rectangles. | Below is the the instruction that describes the task:
### Input:
Return the PGFPlots code for rectangles.
### Response:
def _draw_rectangle(data, obj, draw_options):
"""Return the PGFPlots code for rectangles.
"""
# Objects with labels are plot objects (from bar charts, etc). Even those without
# ... |
def outer_left_join(self, join_streamlet, window_config, join_function):
"""Return a new Streamlet by left join_streamlet with this streamlet
"""
from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt
join_streamlet_result = JoinStreamlet(JoinBolt.OUTER_LEFT, window_config,
... | Return a new Streamlet by left join_streamlet with this streamlet | Below is the the instruction that describes the task:
### Input:
Return a new Streamlet by left join_streamlet with this streamlet
### Response:
def outer_left_join(self, join_streamlet, window_config, join_function):
"""Return a new Streamlet by left join_streamlet with this streamlet
"""
from heronpy... |
def __reset_weights(self, target_phis, res_idxs, obs_idxs):
"""private method to reset weights based on target phi values
for each group. This method should not be called directly
Parameters
----------
target_phis : dict
target phi contribution for groups to reweigh... | private method to reset weights based on target phi values
for each group. This method should not be called directly
Parameters
----------
target_phis : dict
target phi contribution for groups to reweight
res_idxs : dict
the index positions of each group... | Below is the the instruction that describes the task:
### Input:
private method to reset weights based on target phi values
for each group. This method should not be called directly
Parameters
----------
target_phis : dict
target phi contribution for groups to reweight
... |
def trailing_whitespace(physical_line):
r"""Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank, for easier
filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12... | r"""Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank, for easier
filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12 | Below is the the instruction that describes the task:
### Input:
r"""Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank, for easier
filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(obje... |
def do_format(self, format):
"""Apply format selection."""
infile = self.tmpfile
outfile = self.basename + '.out'
outfile_jp2 = self.basename + '.jp2'
# Now convert finished pnm file to output format
# simeon@ice ~>cat m3.pnm | pnmtojpeg > m4.jpg
# simeon@ice ~>c... | Apply format selection. | Below is the the instruction that describes the task:
### Input:
Apply format selection.
### Response:
def do_format(self, format):
"""Apply format selection."""
infile = self.tmpfile
outfile = self.basename + '.out'
outfile_jp2 = self.basename + '.jp2'
# Now convert finishe... |
def get(tzid):
"""Return timezone data"""
ns = {}
path = os.path.join(DATA_DIR, tzid)
with open(path) as f:
raw_data = f.read()
exec(raw_data, ns, ns)
z = ZoneData()
z.types = [(delta(offset), delta(save), abbr)
for offset, save, abbr in ns['types']]
z.times = [(da... | Return timezone data | Below is the the instruction that describes the task:
### Input:
Return timezone data
### Response:
def get(tzid):
"""Return timezone data"""
ns = {}
path = os.path.join(DATA_DIR, tzid)
with open(path) as f:
raw_data = f.read()
exec(raw_data, ns, ns)
z = ZoneData()
z.types = [(d... |
def read_unsigned_byte(self, cmd):
"""
Read an unsigned byte from the specified command register
"""
result = self.bus.read_byte_data(self.address, cmd)
self.log.debug(
"read_unsigned_byte: Read 0x%02X from command register 0x%02X" % (
result, cmd
... | Read an unsigned byte from the specified command register | Below is the the instruction that describes the task:
### Input:
Read an unsigned byte from the specified command register
### Response:
def read_unsigned_byte(self, cmd):
"""
Read an unsigned byte from the specified command register
"""
result = self.bus.read_byte_data(self.address... |
def _is_notation(ip, notation, _isnm):
"""Internally used to check if an IP/netmask is in the given notation."""
notation_orig = notation
notation = _get_notation(notation)
if notation not in _CHECK_FUNCT_KEYS:
raise ValueError('_is_notation: unkown notation: "%s"' % notation_orig)
return _C... | Internally used to check if an IP/netmask is in the given notation. | Below is the the instruction that describes the task:
### Input:
Internally used to check if an IP/netmask is in the given notation.
### Response:
def _is_notation(ip, notation, _isnm):
"""Internally used to check if an IP/netmask is in the given notation."""
notation_orig = notation
notation = _get_no... |
def parse_headerline(self, line):
""" Parses header lines
Header example:
Date 2012/11/15 User anonymous
Time 06:07:08PM Software version: 4.0
Example laboratory
Arizona
"""
if line.startswith('Date'):
split... | Parses header lines
Header example:
Date 2012/11/15 User anonymous
Time 06:07:08PM Software version: 4.0
Example laboratory
Arizona | Below is the the instruction that describes the task:
### Input:
Parses header lines
Header example:
Date 2012/11/15 User anonymous
Time 06:07:08PM Software version: 4.0
Example laboratory
Arizona
### Response:
def parse_headerline(self, ... |
def list(self, search_from=None, search_to=None, limit=None):
"""List all the objects saved in the namespace.
:param search_from: TBI
:param search_to: TBI
:param offset: TBI
:param limit: max number of values to be shows.
:return: list with transactions.
"... | List all the objects saved in the namespace.
:param search_from: TBI
:param search_to: TBI
:param offset: TBI
:param limit: max number of values to be shows.
:return: list with transactions. | Below is the the instruction that describes the task:
### Input:
List all the objects saved in the namespace.
:param search_from: TBI
:param search_to: TBI
:param offset: TBI
:param limit: max number of values to be shows.
:return: list with transactions.
### Response: ... |
def handle(send, msg, args):
"""Implements several XKCD comics."""
output = textutils.gen_xkcd_sub(msg, True)
if output is None:
return
if args['type'] == 'action':
send("correction: * %s %s" % (args['nick'], output))
else:
send("%s actually meant: %s" % (args['nick'], output... | Implements several XKCD comics. | Below is the the instruction that describes the task:
### Input:
Implements several XKCD comics.
### Response:
def handle(send, msg, args):
"""Implements several XKCD comics."""
output = textutils.gen_xkcd_sub(msg, True)
if output is None:
return
if args['type'] == 'action':
send("c... |
def deprecated_conditional(predicate,
removal_version,
entity_description,
hint_message=None,
stacklevel=4):
"""Marks a certain configuration as deprecated.
The predicate is used to determine if that configu... | Marks a certain configuration as deprecated.
The predicate is used to determine if that configuration is deprecated. It is a function that
will be called, if true, then the deprecation warning will issue.
:param () -> bool predicate: A function that returns True if the deprecation warning should be on.
:param... | Below is the the instruction that describes the task:
### Input:
Marks a certain configuration as deprecated.
The predicate is used to determine if that configuration is deprecated. It is a function that
will be called, if true, then the deprecation warning will issue.
:param () -> bool predicate: A functio... |
def _evaluate(self, indices, norm_distances, out=None):
"""Evaluate nearest interpolation."""
idx_res = []
for i, yi in zip(indices, norm_distances):
if self.variant == 'left':
idx_res.append(np.where(yi <= .5, i, i + 1))
else:
idx_res.appe... | Evaluate nearest interpolation. | Below is the the instruction that describes the task:
### Input:
Evaluate nearest interpolation.
### Response:
def _evaluate(self, indices, norm_distances, out=None):
"""Evaluate nearest interpolation."""
idx_res = []
for i, yi in zip(indices, norm_distances):
if self.variant ==... |
def surveys(self):
"""
Returns the list of timesteps when survey measures has been captured
None if xml document is mailformed
xpath: /scenario/monitoring/survey
https://github.com/SwissTPH/openmalaria/wiki/GeneratedSchema32Doc#survey-times-time-steps
"""
survey_t... | Returns the list of timesteps when survey measures has been captured
None if xml document is mailformed
xpath: /scenario/monitoring/survey
https://github.com/SwissTPH/openmalaria/wiki/GeneratedSchema32Doc#survey-times-time-steps | Below is the the instruction that describes the task:
### Input:
Returns the list of timesteps when survey measures has been captured
None if xml document is mailformed
xpath: /scenario/monitoring/survey
https://github.com/SwissTPH/openmalaria/wiki/GeneratedSchema32Doc#survey-times-time-step... |
def get_assembly_size(assembly_file):
"""Returns the number of nucleotides and the size per contig for the
provided assembly file path
Parameters
----------
assembly_file : str
Path to assembly file.
Returns
-------
assembly_size : int
Size of the assembly in nucleotide... | Returns the number of nucleotides and the size per contig for the
provided assembly file path
Parameters
----------
assembly_file : str
Path to assembly file.
Returns
-------
assembly_size : int
Size of the assembly in nucleotides
contig_size : dict
Length of ea... | Below is the the instruction that describes the task:
### Input:
Returns the number of nucleotides and the size per contig for the
provided assembly file path
Parameters
----------
assembly_file : str
Path to assembly file.
Returns
-------
assembly_size : int
Size of th... |
def register_on_serial_port_changed(self, callback):
"""Set the callback function to consume on serial port changed events.
Callback receives a ISerialPortChangedEvent object.
Returns the callback_id
"""
event_type = library.VBoxEventType.on_serial_port_changed
return s... | Set the callback function to consume on serial port changed events.
Callback receives a ISerialPortChangedEvent object.
Returns the callback_id | Below is the the instruction that describes the task:
### Input:
Set the callback function to consume on serial port changed events.
Callback receives a ISerialPortChangedEvent object.
Returns the callback_id
### Response:
def register_on_serial_port_changed(self, callback):
"""Set the ca... |
def _approximate_unkown_bond_lengths(self):
"""Completes the bond length database with approximations based on VDW radii"""
dataset = self.lengths[BOND_SINGLE]
for n1 in periodic.iter_numbers():
for n2 in periodic.iter_numbers():
if n1 <= n2:
pair ... | Completes the bond length database with approximations based on VDW radii | Below is the the instruction that describes the task:
### Input:
Completes the bond length database with approximations based on VDW radii
### Response:
def _approximate_unkown_bond_lengths(self):
"""Completes the bond length database with approximations based on VDW radii"""
dataset = self.lengths... |
def get_enthalpy(self, temperature, electronic_energy = 'Default'):
"""Returns the internal energy of an adsorbed molecule.
Parameters
----------
temperature : numeric
temperature in K
electronic_energy : numeric
energy in eV
Returns
-------
... | Returns the internal energy of an adsorbed molecule.
Parameters
----------
temperature : numeric
temperature in K
electronic_energy : numeric
energy in eV
Returns
-------
internal_energy : numeric
Internal energy in eV | Below is the the instruction that describes the task:
### Input:
Returns the internal energy of an adsorbed molecule.
Parameters
----------
temperature : numeric
temperature in K
electronic_energy : numeric
energy in eV
Returns
-------
inter... |
def save_or_overwrite_slice(
self, args, slc, slice_add_perm, slice_overwrite_perm, slice_download_perm,
datasource_id, datasource_type, datasource_name):
"""Save or overwrite a slice"""
slice_name = args.get('slice_name')
action = args.get('action')
form_data = g... | Save or overwrite a slice | Below is the the instruction that describes the task:
### Input:
Save or overwrite a slice
### Response:
def save_or_overwrite_slice(
self, args, slc, slice_add_perm, slice_overwrite_perm, slice_download_perm,
datasource_id, datasource_type, datasource_name):
"""Save or overwrite a ... |
def module(self):
"""Returns the module that this code element belongs to."""
if self._module is None:
root = self
while self._module is None and root is not None:
if isinstance(root, Module):
self._module = root
else:
... | Returns the module that this code element belongs to. | Below is the the instruction that describes the task:
### Input:
Returns the module that this code element belongs to.
### Response:
def module(self):
"""Returns the module that this code element belongs to."""
if self._module is None:
root = self
while self._module is None ... |
def install_plugin(pkgpath, plugin_type, install_path, register_func):
"""Install specified plugin.
:param pkgpath: Name of plugin to be downloaded from online repo or path to plugin folder or zip file.
:param install_path: Path where plugin will be installed.
:param register_func: Method used to regis... | Install specified plugin.
:param pkgpath: Name of plugin to be downloaded from online repo or path to plugin folder or zip file.
:param install_path: Path where plugin will be installed.
:param register_func: Method used to register and validate plugin. | Below is the the instruction that describes the task:
### Input:
Install specified plugin.
:param pkgpath: Name of plugin to be downloaded from online repo or path to plugin folder or zip file.
:param install_path: Path where plugin will be installed.
:param register_func: Method used to register and v... |
def should_stale_item_be_fetched_synchronously(self, delta, *args, **kwargs):
"""
Return whether to refresh an item synchronously when it is found in the
cache but stale
"""
if self.fetch_on_stale_threshold is None:
return False
return delta > (self.fetch_on_s... | Return whether to refresh an item synchronously when it is found in the
cache but stale | Below is the the instruction that describes the task:
### Input:
Return whether to refresh an item synchronously when it is found in the
cache but stale
### Response:
def should_stale_item_be_fetched_synchronously(self, delta, *args, **kwargs):
"""
Return whether to refresh an item synchron... |
def new_status(self, new_status):
"""
Sets the new_status of this BuildSetStatusChangedEvent.
:param new_status: The new_status of this BuildSetStatusChangedEvent.
:type: str
"""
allowed_values = ["NEW", "DONE", "REJECTED"]
if new_status not in allowed_values:
... | Sets the new_status of this BuildSetStatusChangedEvent.
:param new_status: The new_status of this BuildSetStatusChangedEvent.
:type: str | Below is the the instruction that describes the task:
### Input:
Sets the new_status of this BuildSetStatusChangedEvent.
:param new_status: The new_status of this BuildSetStatusChangedEvent.
:type: str
### Response:
def new_status(self, new_status):
"""
Sets the new_status of this ... |
def scale(self, w=1.0, h=1.0):
"""Resizes the layer to the given width and height.
When width w or height h is a floating-point number,
scales percentual,
otherwise scales to the given size in pixels.
"""
from types import FloatType
w0, h0 = self.... | Resizes the layer to the given width and height.
When width w or height h is a floating-point number,
scales percentual,
otherwise scales to the given size in pixels. | Below is the the instruction that describes the task:
### Input:
Resizes the layer to the given width and height.
When width w or height h is a floating-point number,
scales percentual,
otherwise scales to the given size in pixels.
### Response:
def scale(self, w=1.0, h=1.0):
... |
def imshow(self, key):
"""Show item's image"""
data = self.model.get_data()
import spyder.pyplot as plt
plt.figure()
plt.imshow(data[key])
plt.show() | Show item's image | Below is the the instruction that describes the task:
### Input:
Show item's image
### Response:
def imshow(self, key):
"""Show item's image"""
data = self.model.get_data()
import spyder.pyplot as plt
plt.figure()
plt.imshow(data[key])
plt.show() |
def _load_all_in_directory(self) -> Dict[str, Iterable[DataSourceType]]:
"""
Loads all of the data from the files in directory location.
:return: a origin map of all the loaded data
"""
origin_mapped_data = dict() # type: Dict[str, Iterable[DataSourceType]]
for file_pa... | Loads all of the data from the files in directory location.
:return: a origin map of all the loaded data | Below is the the instruction that describes the task:
### Input:
Loads all of the data from the files in directory location.
:return: a origin map of all the loaded data
### Response:
def _load_all_in_directory(self) -> Dict[str, Iterable[DataSourceType]]:
"""
Loads all of the data from the... |
def getStage(self, personID, nextStageIndex=0):
"""getStage(string, int) -> int
Returns the type of the nth next stage
0 for not-yet-departed
1 for waiting
2 for walking
3 for driving
nextStageIndex 0 retrieves value for the current stage.
nextStag... | getStage(string, int) -> int
Returns the type of the nth next stage
0 for not-yet-departed
1 for waiting
2 for walking
3 for driving
nextStageIndex 0 retrieves value for the current stage.
nextStageIndex must be lower then value of getRemainingStages(perso... | Below is the the instruction that describes the task:
### Input:
getStage(string, int) -> int
Returns the type of the nth next stage
0 for not-yet-departed
1 for waiting
2 for walking
3 for driving
nextStageIndex 0 retrieves value for the current stage.
... |
def linreg_mle(y, X, algorithm='Nelder-Mead', debug=False):
"""MLE for Linear Regression Model
Parameters:
-----------
y : ndarray
target variable with N observations
X : ndarray
The <N x C> design matrix with C independent
variables, features, factors, etc.
algorithm ... | MLE for Linear Regression Model
Parameters:
-----------
y : ndarray
target variable with N observations
X : ndarray
The <N x C> design matrix with C independent
variables, features, factors, etc.
algorithm : str
Optional. Default 'Nelder-Mead' (Simplex).
Th... | Below is the the instruction that describes the task:
### Input:
MLE for Linear Regression Model
Parameters:
-----------
y : ndarray
target variable with N observations
X : ndarray
The <N x C> design matrix with C independent
variables, features, factors, etc.
algorith... |
def _split_text(text, width, height, unicode_aware=True):
"""
Split text to required dimensions.
This will first try to split the text into multiple lines, then put a "..." on the last
3 characters of the last line if this still doesn't fit.
:param text: The text to split.
:param width: The ma... | Split text to required dimensions.
This will first try to split the text into multiple lines, then put a "..." on the last
3 characters of the last line if this still doesn't fit.
:param text: The text to split.
:param width: The maximum width for any line.
:param height: The maximum height for th... | Below is the the instruction that describes the task:
### Input:
Split text to required dimensions.
This will first try to split the text into multiple lines, then put a "..." on the last
3 characters of the last line if this still doesn't fit.
:param text: The text to split.
:param width: The max... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.