code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_slice_end(self):
"""
返回queryset切片的尾巴
"""
value = None
if self.easyui_page:
value = self.easyui_page * self.easyui_rows
return value | 返回queryset切片的尾巴 | Below is the the instruction that describes the task:
### Input:
返回queryset切片的尾巴
### Response:
def get_slice_end(self):
"""
返回queryset切片的尾巴
"""
value = None
if self.easyui_page:
value = self.easyui_page * self.easyui_rows
return value |
def _tree_create_leaf(self, name, trajectory, hdf5_group):
""" Creates a new pypet leaf instance.
Returns the leaf and if it is an explored parameter the length of the range.
"""
class_name = self._all_get_from_attrs(hdf5_group, HDF5StorageService.CLASS_NAME)
# Create the inst... | Creates a new pypet leaf instance.
Returns the leaf and if it is an explored parameter the length of the range. | Below is the the instruction that describes the task:
### Input:
Creates a new pypet leaf instance.
Returns the leaf and if it is an explored parameter the length of the range.
### Response:
def _tree_create_leaf(self, name, trajectory, hdf5_group):
""" Creates a new pypet leaf instance.
... |
def _initfile(path, data="dict"):
"""Initialize an empty JSON file."""
data = {} if data.lower() == "dict" else []
# The file will need to be created if it doesn't exist
if not os.path.exists(path): # The file doesn't exist
# Raise exception if the directory that should contain the file doesn't... | Initialize an empty JSON file. | Below is the the instruction that describes the task:
### Input:
Initialize an empty JSON file.
### Response:
def _initfile(path, data="dict"):
"""Initialize an empty JSON file."""
data = {} if data.lower() == "dict" else []
# The file will need to be created if it doesn't exist
if not os.path.exis... |
def renderHTTP(self, context):
"""
Check to see if the wrapped resource wants to be rendered over HTTPS
and generate a redirect if this is so, if HTTPS is available, and if
the request is not already over HTTPS.
"""
if getattr(self.wrappedResource, 'needsSecure', False):
... | Check to see if the wrapped resource wants to be rendered over HTTPS
and generate a redirect if this is so, if HTTPS is available, and if
the request is not already over HTTPS. | Below is the the instruction that describes the task:
### Input:
Check to see if the wrapped resource wants to be rendered over HTTPS
and generate a redirect if this is so, if HTTPS is available, and if
the request is not already over HTTPS.
### Response:
def renderHTTP(self, context):
"""
... |
def persist(self, name, project=None, drop_model=False, **kwargs):
"""
Persist the execution into a new model.
:param name: model name
:param project: name of the project
:param drop_model: drop model before creation
"""
return super(ODPSModelExpr, self).persist(... | Persist the execution into a new model.
:param name: model name
:param project: name of the project
:param drop_model: drop model before creation | Below is the the instruction that describes the task:
### Input:
Persist the execution into a new model.
:param name: model name
:param project: name of the project
:param drop_model: drop model before creation
### Response:
def persist(self, name, project=None, drop_model=False, **kwargs)... |
def parse_creation_info(self, ci_term):
"""
Parse creators, created and comment.
"""
for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['creator'], None)):
try:
ent = self.builder.create_entity(self.doc, six.text_type(o))
self.bu... | Parse creators, created and comment. | Below is the the instruction that describes the task:
### Input:
Parse creators, created and comment.
### Response:
def parse_creation_info(self, ci_term):
"""
Parse creators, created and comment.
"""
for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['creator'], None... |
def visitNodeConstraintValueSet(self, ctx: ShExDocParser.NodeConstraintValueSetContext):
""" nodeConstraint: valueSet xsFacet* #nodeConstraintValueSet """
self.nodeconstraint.values = []
self.visitChildren(ctx) | nodeConstraint: valueSet xsFacet* #nodeConstraintValueSet | Below is the the instruction that describes the task:
### Input:
nodeConstraint: valueSet xsFacet* #nodeConstraintValueSet
### Response:
def visitNodeConstraintValueSet(self, ctx: ShExDocParser.NodeConstraintValueSetContext):
""" nodeConstraint: valueSet xsFacet* #nodeConstraintValueSet """
self.no... |
def try_write(wd_item, record_id, record_prop, login, edit_summary='', write=True):
"""
Write a PBB_core item. Log if item was created, updated, or skipped.
Catch and log all errors.
:param wd_item: A wikidata item that will be written
:type wd_item: PBB_Core.WDItemEngine
:param record_id: An e... | Write a PBB_core item. Log if item was created, updated, or skipped.
Catch and log all errors.
:param wd_item: A wikidata item that will be written
:type wd_item: PBB_Core.WDItemEngine
:param record_id: An external identifier, to be used for logging
:type record_id: str
:param record_prop: Prop... | Below is the the instruction that describes the task:
### Input:
Write a PBB_core item. Log if item was created, updated, or skipped.
Catch and log all errors.
:param wd_item: A wikidata item that will be written
:type wd_item: PBB_Core.WDItemEngine
:param record_id: An external identifier, to be u... |
def add_psk(self, **kwargs):
"""Add"""
api = self._get_api(bootstrap.PreSharedKeysApi)
item = PreSharedKey._create_request_map(kwargs)
item = models.PreSharedKey(**item)
api.upload_pre_shared_key(item)
return PreSharedKey(item) | Add | Below is the the instruction that describes the task:
### Input:
Add
### Response:
def add_psk(self, **kwargs):
"""Add"""
api = self._get_api(bootstrap.PreSharedKeysApi)
item = PreSharedKey._create_request_map(kwargs)
item = models.PreSharedKey(**item)
api.upload_pre_shared_... |
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S' | ISO 8601 encoding for timedeltas. | Below is the the instruction that describes the task:
### Input:
ISO 8601 encoding for timedeltas.
### Response:
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
r... |
def _wrap_deprecated_function(func, message):
""" Wrap the deprecated function to print out deprecation warnings"""
def _(col):
warnings.warn(message, DeprecationWarning)
return func(col)
return functools.wraps(func)(_) | Wrap the deprecated function to print out deprecation warnings | Below is the the instruction that describes the task:
### Input:
Wrap the deprecated function to print out deprecation warnings
### Response:
def _wrap_deprecated_function(func, message):
""" Wrap the deprecated function to print out deprecation warnings"""
def _(col):
warnings.warn(message, Deprec... |
def update_countries_geo_zone_by_id(cls, countries_geo_zone_id, countries_geo_zone, **kwargs):
"""Update CountriesGeoZone
Update attributes of CountriesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>... | Update CountriesGeoZone
Update attributes of CountriesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_countries_geo_zone_by_id(countries_geo_zone_id, countries_geo_zone, async=True)
... | Below is the the instruction that describes the task:
### Input:
Update CountriesGeoZone
Update attributes of CountriesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_countries_geo_... |
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
"""_handle_long_word(chunks : [string],
cur_line : [string],
cur_len : int, width : int)
Handle a chunk of text (most likely a word, not whitespace) that
is too long... | _handle_long_word(chunks : [string],
cur_line : [string],
cur_len : int, width : int)
Handle a chunk of text (most likely a word, not whitespace) that
is too long to fit in any line. | Below is the the instruction that describes the task:
### Input:
_handle_long_word(chunks : [string],
cur_line : [string],
cur_len : int, width : int)
Handle a chunk of text (most likely a word, not whitespace) that
is too long to fit in any... |
def process_pfa_results(network, pypsa, timesteps):
"""
Assing values from PyPSA to
:meth:`results <edisgo.grid.network.Network.results>`
Parameters
----------
network : Network
The eDisGo grid topology model overall container
pypsa : :pypsa:`pypsa.Network<network>`
The PyPS... | Assing values from PyPSA to
:meth:`results <edisgo.grid.network.Network.results>`
Parameters
----------
network : Network
The eDisGo grid topology model overall container
pypsa : :pypsa:`pypsa.Network<network>`
The PyPSA `Network container
<https://www.pypsa.org/doc/componen... | Below is the the instruction that describes the task:
### Input:
Assing values from PyPSA to
:meth:`results <edisgo.grid.network.Network.results>`
Parameters
----------
network : Network
The eDisGo grid topology model overall container
pypsa : :pypsa:`pypsa.Network<network>`
The... |
def playlist_category(self):
"""doc: http://open.youku.com/docs/doc?id=94
"""
url = 'https://openapi.youku.com/v2/schemas/playlist/category.json'
r = requests.get(url)
check_error(r)
return r.json() | doc: http://open.youku.com/docs/doc?id=94 | Below is the the instruction that describes the task:
### Input:
doc: http://open.youku.com/docs/doc?id=94
### Response:
def playlist_category(self):
"""doc: http://open.youku.com/docs/doc?id=94
"""
url = 'https://openapi.youku.com/v2/schemas/playlist/category.json'
r = requests.get... |
def cli(env, identifier, sortby, cpu, domain, hostname, memory, tag, columns):
"""List guests which are in a dedicated host server."""
mgr = SoftLayer.DedicatedHostManager(env.client)
guests = mgr.list_guests(host_id=identifier,
cpus=cpu,
hostname=h... | List guests which are in a dedicated host server. | Below is the the instruction that describes the task:
### Input:
List guests which are in a dedicated host server.
### Response:
def cli(env, identifier, sortby, cpu, domain, hostname, memory, tag, columns):
"""List guests which are in a dedicated host server."""
mgr = SoftLayer.DedicatedHostManager(env.c... |
def version():
"""Return version string."""
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
'pep8radius',
'main.py')) as input_file:
for line in input_file:
if line.startswith('__version__'):
return pars... | Return version string. | Below is the the instruction that describes the task:
### Input:
Return version string.
### Response:
def version():
"""Return version string."""
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
'pep8radius',
'main.py')) as input_file:... |
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requ... | Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum | Below is the the instruction that describes the task:
### Input:
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
### Response:
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be ... |
def apply_environ(self):
"""Apply changes to target environ.
"""
if self.manager is None:
raise RezSystemError("You must call 'set_manager' on a Python rex "
"interpreter before using it.")
self.target_environ.update(self.manager.environ) | Apply changes to target environ. | Below is the the instruction that describes the task:
### Input:
Apply changes to target environ.
### Response:
def apply_environ(self):
"""Apply changes to target environ.
"""
if self.manager is None:
raise RezSystemError("You must call 'set_manager' on a Python rex "
... |
def file_dict(*packages, **kwargs):
'''
.. versionchanged: 2016.3.0
List the files that belong to a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict nginx
salt '*' pkg.file_dict nginx varnish
'''
errors = []
files = {}
for package in packages:
... | .. versionchanged: 2016.3.0
List the files that belong to a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict nginx
salt '*' pkg.file_dict nginx varnish | Below is the the instruction that describes the task:
### Input:
.. versionchanged: 2016.3.0
List the files that belong to a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict nginx
salt '*' pkg.file_dict nginx varnish
### Response:
def file_dict(*packages, **kwargs)... |
def x11(self, data: ['SASdata', str] = None,
arima: str = None,
by: [str, list] = None,
id: [str, list] = None,
macurves: str = None,
monthly: str = None,
output: [str, bool, 'SASdata'] = None,
pdweights: str = None,
quarter... | Python method to call the X11 procedure
Documentation link:
https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=etsug&docsetTarget=etsug_x11_syntax.htm&locale=en
Either the MONTHLY or QUARTERLY statement must be specified, depending on the type of time series data you... | Below is the the instruction that describes the task:
### Input:
Python method to call the X11 procedure
Documentation link:
https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=etsug&docsetTarget=etsug_x11_syntax.htm&locale=en
Either the MONTHLY or QUARTERLY state... |
def get_friends(self):
"""Get user's friends."""
for k, v in iter(self.user_data.language_data.items()):
data = []
for friend in v['points_ranking_data']:
temp = {'username': friend['username'],
'id': friend['id'],
'... | Get user's friends. | Below is the the instruction that describes the task:
### Input:
Get user's friends.
### Response:
def get_friends(self):
"""Get user's friends."""
for k, v in iter(self.user_data.language_data.items()):
data = []
for friend in v['points_ranking_data']:
temp ... |
def _distance_covariance_sqr_naive(x, y, exponent=1):
"""
Naive biased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm.
"""
a = _distance_matrix(x, exponent=exponent)
b = _distance_matrix(y, e... | Naive biased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm. | Below is the the instruction that describes the task:
### Input:
Naive biased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm.
### Response:
def _distance_covariance_sqr_naive(x, y, exponent=1):
"""
... |
def cgi_method_is_post(environ: Dict[str, str]) -> bool:
"""
Determines if the CGI method was ``POST``, given the CGI environment.
"""
method = environ.get("REQUEST_METHOD", None)
if not method:
return False
return method.upper() == "POST" | Determines if the CGI method was ``POST``, given the CGI environment. | Below is the the instruction that describes the task:
### Input:
Determines if the CGI method was ``POST``, given the CGI environment.
### Response:
def cgi_method_is_post(environ: Dict[str, str]) -> bool:
"""
Determines if the CGI method was ``POST``, given the CGI environment.
"""
method = enviro... |
def _role_present(ret, IdentityPoolId, AuthenticatedRole, UnauthenticatedRole, conn_params):
'''
Helper function to set the Roles to the identity pool
'''
r = __salt__['boto_cognitoidentity.get_identity_pool_roles'](IdentityPoolName='',
Id... | Helper function to set the Roles to the identity pool | Below is the the instruction that describes the task:
### Input:
Helper function to set the Roles to the identity pool
### Response:
def _role_present(ret, IdentityPoolId, AuthenticatedRole, UnauthenticatedRole, conn_params):
'''
Helper function to set the Roles to the identity pool
'''
r = __salt_... |
def add(self, word):
"""Add a word to the dictionary"""
if not word or word.strip() == '':
return
self.words[word]=word | Add a word to the dictionary | Below is the the instruction that describes the task:
### Input:
Add a word to the dictionary
### Response:
def add(self, word):
"""Add a word to the dictionary"""
if not word or word.strip() == '':
return
self.words[word]=word |
def max(self, key=None):
"""
Find the maximum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])
>>> rdd.max()
43.0
>>> rdd.max(key=str)
5.0
"""
if key is None:
... | Find the maximum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])
>>> rdd.max()
43.0
>>> rdd.max(key=str)
5.0 | Below is the the instruction that describes the task:
### Input:
Find the maximum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])
>>> rdd.max()
43.0
>>> rdd.max(key=str)
5.0
### Response:
... |
def assign_method(stochastic, scale=None, verbose=-1):
"""
Returns a step method instance to handle a
variable. If several methods have the same competence,
it picks one arbitrarily (using set.pop()).
"""
# Retrieve set of best candidates
best_candidates = pick_best_methods(stochastic)
... | Returns a step method instance to handle a
variable. If several methods have the same competence,
it picks one arbitrarily (using set.pop()). | Below is the the instruction that describes the task:
### Input:
Returns a step method instance to handle a
variable. If several methods have the same competence,
it picks one arbitrarily (using set.pop()).
### Response:
def assign_method(stochastic, scale=None, verbose=-1):
"""
Returns a step meth... |
def set_url(self, url=None):
"""Sets the url.
:param url: the new copyright
:type url: ``string``
:raise: ``InvalidArgument`` -- ``url`` is invalid
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:raise: ``NullArgument`` -- ``url`` is ``null``
*com... | Sets the url.
:param url: the new copyright
:type url: ``string``
:raise: ``InvalidArgument`` -- ``url`` is invalid
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:raise: ``NullArgument`` -- ``url`` is ``null``
*compliance: mandatory -- This method must b... | Below is the the instruction that describes the task:
### Input:
Sets the url.
:param url: the new copyright
:type url: ``string``
:raise: ``InvalidArgument`` -- ``url`` is invalid
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:raise: ``NullArgument`` -- ``ur... |
def set_long_features(self, features, columns_to_set=[], partition=2):
""" Sets features of double the duration
Example: Setting 14 day RSIs to longer will create add a
feature column of a 28 day RSIs.
Args:
features: Pandas DataFrame instance with columns as numpy.floa... | Sets features of double the duration
Example: Setting 14 day RSIs to longer will create add a
feature column of a 28 day RSIs.
Args:
features: Pandas DataFrame instance with columns as numpy.float32 features.
columns_to_set: List of strings of feature names to make ... | Below is the the instruction that describes the task:
### Input:
Sets features of double the duration
Example: Setting 14 day RSIs to longer will create add a
feature column of a 28 day RSIs.
Args:
features: Pandas DataFrame instance with columns as numpy.float32 features.
... |
def select_by_value(self, value):
"""Selects a DropDownItem by means of the contained text-
Args:
value (str): Textual content of the DropDownItem that have to be selected.
"""
self._selected_key = None
self._selected_item = None
for k in self.children:
... | Selects a DropDownItem by means of the contained text-
Args:
value (str): Textual content of the DropDownItem that have to be selected. | Below is the the instruction that describes the task:
### Input:
Selects a DropDownItem by means of the contained text-
Args:
value (str): Textual content of the DropDownItem that have to be selected.
### Response:
def select_by_value(self, value):
"""Selects a DropDownItem by means of... |
def run_op(self, op, sched):
"""
Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
to whatever t... | Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
to whatever the function returned.
* if StopIterati... | Below is the the instruction that describes the task:
### Input:
Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
... |
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value | Subtracts dates from the given value | Below is the the instruction that describes the task:
### Input:
Subtracts dates from the given value
### Response:
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value |
def unpack_close(self):
"""
Unpack a close message into a status code and a reason. If no payload
is given, the code is None and the reason is an empty string.
"""
if self.payload:
code = struct.unpack('!H', str(self.payload[:2]))[0]
reason = str(self.payl... | Unpack a close message into a status code and a reason. If no payload
is given, the code is None and the reason is an empty string. | Below is the the instruction that describes the task:
### Input:
Unpack a close message into a status code and a reason. If no payload
is given, the code is None and the reason is an empty string.
### Response:
def unpack_close(self):
"""
Unpack a close message into a status code and a reas... |
def get_commits(self, repository_id, search_criteria, project=None, skip=None, top=None):
"""GetCommits.
Retrieve git commits for a project
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param :class:`<Git... | GetCommits.
Retrieve git commits for a project
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param :class:`<GitQueryCommitsCriteria> <azure.devops.v5_0.git.models.GitQueryCommitsCriteria>` search_criteria:
... | Below is the the instruction that describes the task:
### Input:
GetCommits.
Retrieve git commits for a project
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param :class:`<GitQueryCommitsCriteria> <azure.dev... |
def input(self, _in, out, **kw):
"""
Currently Elm does not write to stdout
(https://github.com/elm-lang/elm-make/issues/39), so we need to write
the compiled contents to a temporary file and then read it in order to
output to stdout.
"""
# create a temp file
... | Currently Elm does not write to stdout
(https://github.com/elm-lang/elm-make/issues/39), so we need to write
the compiled contents to a temporary file and then read it in order to
output to stdout. | Below is the the instruction that describes the task:
### Input:
Currently Elm does not write to stdout
(https://github.com/elm-lang/elm-make/issues/39), so we need to write
the compiled contents to a temporary file and then read it in order to
output to stdout.
### Response:
def input(self... |
def spent_outputs(self):
"""Tuple of :obj:`dict`: Inputs of this transaction. Each input
is represented as a dictionary containing a transaction id and
output index.
"""
return (
input_.fulfills.to_dict()
for input_ in self.inputs if input_.fulfills
... | Tuple of :obj:`dict`: Inputs of this transaction. Each input
is represented as a dictionary containing a transaction id and
output index. | Below is the the instruction that describes the task:
### Input:
Tuple of :obj:`dict`: Inputs of this transaction. Each input
is represented as a dictionary containing a transaction id and
output index.
### Response:
def spent_outputs(self):
"""Tuple of :obj:`dict`: Inputs of this transacti... |
def find_by_name(self, term: str, include_placeholders: bool = False) -> List[Account]:
""" Search for account by part of the name """
query = (
self.query
.filter(Account.name.like('%' + term + '%'))
.order_by(Account.name)
)
# Exclude placeholder acc... | Search for account by part of the name | Below is the the instruction that describes the task:
### Input:
Search for account by part of the name
### Response:
def find_by_name(self, term: str, include_placeholders: bool = False) -> List[Account]:
""" Search for account by part of the name """
query = (
self.query
.... |
def last_blank(src):
"""Determine if the input source ends in a blank.
A blank is either a newline or a line consisting of whitespace.
Parameters
----------
src : string
A single or multiline string.
"""
if not src: return False
ll = src.splitlines()[-1]
return (ll == '') or... | Determine if the input source ends in a blank.
A blank is either a newline or a line consisting of whitespace.
Parameters
----------
src : string
A single or multiline string. | Below is the the instruction that describes the task:
### Input:
Determine if the input source ends in a blank.
A blank is either a newline or a line consisting of whitespace.
Parameters
----------
src : string
A single or multiline string.
### Response:
def last_blank(src):
"""Determin... |
def select(self, nowait=True, cb=None):
'''
Set this channel to use publisher confirmations.
'''
nowait = nowait and self.allow_nowait() and not cb
if not self._enabled:
self._enabled = True
self.channel.basic._msg_id = 0
self.channel.basic._l... | Set this channel to use publisher confirmations. | Below is the the instruction that describes the task:
### Input:
Set this channel to use publisher confirmations.
### Response:
def select(self, nowait=True, cb=None):
'''
Set this channel to use publisher confirmations.
'''
nowait = nowait and self.allow_nowait() and not cb
... |
def write_memory_dump():
"""Dump memory to a temporary filename with the meliae package.
@return: JSON filename where memory dump has been written to
@rtype: string
"""
# first do a full garbage collection run
gc.collect()
if gc.garbage:
log.warn(LOG_CHECK, "Unreachabe objects: %s", ... | Dump memory to a temporary filename with the meliae package.
@return: JSON filename where memory dump has been written to
@rtype: string | Below is the the instruction that describes the task:
### Input:
Dump memory to a temporary filename with the meliae package.
@return: JSON filename where memory dump has been written to
@rtype: string
### Response:
def write_memory_dump():
"""Dump memory to a temporary filename with the meliae package... |
def show_editor_buffer(self, editor_buffer):
"""
Open this `EditorBuffer` in the active window.
"""
assert isinstance(editor_buffer, EditorBuffer)
self.active_window.editor_buffer = editor_buffer | Open this `EditorBuffer` in the active window. | Below is the the instruction that describes the task:
### Input:
Open this `EditorBuffer` in the active window.
### Response:
def show_editor_buffer(self, editor_buffer):
"""
Open this `EditorBuffer` in the active window.
"""
assert isinstance(editor_buffer, EditorBuffer)
se... |
def run(items):
"""Run MetaSV if we have enough supported callers, adding output to the set of calls.
"""
assert len(items) == 1, "Expect one input to MetaSV ensemble calling"
data = items[0]
work_dir = _sv_workdir(data)
out_file = os.path.join(work_dir, "variants.vcf.gz")
cmd = _get_cmd() +... | Run MetaSV if we have enough supported callers, adding output to the set of calls. | Below is the the instruction that describes the task:
### Input:
Run MetaSV if we have enough supported callers, adding output to the set of calls.
### Response:
def run(items):
"""Run MetaSV if we have enough supported callers, adding output to the set of calls.
"""
assert len(items) == 1, "Expect one... |
def num_available_breakpoints(self, arm=False, thumb=False, ram=False, flash=False, hw=False):
"""Returns the number of available breakpoints of the specified type.
If ``arm`` is set, gets the number of available ARM breakpoint units.
If ``thumb`` is set, gets the number of available THUMB brea... | Returns the number of available breakpoints of the specified type.
If ``arm`` is set, gets the number of available ARM breakpoint units.
If ``thumb`` is set, gets the number of available THUMB breakpoint
units. If ``ram`` is set, gets the number of available software RAM
breakpoint uni... | Below is the the instruction that describes the task:
### Input:
Returns the number of available breakpoints of the specified type.
If ``arm`` is set, gets the number of available ARM breakpoint units.
If ``thumb`` is set, gets the number of available THUMB breakpoint
units. If ``ram`` is ... |
def get_monitoring_problems(self):
"""Get the current scheduler livesynthesis
:return: live synthesis and problems dictionary
:rtype: dict
"""
res = {}
if not self.sched:
return res
# Get statistics from the scheduler
scheduler_stats = self.s... | Get the current scheduler livesynthesis
:return: live synthesis and problems dictionary
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Get the current scheduler livesynthesis
:return: live synthesis and problems dictionary
:rtype: dict
### Response:
def get_monitoring_problems(self):
"""Get the current scheduler livesynthesis
:return: live synthesis... |
def get_object_or_none(klass, *args, **kwargs):
""" Calls get() on a given model manager, but it returns None instead of the model’s
DoesNotExist exception.
"""
queryset = _get_queryset(klass)
try:
return queryset.get(*args, **kwargs)
except: # noqa: E722
return None | Calls get() on a given model manager, but it returns None instead of the model’s
DoesNotExist exception. | Below is the the instruction that describes the task:
### Input:
Calls get() on a given model manager, but it returns None instead of the model’s
DoesNotExist exception.
### Response:
def get_object_or_none(klass, *args, **kwargs):
""" Calls get() on a given model manager, but it returns None instead o... |
def nested_insert(self, item_list):
""" Create a series of nested LIVVDicts given a list """
if len(item_list) == 1:
self[item_list[0]] = LIVVDict()
elif len(item_list) > 1:
if item_list[0] not in self:
self[item_list[0]] = LIVVDict()
self[item... | Create a series of nested LIVVDicts given a list | Below is the the instruction that describes the task:
### Input:
Create a series of nested LIVVDicts given a list
### Response:
def nested_insert(self, item_list):
""" Create a series of nested LIVVDicts given a list """
if len(item_list) == 1:
self[item_list[0]] = LIVVDict()
el... |
def get_files(dirname):
'''recursion rockz'''
all_files = []
os.chdir(dirname)
for fn in os.listdir(os.path.abspath(dirname)):
fn = os.path.abspath(fn)
if os.path.isdir(fn):
all_files += get_files(fn)
else:
all_files.append(fn)
os.chdir('../')
return all_files | recursion rockz | Below is the the instruction that describes the task:
### Input:
recursion rockz
### Response:
def get_files(dirname):
'''recursion rockz'''
all_files = []
os.chdir(dirname)
for fn in os.listdir(os.path.abspath(dirname)):
fn = os.path.abspath(fn)
if os.path.isdir(fn):
all_files += get_files(f... |
def _fetch_pageviews(self, storage, year, week, ip_users=False):
"""
Fetch PageViews from Elasticsearch.
:param time_from: Staring at timestamp.
:param time_to: To timestamp
"""
prefix = 'Pageviews'
if ip_users:
query_add = "AND !(bot:True) AND (id_us... | Fetch PageViews from Elasticsearch.
:param time_from: Staring at timestamp.
:param time_to: To timestamp | Below is the the instruction that describes the task:
### Input:
Fetch PageViews from Elasticsearch.
:param time_from: Staring at timestamp.
:param time_to: To timestamp
### Response:
def _fetch_pageviews(self, storage, year, week, ip_users=False):
"""
Fetch PageViews from Elastics... |
def _write_html_file(word, translations, data_dir, native=False):
"""Create html file of word translations.
Parameters
----------
word : str
Word that was translated.
tralnslations : dict
Dictionary of word translations.
data_dir : pathlib.Path
Location where html files ... | Create html file of word translations.
Parameters
----------
word : str
Word that was translated.
tralnslations : dict
Dictionary of word translations.
data_dir : pathlib.Path
Location where html files are saved. | Below is the the instruction that describes the task:
### Input:
Create html file of word translations.
Parameters
----------
word : str
Word that was translated.
tralnslations : dict
Dictionary of word translations.
data_dir : pathlib.Path
Location where html files are ... |
def get_possible_importers(file_uris, current_doc=None):
"""
Return all the importer objects that can handle the specified files.
Possible imports may vary depending on the currently active document
"""
importers = []
for importer in IMPORTERS:
if importer.can_import(file_uris, current_... | Return all the importer objects that can handle the specified files.
Possible imports may vary depending on the currently active document | Below is the the instruction that describes the task:
### Input:
Return all the importer objects that can handle the specified files.
Possible imports may vary depending on the currently active document
### Response:
def get_possible_importers(file_uris, current_doc=None):
"""
Return all the importer ... |
def update_dependency(self, tile, depinfo, destdir=None):
"""Attempt to install or update a dependency to the latest version.
Args:
tile (IOTile): An IOTile object describing the tile that has the dependency
depinfo (dict): a dictionary from tile.dependencies specifying the depe... | Attempt to install or update a dependency to the latest version.
Args:
tile (IOTile): An IOTile object describing the tile that has the dependency
depinfo (dict): a dictionary from tile.dependencies specifying the dependency
destdir (string): An optional folder into which to... | Below is the the instruction that describes the task:
### Input:
Attempt to install or update a dependency to the latest version.
Args:
tile (IOTile): An IOTile object describing the tile that has the dependency
depinfo (dict): a dictionary from tile.dependencies specifying the depe... |
def getall(self, key):
"""
Return a list of all values matching the key (may be an empty list)
"""
result = []
for k, v in self._items:
if key == k:
result.append(v)
return result | Return a list of all values matching the key (may be an empty list) | Below is the the instruction that describes the task:
### Input:
Return a list of all values matching the key (may be an empty list)
### Response:
def getall(self, key):
"""
Return a list of all values matching the key (may be an empty list)
"""
result = []
for k, v in self.... |
def remove_post_process(self, name):
"""remove a post-process
Parameters
----------
name : str
name of the post-process to remove.
"""
self._pprocesses = [post_process
for post_process in self._pprocesses
... | remove a post-process
Parameters
----------
name : str
name of the post-process to remove. | Below is the the instruction that describes the task:
### Input:
remove a post-process
Parameters
----------
name : str
name of the post-process to remove.
### Response:
def remove_post_process(self, name):
"""remove a post-process
Parameters
----------... |
def configure_stream_logger(logger='', level=None, formatter='%(levelname)-8s %(message)s'):
"""
Configure the default stream handler for logging messages to the console,
remove other logging handlers, and enable capturing warnings.
.. versionadded:: 1.3.0
:param str logger: The logger to add the stream handler ... | Configure the default stream handler for logging messages to the console,
remove other logging handlers, and enable capturing warnings.
.. versionadded:: 1.3.0
:param str logger: The logger to add the stream handler for.
:param level: The level to set the logger to, will default to WARNING if no level is specifie... | Below is the the instruction that describes the task:
### Input:
Configure the default stream handler for logging messages to the console,
remove other logging handlers, and enable capturing warnings.
.. versionadded:: 1.3.0
:param str logger: The logger to add the stream handler for.
:param level: The level ... |
def update(self, collection_id, title=None, description=None, private=False):
"""
Update an existing collection belonging to the logged-in user.
This requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param title [string]: The ... | Update an existing collection belonging to the logged-in user.
This requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param title [string]: The title of the collection. (Required.)
:param description [string]: The collection’s descrip... | Below is the the instruction that describes the task:
### Input:
Update an existing collection belonging to the logged-in user.
This requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param title [string]: The title of the collection. (Req... |
def _make_json_response(self, data, headers=None, status_code=200):
"""Return a response object from the given JSON data.
:param data: Data to JSON-encode.
:type data: mixed
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_cod... | Return a response object from the given JSON data.
:param data: Data to JSON-encode.
:type data: mixed
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_code: HTTP status code.
:type status_code: int
:rtype: requests.Re... | Below is the the instruction that describes the task:
### Input:
Return a response object from the given JSON data.
:param data: Data to JSON-encode.
:type data: mixed
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_code: HTTP st... |
def _clone_and_score_clusterer(clf, X, n_clusters):
"""Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
... | Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
X (array-like, shape (n_samples, n_features)):
... | Below is the the instruction that describes the task:
### Input:
Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instanc... |
def result_tree_list(cl):
"""
Displays the headers and data list together
"""
import django
result = {
'cl': cl,
'result_headers': list(result_headers(cl)),
'results': list(tree_results(cl))
}
if django.VERSION[0] == 1 and django.VERSION[1] > 2:
from django.co... | Displays the headers and data list together | Below is the the instruction that describes the task:
### Input:
Displays the headers and data list together
### Response:
def result_tree_list(cl):
"""
Displays the headers and data list together
"""
import django
result = {
'cl': cl,
'result_headers': list(result_headers(cl)),... |
def _handle_metadata(self, node, scope, ctxt, stream):
"""Handle metadata for the node
"""
self._dlog("handling node metadata {}".format(node.metadata.keyvals))
keyvals = node.metadata.keyvals
metadata_info = []
if "watch" in node.metadata.keyvals or "update" in keyval... | Handle metadata for the node | Below is the the instruction that describes the task:
### Input:
Handle metadata for the node
### Response:
def _handle_metadata(self, node, scope, ctxt, stream):
"""Handle metadata for the node
"""
self._dlog("handling node metadata {}".format(node.metadata.keyvals))
keyvals = nod... |
def forward(self, # pylint: disable=arguments-differ
inputs: torch.Tensor,
word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]:
"""
Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_si... | Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch.
word_inputs : ``torch.Tensor``, required.
If you passed a cached vocab, you can in addition pass a tensor of shape ``(batch_siz... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch.
word_inputs : ``torch.Tensor``, required.
If you passed a ... |
def calculate(self, **state):
"""
Calculate the material physical property at the specified temperature
in the units specified by the object's 'property_units' property.
:param T: [K] temperature
:returns: physical property value
"""
super().calculate(**state)
... | Calculate the material physical property at the specified temperature
in the units specified by the object's 'property_units' property.
:param T: [K] temperature
:returns: physical property value | Below is the the instruction that describes the task:
### Input:
Calculate the material physical property at the specified temperature
in the units specified by the object's 'property_units' property.
:param T: [K] temperature
:returns: physical property value
### Response:
def calculate(... |
def blog_post_feed(request, format, **kwargs):
"""
Blog posts feeds - maps format to the correct feed view.
"""
try:
return {"rss": PostsRSS, "atom": PostsAtom}[format](**kwargs)(request)
except KeyError:
raise Http404() | Blog posts feeds - maps format to the correct feed view. | Below is the the instruction that describes the task:
### Input:
Blog posts feeds - maps format to the correct feed view.
### Response:
def blog_post_feed(request, format, **kwargs):
"""
Blog posts feeds - maps format to the correct feed view.
"""
try:
return {"rss": PostsRSS, "atom": Posts... |
def set_loglevel(self, level):
"""
Set the minimum loglevel for all components
Args:
level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels
"""
self.log_level = level
log_manager.config_stdio(de... | Set the minimum loglevel for all components
Args:
level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels | Below is the the instruction that describes the task:
### Input:
Set the minimum loglevel for all components
Args:
level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels
### Response:
def set_loglevel(self, level):
"""
... |
def checkout(cwd,
remote,
target=None,
user=None,
username=None,
password=None,
*opts):
'''
Download a working copy of the remote Subversion repository
directory or file
cwd
The path to the Subversion repository
... | Download a working copy of the remote Subversion repository
directory or file
cwd
The path to the Subversion repository
remote : None
URL to checkout
target : None
The name to give the file or directory working copy
Default: svn uses the remote basename
user : Non... | Below is the the instruction that describes the task:
### Input:
Download a working copy of the remote Subversion repository
directory or file
cwd
The path to the Subversion repository
remote : None
URL to checkout
target : None
The name to give the file or directory worki... |
def ansi(string, *args):
""" Convenience function to chain multiple ColorWrappers to a string """
ansi = ''
for arg in args:
arg = str(arg)
if not re.match(ANSI_PATTERN, arg):
raise ValueError('Additional arguments must be ansi strings')
ansi += arg
return ansi + string + colorama.Style.RESET_ALL | Convenience function to chain multiple ColorWrappers to a string | Below is the the instruction that describes the task:
### Input:
Convenience function to chain multiple ColorWrappers to a string
### Response:
def ansi(string, *args):
""" Convenience function to chain multiple ColorWrappers to a string """
ansi = ''
for arg in args:
arg = str(arg)
if not re.match(ANSI_P... |
def center_visible_line(self, before_scroll_offset=False,
after_scroll_offset=False):
"""
Like `first_visible_line`, but for the center visible line.
"""
return (self.first_visible_line(after_scroll_offset) +
(self.last_visible_line(before_scro... | Like `first_visible_line`, but for the center visible line. | Below is the the instruction that describes the task:
### Input:
Like `first_visible_line`, but for the center visible line.
### Response:
def center_visible_line(self, before_scroll_offset=False,
after_scroll_offset=False):
"""
Like `first_visible_line`, but for the cen... |
def group_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/groups#delete-group"
api_path = "/api/v2/groups/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) | https://developer.zendesk.com/rest_api/docs/core/groups#delete-group | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/groups#delete-group
### Response:
def group_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/groups#delete-group"
api_path = "/api/v2/groups/{id}.json"
... |
def from_bytes(cls, image_bytes, affine, crs, band_names=None):
"""Create GeoRaster from image BytesIo object.
:param image_bytes: io.BytesIO object
:param affine: rasters affine
:param crs: rasters crs
:param band_names: e.g. ['red', 'blue'] or 'red'
"""
b = io.... | Create GeoRaster from image BytesIo object.
:param image_bytes: io.BytesIO object
:param affine: rasters affine
:param crs: rasters crs
:param band_names: e.g. ['red', 'blue'] or 'red' | Below is the the instruction that describes the task:
### Input:
Create GeoRaster from image BytesIo object.
:param image_bytes: io.BytesIO object
:param affine: rasters affine
:param crs: rasters crs
:param band_names: e.g. ['red', 'blue'] or 'red'
### Response:
def from_bytes(cls... |
def guid2bytes(s):
"""Converts a GUID to the serialized bytes representation"""
assert isinstance(s, str)
assert len(s) == 36
p = struct.pack
return b"".join([
p("<IHH", int(s[:8], 16), int(s[9:13], 16), int(s[14:18], 16)),
p(">H", int(s[19:23], 16)),
p(">Q", int(s[24:], 16... | Converts a GUID to the serialized bytes representation | Below is the the instruction that describes the task:
### Input:
Converts a GUID to the serialized bytes representation
### Response:
def guid2bytes(s):
"""Converts a GUID to the serialized bytes representation"""
assert isinstance(s, str)
assert len(s) == 36
p = struct.pack
return b"".join([... |
def has_style(node):
"""Tells us if node element has defined styling.
:Args:
- node (:class:`ooxml.doc.Element`): Element
:Returns:
True or False
"""
elements = ['b', 'i', 'u', 'strike', 'color', 'jc', 'sz', 'ind', 'superscript', 'subscript', 'small_caps']
return any([True f... | Tells us if node element has defined styling.
:Args:
- node (:class:`ooxml.doc.Element`): Element
:Returns:
True or False | Below is the the instruction that describes the task:
### Input:
Tells us if node element has defined styling.
:Args:
- node (:class:`ooxml.doc.Element`): Element
:Returns:
True or False
### Response:
def has_style(node):
"""Tells us if node element has defined styling.
:Args:
... |
def predict(self, x):
"""
This function make forward pass through MLP (no update).
**Args:**
* `x` : input vector (1-dimensional array)
**Returns:**
* `y` : output of MLP (float or 1-diemnsional array).
Size depends on number of MLP outputs.
... | This function make forward pass through MLP (no update).
**Args:**
* `x` : input vector (1-dimensional array)
**Returns:**
* `y` : output of MLP (float or 1-diemnsional array).
Size depends on number of MLP outputs. | Below is the the instruction that describes the task:
### Input:
This function make forward pass through MLP (no update).
**Args:**
* `x` : input vector (1-dimensional array)
**Returns:**
* `y` : output of MLP (float or 1-diemnsional array).
Size depends on nu... |
def _get_pdi(cls, df, windows):
""" +DI, positive directional moving index
:param df: data
:param windows: range
:return:
"""
window = cls.get_only_one_positive_int(windows)
pdm_column = 'pdm_{}'.format(window)
tr_column = 'atr_{}'.format(window)... | +DI, positive directional moving index
:param df: data
:param windows: range
:return: | Below is the the instruction that describes the task:
### Input:
+DI, positive directional moving index
:param df: data
:param windows: range
:return:
### Response:
def _get_pdi(cls, df, windows):
""" +DI, positive directional moving index
:param df: data
:... |
def gen(function):
"""
Allows using a generator to chain together reversible actions.
This decorator may be added to a generator that yields reversible actions
(any object with a ``.forwards()`` and ``.backwards()`` method). These may
be constructed manually or via :py:func:`reversible.action`. The... | Allows using a generator to chain together reversible actions.
This decorator may be added to a generator that yields reversible actions
(any object with a ``.forwards()`` and ``.backwards()`` method). These may
be constructed manually or via :py:func:`reversible.action`. The decorated
function, when c... | Below is the the instruction that describes the task:
### Input:
Allows using a generator to chain together reversible actions.
This decorator may be added to a generator that yields reversible actions
(any object with a ``.forwards()`` and ``.backwards()`` method). These may
be constructed manually or... |
def add_group(network_id, group,**kwargs):
"""
Add a resourcegroup to a network
"""
user_id = kwargs.get('user_id')
try:
net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
net_i.check_write_permission(user_id=user_id)
except NoResultFound:
rai... | Add a resourcegroup to a network | Below is the the instruction that describes the task:
### Input:
Add a resourcegroup to a network
### Response:
def add_group(network_id, group,**kwargs):
"""
Add a resourcegroup to a network
"""
user_id = kwargs.get('user_id')
try:
net_i = db.DBSession.query(Network).filter(Networ... |
def get_db_attribute(self, table, record, column, key=None):
"""
Gets values of 'column' in 'record' in 'table'.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl get TBL REC COL[:KEY]
"""
if key is not None:
column = '%s:%s' ... | Gets values of 'column' in 'record' in 'table'.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl get TBL REC COL[:KEY] | Below is the the instruction that describes the task:
### Input:
Gets values of 'column' in 'record' in 'table'.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl get TBL REC COL[:KEY]
### Response:
def get_db_attribute(self, table, record, column, key=None):
... |
def to_css(self):
''' Generate the CSS representation of this RGB color.
Returns:
str, ``"rgb(...)"`` or ``"rgba(...)"``
'''
if self.a == 1.0:
return "rgb(%d, %d, %d)" % (self.r, self.g, self.b)
else:
return "rgba(%d, %d, %d, %s)" % (self.r, ... | Generate the CSS representation of this RGB color.
Returns:
str, ``"rgb(...)"`` or ``"rgba(...)"`` | Below is the the instruction that describes the task:
### Input:
Generate the CSS representation of this RGB color.
Returns:
str, ``"rgb(...)"`` or ``"rgba(...)"``
### Response:
def to_css(self):
''' Generate the CSS representation of this RGB color.
Returns:
str, ... |
def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, **kwargs):
"""
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible w... | Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible with cutout operations.
resolution (int): 0 indicates native resolution.
x_range (list[in... | Below is the the instruction that describes the task:
### Input:
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible with cutout operations.
resolution (... |
def accept(self, title, titleAlignments):
"""
Return C{True} if the read id set in C{titleAlignments} is sufficiently
different from all previously seen read sets.
@param title: A C{str} sequence title.
@param titleAlignments: An instance of L{TitleAlignment}.
@return: A... | Return C{True} if the read id set in C{titleAlignments} is sufficiently
different from all previously seen read sets.
@param title: A C{str} sequence title.
@param titleAlignments: An instance of L{TitleAlignment}.
@return: A C{bool} indicating whether a title has an acceptably novel
... | Below is the the instruction that describes the task:
### Input:
Return C{True} if the read id set in C{titleAlignments} is sufficiently
different from all previously seen read sets.
@param title: A C{str} sequence title.
@param titleAlignments: An instance of L{TitleAlignment}.
@re... |
def tiles_from_bounds(self, bounds, zoom):
"""
Return all tiles intersecting with bounds.
Bounds values will be cleaned if they cross the antimeridian or are
outside of the Northern or Southern tile pyramid bounds.
- bounds: tuple of (left, bottom, right, top) bounding values i... | Return all tiles intersecting with bounds.
Bounds values will be cleaned if they cross the antimeridian or are
outside of the Northern or Southern tile pyramid bounds.
- bounds: tuple of (left, bottom, right, top) bounding values in tile
pyramid CRS
- zoom: zoom level | Below is the the instruction that describes the task:
### Input:
Return all tiles intersecting with bounds.
Bounds values will be cleaned if they cross the antimeridian or are
outside of the Northern or Southern tile pyramid bounds.
- bounds: tuple of (left, bottom, right, top) bounding va... |
def Hypergeometric(N, n, K, tag=None):
"""
A Hypergeometric random variate
Parameters
----------
N : int
The total population size
n : int
The number of individuals of interest in the population
K : int
The number of individuals that will be chosen from the popul... | A Hypergeometric random variate
Parameters
----------
N : int
The total population size
n : int
The number of individuals of interest in the population
K : int
The number of individuals that will be chosen from the population
Example
-------
(Taken f... | Below is the the instruction that describes the task:
### Input:
A Hypergeometric random variate
Parameters
----------
N : int
The total population size
n : int
The number of individuals of interest in the population
K : int
The number of individuals that will be cho... |
def normalize_etpinard_df(df='https://plot.ly/~etpinard/191.csv', columns='x y size text'.split(),
category_col='category', possible_categories=['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']):
"""Reformat a dataframe in etpinard's format for use in plot functions and sklearn models"""... | Reformat a dataframe in etpinard's format for use in plot functions and sklearn models | Below is the the instruction that describes the task:
### Input:
Reformat a dataframe in etpinard's format for use in plot functions and sklearn models
### Response:
def normalize_etpinard_df(df='https://plot.ly/~etpinard/191.csv', columns='x y size text'.split(),
category_col='category',... |
def write(self, iterable):
"""Writes values from iterable into CSV file"""
io_error_text = _("Error writing to file {filepath}.")
io_error_text = io_error_text.format(filepath=self.path)
try:
with open(self.path, "wb") as csvfile:
csv_writer = csv.writer(cs... | Writes values from iterable into CSV file | Below is the the instruction that describes the task:
### Input:
Writes values from iterable into CSV file
### Response:
def write(self, iterable):
"""Writes values from iterable into CSV file"""
io_error_text = _("Error writing to file {filepath}.")
io_error_text = io_error_text.format(fi... |
def loads(cls, value):
'''Returns mapping type deserialized `value`.'''
if len(value) == 1 and cls.sentinel in value:
value = value[cls.sentinel]
return value | Returns mapping type deserialized `value`. | Below is the the instruction that describes the task:
### Input:
Returns mapping type deserialized `value`.
### Response:
def loads(cls, value):
'''Returns mapping type deserialized `value`.'''
if len(value) == 1 and cls.sentinel in value:
value = value[cls.sentinel]
return value |
def _get_splunk_search_props(search):
'''
Get splunk search properties from an object
'''
props = search.content
props["app"] = search.access.app
props["sharing"] = search.access.sharing
return props | Get splunk search properties from an object | Below is the the instruction that describes the task:
### Input:
Get splunk search properties from an object
### Response:
def _get_splunk_search_props(search):
'''
Get splunk search properties from an object
'''
props = search.content
props["app"] = search.access.app
props["sharing"] = sea... |
def to_dotfile(self, filename):
"""
Write graph to `filename`.
>>> from anytree import Node
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)... | Write graph to `filename`.
>>> from anytree import Node
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> s1a = Node("sub1A", parent=s1)
... | Below is the the instruction that describes the task:
### Input:
Write graph to `filename`.
>>> from anytree import Node
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("su... |
def p_state_invariant_section(self, p):
'''state_invariant_section : STATE_INVARIANTS LCURLY state_invariant_list RCURLY SEMI
| STATE_INVARIANTS LCURLY RCURLY SEMI'''
if len(p) == 6:
p[0] = ('invariants', p[3])
elif len(p) == 5:
p[0] = (... | state_invariant_section : STATE_INVARIANTS LCURLY state_invariant_list RCURLY SEMI
| STATE_INVARIANTS LCURLY RCURLY SEMI | Below is the the instruction that describes the task:
### Input:
state_invariant_section : STATE_INVARIANTS LCURLY state_invariant_list RCURLY SEMI
| STATE_INVARIANTS LCURLY RCURLY SEMI
### Response:
def p_state_invariant_section(self, p):
'''state_invariant_section : STA... |
def get_fast_scanner(self):
"""
Return :class:`.FastScanner` for association scan.
Returns
-------
:class:`.FastScanner`
Instance of a class designed to perform very fast association scan.
"""
terms = self._terms
return KronFastScanner(self._Y... | Return :class:`.FastScanner` for association scan.
Returns
-------
:class:`.FastScanner`
Instance of a class designed to perform very fast association scan. | Below is the the instruction that describes the task:
### Input:
Return :class:`.FastScanner` for association scan.
Returns
-------
:class:`.FastScanner`
Instance of a class designed to perform very fast association scan.
### Response:
def get_fast_scanner(self):
"""
... |
def memoized_ignoreargs(func):
"""
A decorator. It performs memoization ignoring the arguments used to call
the function.
"""
def wrapper(*args, **kwargs):
if func not in _MEMOIZED_NOARGS:
res = func(*args, **kwargs)
_MEMOIZED_NOARGS[func] = res
return res... | A decorator. It performs memoization ignoring the arguments used to call
the function. | Below is the the instruction that describes the task:
### Input:
A decorator. It performs memoization ignoring the arguments used to call
the function.
### Response:
def memoized_ignoreargs(func):
"""
A decorator. It performs memoization ignoring the arguments used to call
the function.
"""
... |
def read_histogram(self):
"""Read and reset the histogram. The expected return is a dictionary
containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature,
pressure, the sampling period, the checksum, PM1, PM2.5, and PM10.
**NOTE:** The sampling period for the OPCN1 seems t... | Read and reset the histogram. The expected return is a dictionary
containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature,
pressure, the sampling period, the checksum, PM1, PM2.5, and PM10.
**NOTE:** The sampling period for the OPCN1 seems to be incorrect.
:returns: di... | Below is the the instruction that describes the task:
### Input:
Read and reset the histogram. The expected return is a dictionary
containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature,
pressure, the sampling period, the checksum, PM1, PM2.5, and PM10.
**NOTE:** The sampl... |
def _check_collections(self):
"""Checks node local collection storage sizes"""
self.collection_sizes = {}
self.collection_total = 0
for col in self.db.collection_names(include_system_collections=False):
self.collection_sizes[col] = self.db.command('collstats', col).get(
... | Checks node local collection storage sizes | Below is the the instruction that describes the task:
### Input:
Checks node local collection storage sizes
### Response:
def _check_collections(self):
"""Checks node local collection storage sizes"""
self.collection_sizes = {}
self.collection_total = 0
for col in self.db.collectio... |
def update(gandi, resource, memory, cores, console, password, background,
reboot):
"""Update a virtual machine.
Resource can be a Hostname or an ID
"""
pwd = None
if password:
pwd = click.prompt('password', hide_input=True,
confirmation_prompt=True)
... | Update a virtual machine.
Resource can be a Hostname or an ID | Below is the the instruction that describes the task:
### Input:
Update a virtual machine.
Resource can be a Hostname or an ID
### Response:
def update(gandi, resource, memory, cores, console, password, background,
reboot):
"""Update a virtual machine.
Resource can be a Hostname or an ID
... |
def add_population(self,pop):
"""Adds population to PopulationSet
"""
if pop.model in self.modelnames:
raise ValueError('%s model already in PopulationSet.' % pop.model)
self.modelnames.append(pop.model)
self.shortmodelnames.append(pop.modelshort)
self.poplist... | Adds population to PopulationSet | Below is the the instruction that describes the task:
### Input:
Adds population to PopulationSet
### Response:
def add_population(self,pop):
"""Adds population to PopulationSet
"""
if pop.model in self.modelnames:
raise ValueError('%s model already in PopulationSet.' % pop.mode... |
def option_attrname(self, opt, optdict=None):
"""get the config attribute corresponding to opt"""
if optdict is None:
optdict = self.get_option_def(opt)
return optdict.get("dest", opt.replace("-", "_")) | get the config attribute corresponding to opt | Below is the the instruction that describes the task:
### Input:
get the config attribute corresponding to opt
### Response:
def option_attrname(self, opt, optdict=None):
"""get the config attribute corresponding to opt"""
if optdict is None:
optdict = self.get_option_def(opt)
r... |
def wrap(self, text):
"""wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
and all other whitespace characte... | wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
and all other whitespace characters (including newline) are
... | Below is the the instruction that describes the task:
### Input:
wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
... |
def serve(context, config, host, port, debug, livereload):
"""Start the web server."""
pymongo_config = dict(
MONGO_HOST=context.obj['host'],
MONGO_PORT=context.obj['port'],
MONGO_DBNAME=context.obj['mongodb'],
MONGO_USERNAME=context.obj['username'],
MONGO_PASSWORD=contex... | Start the web server. | Below is the the instruction that describes the task:
### Input:
Start the web server.
### Response:
def serve(context, config, host, port, debug, livereload):
"""Start the web server."""
pymongo_config = dict(
MONGO_HOST=context.obj['host'],
MONGO_PORT=context.obj['port'],
MONGO_DB... |
def is_deterministic(self):
"""Tests whether machine is deterministic."""
# naive quadratic algorithm
patterns = [t.lhs for t in self.transitions] + list(self.accept_configs)
for i, t1 in enumerate(patterns):
for t2 in patterns[:i]:
match = True
... | Tests whether machine is deterministic. | Below is the the instruction that describes the task:
### Input:
Tests whether machine is deterministic.
### Response:
def is_deterministic(self):
"""Tests whether machine is deterministic."""
# naive quadratic algorithm
patterns = [t.lhs for t in self.transitions] + list(self.accept_config... |
def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> SpotifyArtistNode:
"""
Returns a new `SpotifyArtistNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node ... | Returns a new `SpotifyArtistNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node to create.
external_id (Optional[str]): The external ID of the node. | Below is the the instruction that describes the task:
### Input:
Returns a new `SpotifyArtistNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node to create.
external_id (Optional[str]): Th... |
def punchcard(self, branch='master', limit=None, days=None, by=None, normalize=None, ignore_globs=None,
include_globs=None):
"""
Returns a pandas DataFrame containing all of the data for a punchcard.
* day_of_week
* hour_of_day
* author / committer
... | Returns a pandas DataFrame containing all of the data for a punchcard.
* day_of_week
* hour_of_day
* author / committer
* lines
* insertions
* deletions
* net
:param branch: the branch to return commits for
:param limit: (optional, default... | Below is the the instruction that describes the task:
### Input:
Returns a pandas DataFrame containing all of the data for a punchcard.
* day_of_week
* hour_of_day
* author / committer
* lines
* insertions
* deletions
* net
:param branch: the ... |
def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix,
source_vocab_size, target_vocab_size):
"""Generate source and target data from a single file."""
filename = "parsing_{0}.pairs".format("train" if train else "dev")
source_vocab = generator_utils.get_or_generate... | Generate source and target data from a single file. | Below is the the instruction that describes the task:
### Input:
Generate source and target data from a single file.
### Response:
def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix,
source_vocab_size, target_vocab_size):
"""Generate source and target data from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.