INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Get RemoteAccount object for user. | 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. | 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. | 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. | 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. | 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. | 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. | 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 | 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. | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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: | 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 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 modules not classes or functions ):: | 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 ). | 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:: | 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 started and the NuMap. _started ... | 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 output queues respectively. If the ends arg... | 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 until a TimeoutError is raised. - task ( int ) id of the task f... | 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. | 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. | 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... |
Edit a job. | def edit(self, resource):
"""Edit a job.
:param resource: :class:`jobs.Job <jobs.Job>` object
:return: :class:`jobs.Job <jobs.Job>` object
:rtype: jobs.Job
"""
schema = JobSchema(exclude=('id', 'status', 'options', 'package_name', 'config_name', 'device_name', 'result_id... |
Launch a new job. | def launch(self, resource):
"""Launch a new job.
:param resource: :class:`jobs.Job <jobs.Job>` object
:return: :class:`jobs.Job <jobs.Job>` object
:rtype: jobs.Job
"""
schema = JobSchema(exclude=('id', 'status', 'package_name', 'config_name', 'device_name', 'result_id', ... |
Bulk launch a set of jobs. | def bulk_launch(self, jobs=None, filter=None, all=False): # pylint: disable=redefined-builtin
"""Bulk launch a set of jobs.
:param jobs: :class:`jobs.Job <jobs.Job>` list
:param filter: (optional) Filters to apply as a string list.
:param all: (optional) Apply to all if bool `True`.
... |
G square test for a binary data. | def g_square_bin(dm, x, y, s):
"""G square test for a binary data.
Args:
dm: the data matrix to be used (as a numpy.ndarray).
x: the first node (as an integer).
y: the second node (as an integer).
s: the set of neibouring nodes of x and y (as a set()).
Returns:
p_va... |
Get a highlight. | def get(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin
"""Get a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param line: Line number in TestResult's logfile as an int.
:return: :class:`highlights.Highlight <hig... |
Create or edit a highlight. | def create_or_edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin
"""Create or edit a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param resource: :class:`highlights.Highlight <highlights.Highlight>` object
... |
Create a highlight. | def create(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin
"""Create a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param resource: :class:`highlights.Highlight <highlights.Highlight>` object
:return: :class... |
Edit a highlight. | def edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin
"""Edit a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param resource: :class:`highlights.Highlight <highlights.Highlight>` object
:return: :class:`hi... |
Delete a highlight. | def delete(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin
"""Delete a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param line: Line number in TestResult's logfile as an int.
"""
return self.service.dele... |
Setup blueprint. | def post_ext_init(state):
"""Setup blueprint."""
app = state.app
app.config.setdefault(
'OAUTHCLIENT_SITENAME',
app.config.get('THEME_SITENAME', 'Invenio'))
app.config.setdefault(
'OAUTHCLIENT_BASE_TEMPLATE',
app.config.get('BASE_TEMPLATE',
'inveni... |
Send user to remote application for authentication. | def login(remote_app):
"""Send user to remote application for authentication."""
oauth = current_app.extensions['oauthlib.client']
if remote_app not in oauth.remote_apps:
return abort(404)
# Get redirect target in safe manner.
next_param = get_safe_redirect_target(arg='next')
# Redire... |
Authorized handler callback. | def authorized(remote_app=None):
"""Authorized handler callback."""
if remote_app not in current_oauthclient.handlers:
return abort(404)
state_token = request.args.get('state')
# Verify state parameter
try:
assert state_token
# Checks authenticity and integrity of state and... |
Extra signup step. | def signup(remote_app):
"""Extra signup step."""
if remote_app not in current_oauthclient.signup_handlers:
return abort(404)
res = current_oauthclient.signup_handlers[remote_app]['view']()
return abort(404) if res is None else res |
Disconnect user from remote application. | def disconnect(remote_app):
"""Disconnect user from remote application.
Removes application as well as associated information.
"""
if remote_app not in current_oauthclient.disconnect_handlers:
return abort(404)
ret = current_oauthclient.disconnect_handlers[remote_app]()
db.session.comm... |
Returns the checksum in bytes for an address in bytes | def address_checksum(address):
"""
Returns the checksum in bytes for an address in bytes
"""
address_bytes = address
h = blake2b(digest_size=5)
h.update(address_bytes)
checksum = bytearray(h.digest())
checksum.reverse()
return checksum |
Generates a deterministic keypair from seed based on index | def keypair_from_seed(seed, index=0):
"""
Generates a deterministic keypair from `seed` based on `index`
:param seed: bytes value of seed
:type seed: bytes
:param index: offset from seed
:type index: int
:return: dict of the form: {
'private': private_key
'public': public_... |
Verifies signature is correct for a message signed with public_key | def verify_signature(message, signature, public_key):
"""
Verifies `signature` is correct for a `message` signed with `public_key`
:param message: message to check
:type message: bytes
:param signature: signature to check
:type signature: bytes
:param public_key: public_key to check
:... |
Signs a message using private_key and public_key | def sign_message(message, private_key, public_key=None):
"""
Signs a `message` using `private_key` and `public_key`
.. warning:: Not safe to use with secret keys or secret data. See module
docstring. This function should be used for testing only.
:param message: the message to sign
... |
Check the CDRouter Support Lounge for eligible upgrades using your Support Lounge email & password. | def check_for_lounge_upgrade(self, email, password):
"""Check the CDRouter Support Lounge for eligible upgrades using your
Support Lounge email & password.
:param email: CDRouter Support Lounge email as a string.
:param password: CDRouter Support Lounge password as a string.
:re... |
Download & install an upgrade from the CDRouter Support Lounge using your Support Lounge email & password. Please note that any running tests will be stopped. | def lounge_upgrade(self, email, password, release_id):
"""Download & install an upgrade from the CDRouter Support Lounge
using your Support Lounge email & password. Please note that any
running tests will be stopped.
:param email: CDRouter Support Lounge email as a string.
:para... |
Download & install a license for your CDRouter system from the CDRouter Support Lounge. | def lounge_update_license(self):
"""Download & install a license for your CDRouter system from the
CDRouter Support Lounge.
:return: :class:`system.Upgrade <system.Upgrade>` object
:rtype: system.Upgrade
"""
schema = UpgradeSchema()
resp = self.service.post(self.... |
Update the license on your CDRouter system manually by uploading a. lic license from the CDRouter Support Lounge. | def manual_update_license(self, fd, filename='cdrouter.lic'):
"""Update the license on your CDRouter system manually by uploading a
.lic license from the CDRouter Support Lounge.
:param fd: File-like object to upload.
:param filename: (optional) Filename to use for license as string.
... |
Get system disk space usage. | def space(self):
"""Get system disk space usage.
:return: :class:`system.Space <system.Space>` object
:rtype: system.Space
"""
schema = SpaceSchema()
resp = self.service.get(self.base+'space/')
return self.service.decode(schema, resp) |
Get system interfaces. | def interfaces(self, addresses=False):
"""Get system interfaces.
:param addresses: (optional) If bool `True`, include interface addresses.
:return: :class:`system.Interface <system.Interface>` list
"""
schema = InterfaceSchema()
resp = self.service.get(self.base+'interfa... |
Get preferences from/ usr/ cdrouter - data/ etc/ config. yml. | def get_preferences(self):
"""Get preferences from /usr/cdrouter-data/etc/config.yml.
:return: :class:`system.Preferences <system.Preferences>` object
:rtype: system.Preferences
"""
schema = PreferencesSchema()
resp = self.service.get(self.base+'preferences/')
re... |
Edit preferences in/ usr/ cdrouter - data/ etc/ config. yml. | def edit_preferences(self, resource):
"""Edit preferences in /usr/cdrouter-data/etc/config.yml.
:param resource: :class:`system.Preferences <system.Preferences>` object
:return: :class:`system.Preferences <system.Preferences>` object
:rtype: system.Preferences
"""
schema... |
Save fields value only for non - m2m fields. | def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), F... |
Check if some tracked fields have changed | def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, ... |
Check if some related tracked fields have changed | def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
... |
Create a new event getting the use if django - cuser is available. | def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user... |
Create a TrackedFieldModification for the instance. | def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: Th... |
Create a TrackingEvent and TrackedFieldModification for a CREATE event. | def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create... |
Create a TrackingEvent and TrackedFieldModification for an UPDATE event. | def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
... |
Create a TrackingEvent and TrackedFieldModification for an UPDATE event for each related model. | def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_field... |
Get the field name from a model and a sender from m2m_changed signal. | def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
... |
Create the TrackedEvent and it s related TrackedFieldModification for a m2m modification. The first thing needed is to get the m2m field on the object being tracked. The current related objects are then taken ( old_value ). The new value is calculated in function of action ( new_value ). The TrackedFieldModification is... | def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old... |
Post save detect creation or changes and log them. We need post_save to have the object for a create. | def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_cr... |
m2m_changed callback. The idea is to get the model and the instance of the object being tracked and the different objects being added/ removed. It is then send to the _create_tracked_field_m2m method to extract the proper attribute for the TrackedFieldModification. | def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` meth... |
Perform additional setup after user have been logged in. | def account_setup(remote, token, resp):
"""Perform additional setup after user have been logged in.
:param remote: The remote application.
:param token: The token value.
:param resp: The response.
"""
with db.session.begin_nested():
# Retrieve ORCID from response.
orcid = resp.g... |
: yield: The next LogEntry from the REST API: raise: StopIteration when there are no more log entries to show please note that if you call this again at a later time the REST API could have different results and more data could be returned | def log_entry_generator(log_instance):
"""
:yield: The next LogEntry from the REST API
:raise: StopIteration when there are no more log entries to show, please
note that if you call this again at a later time the REST API
could have different results and more data could be returned
... |
This is a constructor for the LogEntry class. | def from_entry_dict(cls, entry_dict):
"""
This is a "constructor" for the LogEntry class.
:param entry_dict: A dict we get from the REST API
:return: An instance of LogEntry.
"""
# Debug helper
# https://circleci.com/gh/andresriancho/w3af-api-docker/30
tr... |
: yield: Log entries starting from: start_id: and ending 200 entries after. In most cases easier to call than the paginate one because there is no need to keep track of the already read entries in a specific page. | def get_by_start_id(self, start_id):
"""
:yield: Log entries starting from :start_id: and ending 200 entries
after. In most cases easier to call than the paginate one
because there is no need to keep track of the already read
entries in a specific page.
... |
Get a list of captures. | def list(self, id, seq): # pylint: disable=invalid-name,redefined-builtin
"""Get a list of captures.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:return: :class:`captures.Capture <captures.Capture>` list
"""
schema = CaptureSchema(exclud... |
Get a capture. | def get(self, id, seq, intf): # pylint: disable=invalid-name,redefined-builtin
"""Get a capture.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param intf: Interface name as string.
:return: :class:`captures.Capture <captures.Capture>` object
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.