INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Waits (blocks) until a running pipeline finishes.
Arguments:
- timeout(``int``) [default: ``None``] Specifies the timeout,
``RuntimeError`` will be raised. The default is to wait indefinetely
for the pipeline to finish. | def wait(self, timeout=None):
"""
Waits (blocks) until a running pipeline finishes.
Arguments:
- timeout(``int``) [default: ``None``] Specifies the timeout,
``RuntimeError`` will be raised. The default is to wait indefinetely
for the pipeline ... |
Pauses a running pipeline. This will stop retrieving results from the
pipeline. Parallel parts of the pipeline will stop after the ``NuMap``
buffer is has been filled. A paused pipeline can be run or stopped. | def pause(self):
"""
Pauses a running pipeline. This will stop retrieving results from the
pipeline. Parallel parts of the pipeline will stop after the ``NuMap``
buffer is has been filled. A paused pipeline can be run or stopped.
"""
# 1. stop the plumbing thr... |
Stops a paused pipeline. This will a trigger a ``StopIteration`` in the
inputs of the pipeline. And retrieve the buffered results. This will
stop all ``Pipers`` and ``NuMaps``. Python will not terminate cleanly
if a pipeline is running or paused. | def stop(self):
"""
Stops a paused pipeline. This will a trigger a ``StopIteration`` in the
inputs of the pipeline. And retrieve the buffered results. This will
stop all ``Pipers`` and ``NuMaps``. Python will not terminate cleanly
if a pipeline is running or paused.
... |
Makes the ``Piper`` ready to return results. This involves starting the
the provided ``NuMap`` instance. If multiple ``Pipers`` share a
``NuMap`` instance the order in which these ``Pipers`` are started is
important. The valid order is upstream before downstream. The ``NuMap``
instan... | def start(self, stages=None):
"""
Makes the ``Piper`` ready to return results. This involves starting the
the provided ``NuMap`` instance. If multiple ``Pipers`` share a
``NuMap`` instance the order in which these ``Pipers`` are started is
important. The valid order is upstrea... |
Connects the ``Piper`` instance to its upstream ``Pipers`` that should
be given as a sequence. This connects this ``Piper.inbox`` with the
upstream ``Piper.outbox`` respecting any "consume", "spawn" and
"produce" arguments.
Arguments:
- inbox(sequence) seque... | def connect(self, inbox):
"""
Connects the ``Piper`` instance to its upstream ``Pipers`` that should
be given as a sequence. This connects this ``Piper.inbox`` with the
upstream ``Piper.outbox`` respecting any "consume", "spawn" and
"produce" arguments.
Argumen... |
Attempts to cleanly stop the ``Piper`` instance. A ``Piper`` is
"started" if its ``NuMap`` instance is "started". Non-parallel
``Pipers`` do not have to be started or stopped. An ``NuMap`` instance
can be stopped by triggering its stopping procedure and retrieving
results from the ``... | def stop(self, forced=False, **kwargs):
"""
Attempts to cleanly stop the ``Piper`` instance. A ``Piper`` is
"started" if its ``NuMap`` instance is "started". Non-parallel
``Pipers`` do not have to be started or stopped. An ``NuMap`` instance
can be stopped by triggering its st... |
Disconnects the ``Piper`` instance from its upstream ``Pipers`` or
input data if the ``Piper`` is the input node of a pipeline.
Arguments:
- forced(``bool``) [default: ``False``] If ``True`` the ``Piper`` will
try to forcefully remove all tasks (including the spa... | def disconnect(self, forced=False):
"""
Disconnects the ``Piper`` instance from its upstream ``Pipers`` or
input data if the ``Piper`` is the input node of a pipeline.
Arguments:
- forced(``bool``) [default: ``False``] If ``True`` the ``Piper`` will
... |
Returns the next result. If no result is availble within the specified
(during construction) "timeout" then a ``PiperError`` which wraps a
``TimeoutError`` is **returned**.
If the result is a ``WorkerError`` it is also wrapped in a
``PiperError`` and is returned or raised if "debug"... | def next(self):
"""
Returns the next result. If no result is availble within the specified
(during construction) "timeout" then a ``PiperError`` which wraps a
``TimeoutError`` is **returned**.
If the result is a ``WorkerError`` it is also wrapped in a
``PiperError`` ... |
(internal) inject/replace all functions into a rpyc connection object. | def _inject(self, conn):
"""
(internal) inject/replace all functions into a rpyc connection object.
"""
# provide PAPY_DEFAULTS remotely
# provide PAPY_RUNTIME remotely
if not 'PAPY_INJECTED' in conn.namespace:
_inject_func(get_defaults, conn)
... |
Returns the next sequence of results, given stride and n. | def next(self):
"""
Returns the next sequence of results, given stride and n.
"""
try:
results = self._stride_buffer.pop()
except (IndexError, AttributeError):
self._rebuffer()
results = self._stride_buffer.pop()
if not results... |
Returns the next result from the chained iterables given ``"stride"``. | def next(self):
"""
Returns the next result from the chained iterables given ``"stride"``.
"""
if self.s:
self.s -= 1
else:
self.s = self.stride - 1
self.i = (self.i + 1) % self.l # new iterable
return self.iterables[self.i].ne... |
(very internal) refill the repeat buffer | def _rebuffer(self):
"""
(very internal) refill the repeat buffer
"""
results = []
exceptions = []
for i in xrange(self.stride):
try:
results.append(self.iterable.next())
exceptions.append(False)
except Exception, ex... |
(very internal) returns the next result, given ``"stride"`` and ``"n"``. | def next(self):
"""
(very internal) returns the next result, given ``"stride"`` and ``"n"``.
"""
try:
res, excp = self._stride_buffer.next()
except (StopIteration, AttributeError):
try:
self._stride_buffer = izip(*self._repeat_buff... |
(internal) refill the repeat buffer | def _rebuffer(self):
"""
(internal) refill the repeat buffer
"""
# collect a stride worth of results(result lists) or exceptions
results = []
exceptions = []
for i in xrange(self.stride):
try:
results.append(self.iterable.next(... |
(internal) returns the next result from the iterator if the piper is
started. | def next(self):
"""
(internal) returns the next result from the iterator if the piper is
started.
"""
if self.piper.imap is imap and \
self.piper.started is False:
raise StopIteration
else:
return self.iterator.next() |
(internal) returns the next result from the ``itertools.tee`` object for
the wrapped ``Piper`` instance or re-raises an ``Exception``. | def next(self):
"""
(internal) returns the next result from the ``itertools.tee`` object for
the wrapped ``Piper`` instance or re-raises an ``Exception``.
"""
# do not acquire lock if NuMap is not finished.
if self.finished:
raise StopIteration
... |
Get a list of results as CSV.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields to apply as string list.
:param limit: (optional) Limit returned list length.
:param page: (option... | def list_csv(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin
"""Get a list of results as CSV.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) S... |
Get updates of a running result via long-polling. If no updates are available, CDRouter waits up to 10 seconds before sending an empty response.
:param id: Result ID as an int.
:param update_id: (optional) Update ID as an int.
:return: :class:`results.Update <results.Update>` object
:r... | def updates(self, id, update_id=None): # pylint: disable=invalid-name,redefined-builtin
"""Get updates of a running result via long-polling. If no updates are available, CDRouter waits up to 10 seconds before sending an empty response.
:param id: Result ID as an int.
:param update_id: (optiona... |
Pause a running result.
:param id: Result ID as an int.
:param when: Must be string `end-of-test` or `end-of-loop`. | def pause(self, id, when=None): # pylint: disable=invalid-name,redefined-builtin
"""Pause a running result.
:param id: Result ID as an int.
:param when: Must be string `end-of-test` or `end-of-loop`.
"""
return self.service.post(self.base+str(id)+'/pause/', params={'when': when}... |
Unpause a running result.
:param id: Result ID as an int. | def unpause(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Unpause a running result.
:param id: Result ID as an int.
"""
return self.service.post(self.base+str(id)+'/unpause/') |
Export a result.
:param id: Result ID as an int.
:param exclude_captures: If bool `True`, don't export capture files
:rtype: tuple `(io.BytesIO, 'filename')` | def export(self, id, exclude_captures=False): # pylint: disable=invalid-name,redefined-builtin
"""Export a result.
:param id: Result ID as an int.
:param exclude_captures: If bool `True`, don't export capture files
:rtype: tuple `(io.BytesIO, 'filename')`
"""
return self... |
Bulk export a set of results.
:param ids: Int list of result IDs.
:rtype: tuple `(io.BytesIO, 'filename')` | def bulk_export(self, ids, exclude_captures=False):
"""Bulk export a set of results.
:param ids: Int list of result IDs.
:rtype: tuple `(io.BytesIO, 'filename')`
"""
return self.service.bulk_export(self.base, ids, params={'exclude_captures': exclude_captures}) |
Bulk copy a set of results.
:param ids: Int list of result IDs.
:return: :class:`results.Result <results.Result>` list | def bulk_copy(self, ids):
"""Bulk copy a set of results.
:param ids: Int list of result IDs.
:return: :class:`results.Result <results.Result>` list
"""
schema = ResultSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) |
Compute stats for all results.
:return: :class:`results.AllStats <results.AllStats>` object
:rtype: results.AllStats | def all_stats(self):
"""Compute stats for all results.
:return: :class:`results.AllStats <results.AllStats>` object
:rtype: results.AllStats
"""
schema = AllStatsSchema()
resp = self.service.post(self.base, params={'stats': 'all'})
return self.service.decode(sche... |
Compute stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.SetStats <results.SetStats>` object
:rtype: results.SetStats | def set_stats(self, ids):
"""Compute stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.SetStats <results.SetStats>` object
:rtype: results.SetStats
"""
schema = SetStatsSchema()
resp = self.service.post(self.base, params={'st... |
Compute diff stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.DiffStats <results.DiffStats>` object
:rtype: results.DiffStats | def diff_stats(self, ids):
"""Compute diff stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.DiffStats <results.DiffStats>` object
:rtype: results.DiffStats
"""
schema = DiffStatsSchema()
resp = self.service.post(self.base, p... |
Compute stats for a result.
:param id: Result ID as an int.
:return: :class:`results.SingleStats <results.SingleStats>` object
:rtype: results.SingleStats | def single_stats(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Compute stats for a result.
:param id: Result ID as an int.
:return: :class:`results.SingleStats <results.SingleStats>` object
:rtype: results.SingleStats
"""
schema = SingleStatsSchema()
... |
Compute progress stats for a result.
:param id: Result ID as an int.
:return: :class:`results.Progress <results.Progress>` object
:rtype: results.Progress | def progress_stats(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Compute progress stats for a result.
:param id: Result ID as an int.
:return: :class:`results.Progress <results.Progress>` object
:rtype: results.Progress
"""
schema = ProgressSchema()
... |
Compute summary stats for a result.
:param id: Result ID as an int.
:return: :class:`results.SummaryStats <results.SummaryStats>` object
:rtype: results.SummaryStats | def summary_stats(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Compute summary stats for a result.
:param id: Result ID as an int.
:return: :class:`results.SummaryStats <results.SummaryStats>` object
:rtype: results.SummaryStats
"""
schema = SummaryStat... |
Get a list of logdir files.
:param id: Result ID as an int.
:param filter: Filter to apply as string.
:param sort: Sort field to apply as string.
:return: :class:`results.LogDirFile <results.LogDirFile>` list | def list_logdir(self, id, filter=None, sort=None): # pylint: disable=invalid-name,redefined-builtin
"""Get a list of logdir files.
:param id: Result ID as an int.
:param filter: Filter to apply as string.
:param sort: Sort field to apply as string.
:return: :class:`results.LogDi... |
Download a logdir file.
:param id: Result ID as an int.
:param filename: Logdir filename as string.
:rtype: tuple `(io.BytesIO, 'filename')` | def get_logdir_file(self, id, filename): # pylint: disable=invalid-name,redefined-builtin
"""Download a logdir file.
:param id: Result ID as an int.
:param filename: Logdir filename as string.
:rtype: tuple `(io.BytesIO, 'filename')`
"""
resp = self.service.get(self.base... |
Download logdir archive in tgz or zip format.
:param id: Result ID as an int.
:param format: (optional) Format to download, must be string `zip` or `tgz`.
:param exclude_captures: If bool `True`, don't include capture files
:rtype: tuple `(io.BytesIO, 'filename')` | def download_logdir_archive(self, id, format='zip', exclude_captures=False): # pylint: disable=invalid-name,redefined-builtin
"""Download logdir archive in tgz or zip format.
:param id: Result ID as an int.
:param format: (optional) Format to download, must be string `zip` or `tgz`.
:pa... |
CERN logout view. | def logout():
"""CERN logout view."""
logout_url = REMOTE_APP['logout_url']
apps = current_app.config.get('OAUTHCLIENT_REMOTE_APPS')
if apps:
cern_app = apps.get('cern', REMOTE_APP)
logout_url = cern_app['logout_url']
return redirect(logout_url, code=302) |
Return a remote application based with given client ID. | def find_remote_by_client_id(client_id):
"""Return a remote application based with given client ID."""
for remote in current_oauthclient.oauth.remote_apps.values():
if remote.name == 'cern' and remote.consumer_key == client_id:
return remote |
Prepare list of allowed group names.
:param groups: The complete list of groups.
:returns: A filtered list of groups. | def fetch_groups(groups):
"""Prepare list of allowed group names.
:param groups: The complete list of groups.
:returns: A filtered list of groups.
"""
hidden_groups = current_app.config.get(
'OAUTHCLIENT_CERN_HIDDEN_GROUPS', OAUTHCLIENT_CERN_HIDDEN_GROUPS)
hidden_groups_re = current_app... |
Return a dict with extra data retrieved from cern oauth. | def fetch_extra_data(resource):
"""Return a dict with extra data retrieved from cern oauth."""
person_id = resource.get('PersonID', [None])[0]
identity_class = resource.get('IdentityClass', [None])[0]
department = resource.get('Department', [None])[0]
return dict(
person_id=person_id,
... |
Fetch account groups and extra data from resource if necessary. | def account_groups_and_extra_data(account, resource,
refresh_timedelta=None):
"""Fetch account groups and extra data from resource if necessary."""
updated = datetime.utcnow()
modified_since = updated
if refresh_timedelta is not None:
modified_since += refresh_t... |
Extend identity with roles based on CERN groups. | def extend_identity(identity, groups):
"""Extend identity with roles based on CERN groups."""
provides = set([UserNeed(current_user.email)] + [
RoleNeed('{0}@cern.ch'.format(name)) for name in groups
])
identity.provides |= provides
session[OAUTHCLIENT_CERN_SESSION_KEY] = provides |
Prepare new mapping with 'Value's groupped by 'Type'. | def get_dict_from_response(response):
"""Prepare new mapping with 'Value's groupped by 'Type'."""
result = {}
if getattr(response, '_resp') and response._resp.code > 400:
return result
for i in response.data:
# strip the schema from the key
k = i['Type'].replace(REMOTE_APP_RESOU... |
Query CERN Resources to get user info and groups. | def get_resource(remote):
"""Query CERN Resources to get user info and groups."""
cached_resource = session.pop('cern_resource', None)
if cached_resource:
return cached_resource
response = remote.get(REMOTE_APP_RESOURCE_API_URL)
dict_response = get_dict_from_response(response)
session['... |
Retrieve remote account information used to find local user. | def account_info(remote, resp):
"""Retrieve remote account information used to find local user."""
resource = get_resource(remote)
valid_identities = current_app.config.get(
'OAUTHCLIENT_CERN_ALLOWED_IDENTITY_CLASSES',
OAUTHCLIENT_CERN_ALLOWED_IDENTITY_CLASSES
)
identity_class = res... |
Handle unlinking of remote account. | def disconnect_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account."""
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
account = RemoteAccount.get(user_id=current_user.get_id(),
client_id=remote.consumer_key)
... |
Perform additional setup after user have been logged in. | def account_setup(remote, token, resp):
"""Perform additional setup after user have been logged in."""
resource = get_resource(remote)
with db.session.begin_nested():
person_id = resource.get('PersonID', [None])
external_id = resource.get('uidNumber', person_id)[0]
# Set CERN perso... |
Store groups in session whenever identity changes.
:param identity: The user identity where information are stored. | def on_identity_changed(sender, identity):
"""Store groups in session whenever identity changes.
:param identity: The user identity where information are stored.
"""
if isinstance(identity, AnonymousIdentity):
return
client_id = current_app.config['CERN_APP_CREDENTIALS']['consumer_key']
... |
Get RemoteAccount object for user.
:param user_id: User id
:param client_id: Client id.
:returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance. | def get(cls, user_id, client_id):
"""Get RemoteAccount object for user.
:param user_id: User id
:param client_id: Client id.
:returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance.
"""
return cls.query.filter_by(
user_id=user_id,
c... |
Create new remote account for user.
:param user_id: User id.
:param client_id: Client id.
:param extra_data: JSON-serializable dictionary of any extra data that
needs to be save together with this link.
:returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance. | def create(cls, user_id, client_id, extra_data):
"""Create new remote account for user.
:param user_id: User id.
:param client_id: Client id.
:param extra_data: JSON-serializable dictionary of any extra data that
needs to be save together with this link.
:returns: A ... |
Update token with new values.
:param token: The token value.
:param secret: The secret key. | def update_token(self, token, secret):
"""Update token with new values.
:param token: The token value.
:param secret: The secret key.
"""
if self.access_token != token or self.secret != secret:
with db.session.begin_nested():
self.access_token = token... |
Get RemoteToken for user.
:param user_id: The user id.
:param client_id: The client id.
:param token_type: The token type. (Default: ``''``)
:param access_token: If set, will filter also by access token.
(Default: ``None``)
:returns: A :class:`invenio_oauthclient.mod... | def get(cls, user_id, client_id, token_type='', access_token=None):
"""Get RemoteToken for user.
:param user_id: The user id.
:param client_id: The client id.
:param token_type: The token type. (Default: ``''``)
:param access_token: If set, will filter also by access token.
... |
Get RemoteAccount object for token.
:param client_id: The client id.
:param access_token: The access token.
:param token_type: The token type. (Default: ``''``)
:returns: A :class:`invenio_oauthclient.models.RemoteToken` instance. | def get_by_token(cls, client_id, access_token, token_type=''):
"""Get RemoteAccount object for token.
:param client_id: The client id.
:param access_token: The access token.
:param token_type: The token type. (Default: ``''``)
:returns: A :class:`invenio_oauthclient.models.Remot... |
Create a new access token.
.. note:: Creates RemoteAccount as well if it does not exists.
:param user_id: The user id.
:param client_id: The client id.
:param token: The token.
:param secret: The secret key.
:param token_type: The token type. (Default: ``''``)
:... | def create(cls, user_id, client_id, token, secret,
token_type='', extra_data=None):
"""Create a new access token.
.. note:: Creates RemoteAccount as well if it does not exists.
:param user_id: The user id.
:param client_id: The client id.
:param token: The token.... |
Bulk export a set of configs, devices, packages and results.
:param config_ids: (optional) Int list of config IDs.
:param device_ids: (optional) Int list of device IDs.
:param package_ids: (optional) Int list of package IDs.
:param result_ids: (optional) Int list of result IDs.
... | def bulk_export(self, config_ids=None, device_ids=None, package_ids=None, result_ids=None, exclude_captures=False):
"""Bulk export a set of configs, devices, packages and results.
:param config_ids: (optional) Int list of config IDs.
:param device_ids: (optional) Int list of device IDs.
... |
create the report directory and return the directory name | def _init_report(self):
"""create the report directory and return the directory name"""
self.sections = []
self.section_names = []
# if the directory already exists, print a warning
try:
if os.path.isdir(self.directory) is False:
if self.verbose:
... |
Returns a time stamp | def get_time_now(self):
"""Returns a time stamp"""
import datetime
import getpass
username = getpass.getuser()
# this is not working on some systems: os.environ["USERNAME"]
timenow = str(datetime.datetime.now())
timenow = timenow.split('.')[0]
msg = '<div ... |
Returns dependencies of the pipeline as an HTML/XML table
The dependencies are the python dependencies as returned by
pkg_resource module. | def get_table_dependencies(self, package="reports"):
"""Returns dependencies of the pipeline as an HTML/XML table
The dependencies are the python dependencies as returned by
pkg_resource module.
"""
dependencies = easydev.get_dependencies(package)
# TODO: Could re-use n... |
Track a field on a related model | def _track_class_related_field(cls, field):
""" Track a field on a related model """
# field = field on current model
# related_field = field on related model
(field, related_field) = field.split('__', 1)
field_obj = cls._meta.get_field(field)
related_cls = field_obj.remote_field.model
relat... |
Track a field on the current model | def _track_class_field(cls, field):
""" Track a field on the current model """
if '__' in field:
_track_class_related_field(cls, field)
return
# Will raise FieldDoesNotExist if there is an error
cls._meta.get_field(field)
# Detect m2m fields changes
if isinstance(cls._meta.get_fi... |
Track fields on the specified model | def _track_class(cls, fields):
""" Track fields on the specified model """
# Small tests to ensure everything is all right
assert not getattr(cls, '_is_tracked', False)
for field in fields:
_track_class_field(cls, field)
_add_signals_to_cls(cls)
# Mark the class as tracked
cls._is... |
Add a method to get the tracking url of an object. | def _add_get_tracking_url(cls):
""" Add a method to get the tracking url of an object. """
def get_tracking_url(self):
""" return url to tracking view in admin panel """
url = reverse('admin:tracking_fields_trackingevent_changelist')
object_id = '{0}%3A{1}'.format(
ContentTyp... |
Decorator used to track changes on Model's fields.
:Example:
>>> @track('name')
... class Human(models.Model):
... name = models.CharField(max_length=30) | def track(*fields):
"""
Decorator used to track changes on Model's fields.
:Example:
>>> @track('name')
... class Human(models.Model):
... name = models.CharField(max_length=30)
"""
def inner(cls):
_track_class(cls, fields)
_add_get_tracking_url(cls)
... |
Indent a value by `n` `character`s
:param value: string to indent
:param n: number of characters to indent by
:param character: character to indent with | def indent(value, n=2, character=' '):
"""
Indent a value by `n` `character`s
:param value: string to indent
:param n: number of characters to indent by
:param character: character to indent with
"""
prefix = n * character
return '\n'.join(prefix + line for line in value.splitlines()) |
Parses the nano.rpc.Client for methods that have a __doc_meta__ attribute
and saves generated docs | def extract_docs():
"""
Parses the nano.rpc.Client for methods that have a __doc_meta__ attribute
and saves generated docs
"""
methods = []
def _key(entry):
return
sorted_entries = sorted(Client.__dict__.items(), key=lambda x: x[0])
tree = {}
meta_key = '__doc_meta__'
... |
Wrapper that tests the type of _session.
Purpose: This decorator function is used by all functions within
| the Jaide class that interact with a device to ensure the
| proper session type is in use. If it is not, it will
| attempt to migrate _session to that type befor... | def check_instance(function):
""" Wrapper that tests the type of _session.
Purpose: This decorator function is used by all functions within
| the Jaide class that interact with a device to ensure the
| proper session type is in use. If it is not, it will
| atte... |
Move _shell to the shell from the command line interface (CLI). | def cli_to_shell(self):
""" Move _shell to the shell from the command line interface (CLI). """
if self._in_cli:
self._shell.send("start shell\n")
time.sleep(2)
self._shell.recv(9999)
self._in_cli = False
return True
return False |
Perform a commit operation.
Purpose: Executes a commit operation. All parameters are optional.
| commit confirm and commit at are mutually exclusive. All
| the others can be used with each other and commit confirm/at.
@param commands: A string or list of multiple commands... | def commit(self, commands="", confirmed=None, comment=None,
at_time=None, synchronize=False, req_format='text'):
""" Perform a commit operation.
Purpose: Executes a commit operation. All parameters are optional.
| commit confirm and commit at are mutually exclusive. All
... |
Execute a commit check operation.
Purpose: This method will take in string of multiple commands,
| and perform and 'commit check' on the device to ensure
| the commands are syntactically correct. The response can
| be formatted as text or as xml.
@param com... | def commit_check(self, commands="", req_format="text"):
""" Execute a commit check operation.
Purpose: This method will take in string of multiple commands,
| and perform and 'commit check' on the device to ensure
| the commands are syntactically correct. The response can
... |
Execute a 'show | compare' against the specified commands.
Purpose: This method will take in string of multiple commands,
| and perform and 'show | compare' on the device to show the
| differences between the active running configuration and
| the changes proposed b... | def compare_config(self, commands="", req_format="text"):
""" Execute a 'show | compare' against the specified commands.
Purpose: This method will take in string of multiple commands,
| and perform and 'show | compare' on the device to show the
| differences between the ac... |
Establish a connection to the device.
Purpose: This method is used to make a connection to the junos
| device. The internal property conn_type is what
| determines the type of connection we make to the device.
| - 'paramiko' is used for operational commands (to allo... | def connect(self):
""" Establish a connection to the device.
Purpose: This method is used to make a connection to the junos
| device. The internal property conn_type is what
| determines the type of connection we make to the device.
| - 'paramiko' is used fo... |
Echo status of an SCP operation.
Purpose: Callback function for an SCP operation. Used to show
| the progress of an actively running copy. This directly
| prints to stdout, one line for each file as it's copied.
| The parameters received by this function are those r... | def _copy_status(self, filename, size, sent):
""" Echo status of an SCP operation.
Purpose: Callback function for an SCP operation. Used to show
| the progress of an actively running copy. This directly
| prints to stdout, one line for each file as it's copied.
... |
Pull basic device information.
Purpose: This function grabs the hostname, model, running version, and
| serial number of the device.
@returns: The output that should be shown to the user.
@rtype: str | def device_info(self):
""" Pull basic device information.
Purpose: This function grabs the hostname, model, running version, and
| serial number of the device.
@returns: The output that should be shown to the user.
@rtype: str
"""
# get hostname, model, a... |
Generate configuration differences with a second device.
Purpose: Open a second ncclient.manager.Manager with second_host, and
| and pull the configuration from it. We then use difflib to
| get the delta between the two, and yield the results.
@param second_host: the IP o... | def diff_config(self, second_host, mode='stanza'):
""" Generate configuration differences with a second device.
Purpose: Open a second ncclient.manager.Manager with second_host, and
| and pull the configuration from it. We then use difflib to
| get the delta between the tw... |
Close the connection(s) to the device.
Purpose: Closes the current connection(s) to the device, no matter
| what types exist.
@returns: None
@rtype: None | def disconnect(self):
""" Close the connection(s) to the device.
Purpose: Closes the current connection(s) to the device, no matter
| what types exist.
@returns: None
@rtype: None
"""
if self._shell:
self._shell.close()
self._shell... |
Parse the extensive xml output of an interface and yield errors.
Purpose: Takes the xml output of 'show interfaces extensive' for a
| given interface and yields the error types that have a
| significant number of errors.
@param interface: The xml output of the 'sh int ext... | def _error_parse(self, interface, face):
""" Parse the extensive xml output of an interface and yield errors.
Purpose: Takes the xml output of 'show interfaces extensive' for a
| given interface and yields the error types that have a
| significant number of errors.
... |
Pull health and alarm information from the device.
Purpose: Grab the cpu/mem usage, system/chassis alarms, top 5
| processes, and states if the primary/backup partitions are on
| different versions.
@returns: The output that should be shown to the user.
@rtype: st... | def health_check(self):
""" Pull health and alarm information from the device.
Purpose: Grab the cpu/mem usage, system/chassis alarms, top 5
| processes, and states if the primary/backup partitions are on
| different versions.
@returns: The output that should be s... |
Parse 'show interfaces extensive' and return interfaces with errors.
Purpose: This function is called for the -e flag. It will let the user
| know if there are any interfaces with errors, and what those
| interfaces are.
@returns: The output that should be shown to the us... | def interface_errors(self):
""" Parse 'show interfaces extensive' and return interfaces with errors.
Purpose: This function is called for the -e flag. It will let the user
| know if there are any interfaces with errors, and what those
| interfaces are.
@returns: T... |
Lock the candidate config. Requires ncclient.manager.Manager. | def lock(self):
""" Lock the candidate config. Requires ncclient.manager.Manager. """
if isinstance(self._session, manager.Manager):
self._session.lock() |
Execute an operational mode command.
Purpose: Used to send an operational mode command to the connected
| device. This requires and uses a paramiko.SSHClient() as
| the handler so that we can easily pass and allow all pipe
| commands to be used.
|
... | def op_cmd(self, command, req_format='text', xpath_expr=""):
""" Execute an operational mode command.
Purpose: Used to send an operational mode command to the connected
| device. This requires and uses a paramiko.SSHClient() as
| the handler so that we can easily pass and ... |
Makes an SCP pull request for the specified file(s)/dir.
Purpose: By leveraging the _scp private variable, we make an scp pull
| request to retrieve file(s) from a Junos device.
@param src: string containing the source file or directory
@type src: str
@param dest: destin... | def scp_pull(self, src, dest, progress=False, preserve_times=True):
""" Makes an SCP pull request for the specified file(s)/dir.
Purpose: By leveraging the _scp private variable, we make an scp pull
| request to retrieve file(s) from a Junos device.
@param src: string containing... |
Purpose: Makes an SCP push request for the specified file(s)/dir.
@param src: string containing the source file or directory
@type src: str
@param dest: destination string of where to put the file(s)/dir
@type dest: str
@param progress: set to `True` to have the progress callbac... | def scp_push(self, src, dest, progress=False, preserve_times=True):
""" Purpose: Makes an SCP push request for the specified file(s)/dir.
@param src: string containing the source file or directory
@type src: str
@param dest: destination string of where to put the file(s)/dir
@ty... |
Execute a shell command.
Purpose: Used to send a shell command to the connected device.
| This uses the self._shell instance, which should be a
| paramiko.Channel object, instead of a SSHClient.
| This is because we cannot send shell commands to the
|... | def shell_cmd(self, command=""):
""" Execute a shell command.
Purpose: Used to send a shell command to the connected device.
| This uses the self._shell instance, which should be a
| paramiko.Channel object, instead of a SSHClient.
| This is because we canno... |
Unlock the candidate config.
Purpose: Unlocks the candidate configuration, so that other people can
| edit the device. Requires the _session private variable to be
| a type of a ncclient.manager.Manager. | def unlock(self):
""" Unlock the candidate config.
Purpose: Unlocks the candidate configuration, so that other people can
| edit the device. Requires the _session private variable to be
| a type of a ncclient.manager.Manager.
"""
if isinstance(self._session... |
Test:
>>> from common_cache import Cache
>>> import time
>>> cache = Cache(expire=1, cleanup_func=basic_cleanup, regularly_cleanup=False)
>>> cache.put('a', value=0)
>>> cache.put('b', value=1)
>>> cache.put('c', value=2)
>>> cache.put('d', value=3, expire=3)
>>> cache.size()
4
... | def basic_cleanup(self):
"""
Test:
>>> from common_cache import Cache
>>> import time
>>> cache = Cache(expire=1, cleanup_func=basic_cleanup, regularly_cleanup=False)
>>> cache.put('a', value=0)
>>> cache.put('b', value=1)
>>> cache.put('c', value=2)
>>> cache.put('d', value=3, expi... |
Wraps an existing method on an object with the provided generator, which
will be "sent" the value when it yields control.
::
>>> def ensure_primary_key_is_set():
... assert model.pk is None
... saved = yield
... aasert model is saved
... assert model.pk ... | def intercept(obj, methodname, wrapper):
"""
Wraps an existing method on an object with the provided generator, which
will be "sent" the value when it yields control.
::
>>> def ensure_primary_key_is_set():
... assert model.pk is None
... saved = yield
... a... |
Should be used as a decorator to *attach* import statments to function
definitions. These imports are added to the global (i.e. module-level of
the decorated function) namespace.
Two forms of import statements are supported (in the following examples
``foo``, ``bar``, ``oof, and ``rab`` are mo... | def imports(modules, forgive=False):
"""
Should be used as a decorator to *attach* import statments to function
definitions. These imports are added to the global (i.e. module-level of
the decorated function) namespace.
Two forms of import statements are supported (in the following example... |
(internal) Function which is executed by worker pool processes or threads.
It waits for tasks (function, data, arguments) at the input queue "inqueue"
evaluates the result and passes it to the output queue "outqueue". It
optionally evaluates the function on a remote host. | def _pool_worker(inqueue, outqueue, host=None):
"""
(internal) Function which is executed by worker pool processes or threads.
It waits for tasks (function, data, arguments) at the input queue "inqueue"
evaluates the result and passes it to the output queue "outqueue". It
optionally evaluates the f... |
(internal) injects a function object into a RPyC connection object. | def _inject_func(func, conn):
"""
(internal) injects a function object into a RPyC connection object.
"""
name = func.__name__
if not name in conn.namespace:
if isbuiltin(func):
inject_code = '%s = %s' % (name, name)
elif isfunction(func):
inject_code = getsou... |
(internal) Intended to be run in a seperate thread. Feeds tasks into
to the pool whenever semaphore permits. Finishes if self._stopping is
set. | def _pool_put(pool_semaphore, tasks, put_to_pool_in, pool_size, id_self, \
is_stopping):
"""
(internal) Intended to be run in a seperate thread. Feeds tasks into
to the pool whenever semaphore permits. Finishes if self._stopping is
set.
"""
log.debug(... |
(internal) Intended to be run in a separate thread and take results from
the pool and put them into queues depending on the task of the result.
It finishes if it receives termination-sentinels from all pool workers. | def _pool_get(get, results, next_available, task_next_lock, to_skip, \
task_num, pool_size, id_self):
"""
(internal) Intended to be run in a separate thread and take results from
the pool and put them into queues depending on the task of the result.
It finishes if it ... |
(internal) starts input and output pool queue manager threads. | def _start_managers(self):
"""
(internal) starts input and output pool queue manager threads.
"""
self._task_queue = _Weave(self._tasks, self.stride)
# here we determine the size of the maximum memory consumption
self._semaphore_value = (self.buffer or (len(self._tasks) *... |
(internal) starts **worker pool** threads or processes. | def _start_workers(self):
"""
(internal) starts **worker pool** threads or processes.
"""
# creating the pool of worker process or threads
log.debug('%s starts a %s-pool of %s workers.' % \
(self, self.worker_type, self.worker_num))
self.pool = []
... |
(internal) stops input and output pool queue manager threads. | def _stop(self):
"""
(internal) stops input and output pool queue manager threads.
"""
if self._started.isSet():
# join threads
self._pool_getter.join()
self._pool_putter.join()
for worker in self.pool:
worker.join()
... |
Adds a **task** to evaluate. A **task** is jointly a function or
callable an iterable with optional arguments and keyworded arguments.
The iterable can be the result iterator of a previously added **task**
(to the same or to a different ``NuMap`` instance).
Arguments:
... | def add_task(self, func, iterable, args=None, kwargs=None, timeout=None, \
block=True, track=False):
"""
Adds a **task** to evaluate. A **task** is jointly a function or
callable an iterable with optional arguments and keyworded arguments.
The iterable can be the result... |
Removes a previously added **task** from the ``NuMap`` instance.
Arguments:
- number (``int`` or ``True``) A positive integer specifying the
number of **tasks** to pop. If number is set ``True`` all **tasks**
will be popped. | def pop_task(self, number):
"""
Removes a previously added **task** from the ``NuMap`` instance.
Arguments:
- number (``int`` or ``True``) A positive integer specifying the
number of **tasks** to pop. If number is set ``True`` all **tasks**
w... |
Returns an iterator which results are limited to one **task**. The
default iterator the one which e.g. will be used in a for loop is the
iterator for the first task (task =0). The returned iterator is a
``_NuMapTask`` instance.
Compare::
for result_from_task_0 in ... | def get_task(self, task=0, timeout=None, block=True):
"""
Returns an iterator which results are limited to one **task**. The
default iterator the one which e.g. will be used in a for loop is the
iterator for the first task (task =0). The returned iterator is a
``_NuMapTask`` in... |
Starts the processes or threads in the internal pool and the threads,
which manage the **worker pool** input and output queues. The
**starting mode** is split into **two stages**, which can be initiated
seperately. After the first stage the **worker pool** processes or
threads are s... | def start(self, stages=(1, 2)):
"""
Starts the processes or threads in the internal pool and the threads,
which manage the **worker pool** input and output queues. The
**starting mode** is split into **two stages**, which can be initiated
seperately. After the first stage the ... |
Stops an ``NuMap`` instance. If the list of end tasks is specified *via*
the "ends" argument a call to ``NuMap.stop`` will block the calling
thread and retrieve (discards) a maximum of 2 * stride of results. This
will stop the worker pool and the threads which manage its input and
ou... | def stop(self, ends=None, forced=False):
"""
Stops an ``NuMap`` instance. If the list of end tasks is specified *via*
the "ends" argument a call to ``NuMap.stop`` will block the calling
thread and retrieve (discards) a maximum of 2 * stride of results. This
will stop the worke... |
Returns the next result for the given **task**. Defaults to ``0``, which
is the first **task**. If multiple chained tasks are evaluated then the
next method of only the last should be called directly.
Arguments:
- timeout (``float``) Number of seconds to wait... | def next(self, timeout=None, task=0, block=True):
"""
Returns the next result for the given **task**. Defaults to ``0``, which
is the first **task**. If multiple chained tasks are evaluated then the
next method of only the last should be called directly.
Argumen... |
Returns the next element or raises ``StopIteration`` if stopped. | def next(self):
"""
Returns the next element or raises ``StopIteration`` if stopped.
"""
# need new iterable?
if self.r == self.repeats:
self.i = (self.i + 1) % self.lenght
self.r = 0
self.r += 1
if self.stopping and self.i == 0 and self.r... |
Returns a result if availble within "timeout" else raises a
``TimeoutError`` exception. See documentation for ``NuMap.next``. | def next(self):
"""
Returns a result if availble within "timeout" else raises a
``TimeoutError`` exception. See documentation for ``NuMap.next``.
"""
return self.iterator.next(task=self.task, timeout=self.timeout,
block=self.bl... |
Write language-specific script template to file.
Arguments:
- fn(``string``) path to save the template to
- lang('python', 'bash') which programming language | def write_template(fn, lang="python"):
"""
Write language-specific script template to file.
Arguments:
- fn(``string``) path to save the template to
- lang('python', 'bash') which programming language
"""
with open(fn, "wb") as fh:
if lang == "python":
fh.wri... |
Execute arbitrary scripts.
Arguments:
- cfg(``dict``) script configuartion dictionary | def script(inbox, cfg):
"""
Execute arbitrary scripts.
Arguments:
- cfg(``dict``) script configuartion dictionary
"""
script_name = cfg["id"]
script_id = str(abs(hash((cfg["id"],) + tuple(inbox[0].values()))))[0:8]
# LOG.log(mp.DEFAULT, "@papy;script %s:%s started" % (script_na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.