code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def compare_files(path1, path2):
# type: (str, str) -> List[str]
"""Returns the delta between two files using -, ?, + format excluding
lines that are the same
Args:
path1 (str): Path to first file
path2 (str): Path to second file
Returns:
List[str]: Delta between the two fi... | Returns the delta between two files using -, ?, + format excluding
lines that are the same
Args:
path1 (str): Path to first file
path2 (str): Path to second file
Returns:
List[str]: Delta between the two files | Below is the the instruction that describes the task:
### Input:
Returns the delta between two files using -, ?, + format excluding
lines that are the same
Args:
path1 (str): Path to first file
path2 (str): Path to second file
Returns:
List[str]: Delta between the two files
###... |
def _docf(self, tag, val):
"""
Callback used as the handler argument to process_docs(). This converts
Stone doc references to Sphinx-friendly annotations.
"""
if tag == 'type':
return ':class:`{}`'.format(val)
elif tag == 'route':
if self.args.rout... | Callback used as the handler argument to process_docs(). This converts
Stone doc references to Sphinx-friendly annotations. | Below is the the instruction that describes the task:
### Input:
Callback used as the handler argument to process_docs(). This converts
Stone doc references to Sphinx-friendly annotations.
### Response:
def _docf(self, tag, val):
"""
Callback used as the handler argument to process_docs(). ... |
def map_exception_codes():
'''Helper function to intialise CODES_TO_EXCEPTIONS.'''
werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None))
return {e.code: e for _, e in werkex} | Helper function to intialise CODES_TO_EXCEPTIONS. | Below is the the instruction that describes the task:
### Input:
Helper function to intialise CODES_TO_EXCEPTIONS.
### Response:
def map_exception_codes():
'''Helper function to intialise CODES_TO_EXCEPTIONS.'''
werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None))
return {e.code:... |
def session(self, sid, namespace=None):
"""Return the user session for a client with context manager syntax.
:param sid: The session id of the client.
This is a context manager that returns the user session dictionary for
the client. Any changes that are made to this dictionary inside ... | Return the user session for a client with context manager syntax.
:param sid: The session id of the client.
This is a context manager that returns the user session dictionary for
the client. Any changes that are made to this dictionary inside the
context manager block are saved back to... | Below is the the instruction that describes the task:
### Input:
Return the user session for a client with context manager syntax.
:param sid: The session id of the client.
This is a context manager that returns the user session dictionary for
the client. Any changes that are made to this ... |
def reset_index(self):
"""
Resets the index of the Series to simple integer list and the index name to 'index'.
:return: nothing
"""
self.index = list(range(self.__len__()))
self.index_name = 'index' | Resets the index of the Series to simple integer list and the index name to 'index'.
:return: nothing | Below is the the instruction that describes the task:
### Input:
Resets the index of the Series to simple integer list and the index name to 'index'.
:return: nothing
### Response:
def reset_index(self):
"""
Resets the index of the Series to simple integer list and the index name to 'index... |
def get_output_nodes(G: nx.DiGraph) -> List[str]:
""" Get all output nodes from a network. """
return [n for n, d in G.out_degree() if d == 0] | Get all output nodes from a network. | Below is the the instruction that describes the task:
### Input:
Get all output nodes from a network.
### Response:
def get_output_nodes(G: nx.DiGraph) -> List[str]:
""" Get all output nodes from a network. """
return [n for n, d in G.out_degree() if d == 0] |
def get_most_recent_versions(self, group, artifact, limit, remote=False, integration=False):
"""Get a list of the version numbers of the most recent artifacts (integration
or non-integration), ordered by the version number, for a particular group and
artifact combination.
:param str gro... | Get a list of the version numbers of the most recent artifacts (integration
or non-integration), ordered by the version number, for a particular group and
artifact combination.
:param str group: Group of the artifact to get versions of
:param str artifact: Name of the artifact to get ve... | Below is the the instruction that describes the task:
### Input:
Get a list of the version numbers of the most recent artifacts (integration
or non-integration), ordered by the version number, for a particular group and
artifact combination.
:param str group: Group of the artifact to get ve... |
def logodds(args):
"""
%prog logodds cnt1 cnt2
Compute log likelihood between two db.
"""
from math import log
from jcvi.formats.base import DictFile
p = OptionParser(logodds.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
cnt1... | %prog logodds cnt1 cnt2
Compute log likelihood between two db. | Below is the the instruction that describes the task:
### Input:
%prog logodds cnt1 cnt2
Compute log likelihood between two db.
### Response:
def logodds(args):
"""
%prog logodds cnt1 cnt2
Compute log likelihood between two db.
"""
from math import log
from jcvi.formats.base import Di... |
def create_rflink_connection(port=None, host=None, baud=57600, protocol=RflinkProtocol,
packet_callback=None, event_callback=None,
disconnect_callback=None, ignore=None, loop=None):
"""Create Rflink manager class, returns transport coroutine."""
# use de... | Create Rflink manager class, returns transport coroutine. | Below is the the instruction that describes the task:
### Input:
Create Rflink manager class, returns transport coroutine.
### Response:
def create_rflink_connection(port=None, host=None, baud=57600, protocol=RflinkProtocol,
packet_callback=None, event_callback=None,
... |
def model_builds(self):
"""
Access the model_builds
:returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList
:rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList
"""
if self._model_builds is None:
self._model_builds = ModelBuil... | Access the model_builds
:returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList
:rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList | Below is the the instruction that describes the task:
### Input:
Access the model_builds
:returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList
:rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildList
### Response:
def model_builds(self):
"""
Access th... |
def _get_dep_to_dot_name_mapping(dependencies):
""" Creates mapping between Dependency classes and names used in DOT graph
"""
dot_name_to_deps = {}
for dep in dependencies:
dot_name = dep.name
if dot_name not in dot_name_to_deps:
dot_name... | Creates mapping between Dependency classes and names used in DOT graph | Below is the the instruction that describes the task:
### Input:
Creates mapping between Dependency classes and names used in DOT graph
### Response:
def _get_dep_to_dot_name_mapping(dependencies):
""" Creates mapping between Dependency classes and names used in DOT graph
"""
dot_name_to... |
def nth(iterable, n, default=None):
"""Returns the nth item or a default value.
Example::
>>> nth([0, 1, 2], 1)
1
>>> nth([0, 1, 2], 100)
None
**中文文档**
取出一个可循环对象中的第n个元素。等效于list(iterable)[n], 但占用极小的内存。
因为list(iterable)要将所有元素放在内存中并生成一个新列表。该方法常用语对于
那些取index操作被改写... | Returns the nth item or a default value.
Example::
>>> nth([0, 1, 2], 1)
1
>>> nth([0, 1, 2], 100)
None
**中文文档**
取出一个可循环对象中的第n个元素。等效于list(iterable)[n], 但占用极小的内存。
因为list(iterable)要将所有元素放在内存中并生成一个新列表。该方法常用语对于
那些取index操作被改写了的可循环对象。 | Below is the the instruction that describes the task:
### Input:
Returns the nth item or a default value.
Example::
>>> nth([0, 1, 2], 1)
1
>>> nth([0, 1, 2], 100)
None
**中文文档**
取出一个可循环对象中的第n个元素。等效于list(iterable)[n], 但占用极小的内存。
因为list(iterable)要将所有元素放在内存中并生成一个新列表。... |
def suggest_pairs(top_n=10, per_n=3, ignore_before=300):
""" Find the maximally interesting pairs of players to match up
First, sort the ratings by uncertainty.
Then, take the ten highest players with the highest uncertainty
For each of them, call them `p1`
Sort all the models by their distance from... | Find the maximally interesting pairs of players to match up
First, sort the ratings by uncertainty.
Then, take the ten highest players with the highest uncertainty
For each of them, call them `p1`
Sort all the models by their distance from p1's rating and take the 20
nearest rated models. ('candidat... | Below is the the instruction that describes the task:
### Input:
Find the maximally interesting pairs of players to match up
First, sort the ratings by uncertainty.
Then, take the ten highest players with the highest uncertainty
For each of them, call them `p1`
Sort all the models by their distance ... |
def load(self, yr=None, doy=None, date=None, fname=None, fid=None,
verifyPad=False):
"""Load instrument data into Instrument object .data.
Parameters
----------
yr : integer
year for desired data
doy : integer
day of year
date : date... | Load instrument data into Instrument object .data.
Parameters
----------
yr : integer
year for desired data
doy : integer
day of year
date : datetime object
date to load
fname : 'string'
filename to be loaded
verify... | Below is the the instruction that describes the task:
### Input:
Load instrument data into Instrument object .data.
Parameters
----------
yr : integer
year for desired data
doy : integer
day of year
date : datetime object
date to load
... |
def get(self, event):
"""Return a single schema"""
self.log("Schemarequest for", event.data, "from",
event.user, lvl=debug)
if event.data in schemastore:
response = {
'component': 'hfos.events.schemamanager',
'action': 'get',
... | Return a single schema | Below is the the instruction that describes the task:
### Input:
Return a single schema
### Response:
def get(self, event):
"""Return a single schema"""
self.log("Schemarequest for", event.data, "from",
event.user, lvl=debug)
if event.data in schemastore:
respon... |
def mangle_coverage(local_path, log):
"""Edit .coverage file substituting Windows file paths to Linux paths.
:param str local_path: Destination path to save file to.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
"""
# Read the file, or return if not a .cove... | Edit .coverage file substituting Windows file paths to Linux paths.
:param str local_path: Destination path to save file to.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator. | Below is the the instruction that describes the task:
### Input:
Edit .coverage file substituting Windows file paths to Linux paths.
:param str local_path: Destination path to save file to.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
### Response:
def mangle_cov... |
def encode_basestring(s):
"""Return a JSON representation of a Python string
"""
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
s = s.decode('utf-8')
def replace(match):
return ESCAPE_DCT[match.group(0)]
return u'"' + ESCAPE.sub(replace, s) + u'"' | Return a JSON representation of a Python string | Below is the the instruction that describes the task:
### Input:
Return a JSON representation of a Python string
### Response:
def encode_basestring(s):
"""Return a JSON representation of a Python string
"""
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
s = s.decode('utf-8')
de... |
def _bucket_time(self, event_time):
"""
The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12... | The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12:00, 12:10, ... on each day. | Below is the the instruction that describes the task:
### Input:
The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
... |
def derive_iobject_type(self, embedding_ns, embedded_ns, elt_name):
"""
Derive type of information object stemming from an embedded element
based on namespace information of embedding element, the embedded
element itself, and the name of the element.
"""
# Extract name... | Derive type of information object stemming from an embedded element
based on namespace information of embedding element, the embedded
element itself, and the name of the element. | Below is the the instruction that describes the task:
### Input:
Derive type of information object stemming from an embedded element
based on namespace information of embedding element, the embedded
element itself, and the name of the element.
### Response:
def derive_iobject_type(self, embedding_n... |
def _prm_write_shared_array(self, key, data, hdf5_group, full_name, flag, **kwargs):
"""Creates and array that can be used with an HDF5 array object"""
if flag == HDF5StorageService.ARRAY:
self._prm_write_into_array(key, data, hdf5_group, full_name, **kwargs)
elif flag in (HDF5Stora... | Creates and array that can be used with an HDF5 array object | Below is the the instruction that describes the task:
### Input:
Creates and array that can be used with an HDF5 array object
### Response:
def _prm_write_shared_array(self, key, data, hdf5_group, full_name, flag, **kwargs):
"""Creates and array that can be used with an HDF5 array object"""
if fla... |
def put_job_into(self, tube_name, data, pri=65536, delay=0, ttr=120):
"""Insert a new job into a specific queue. Wrapper around :func:`put_job`.
:param tube_name: Tube name
:type tube_name: str
:param data: Job body
:type data: Text (either str which will be encoded as utf-8, or... | Insert a new job into a specific queue. Wrapper around :func:`put_job`.
:param tube_name: Tube name
:type tube_name: str
:param data: Job body
:type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8
:param pri: Priority for the job
:... | Below is the the instruction that describes the task:
### Input:
Insert a new job into a specific queue. Wrapper around :func:`put_job`.
:param tube_name: Tube name
:type tube_name: str
:param data: Job body
:type data: Text (either str which will be encoded as utf-8, or bytes which... |
def volume_to_distance_with_errors(vol, vol_err):
""" Return the distance and standard deviation upper and lower bounds
Parameters
----------
vol: float
vol_err: float
Returns
-------
dist: float
ehigh: float
elow: float
"""
dist = (vol * 3.0/4.0/numpy.pi) ** (1.0/3.0)... | Return the distance and standard deviation upper and lower bounds
Parameters
----------
vol: float
vol_err: float
Returns
-------
dist: float
ehigh: float
elow: float | Below is the the instruction that describes the task:
### Input:
Return the distance and standard deviation upper and lower bounds
Parameters
----------
vol: float
vol_err: float
Returns
-------
dist: float
ehigh: float
elow: float
### Response:
def volume_to_distance_with_err... |
def _tr_paren(line_info):
"Translate lines escaped with: /"
return '%s%s(%s)' % (line_info.pre, line_info.ifun,
", ".join(line_info.the_rest.split())) | Translate lines escaped with: / | Below is the the instruction that describes the task:
### Input:
Translate lines escaped with: /
### Response:
def _tr_paren(line_info):
"Translate lines escaped with: /"
return '%s%s(%s)' % (line_info.pre, line_info.ifun,
", ".join(line_info.the_rest.split())) |
def _CreateRoutePatternsFolder(self, parent, route,
style_id=None, visible=True):
"""Create a KML Folder containing placemarks for each pattern in the route.
A pattern is a sequence of stops used by one of the trips in the route.
If there are not patterns for the route t... | Create a KML Folder containing placemarks for each pattern in the route.
A pattern is a sequence of stops used by one of the trips in the route.
If there are not patterns for the route then no folder is created and None
is returned.
Args:
parent: The parent ElementTree.Element instance.
r... | Below is the the instruction that describes the task:
### Input:
Create a KML Folder containing placemarks for each pattern in the route.
A pattern is a sequence of stops used by one of the trips in the route.
If there are not patterns for the route then no folder is created and None
is returned.
... |
def get_metaData(self, dcmlist, series_number):
"""
Get metadata.
Voxel size is obtained from PixelSpacing and difference of
SliceLocation of two neighboorhoding slices (first have index ifile).
Files in are used.
"""
# if dcmlist is None:
# dcmlist = ... | Get metadata.
Voxel size is obtained from PixelSpacing and difference of
SliceLocation of two neighboorhoding slices (first have index ifile).
Files in are used. | Below is the the instruction that describes the task:
### Input:
Get metadata.
Voxel size is obtained from PixelSpacing and difference of
SliceLocation of two neighboorhoding slices (first have index ifile).
Files in are used.
### Response:
def get_metaData(self, dcmlist, series_number):
... |
def horizon_main_nav(context):
"""Generates top-level dashboard navigation entries."""
if 'request' not in context:
return {}
current_dashboard = context['request'].horizon.get('dashboard', None)
dashboards = []
for dash in Horizon.get_dashboards():
if dash.can_access(context):
... | Generates top-level dashboard navigation entries. | Below is the the instruction that describes the task:
### Input:
Generates top-level dashboard navigation entries.
### Response:
def horizon_main_nav(context):
"""Generates top-level dashboard navigation entries."""
if 'request' not in context:
return {}
current_dashboard = context['request'].h... |
def mailto_to_envelope(mailto_str):
"""
Interpret mailto-string into a :class:`alot.db.envelope.Envelope`
"""
from alot.db.envelope import Envelope
headers, body = parse_mailto(mailto_str)
return Envelope(bodytext=body, headers=headers) | Interpret mailto-string into a :class:`alot.db.envelope.Envelope` | Below is the the instruction that describes the task:
### Input:
Interpret mailto-string into a :class:`alot.db.envelope.Envelope`
### Response:
def mailto_to_envelope(mailto_str):
"""
Interpret mailto-string into a :class:`alot.db.envelope.Envelope`
"""
from alot.db.envelope import Envelope
he... |
def quantile_gaussianize(x):
"""Normalize a sequence of values via rank and Normal c.d.f.
Args:
x (array_like): sequence of values.
Returns:
Gaussian-normalized values.
Example:
.. doctest::
>>> from scipy_sugar.stats import quantile_gaussianize
>>> print(quantil... | Normalize a sequence of values via rank and Normal c.d.f.
Args:
x (array_like): sequence of values.
Returns:
Gaussian-normalized values.
Example:
.. doctest::
>>> from scipy_sugar.stats import quantile_gaussianize
>>> print(quantile_gaussianize([-1, 0, 2]))
[... | Below is the the instruction that describes the task:
### Input:
Normalize a sequence of values via rank and Normal c.d.f.
Args:
x (array_like): sequence of values.
Returns:
Gaussian-normalized values.
Example:
.. doctest::
>>> from scipy_sugar.stats import quantile_gaus... |
def handle(self, *args, **options):
""" Purge notifications """
# retrieve layers
notifications = self.retrieve_old_notifications()
count = len(notifications)
if count > 0:
self.output('found %d notifications to purge...' % count)
notifications.delete()
... | Purge notifications | Below is the the instruction that describes the task:
### Input:
Purge notifications
### Response:
def handle(self, *args, **options):
""" Purge notifications """
# retrieve layers
notifications = self.retrieve_old_notifications()
count = len(notifications)
if count > 0:
... |
def _get_token_possibilities(cls, token, mode):
"""
Returns all possible component types of a token without regard to its context. For example "26" could be year,
date or minute, but can't be a month or an hour.
:param token: the token to classify
:param mode: the parse mode
... | Returns all possible component types of a token without regard to its context. For example "26" could be year,
date or minute, but can't be a month or an hour.
:param token: the token to classify
:param mode: the parse mode
:return: the dict of possible types and values if token was of t... | Below is the the instruction that describes the task:
### Input:
Returns all possible component types of a token without regard to its context. For example "26" could be year,
date or minute, but can't be a month or an hour.
:param token: the token to classify
:param mode: the parse mode
... |
def _read_config_list():
"""
配置列表读取
"""
with codecs.open('conf.ini', 'w+', encoding='utf-8') as f1:
conf_list = [conf for conf in f1.read().split('\n') if conf != '']
return conf_list | 配置列表读取 | Below is the the instruction that describes the task:
### Input:
配置列表读取
### Response:
def _read_config_list():
"""
配置列表读取
"""
with codecs.open('conf.ini', 'w+', encoding='utf-8') as f1:
conf_list = [conf for conf in f1.read().split('\n') if conf != '']
return conf_list |
def parse_answers(html_question):
"""Parse the answers of a given HTML question.
The method parses the answers related with a given HTML question,
as well as all the comments related to the answer.
:param html_question: raw HTML question element
:returns: a list with the answe... | Parse the answers of a given HTML question.
The method parses the answers related with a given HTML question,
as well as all the comments related to the answer.
:param html_question: raw HTML question element
:returns: a list with the answers | Below is the the instruction that describes the task:
### Input:
Parse the answers of a given HTML question.
The method parses the answers related with a given HTML question,
as well as all the comments related to the answer.
:param html_question: raw HTML question element
:return... |
def callback_read_char(self):
u'''Reads a character and informs the readline callback interface when a line is received'''
if self.keyboard_poll():
line = self.get_line_buffer() + u'\n'
# however there is another newline added by
# self.mode.readline_setup(prompt) whi... | u'''Reads a character and informs the readline callback interface when a line is received | Below is the the instruction that describes the task:
### Input:
u'''Reads a character and informs the readline callback interface when a line is received
### Response:
def callback_read_char(self):
u'''Reads a character and informs the readline callback interface when a line is received'''
if self... |
def pull_raw(url, name, verify=False):
'''
Execute a ``machinectl pull-raw`` to download a .qcow2 or raw disk image,
and add it to /var/lib/machines as a new container.
.. note::
**Requires systemd >= 219**
url
URL from which to download the container
name
Name for th... | Execute a ``machinectl pull-raw`` to download a .qcow2 or raw disk image,
and add it to /var/lib/machines as a new container.
.. note::
**Requires systemd >= 219**
url
URL from which to download the container
name
Name for the new container
verify : False
Perform... | Below is the the instruction that describes the task:
### Input:
Execute a ``machinectl pull-raw`` to download a .qcow2 or raw disk image,
and add it to /var/lib/machines as a new container.
.. note::
**Requires systemd >= 219**
url
URL from which to download the container
name
... |
def countdown_timer(seconds=10):
"""Show a simple countdown progress bar
Parameters
----------
seconds
Period of time the progress bar takes to reach zero.
"""
tick = 0.1 # seconds
n_ticks = int(seconds / tick)
widgets = ['Pause for panic: ', progressbar.ETA(), ' ', progressb... | Show a simple countdown progress bar
Parameters
----------
seconds
Period of time the progress bar takes to reach zero. | Below is the the instruction that describes the task:
### Input:
Show a simple countdown progress bar
Parameters
----------
seconds
Period of time the progress bar takes to reach zero.
### Response:
def countdown_timer(seconds=10):
"""Show a simple countdown progress bar
Parameters
... |
def variance(self):
'''
Compute variance.
Returns:
variance.
'''
alpha = self.__success + self.__default_alpha
beta = self.__failure + self.__default_beta
try:
variance = alpha * beta / ((alpha + beta) ** 2) * (alpha + beta + 1)
e... | Compute variance.
Returns:
variance. | Below is the the instruction that describes the task:
### Input:
Compute variance.
Returns:
variance.
### Response:
def variance(self):
'''
Compute variance.
Returns:
variance.
'''
alpha = self.__success + self.__default_alpha
beta =... |
def _check_field_value(field_value, pattern):
"""Check a song metadata field value for a pattern."""
if isinstance(field_value, list):
return any(re.search(pattern, str(value), re.I) for value in field_value)
else:
return re.search(pattern, str(field_value), re.I) | Check a song metadata field value for a pattern. | Below is the the instruction that describes the task:
### Input:
Check a song metadata field value for a pattern.
### Response:
def _check_field_value(field_value, pattern):
"""Check a song metadata field value for a pattern."""
if isinstance(field_value, list):
return any(re.search(pattern, str(value), re.I)... |
def es_query_template(path):
"""
RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE
:param path: THE NESTED PATH (NOT INCLUDING TABLE NAME)
:return: (es_query, es_filters) TUPLE
"""
if not is_text(path):
Log.error("expecting path to be a string")
if path != ".":
f0 = {}
... | RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE
:param path: THE NESTED PATH (NOT INCLUDING TABLE NAME)
:return: (es_query, es_filters) TUPLE | Below is the the instruction that describes the task:
### Input:
RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE
:param path: THE NESTED PATH (NOT INCLUDING TABLE NAME)
:return: (es_query, es_filters) TUPLE
### Response:
def es_query_template(path):
"""
RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUP... |
def TaxonomicAmendmentStore(repos_dict=None,
repos_par=None,
with_caching=True,
assumed_doc_version=None,
git_ssh=None,
pkey=None,
git_action_class=Taxo... | Factory function for a _TaxonomicAmendmentStore object.
A wrapper around the _TaxonomicAmendmentStore class instantiation for
the most common use case: a singleton _TaxonomicAmendmentStore.
If you need distinct _TaxonomicAmendmentStore objects, you'll need to
call that class directly. | Below is the the instruction that describes the task:
### Input:
Factory function for a _TaxonomicAmendmentStore object.
A wrapper around the _TaxonomicAmendmentStore class instantiation for
the most common use case: a singleton _TaxonomicAmendmentStore.
If you need distinct _TaxonomicAmendmentStore ob... |
def cli(parser):
'''
Currently a cop-out -- just calls easy_install
'''
parser.add_argument('-n', '--dry-run', action='store_true', help='Print uninstall actions without running')
parser.add_argument('packages', nargs='+', help='Packages to install')
opts = parser.parse_args()
for package i... | Currently a cop-out -- just calls easy_install | Below is the the instruction that describes the task:
### Input:
Currently a cop-out -- just calls easy_install
### Response:
def cli(parser):
'''
Currently a cop-out -- just calls easy_install
'''
parser.add_argument('-n', '--dry-run', action='store_true', help='Print uninstall actions without run... |
def _get_item_cache(self, item):
"""Return the cached item, item represents a label indexer."""
cache = self._item_cache
res = cache.get(item)
if res is None:
values = self._data.get(item)
res = self._box_item_values(item, values)
cache[item] = res
... | Return the cached item, item represents a label indexer. | Below is the the instruction that describes the task:
### Input:
Return the cached item, item represents a label indexer.
### Response:
def _get_item_cache(self, item):
"""Return the cached item, item represents a label indexer."""
cache = self._item_cache
res = cache.get(item)
if r... |
def meta_set(self, key, metafield, value):
''' Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys. '''
self._meta.setdefault(key, {})[metafield] = value
if key in self:
self[key] = self[key] | Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys. | Below is the the instruction that describes the task:
### Input:
Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys.
### Response:
def meta_set(self, key, metafield, value):
''' Set the meta field for a key to a new value. This triggers the
... |
def bbox_transform(ex_rois, gt_rois, box_stds):
"""
compute bounding box regression targets from ex_rois to gt_rois
:param ex_rois: [N, 4]
:param gt_rois: [N, 4]
:return: [N, 4]
"""
assert ex_rois.shape[0] == gt_rois.shape[0], 'inconsistent rois number'
ex_widths = ex_rois[:, 2] - ex_ro... | compute bounding box regression targets from ex_rois to gt_rois
:param ex_rois: [N, 4]
:param gt_rois: [N, 4]
:return: [N, 4] | Below is the the instruction that describes the task:
### Input:
compute bounding box regression targets from ex_rois to gt_rois
:param ex_rois: [N, 4]
:param gt_rois: [N, 4]
:return: [N, 4]
### Response:
def bbox_transform(ex_rois, gt_rois, box_stds):
"""
compute bounding box regression target... |
def p_sysargs(self, p):
'sysargs : sysargs COMMA sysarg'
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | sysargs : sysargs COMMA sysarg | Below is the the instruction that describes the task:
### Input:
sysargs : sysargs COMMA sysarg
### Response:
def p_sysargs(self, p):
'sysargs : sysargs COMMA sysarg'
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) |
def get_winner_number(self):
"""!
@brief Calculates number of winner at the last step of learning process.
@return (uint) Number of winner.
"""
if self.__ccore_som_pointer is not None:
self._award = wrapper.som_get_awards(self.__cco... | !
@brief Calculates number of winner at the last step of learning process.
@return (uint) Number of winner. | Below is the the instruction that describes the task:
### Input:
!
@brief Calculates number of winner at the last step of learning process.
@return (uint) Number of winner.
### Response:
def get_winner_number(self):
"""!
@brief Calculates number of winner at the last s... |
def call_on_each_endpoint(self, callback):
"""Find all server endpoints defined in the swagger spec and calls 'callback' for each,
with an instance of EndpointData as argument.
"""
if 'paths' not in self.swagger_dict:
return
for path, d in list(self.swagger_dict['pa... | Find all server endpoints defined in the swagger spec and calls 'callback' for each,
with an instance of EndpointData as argument. | Below is the the instruction that describes the task:
### Input:
Find all server endpoints defined in the swagger spec and calls 'callback' for each,
with an instance of EndpointData as argument.
### Response:
def call_on_each_endpoint(self, callback):
"""Find all server endpoints defined in the sw... |
def solve(self, reaction_1, reaction_2):
"""Return the flux coupling between two reactions
The flux coupling is returned as a tuple indicating the minimum and
maximum value of the v1/v2 reaction flux ratio. A value of None as
either the minimum or maximum indicates that the interval is ... | Return the flux coupling between two reactions
The flux coupling is returned as a tuple indicating the minimum and
maximum value of the v1/v2 reaction flux ratio. A value of None as
either the minimum or maximum indicates that the interval is unbounded
in that direction. | Below is the the instruction that describes the task:
### Input:
Return the flux coupling between two reactions
The flux coupling is returned as a tuple indicating the minimum and
maximum value of the v1/v2 reaction flux ratio. A value of None as
either the minimum or maximum indicates that... |
def clear_alarms(alarm):
'''
Clear (acknowledge) an alarm event. The arguments are “all” for all current
alarms, a specific alarm number (e.g. ‘‘1’‘), or an alarm string identifier
(e.g. ‘’MGMT_ALARM_PROXY_CONFIG_ERROR’‘).
.. code-block:: bash
salt '*' trafficserver.clear_alarms [all | #ev... | Clear (acknowledge) an alarm event. The arguments are “all” for all current
alarms, a specific alarm number (e.g. ‘‘1’‘), or an alarm string identifier
(e.g. ‘’MGMT_ALARM_PROXY_CONFIG_ERROR’‘).
.. code-block:: bash
salt '*' trafficserver.clear_alarms [all | #event | name] | Below is the the instruction that describes the task:
### Input:
Clear (acknowledge) an alarm event. The arguments are “all” for all current
alarms, a specific alarm number (e.g. ‘‘1’‘), or an alarm string identifier
(e.g. ‘’MGMT_ALARM_PROXY_CONFIG_ERROR’‘).
.. code-block:: bash
salt '*' traff... |
def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
# If initial Y is non-zero, initial U is chosen so that
# the relevant dual optimality criterion (see (3.10) i... | Return initialiser for working variable U. | Below is the the instruction that describes the task:
### Input:
Return initialiser for working variable U.
### Response:
def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
... |
def _make_operator(method_name):
"""Return an operator method that takes parameters of type
:class:`Dimension`, evaluates them, and delegates to the :class:`float`
operator with name `method_name`"""
def operator(self, other):
"""Operator delegating to the :class:`float` meth... | Return an operator method that takes parameters of type
:class:`Dimension`, evaluates them, and delegates to the :class:`float`
operator with name `method_name` | Below is the the instruction that describes the task:
### Input:
Return an operator method that takes parameters of type
:class:`Dimension`, evaluates them, and delegates to the :class:`float`
operator with name `method_name`
### Response:
def _make_operator(method_name):
"""Return an opera... |
def get_out_ip_addr(cls, tenant_id):
"""Retrieves the 'out' service subnet attributes. """
if tenant_id not in cls.serv_obj_dict:
LOG.error("Fabric not prepared for tenant %s", tenant_id)
return
tenant_obj = cls.serv_obj_dict.get(tenant_id)
return tenant_obj.get_o... | Retrieves the 'out' service subnet attributes. | Below is the the instruction that describes the task:
### Input:
Retrieves the 'out' service subnet attributes.
### Response:
def get_out_ip_addr(cls, tenant_id):
"""Retrieves the 'out' service subnet attributes. """
if tenant_id not in cls.serv_obj_dict:
LOG.error("Fabric not prepared ... |
def destroy(self):
"""Destroys a session completely, by deleting all keys and removing it
from the internal store immediately.
This allows removing a session for security reasons, e.g. a login
stored in a session will cease to exist if the session is destroyed.
"""
for k... | Destroys a session completely, by deleting all keys and removing it
from the internal store immediately.
This allows removing a session for security reasons, e.g. a login
stored in a session will cease to exist if the session is destroyed. | Below is the the instruction that describes the task:
### Input:
Destroys a session completely, by deleting all keys and removing it
from the internal store immediately.
This allows removing a session for security reasons, e.g. a login
stored in a session will cease to exist if the session ... |
def spread_value(value: Decimal, spread_p: Decimal) -> Tuple[Decimal, Decimal]:
"""Returns a lower and upper value separated by a spread percentage"""
upper = value * (1 + spread_p)
lower = value / (1 + spread_p)
return lower, upper | Returns a lower and upper value separated by a spread percentage | Below is the the instruction that describes the task:
### Input:
Returns a lower and upper value separated by a spread percentage
### Response:
def spread_value(value: Decimal, spread_p: Decimal) -> Tuple[Decimal, Decimal]:
"""Returns a lower and upper value separated by a spread percentage"""
upper = valu... |
def prepare_relationship(config, model_name, raml_resource):
""" Create referenced model if it doesn't exist.
When preparing a relationship, we check to see if the model that will be
referenced already exists. If not, it is created so that it will be possible
to use it in a relationship. Thus the first... | Create referenced model if it doesn't exist.
When preparing a relationship, we check to see if the model that will be
referenced already exists. If not, it is created so that it will be possible
to use it in a relationship. Thus the first usage of this model in RAML file
must provide its schema in POST... | Below is the the instruction that describes the task:
### Input:
Create referenced model if it doesn't exist.
When preparing a relationship, we check to see if the model that will be
referenced already exists. If not, it is created so that it will be possible
to use it in a relationship. Thus the first... |
def new_rsa_key(key_size=2048, kid='', use='', public_exponent=65537):
"""
Creates a new RSA key pair and wraps it in a
:py:class:`cryptojwt.jwk.rsa.RSAKey` instance
:param key_size: The size of the key
:param kid: The key ID
:param use: What the is supposed to be used for. 2 choices 'sig'/'enc... | Creates a new RSA key pair and wraps it in a
:py:class:`cryptojwt.jwk.rsa.RSAKey` instance
:param key_size: The size of the key
:param kid: The key ID
:param use: What the is supposed to be used for. 2 choices 'sig'/'enc'
:param public_exponent: The value of the public exponent.
:return: A :py:... | Below is the the instruction that describes the task:
### Input:
Creates a new RSA key pair and wraps it in a
:py:class:`cryptojwt.jwk.rsa.RSAKey` instance
:param key_size: The size of the key
:param kid: The key ID
:param use: What the is supposed to be used for. 2 choices 'sig'/'enc'
:param p... |
def iter_predecessors(self, graph, dest, branch, turn, tick, *, forward=None):
"""Iterate over predecessors to a given destination node at a given time."""
if self.db._no_kc:
yield from self._adds_dels_sucpred(self.predecessors[graph, dest], branch, turn, tick)[0]
return
... | Iterate over predecessors to a given destination node at a given time. | Below is the the instruction that describes the task:
### Input:
Iterate over predecessors to a given destination node at a given time.
### Response:
def iter_predecessors(self, graph, dest, branch, turn, tick, *, forward=None):
"""Iterate over predecessors to a given destination node at a given time."""
... |
def bidi(request):
"""Adds to the context BiDi related variables
LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl')
LANGUAGE_START -- Start of language layout ('right' for rtl, 'left'
for 'ltr')
LANGUAGE_END -- End of language layout ('left' for rtl, 'right'
... | Adds to the context BiDi related variables
LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl')
LANGUAGE_START -- Start of language layout ('right' for rtl, 'left'
for 'ltr')
LANGUAGE_END -- End of language layout ('left' for rtl, 'right'
for 'ltr... | Below is the the instruction that describes the task:
### Input:
Adds to the context BiDi related variables
LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl')
LANGUAGE_START -- Start of language layout ('right' for rtl, 'left'
for 'ltr')
LANGUAGE_END -- End of la... |
def _int_to_pos(self, flat_position):
"""Returns x, y from flat_position integer.
Args:
flat_position: flattened position integer
Returns: x, y
"""
return flat_position % self.env.action_space.screen_shape[0],\
flat_position % self.env.action_space.scre... | Returns x, y from flat_position integer.
Args:
flat_position: flattened position integer
Returns: x, y | Below is the the instruction that describes the task:
### Input:
Returns x, y from flat_position integer.
Args:
flat_position: flattened position integer
Returns: x, y
### Response:
def _int_to_pos(self, flat_position):
"""Returns x, y from flat_position integer.
Args... |
def _decrypt(self, fp, password=None):
"""
Internal decryption function
Uses either the password argument for the decryption,
or, if not supplied, the password field of the object
:param fp: a file object or similar which supports the readline and read methods
:rtype: P... | Internal decryption function
Uses either the password argument for the decryption,
or, if not supplied, the password field of the object
:param fp: a file object or similar which supports the readline and read methods
:rtype: Proxy | Below is the the instruction that describes the task:
### Input:
Internal decryption function
Uses either the password argument for the decryption,
or, if not supplied, the password field of the object
:param fp: a file object or similar which supports the readline and read methods
... |
def array(
item_processor, # type: Processor
alias=None, # type: Optional[Text]
nested=None, # type: Optional[Text]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create an array processor that can be used ... | Create an array processor that can be used to parse and serialize array data.
XML arrays may be nested within an array element, or they may be embedded
within their parent. A nested array would look like:
.. sourcecode:: xml
<root-element>
<some-element>ABC</some-element>
... | Below is the the instruction that describes the task:
### Input:
Create an array processor that can be used to parse and serialize array data.
XML arrays may be nested within an array element, or they may be embedded
within their parent. A nested array would look like:
.. sourcecode:: xml
<ro... |
def rand_ssn():
"""Random SSN. (9 digits)
Example::
>>> rand_ssn()
295-50-0178
"""
return "%s-%s-%s" % (rand_str(3, string.digits),
rand_str(2, string.digits),
rand_str(4, string.digits)) | Random SSN. (9 digits)
Example::
>>> rand_ssn()
295-50-0178 | Below is the the instruction that describes the task:
### Input:
Random SSN. (9 digits)
Example::
>>> rand_ssn()
295-50-0178
### Response:
def rand_ssn():
"""Random SSN. (9 digits)
Example::
>>> rand_ssn()
295-50-0178
"""
return "%s-%s-%s" % (rand_str(3, stri... |
def update(self):
"""update performs the analysis, then runs the forecast using the updated self.parensemble.
This can be called repeatedly to iterate..."""
parensemble = self.analysis_evensen()
obsensemble = self.forecast(parensemble=parensemble)
# todo: check for phi improveme... | update performs the analysis, then runs the forecast using the updated self.parensemble.
This can be called repeatedly to iterate... | Below is the the instruction that describes the task:
### Input:
update performs the analysis, then runs the forecast using the updated self.parensemble.
This can be called repeatedly to iterate...
### Response:
def update(self):
"""update performs the analysis, then runs the forecast using the upd... |
def create_widget(self, place, type, file=None, **kwargs):
'''
Create a widget object based on given arguments.
If file object is provided, callable arguments will be resolved:
its return value will be used after calling them with file as first
parameter.
All extra `kwa... | Create a widget object based on given arguments.
If file object is provided, callable arguments will be resolved:
its return value will be used after calling them with file as first
parameter.
All extra `kwargs` parameters will be passed to widget constructor.
:param place: pl... | Below is the the instruction that describes the task:
### Input:
Create a widget object based on given arguments.
If file object is provided, callable arguments will be resolved:
its return value will be used after calling them with file as first
parameter.
All extra `kwargs` param... |
def export_element(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="",
who="", add_join=False):
"""
Export a node with "Element" classification (task, subprocess or gateway)
:param bpmn_graph: an instance of BpmnDiagramGraph class,
... | Export a node with "Element" classification (task, subprocess or gateway)
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:... | Below is the the instruction that describes the task:
### Input:
Export a node with "Element" classification (task, subprocess or gateway)
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters... |
def partial_autocorrelation(x, param):
"""
Calculates the value of the partial autocorrelation function at the given lag. The lag `k` partial autocorrelation
of a time series :math:`\\lbrace x_t, t = 1 \\ldots T \\rbrace` equals the partial correlation of :math:`x_t` and
:math:`x_{t-k}`, adjusted for th... | Calculates the value of the partial autocorrelation function at the given lag. The lag `k` partial autocorrelation
of a time series :math:`\\lbrace x_t, t = 1 \\ldots T \\rbrace` equals the partial correlation of :math:`x_t` and
:math:`x_{t-k}`, adjusted for the intermediate variables
:math:`\\lbrace x_{t-1... | Below is the the instruction that describes the task:
### Input:
Calculates the value of the partial autocorrelation function at the given lag. The lag `k` partial autocorrelation
of a time series :math:`\\lbrace x_t, t = 1 \\ldots T \\rbrace` equals the partial correlation of :math:`x_t` and
:math:`x_{t-k}... |
def get(self, key=None, **kwargs):
"""
Ensures that only one result is returned from DB and raises an exception otherwise.
Can work in 3 different way.
- If no argument is given, only does "ensuring about one and only object" job.
- If key given as only argument, retriev... | Ensures that only one result is returned from DB and raises an exception otherwise.
Can work in 3 different way.
- If no argument is given, only does "ensuring about one and only object" job.
- If key given as only argument, retrieves the object from DB.
- if query filters g... | Below is the the instruction that describes the task:
### Input:
Ensures that only one result is returned from DB and raises an exception otherwise.
Can work in 3 different way.
- If no argument is given, only does "ensuring about one and only object" job.
- If key given as only arg... |
def listar_por_equipamento(self, id_equipment):
"""List all Script related Equipment.
:param id_equipment: Identifier of the Equipment. Integer value and greater than zero.
:return: Dictionary with the following structure:
::
{script': [{‘id’: < id >,
‘nome’: ... | List all Script related Equipment.
:param id_equipment: Identifier of the Equipment. Integer value and greater than zero.
:return: Dictionary with the following structure:
::
{script': [{‘id’: < id >,
‘nome’: < nome >,
‘descricao’: < descricao >,
... | Below is the the instruction that describes the task:
### Input:
List all Script related Equipment.
:param id_equipment: Identifier of the Equipment. Integer value and greater than zero.
:return: Dictionary with the following structure:
::
{script': [{‘id’: < id >,
... |
def enter_event_loop(self):
"""\
Main loop of the IRCConnection - reads from the socket and dispatches
based on regex matching
"""
patterns = self.dispatch_patterns()
self.logger.debug('entering receive loop')
while 1:
try:
data = self... | \
Main loop of the IRCConnection - reads from the socket and dispatches
based on regex matching | Below is the the instruction that describes the task:
### Input:
\
Main loop of the IRCConnection - reads from the socket and dispatches
based on regex matching
### Response:
def enter_event_loop(self):
"""\
Main loop of the IRCConnection - reads from the socket and dispatches
... |
def create_page(cls, webdriver=None, **kwargs):
"""Class method short cut to call PageFactory on itself. Use it to instantiate
this PageObject using a webdriver.
Args:
webdriver (Webdriver): Instance of Selenium Webdriver.
Returns:
PageObject
Raises:
... | Class method short cut to call PageFactory on itself. Use it to instantiate
this PageObject using a webdriver.
Args:
webdriver (Webdriver): Instance of Selenium Webdriver.
Returns:
PageObject
Raises:
InvalidPageError | Below is the the instruction that describes the task:
### Input:
Class method short cut to call PageFactory on itself. Use it to instantiate
this PageObject using a webdriver.
Args:
webdriver (Webdriver): Instance of Selenium Webdriver.
Returns:
PageObject
... |
def indicate_fulfillment_ficon(self, control_unit, unit_address):
"""
TODO: Add ControlUnit objects etc for FICON support.
Indicate completion of :term:`fulfillment` for this ECKD (=FICON)
storage volume and provide identifying information (control unit
and unit address) about t... | TODO: Add ControlUnit objects etc for FICON support.
Indicate completion of :term:`fulfillment` for this ECKD (=FICON)
storage volume and provide identifying information (control unit
and unit address) about the actual storage volume on the storage
subsystem.
Manually indicatin... | Below is the the instruction that describes the task:
### Input:
TODO: Add ControlUnit objects etc for FICON support.
Indicate completion of :term:`fulfillment` for this ECKD (=FICON)
storage volume and provide identifying information (control unit
and unit address) about the actual storage... |
def bread(stream):
""" Decode a file or stream to an object.
"""
if hasattr(stream, "read"):
return bdecode(stream.read())
else:
handle = open(stream, "rb")
try:
return bdecode(handle.read())
finally:
handle.close() | Decode a file or stream to an object. | Below is the the instruction that describes the task:
### Input:
Decode a file or stream to an object.
### Response:
def bread(stream):
""" Decode a file or stream to an object.
"""
if hasattr(stream, "read"):
return bdecode(stream.read())
else:
handle = open(stream, "rb")
t... |
def minowski(h1, h2, p = 2): # 46..45..14,11..43..44 / 45 us for p=int(-inf..-24..-1,1..24..inf) / float @array, +20 us @list \w 100 bins
r"""
Minowski distance.
With :math:`p=2` equal to the Euclidean distance, with :math:`p=1` equal to the Manhattan distance,
and the Chebyshev distance implementa... | r"""
Minowski distance.
With :math:`p=2` equal to the Euclidean distance, with :math:`p=1` equal to the Manhattan distance,
and the Chebyshev distance implementation represents the case of :math:`p=\pm inf`.
The Minowksi distance between two histograms :math:`H` and :math:`H'` of size :math:`m... | Below is the the instruction that describes the task:
### Input:
r"""
Minowski distance.
With :math:`p=2` equal to the Euclidean distance, with :math:`p=1` equal to the Manhattan distance,
and the Chebyshev distance implementation represents the case of :math:`p=\pm inf`.
The Minowksi dist... |
def missing_values(self):
'''
Computes the values that must be missing from each
player's hand, based on when they have passed.
:return: a list of sets, each one containing the
values that must be missing from the
corresponding player's hand
'''... | Computes the values that must be missing from each
player's hand, based on when they have passed.
:return: a list of sets, each one containing the
values that must be missing from the
corresponding player's hand | Below is the the instruction that describes the task:
### Input:
Computes the values that must be missing from each
player's hand, based on when they have passed.
:return: a list of sets, each one containing the
values that must be missing from the
corresponding pl... |
def is_defined_by_module(item, module, parent=None):
"""
Check if item is directly defined by a module.
This check may be prone to errors.
"""
flag = False
if isinstance(item, types.ModuleType):
if not hasattr(item, '__file__'):
try:
# hack for cv2 and xfeatur... | Check if item is directly defined by a module.
This check may be prone to errors. | Below is the the instruction that describes the task:
### Input:
Check if item is directly defined by a module.
This check may be prone to errors.
### Response:
def is_defined_by_module(item, module, parent=None):
"""
Check if item is directly defined by a module.
This check may be prone to errors.... |
def describeSObject(self, sObjectsType):
'''
Describes metadata (field list and object properties) for the specified
object.
'''
self._setHeaders('describeSObject')
return self._sforce.service.describeSObject(sObjectsType) | Describes metadata (field list and object properties) for the specified
object. | Below is the the instruction that describes the task:
### Input:
Describes metadata (field list and object properties) for the specified
object.
### Response:
def describeSObject(self, sObjectsType):
'''
Describes metadata (field list and object properties) for the specified
object.
'''
sel... |
def can_start_on_cluster(nodes_status,
nodes,
start,
walltime):
"""Check if #nodes can be started on a given cluster.
This is intended to give a good enough approximation.
This can be use to prefiltered possible reservation dates be... | Check if #nodes can be started on a given cluster.
This is intended to give a good enough approximation.
This can be use to prefiltered possible reservation dates before submitting
them on oar. | Below is the the instruction that describes the task:
### Input:
Check if #nodes can be started on a given cluster.
This is intended to give a good enough approximation.
This can be use to prefiltered possible reservation dates before submitting
them on oar.
### Response:
def can_start_on_cluster(node... |
def new_from_tokens(self, *args, **kwargs):
"""
Takes in a name that has been split by spaces.
Names which are in [last, first] format need to be preprocessed.
The nickname must be in double quotes to be recognized as such.
This can take name parts in in these or... | Takes in a name that has been split by spaces.
Names which are in [last, first] format need to be preprocessed.
The nickname must be in double quotes to be recognized as such.
This can take name parts in in these orders:
first, middle, last, nick, suffix, honorific
... | Below is the the instruction that describes the task:
### Input:
Takes in a name that has been split by spaces.
Names which are in [last, first] format need to be preprocessed.
The nickname must be in double quotes to be recognized as such.
This can take name parts in in these o... |
def write(self, *data):
"""Augment write routine to keep track of current line"""
for l in data:
## print("XXX write: '%s'" % l)
for i in str(l):
if i == '\n':
self.current_line_number += 1
pass
pass
... | Augment write routine to keep track of current line | Below is the the instruction that describes the task:
### Input:
Augment write routine to keep track of current line
### Response:
def write(self, *data):
"""Augment write routine to keep track of current line"""
for l in data:
## print("XXX write: '%s'" % l)
for i in str(l)... |
def remove_not_valid_selections(self):
"""
update the value to remove any that are (no longer) valid
"""
value = [v for v in self.get_value() if self.valid_selection(v)]
self.set_value(value) | update the value to remove any that are (no longer) valid | Below is the the instruction that describes the task:
### Input:
update the value to remove any that are (no longer) valid
### Response:
def remove_not_valid_selections(self):
"""
update the value to remove any that are (no longer) valid
"""
value = [v for v in self.get_value() if s... |
def DataCopyWithOverlay(self, dcmfilelist, out_dir, overlays):
"""
Function make 3D data from dicom file slices
:dcmfilelist list of sorted .dcm files
:overlays dictionary of binary overlays. {1:np.array([...]), 3:...}
:out_dir output directory
"""
dcmlist = dcm... | Function make 3D data from dicom file slices
:dcmfilelist list of sorted .dcm files
:overlays dictionary of binary overlays. {1:np.array([...]), 3:...}
:out_dir output directory | Below is the the instruction that describes the task:
### Input:
Function make 3D data from dicom file slices
:dcmfilelist list of sorted .dcm files
:overlays dictionary of binary overlays. {1:np.array([...]), 3:...}
:out_dir output directory
### Response:
def DataCopyWithOverlay(self, dcm... |
def cluster(self, window):
""" Cluster the dict array, assuming it has the relevant Coinc colums,
time1, time2, stat, and timeslide_id
"""
# If no events, do nothing
pivot_ifo = self.attrs['pivot']
fixed_ifo = self.attrs['fixed']
if len(self.data['%s/time' % pivot... | Cluster the dict array, assuming it has the relevant Coinc colums,
time1, time2, stat, and timeslide_id | Below is the the instruction that describes the task:
### Input:
Cluster the dict array, assuming it has the relevant Coinc colums,
time1, time2, stat, and timeslide_id
### Response:
def cluster(self, window):
""" Cluster the dict array, assuming it has the relevant Coinc colums,
time1, tim... |
def p_namespace(self, p):
'''namespace : NAMESPACE namespace_scope IDENTIFIER'''
p[0] = ast.Namespace(scope=p[2], name=p[3], lineno=p.lineno(1)) | namespace : NAMESPACE namespace_scope IDENTIFIER | Below is the the instruction that describes the task:
### Input:
namespace : NAMESPACE namespace_scope IDENTIFIER
### Response:
def p_namespace(self, p):
'''namespace : NAMESPACE namespace_scope IDENTIFIER'''
p[0] = ast.Namespace(scope=p[2], name=p[3], lineno=p.lineno(1)) |
def search_all(self, quiet=False):
'''a "show all" search that doesn't require a query
Parameters
==========
quiet: if quiet is True, we only are using the function to return
rows of results.
'''
results = []
for obj in self.bucket.objects.all():
subsr... | a "show all" search that doesn't require a query
Parameters
==========
quiet: if quiet is True, we only are using the function to return
rows of results. | Below is the the instruction that describes the task:
### Input:
a "show all" search that doesn't require a query
Parameters
==========
quiet: if quiet is True, we only are using the function to return
rows of results.
### Response:
def search_all(self, quiet=False):
... |
def get_topclasses(cls):
"""Gets the base classes that are in pycbc."""
bases = [c for c in inspect.getmro(cls)
if c.__module__.startswith('pycbc') and c != cls]
return ', '.join(['{}.{}'.format(c.__module__, c.__name__) for c in bases]) | Gets the base classes that are in pycbc. | Below is the the instruction that describes the task:
### Input:
Gets the base classes that are in pycbc.
### Response:
def get_topclasses(cls):
"""Gets the base classes that are in pycbc."""
bases = [c for c in inspect.getmro(cls)
if c.__module__.startswith('pycbc') and c != cls]
return '... |
def linear_set_layer(layer_size,
inputs,
context=None,
activation_fn=tf.nn.relu,
dropout=0.0,
name=None):
"""Basic layer type for doing funky things with sets.
Applies a linear transformation to each element in... | Basic layer type for doing funky things with sets.
Applies a linear transformation to each element in the input set.
If a context is supplied, it is concatenated with the inputs.
e.g. One can use global_pool_1d to get a representation of the set which
can then be used as the context for the next layer.
... | Below is the the instruction that describes the task:
### Input:
Basic layer type for doing funky things with sets.
Applies a linear transformation to each element in the input set.
If a context is supplied, it is concatenated with the inputs.
e.g. One can use global_pool_1d to get a representation of the ... |
def _read_para_puzzle(self, code, cbit, clen, *, desc, length, version):
"""Read HIP PUZZLE parameter.
Structure of HIP PUZZLE parameter [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 ... | Read HIP PUZZLE parameter.
Structure of HIP PUZZLE parameter [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-... | Below is the the instruction that describes the task:
### Input:
Read HIP PUZZLE parameter.
Structure of HIP PUZZLE parameter [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
... |
def xline(self):
"""
Interact with segy in crossline mode
Returns
-------
xline : Line or None
Raises
------
ValueError
If the file is unstructured
Notes
-----
.. versionadded:: 1.1
"""
if self.unstruc... | Interact with segy in crossline mode
Returns
-------
xline : Line or None
Raises
------
ValueError
If the file is unstructured
Notes
-----
.. versionadded:: 1.1 | Below is the the instruction that describes the task:
### Input:
Interact with segy in crossline mode
Returns
-------
xline : Line or None
Raises
------
ValueError
If the file is unstructured
Notes
-----
.. versionadded:: 1.1
###... |
def makeelement(E, tagname, **kwargs):
"""Internal function"""
if sys.version < '3':
try:
kwargs2 = {}
for k,v in kwargs.items():
kwargs2[k.encode('utf-8')] = v.encode('utf-8')
#return E._makeelement(tagname.encode('utf-8'), **{ k.encode('utf-8'): ... | Internal function | Below is the the instruction that describes the task:
### Input:
Internal function
### Response:
def makeelement(E, tagname, **kwargs):
"""Internal function"""
if sys.version < '3':
try:
kwargs2 = {}
for k,v in kwargs.items():
kwargs2[k.encode('utf-8')] = v.e... |
def zero_pad_features(features: List[np.ndarray],
target_shape: tuple) -> List[np.ndarray]:
"""
Zero pad to numpy array.
:param features: List of numpy arrays.
:param target_shape: Target shape of each numpy array in the list feat. Note:
target_shape should be g... | Zero pad to numpy array.
:param features: List of numpy arrays.
:param target_shape: Target shape of each numpy array in the list feat. Note:
target_shape should be greater that the largest shapes in feat.
:return: A list of padded numpy arrays. | Below is the the instruction that describes the task:
### Input:
Zero pad to numpy array.
:param features: List of numpy arrays.
:param target_shape: Target shape of each numpy array in the list feat. Note:
target_shape should be greater that the largest shapes in feat.
:return: A li... |
def clickable(self):
"""
Property used for determining if the widget should be clickable by the user.
This is only true if the submenu of this widget is active and this widget is enabled.
The widget may be either disabled by setting this property or the :py:attr:`enable... | Property used for determining if the widget should be clickable by the user.
This is only true if the submenu of this widget is active and this widget is enabled.
The widget may be either disabled by setting this property or the :py:attr:`enabled` attribute. | Below is the the instruction that describes the task:
### Input:
Property used for determining if the widget should be clickable by the user.
This is only true if the submenu of this widget is active and this widget is enabled.
The widget may be either disabled by setting this prop... |
def gen_random_company_name():
"""
随机生成一个公司名称
:returns:
* company_name: (string) 银行名称
举例如下::
print('--- gen_random_company_name demo ---')
print(gen_random_company_name())
print('---')
输出结果::
--- gen_random_company_name demo ---
上海大升旅游质询有限责任公司
... | 随机生成一个公司名称
:returns:
* company_name: (string) 银行名称
举例如下::
print('--- gen_random_company_name demo ---')
print(gen_random_company_name())
print('---')
输出结果::
--- gen_random_company_name demo ---
上海大升旅游质询有限责任公司
--- | Below is the the instruction that describes the task:
### Input:
随机生成一个公司名称
:returns:
* company_name: (string) 银行名称
举例如下::
print('--- gen_random_company_name demo ---')
print(gen_random_company_name())
print('---')
输出结果::
--- gen_random_company_name demo ---
... |
def data(self):
"""bytes: value data as a byte string.
Raises:
WinRegistryValueError: if the value data cannot be read.
"""
try:
return self._pyregf_value.data
except IOError as exception:
raise errors.WinRegistryValueError(
'Unable to read data from value: {0:s} with er... | bytes: value data as a byte string.
Raises:
WinRegistryValueError: if the value data cannot be read. | Below is the the instruction that describes the task:
### Input:
bytes: value data as a byte string.
Raises:
WinRegistryValueError: if the value data cannot be read.
### Response:
def data(self):
"""bytes: value data as a byte string.
Raises:
WinRegistryValueError: if the value data canno... |
def get_config(self):
"""
serialize to a dict all attributes except model weights
Returns
-------
dict
"""
self.update_network_description()
result = dict(self.__dict__)
result['_network'] = None
result['network_weights'] = None
... | serialize to a dict all attributes except model weights
Returns
-------
dict | Below is the the instruction that describes the task:
### Input:
serialize to a dict all attributes except model weights
Returns
-------
dict
### Response:
def get_config(self):
"""
serialize to a dict all attributes except model weights
Returns
... |
def _initialize(self, runtime):
"""Common initializer for OsidManager and OsidProxyManager"""
if runtime is None:
raise NullArgument()
if self._my_runtime is not None:
raise IllegalState('this manager has already been initialized.')
self._my_runtime = runtime
... | Common initializer for OsidManager and OsidProxyManager | Below is the the instruction that describes the task:
### Input:
Common initializer for OsidManager and OsidProxyManager
### Response:
def _initialize(self, runtime):
"""Common initializer for OsidManager and OsidProxyManager"""
if runtime is None:
raise NullArgument()
if self.... |
def new(self, rows, columns=None):
"""
A shortcut for manually instantiating a new
:class:`~riak.ts_object.TsObject`
:param rows: An list of lists with timeseries data
:type rows: list
:param columns: An list of Column names and types. Optional.
:type columns: li... | A shortcut for manually instantiating a new
:class:`~riak.ts_object.TsObject`
:param rows: An list of lists with timeseries data
:type rows: list
:param columns: An list of Column names and types. Optional.
:type columns: list
:rtype: :class:`~riak.ts_object.TsObject` | Below is the the instruction that describes the task:
### Input:
A shortcut for manually instantiating a new
:class:`~riak.ts_object.TsObject`
:param rows: An list of lists with timeseries data
:type rows: list
:param columns: An list of Column names and types. Optional.
:ty... |
def predict(self, u=0):
"""
Predict next state (prior) using the Kalman filter state propagation
equations.
Parameters
----------
u : np.array, optional
Optional control vector. If non-zero, it is multiplied by B
to create the control input into ... | Predict next state (prior) using the Kalman filter state propagation
equations.
Parameters
----------
u : np.array, optional
Optional control vector. If non-zero, it is multiplied by B
to create the control input into the system. | Below is the the instruction that describes the task:
### Input:
Predict next state (prior) using the Kalman filter state propagation
equations.
Parameters
----------
u : np.array, optional
Optional control vector. If non-zero, it is multiplied by B
to creat... |
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
if not retcode:
return True
... | Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name> | Below is the the instruction that describes the task:
### Input:
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
### Response:
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*... |
def settings(self, **kwargs):
'''
Pass a load of settings into the canvas
'''
for k, v in kwargs.items():
setattr(self, k, v) | Pass a load of settings into the canvas | Below is the the instruction that describes the task:
### Input:
Pass a load of settings into the canvas
### Response:
def settings(self, **kwargs):
'''
Pass a load of settings into the canvas
'''
for k, v in kwargs.items():
setattr(self, k, v) |
async def stream_as_text(stream):
"""
Given a stream of bytes or text, if any of the items in the stream
are bytes convert them to text.
This function can be removed once we return text streams
instead of byte streams.
"""
async for data in stream:
if not isinstance(data, six.text_ty... | Given a stream of bytes or text, if any of the items in the stream
are bytes convert them to text.
This function can be removed once we return text streams
instead of byte streams. | Below is the the instruction that describes the task:
### Input:
Given a stream of bytes or text, if any of the items in the stream
are bytes convert them to text.
This function can be removed once we return text streams
instead of byte streams.
### Response:
async def stream_as_text(stream):
"""
... |
def pcpool(name, cvals):
"""
This entry point provides toolkit programmers a method for
programmatically inserting character data into the
kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pcpool_c.html
:param name: The kernel pool name to associate with cvals.
:type nam... | This entry point provides toolkit programmers a method for
programmatically inserting character data into the
kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pcpool_c.html
:param name: The kernel pool name to associate with cvals.
:type name: str
:param cvals: An array of ... | Below is the the instruction that describes the task:
### Input:
This entry point provides toolkit programmers a method for
programmatically inserting character data into the
kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pcpool_c.html
:param name: The kernel pool name to ass... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.