text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
method performs logging into log file and the freerun_entry
<END_TASK>
<USER_TASK:>
Description:
def _log_message(self, level, freerun_entry, msg):
""" method performs logging into log file and the freerun_entry """ |
self.logger.log(level, msg)
assert isinstance(freerun_entry, FreerunProcessEntry)
event_log = freerun_entry.event_log
if len(event_log) > MAX_NUMBER_OF_EVENTS:
del event_log[-1]
event_log.insert(0, msg)
self.freerun_process_dao.update(freerun_entry) |
<SYSTEM_TASK:>
method that takes care of processing unit_of_work records in
<END_TASK>
<USER_TASK:>
Description:
def _process_terminal_state(self, freerun_entry, uow, flow_request=None):
""" method that takes care of processing unit_of_work records in
STATE_PROCESSED, STATE_NOOP, STATE_INVALID, STATE_CANCELED states""" |
msg = 'UOW for {0} found in state {1}.'.format(freerun_entry.schedulable_name, uow.state)
self._log_message(INFO, freerun_entry, msg)
self.insert_and_publish_uow(freerun_entry, flow_request, reset_uow=True) |
<SYSTEM_TASK:>
method main duty - is to _avoid_ publishing another unit_of_work, if previous was not yet processed
<END_TASK>
<USER_TASK:>
Description:
def manage_schedulable(self, freerun_entry, flow_request=None):
""" method main duty - is to _avoid_ publishing another unit_of_work, if previous was not yet processed
In case the Scheduler sees that the unit_of_work is pending,
it will issue new WorkerMqRequest for the same UOW """ |
assert isinstance(freerun_entry, FreerunProcessEntry)
uow = None
if freerun_entry.related_unit_of_work:
uow = self.uow_dao.get_one(freerun_entry.related_unit_of_work)
try:
if uow is None:
self._process_state_embryo(freerun_entry, flow_request)
elif uow.is_requested or uow.is_in_progress:
self._process_state_in_progress(freerun_entry, uow)
elif uow.is_finished or uow.is_invalid:
self._process_terminal_state(freerun_entry, uow, flow_request)
else:
msg = 'Unknown state {0} of the UOW {1}'.format(uow.state, uow.db_id)
self._log_message(ERROR, freerun_entry, msg)
except LookupError as e:
msg = 'Lookup issue for schedulable: {0} in timeperiod {1}, because of: {2}' \
.format(freerun_entry.db_id, uow.timeperiod, e)
self._log_message(WARNING, freerun_entry, msg) |
<SYSTEM_TASK:>
fine-tuned data engine. MongoDB legacy
<END_TASK>
<USER_TASK:>
Description:
def _run_custom_data_engine(self, start_id_obj, end_id_obj, start_timeperiod, end_timeperiod):
""" fine-tuned data engine. MongoDB legacy """ |
collection_name = context.process_context[self.process_name].source
iteration = 0
while True:
cursor = self.ds.cursor_fine(collection_name,
start_id_obj,
end_id_obj,
iteration,
start_timeperiod,
end_timeperiod)
if iteration == 0 and cursor.count(with_limit_and_skip=True) == 0:
msg = 'No entries in {0} at range [{1} : {2}]'.format(collection_name, start_id_obj, end_id_obj)
self.logger.warning(msg)
break
start_id_obj = None
for document in cursor:
start_id_obj = document['_id']
self._process_single_document(document)
self.performance_tracker.increment_success()
if start_id_obj is None:
break
iteration += 1
self._cursor_exploited()
msg = 'Cursor exploited after {0} iterations'.format(iteration)
self.logger.info(msg) |
<SYSTEM_TASK:>
regular data engine
<END_TASK>
<USER_TASK:>
Description:
def _run_data_engine(self, start_timeperiod, end_timeperiod):
""" regular data engine """ |
collection_name = context.process_context[self.process_name].source
cursor = self.ds.cursor_batch(collection_name,
start_timeperiod,
end_timeperiod)
for document in cursor:
self._process_single_document(document)
self.performance_tracker.increment_success()
self._cursor_exploited()
msg = 'Cursor exploited after fetching {0} documents'.format(self.performance_tracker.success_per_job)
self.logger.info(msg) |
<SYSTEM_TASK:>
Build a request body object.
<END_TASK>
<USER_TASK:>
Description:
def build_request_body(type, id, attributes=None, relationships=None):
"""Build a request body object.
A body JSON object is used for any of the ``update`` or ``create``
methods on :class:`Resource` subclasses. In normal library use you
should not have to use this function directly.
Args:
type(string): The resource type for the attribute
id(uuid): The id of the object to update. This may be ``None``
Keyword Args:
attributes(dict): A JSON dictionary of the attributes to set
relationships(dict) A JSON dictionary of relationships to set
Returns:
A valid attribute dictionary. Often used in the ``update`` or
``create`` :class:`Resource`` methods.
""" |
result = {
"data": {
"type": type
}
}
data = result['data']
if attributes is not None:
data['attributes'] = attributes
if relationships is not None:
data['relationships'] = relationships
if id is not None:
data['id'] = id
return result |
<SYSTEM_TASK:>
Build a relationship list.
<END_TASK>
<USER_TASK:>
Description:
def build_request_relationship(type, ids):
"""Build a relationship list.
A relationship list is used to update relationships between two
resources. Setting sensors on a label, for example, uses this
function to construct the list of sensor ids to pass to the Helium
API.
Args:
type(string): The resource type for the ids in the relationship
ids([uuid] or uuid): Just one or a list of resource uuids to use
in the relationship
Returns:
A ready to use relationship JSON object.
""" |
if ids is None:
return {
'data': None
}
elif isinstance(ids, str):
return {
'data': {'id': ids, 'type': type}
}
else:
return {
"data": [{"id": id, "type": type} for id in ids]
} |
<SYSTEM_TASK:>
Augment request parameters with includes.
<END_TASK>
<USER_TASK:>
Description:
def build_request_include(include, params):
"""Augment request parameters with includes.
When one or all resources are requested an additional set of
resources can be requested as part of the request. This function
extends the given parameters for a request with a list of resource
types passed in as a list of :class:`Resource` subclasses.
Args:
include([Resource class]): A list of resource classes to include
params(dict): The (optional) dictionary of request parameters to extend
Returns:
An updated or new dictionary of parameters extended with an
include query parameter.
""" |
params = params or OrderedDict()
if include is not None:
params['include'] = ','.join([cls._resource_type() for cls in include])
return params |
<SYSTEM_TASK:>
Retrieve a single resource.
<END_TASK>
<USER_TASK:>
Description:
def find(cls, session, resource_id, include=None):
"""Retrieve a single resource.
This should only be called from sub-classes.
Args:
session(Session): The session to find the resource in
resource_id: The ``id`` for the resource to look up
Keyword Args:
include: Resource classes to include
Returns:
Resource: An instance of a resource, or throws a
:class:`NotFoundError` if the resource can not be found.
""" |
url = session._build_url(cls._resource_path(), resource_id)
params = build_request_include(include, None)
process = cls._mk_one(session, include=include)
return session.get(url, CB.json(200, process), params=params) |
<SYSTEM_TASK:>
Get filtered resources of the given resource class.
<END_TASK>
<USER_TASK:>
Description:
def where(cls, session, include=None, metadata=None, filter=None):
"""Get filtered resources of the given resource class.
This should be called on sub-classes only.
The include argument allows relationship fetches to be
optimized by including the target resources in the request of
the containing resource. For example::
.. code-block:: python
org = Organization.singleton(session, include=[Sensor])
org.sensors(use_included=True)
Will fetch the sensors for the authorized organization as part
of retrieving the organization. The ``use_included`` forces
the use of included resources and avoids making a separate
request to get the sensors for the organization.
The metadata argument enables filtering on resources that
support metadata filters. For example::
.. code-block:: python
sensors = Sensor.where(session, metadata={ 'asset_id': '23456' })
Will fetch all sensors that match the given metadata attribute.
The filter argument enables filtering the resulting resources
based on a passed in function. For example::
.. code-block::python
sensors = Sensor.where(session, filter=lambda s: s.name.startswith("a"))
Will fetch all sensors and apply the given filter to only
return sensors who's name start with the given string.
Args:
session(Session): The session to look up the resources in
Keyword Args:
incldue(list): The resource classes to include in the
request.
metadata(dict or list): The metadata filter to apply
Returns:
iterable(Resource): An iterator over all found resources
of this type
""" |
url = session._build_url(cls._resource_path())
params = build_request_include(include, None)
if metadata is not None:
params['filter[metadata]'] = to_json(metadata)
process = cls._mk_many(session, include=include, filter=filter)
return session.get(url, CB.json(200, process), params=params) |
<SYSTEM_TASK:>
Create a resource of the resource.
<END_TASK>
<USER_TASK:>
Description:
def create(cls, session, attributes=None, relationships=None):
"""Create a resource of the resource.
This should only be called from sub-classes
Args:
session(Session): The session to create the resource in.
attributes(dict): Any attributes that are valid for the
given resource type.
relationships(dict): Any relationships that are valid for the
given resource type.
Returns:
Resource: An instance of a resource.
""" |
resource_type = cls._resource_type()
resource_path = cls._resource_path()
url = session._build_url(resource_path)
json = build_request_body(resource_type, None,
attributes=attributes,
relationships=relationships)
process = cls._mk_one(session)
return session.post(url, CB.json(201, process), json=json) |
<SYSTEM_TASK:>
Get the a singleton API resource.
<END_TASK>
<USER_TASK:>
Description:
def singleton(cls, session, include=None):
"""Get the a singleton API resource.
Some Helium API resources are singletons. The authorized user
and organization for a given API key are examples of this.
.. code-block:: python
authorized_user = User.singleton(session)
will retrieve the authorized user for the given
:class:`Session`
Keyword Args:
include: Resource classes to include
""" |
params = build_request_include(include, None)
url = session._build_url(cls._resource_path())
process = cls._mk_one(session, singleton=True, include=include)
return session.get(url, CB.json(200, process), params=params) |
<SYSTEM_TASK:>
Update this resource.
<END_TASK>
<USER_TASK:>
Description:
def update(self, attributes=None):
"""Update this resource.
Not all aspects of a resource can be updated. If the server
rejects updates an error will be thrown.
Keyword Arguments:
attributes(dict): Attributes that are to be updated
Returns:
Resource: A new instance of this type of resource with the
updated attribute. On errors an exception is thrown.
""" |
resource_type = self._resource_type()
resource_path = self._resource_path()
session = self._session
singleton = self.is_singleton()
id = None if singleton else self.id
url = session._build_url(resource_path, id)
attributes = build_request_body(resource_type, self.id,
attributes=attributes)
process = self._mk_one(session, singleton=singleton)
return session.patch(url, CB.json(200, process), json=attributes) |
<SYSTEM_TASK:>
Delete the resource.
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Delete the resource.
Returns:
True if the delete is successful. Will throw an error if
other errors occur
""" |
session = self._session
url = session._build_url(self._resource_path(), self.id)
return session.delete(url, CB.boolean(204)) |
<SYSTEM_TASK:>
Changes file mode permissions.
<END_TASK>
<USER_TASK:>
Description:
def chmod(path, mode=None, user=None, group=None, other=None, recursive=False):
"""Changes file mode permissions.
>>> if chmod('/tmp/one', 0755):
... print('OK')
OK
NOTE: The precending ``0`` is required when using a numerical mode.
""" |
successful = True
mode = _ops_mode(mode)
if user is not None:
mode.user = user
if group is not None:
mode.group = group
if other is not None:
mode.other = other
if recursive:
for p in find(path, no_peek=True):
successful = _chmod(p, mode) and successful
else:
successful = _chmod(path, mode)
return successful |
<SYSTEM_TASK:>
Create a directory at the specified path. By default this function
<END_TASK>
<USER_TASK:>
Description:
def mkdir(path, recursive=True):
"""Create a directory at the specified path. By default this function
recursively creates the path.
>>> if mkdir('/tmp/one/two'):
... print('OK')
OK
""" |
if os.path.exists(path):
return True
try:
if recursive:
os.makedirs(path)
else:
os.mkdir(path)
except OSError as error:
log.error('mkdir: execute failed: %s (%s)' % (path, error))
return False
return True |
<SYSTEM_TASK:>
Convert string variables to a specified type.
<END_TASK>
<USER_TASK:>
Description:
def normalize(value, default=None, type=None, raise_exception=False):
"""Convert string variables to a specified type.
>>> normalize('true', type='boolean')
True
>>> normalize('11', type='number')
11
>>> normalize('10.3', default=11.0)
10.3
""" |
NUMBER_RE = re.compile('^[-+]?(([0-9]+\.?[0-9]*)|([0-9]*\.?[0-9]+))$')
if type is None and default is None:
type = unicode_type
elif type is None:
type = type_(default)
if type in str_types:
if value is not None:
if isinstance(value, unicode_type):
return value
elif py3 and isinstance(value, bytes_type):
return value.decode('utf-8')
return unicode_type(value)
if default is None:
if raise_exception:
raise ValidationError('invalid string')
else:
return unicode_type()
elif type in (bool, 'bool', 'boolean'):
if value is not None:
value = value.lower().strip()
if value in ('1', 'true', 'yes', 'on'):
return True
elif value in ('0', 'false', 'no', 'off'):
return False
if default is None:
if raise_exception:
raise ValidationError('invalid boolean')
else:
return False
elif type in (numbers.Number, 'number'):
if value is not None:
if value.isdigit():
return int(value)
elif NUMBER_RE.match(value):
return eval(value)
if default is None:
if raise_exception:
raise ValidationError('invalid number')
else:
return 0
elif type in (int, 'int', 'integer'):
try:
return int(value)
except Exception:
if isinstance(value, basestring_type) and NUMBER_RE.match(value):
return int(eval(value))
if default is None:
if raise_exception:
raise ValidationError('invalid number')
else:
return 0
elif type in (float, 'float'):
if value is not None and NUMBER_RE.match(value):
return float(value)
if default is None:
if raise_exception:
raise ValidationError('invalid number')
else:
return 0.0
return default |
<SYSTEM_TASK:>
Delete a specified file or directory. This function does not recursively
<END_TASK>
<USER_TASK:>
Description:
def rm(path, recursive=False):
"""Delete a specified file or directory. This function does not recursively
delete by default.
>>> if rm('/tmp/build', recursive=True):
... print('OK')
OK
""" |
try:
if recursive:
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
else:
if os.path.isfile(path):
os.remove(path)
else:
os.rmdir(path)
except OSError as error:
log.error('rm: execute failed: %s (%s)' % (path, error))
return False
return True |
<SYSTEM_TASK:>
Ensure a MongoDB index on a particular field name
<END_TASK>
<USER_TASK:>
Description:
def simple_ensure_index(request, database_name, collection_name):
"""Ensure a MongoDB index on a particular field name""" |
name = "Ensure a MongoDB index on a particular field name"
if request.method == 'POST':
form = EnsureIndexForm(request.POST)
if form.is_valid():
result = form.save(database_name, collection_name)
messages.success(request,
_("Index for %s created successfully" % result))
return HttpResponseRedirect(reverse('djmongo_show_dbs'))
else:
# The form is invalid
messages.error(
request, _("Please correct the errors in the form."))
return render(request,
'djmongo/console/generic/bootstrapform.html',
{'form': form, 'name': name})
else:
# this is a GET
context = {'name': name,
'form': EnsureIndexForm(
initial={"database_name": database_name,
"collection_name": collection_name})
}
return render(request, 'djmongo/console/generic/bootstrapform.html',
context) |
<SYSTEM_TASK:>
Create a New Mongo Database by adding a single document.
<END_TASK>
<USER_TASK:>
Description:
def create_new_database(request):
"""Create a New Mongo Database by adding a single document.""" |
name = "Create a New MongoDB Database"
if request.method == 'POST':
form = CreateDatabaseForm(request.POST)
if form.is_valid():
result = form.save()
if "error" in result:
messages.error(
request, "The database creation operation failed.")
messages.error(request, result["error"])
else:
messages.success(request, "Database created.")
return HttpResponseRedirect(reverse('djmongo_show_dbs'))
else:
# The form is invalid
messages.error(
request, _("Please correct the errors in the form."))
return render(request,
'djmongo/console/generic/bootstrapform.html',
{'form': form,
'name': name})
else:
# this is a GET
context = {'name': name,
'form': CreateDatabaseForm(
initial={"initial_document": '{ "foo" : "bar" }'
})
}
return render(request, 'djmongo/console/generic/bootstrapform.html',
context) |
<SYSTEM_TASK:>
wraps method with verification for is_request_valid
<END_TASK>
<USER_TASK:>
Description:
def valid_action_request(method):
""" wraps method with verification for is_request_valid""" |
@functools.wraps(method)
def _wrapper(self, *args, **kwargs):
assert isinstance(self, BaseRequestHandler)
if not self.is_request_valid:
return self.reply_bad_request()
try:
return method(self, *args, **kwargs)
except UserWarning as e:
return self.reply_server_error(e)
except Exception as e:
return self.reply_server_error(e)
return _wrapper |
<SYSTEM_TASK:>
makes sure the response' document has all leaf-fields converted to string
<END_TASK>
<USER_TASK:>
Description:
def safe_json_response(method):
""" makes sure the response' document has all leaf-fields converted to string """ |
def _safe_document(document):
""" function modifies the document in place
it iterates over the json document and stringify all non-string types
:return: modified document """
assert isinstance(document, dict), 'Error: provided document is not of DICT type: {0}' \
.format(document.__class__.__name__)
for key, value in document.items():
if isinstance(value, dict):
document[key] = {k: str(v) for k, v in value.items()}
elif isinstance(value, list):
document[key] = [str(v) for v in value]
else:
document[key] = str(document[key])
return document
@functools.wraps(method)
def _wrapper(self, *args, **kwargs):
try:
document = method(self, *args, **kwargs)
return _safe_document(document)
except Exception as e:
return self.reply_server_error(e)
return _wrapper |
<SYSTEM_TASK:>
Authentificate user and store token
<END_TASK>
<USER_TASK:>
Description:
def _auth(self, username, password) :
""" Authentificate user and store token """ |
self.user_credentials = self.call('auth', {'username': username, 'password': password})
if 'error' in self.user_credentials:
raise T411Exception('Error while fetching authentication token: %s'\
% self.user_credentials['error'])
# Create or update user file
user_data = dumps({'uid': '%s' % self.user_credentials['uid'], 'token': '%s' % self.user_credentials['token']})
with open(USER_CREDENTIALS_FILE, 'w') as user_cred_file:
user_cred_file.write(user_data)
return True |
<SYSTEM_TASK:>
method iterates over each reprocessing queues and re-submits UOW whose waiting time has expired
<END_TASK>
<USER_TASK:>
Description:
def flush(self, ignore_priority=False):
""" method iterates over each reprocessing queues and re-submits UOW whose waiting time has expired """ |
for process_name, q in self.reprocess_uows.items():
self._flush_queue(q, ignore_priority) |
<SYSTEM_TASK:>
method iterates over the reprocessing queue and synchronizes state of every UOW with the DB
<END_TASK>
<USER_TASK:>
Description:
def validate(self):
""" method iterates over the reprocessing queue and synchronizes state of every UOW with the DB
should it change via the MX to STATE_CANCELED - remove the UOW from the queue """ |
for process_name, q in self.reprocess_uows.items():
if not q:
continue
invalid_entries = list()
for entry in q.queue:
assert isinstance(entry, PriorityEntry)
uow = self.uow_dao.get_one(entry.entry.db_id)
if uow.is_canceled:
invalid_entries.append(entry)
thread_handler = self.managed_handlers[uow.process_name]
assert isinstance(thread_handler, ManagedThreadHandler)
if not thread_handler.process_entry.is_on:
invalid_entries.append(entry)
for entry in invalid_entries:
q.queue.remove(entry)
self.logger.info('reprocessing queue validated') |
<SYSTEM_TASK:>
method iterates over the reprocessing queue for the given process
<END_TASK>
<USER_TASK:>
Description:
def flush_one(self, process_name, ignore_priority=False):
""" method iterates over the reprocessing queue for the given process
and re-submits UOW whose waiting time has expired """ |
q = self.reprocess_uows[process_name]
self._flush_queue(q, ignore_priority) |
<SYSTEM_TASK:>
return trees assigned to given MX Page
<END_TASK>
<USER_TASK:>
Description:
def mx_page_trees(self, mx_page):
""" return trees assigned to given MX Page """ |
resp = dict()
for tree_name, tree in self.scheduler.timetable.trees.items():
if tree.mx_page == mx_page:
rest_tree = self._get_tree_details(tree_name)
resp[tree.tree_name] = rest_tree.document
return resp |
<SYSTEM_TASK:>
Compute 2D coordinates of the piece.
<END_TASK>
<USER_TASK:>
Description:
def compute_coordinates(self):
""" Compute 2D coordinates of the piece. """ |
self._x, self._y = self.board.index_to_coordinates(self.index) |
<SYSTEM_TASK:>
All horizontal squares from the piece's point of view.
<END_TASK>
<USER_TASK:>
Description:
def horizontals(self):
""" All horizontal squares from the piece's point of view.
Returns a list of relative movements up to the board's bound.
""" |
horizontal_shifts = set(izip_longest(map(
lambda i: i - self.x, range(self.board.length)), [], fillvalue=0))
horizontal_shifts.discard((0, 0))
return horizontal_shifts |
<SYSTEM_TASK:>
All vertical squares from the piece's point of view.
<END_TASK>
<USER_TASK:>
Description:
def verticals(self):
""" All vertical squares from the piece's point of view.
Returns a list of relative movements up to the board's bound.
""" |
vertical_shifts = set(izip_longest([], map(
lambda i: i - self.y, range(self.board.height)), fillvalue=0))
vertical_shifts.discard((0, 0))
return vertical_shifts |
<SYSTEM_TASK:>
All diagonal squares from the piece's point of view.
<END_TASK>
<USER_TASK:>
Description:
def diagonals(self):
""" All diagonal squares from the piece's point of view.
Returns a list of relative movements up to the board's bound.
""" |
left_top_shifts = map(lambda i: (-(i + 1), -(i + 1)), range(min(
self.left_distance, self.top_distance)))
left_bottom_shifts = map(lambda i: (-(i + 1), +(i + 1)), range(min(
self.left_distance, self.bottom_distance)))
right_top_shifts = map(lambda i: (+(i + 1), -(i + 1)), range(min(
self.right_distance, self.top_distance)))
right_bottom_shifts = map(lambda i: (+(i + 1), +(i + 1)), range(min(
self.right_distance, self.bottom_distance)))
return set(chain(
left_top_shifts, left_bottom_shifts,
right_top_shifts, right_bottom_shifts)) |
<SYSTEM_TASK:>
Return the cached territory occupied by the piece.
<END_TASK>
<USER_TASK:>
Description:
def territory(self):
""" Return the cached territory occupied by the piece. """ |
cache_key = (
self.board.length, self.board.height, self.uid, self.index)
if cache_key not in self.territory_cache:
vector = self.compute_territory()
self.territory_cache[cache_key] = vector
else:
vector = self.territory_cache[cache_key]
return vector |
<SYSTEM_TASK:>
Compute territory reachable by the piece from its current position.
<END_TASK>
<USER_TASK:>
Description:
def compute_territory(self):
""" Compute territory reachable by the piece from its current position.
Returns a list of boolean flags of squares indexed linearly, for which
a True means the square is reachable.
""" |
# Initialize the square occupancy vector of the board.
vector = self.board.new_vector()
# Mark current position as reachable.
vector[self.index] = True
# List all places reacheable by the piece from its current position.
for x_shift, y_shift in self.movements:
# Mark side positions as reachable if in the limit of the board.
try:
reachable_index = self.board.coordinates_to_index(
self.x, self.y, x_shift, y_shift)
except ForbiddenCoordinates:
continue
vector[reachable_index] = True
return vector |
<SYSTEM_TASK:>
Empty board, remove all pieces and reset internal states.
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Empty board, remove all pieces and reset internal states. """ |
# Store positionned pieces on the board.
self.pieces = set()
# Squares on the board already occupied by a piece.
self.occupancy = self.new_vector()
# Territory susceptible to attacke, i.e. squares reachable by at least
# a piece.
self.exposed_territory = self.new_vector() |
<SYSTEM_TASK:>
Generator producing all 2D positions of all squares.
<END_TASK>
<USER_TASK:>
Description:
def positions(self):
""" Generator producing all 2D positions of all squares. """ |
for y in range(self.height):
for x in range(self.length):
yield x, y |
<SYSTEM_TASK:>
Check that a linear index of a square is within board's bounds.
<END_TASK>
<USER_TASK:>
Description:
def validate_index(self, index):
""" Check that a linear index of a square is within board's bounds. """ |
if index < 0 or index >= self.size:
raise ForbiddenIndex("Linear index {} not in {}x{} board.".format(
index, self.length, self.height)) |
<SYSTEM_TASK:>
Check if the piece lie within the board.
<END_TASK>
<USER_TASK:>
Description:
def validate_coordinates(self, x, y):
""" Check if the piece lie within the board. """ |
if not(0 <= x < self.length and 0 <= y < self.height):
raise ForbiddenCoordinates(
"x={}, y={} outside of {}x{} board.".format(
x, y, self.length, self.height)) |
<SYSTEM_TASK:>
Return a linear index from a set of 2D coordinates.
<END_TASK>
<USER_TASK:>
Description:
def coordinates_to_index(self, x, y, x_shift=0, y_shift=0):
""" Return a linear index from a set of 2D coordinates.
Optionnal vertical and horizontal shifts might be applied.
""" |
target_x = x + x_shift
target_y = y + y_shift
self.validate_coordinates(target_x, target_y)
index = (target_y * self.length) + target_x
return index |
<SYSTEM_TASK:>
Add a piece to the board at the provided linear position.
<END_TASK>
<USER_TASK:>
Description:
def add(self, piece_uid, index):
""" Add a piece to the board at the provided linear position. """ |
# Square already occupied by another piece.
if self.occupancy[index]:
raise OccupiedPosition
# Square reachable by another piece.
if self.exposed_territory[index]:
raise VulnerablePosition
# Create a new instance of the piece.
klass = PIECE_CLASSES[piece_uid]
piece = klass(self, index)
# Check if a piece can attack another one from its position.
territory = piece.territory
for i in self.indexes:
if self.occupancy[i] and territory[i]:
raise AttackablePiece
# Mark the territory covered by the piece as exposed and secure its
# position on the board.
self.pieces.add(piece)
self.occupancy[index] = True
self.exposed_territory = list(
map(or_, self.exposed_territory, territory)) |
<SYSTEM_TASK:>
Return piece placed at the provided coordinates.
<END_TASK>
<USER_TASK:>
Description:
def get(self, x, y):
""" Return piece placed at the provided coordinates. """ |
for piece in self.pieces:
if (piece.x, piece.y) == (x, y):
return piece |
<SYSTEM_TASK:>
Returns descriptive information about this cruddy handler and the
<END_TASK>
<USER_TASK:>
Description:
def describe(self, **kwargs):
"""
Returns descriptive information about this cruddy handler and the
methods supported by it.
""" |
response = self._new_response()
description = {
'cruddy_version': __version__,
'table_name': self.table_name,
'supported_operations': copy.copy(self.supported_ops),
'prototype': copy.deepcopy(self.prototype),
'operations': {}
}
for name, method in inspect.getmembers(self, inspect.ismethod):
if not name.startswith('_'):
argspec = inspect.getargspec(method)
if argspec.defaults is None:
defaults = None
else:
defaults = list(argspec.defaults)
method_info = {
'docs': inspect.getdoc(method),
'argspec': {
'args': argspec.args,
'varargs': argspec.varargs,
'keywords': argspec.keywords,
'defaults': defaults
}
}
description['operations'][name] = method_info
response.data = description
return response |
<SYSTEM_TASK:>
Cruddy provides a limited but useful interface to search GSI indexes in
<END_TASK>
<USER_TASK:>
Description:
def search(self, query, **kwargs):
"""
Cruddy provides a limited but useful interface to search GSI indexes in
DynamoDB with the following limitations (hopefully some of these will
be expanded or eliminated in the future.
* The GSI must be configured with a only HASH and not a RANGE.
* The only operation supported in the query is equality
To use the ``search`` operation you must pass in a query string of this
form:
<attribute_name>=<value>
As stated above, the only operation currently supported is equality (=)
but other operations will be added over time. Also, the
``attribute_name`` must be an attribute which is configured as the
``HASH`` of a GSI in the DynamoDB table. If all of the above
conditions are met, the ``query`` operation will return a list
(possibly empty) of all items matching the query and the ``status`` of
the response will be ``success``. Otherwise, the ``status`` will be
``error`` and the ``error_type`` and ``error_message`` will provide
further information about the error.
""" |
response = self._new_response()
if self._check_supported_op('search', response):
if '=' not in query:
response.status = 'error'
response.error_type = 'InvalidQuery'
msg = 'Only the = operation is supported'
response.error_message = msg
else:
key, value = query.split('=')
if key not in self._indexes:
response.status = 'error'
response.error_type = 'InvalidQuery'
msg = 'Attribute {} is not indexed'.format(key)
response.error_message = msg
else:
params = {'KeyConditionExpression': Key(key).eq(value)}
index_name = self._indexes[key]
if index_name:
params['IndexName'] = index_name
pe = kwargs.get('projection_expression')
if pe:
params['ProjectionExpression'] = pe
self._call_ddb_method(self.table.query,
params, response)
if response.status == 'success':
response.data = self._replace_decimals(
response.raw_response['Items'])
response.prepare()
return response |
<SYSTEM_TASK:>
Returns a list of items in the database. Encrypted attributes are not
<END_TASK>
<USER_TASK:>
Description:
def list(self, **kwargs):
"""
Returns a list of items in the database. Encrypted attributes are not
decrypted when listing items.
""" |
response = self._new_response()
if self._check_supported_op('list', response):
self._call_ddb_method(self.table.scan, {}, response)
if response.status == 'success':
response.data = self._replace_decimals(
response.raw_response['Items'])
response.prepare()
return response |
<SYSTEM_TASK:>
Creates a new item. You pass in an item containing initial values.
<END_TASK>
<USER_TASK:>
Description:
def create(self, item, **kwargs):
"""
Creates a new item. You pass in an item containing initial values.
Any attribute names defined in ``prototype`` that are missing from the
item will be added using the default value defined in ``prototype``.
""" |
response = self._new_response()
if self._prototype_handler.check(item, 'create', response):
self._encrypt(item)
params = {'Item': item}
self._call_ddb_method(self.table.put_item,
params, response)
if response.status == 'success':
response.data = item
response.prepare()
return response |
<SYSTEM_TASK:>
Updates the item based on the current values of the dictionary passed
<END_TASK>
<USER_TASK:>
Description:
def update(self, item, encrypt=True, **kwargs):
"""
Updates the item based on the current values of the dictionary passed
in.
""" |
response = self._new_response()
if self._check_supported_op('update', response):
if self._prototype_handler.check(item, 'update', response):
if encrypt:
self._encrypt(item)
params = {'Item': item}
self._call_ddb_method(self.table.put_item,
params, response)
if response.status == 'success':
response.data = item
response.prepare()
return response |
<SYSTEM_TASK:>
Atomically increments a counter attribute in the item identified by
<END_TASK>
<USER_TASK:>
Description:
def increment_counter(self, id, counter_name, increment=1,
id_name='id', **kwargs):
"""
Atomically increments a counter attribute in the item identified by
``id``. You must specify the name of the attribute as ``counter_name``
and, optionally, the ``increment`` which defaults to ``1``.
""" |
response = self._new_response()
if self._check_supported_op('increment_counter', response):
params = {
'Key': {id_name: id},
'UpdateExpression': 'set #ctr = #ctr + :val',
'ExpressionAttributeNames': {"#ctr": counter_name},
'ExpressionAttributeValues': {
':val': decimal.Decimal(increment)},
'ReturnValues': 'UPDATED_NEW'
}
self._call_ddb_method(self.table.update_item, params, response)
if response.status == 'success':
if 'Attributes' in response.raw_response:
self._replace_decimals(response.raw_response)
attr = response.raw_response['Attributes'][counter_name]
response.data = attr
response.prepare()
return response |
<SYSTEM_TASK:>
Deletes the item corresponding to ``id``.
<END_TASK>
<USER_TASK:>
Description:
def delete(self, id, id_name='id', **kwargs):
"""
Deletes the item corresponding to ``id``.
""" |
response = self._new_response()
if self._check_supported_op('delete', response):
params = {'Key': {id_name: id}}
self._call_ddb_method(self.table.delete_item, params, response)
response.data = 'true'
response.prepare()
return response |
<SYSTEM_TASK:>
Perform a search and delete all items that match.
<END_TASK>
<USER_TASK:>
Description:
def bulk_delete(self, query, **kwargs):
"""
Perform a search and delete all items that match.
""" |
response = self._new_response()
if self._check_supported_op('search', response):
n = 0
pe = 'id'
response = self.search(query, projection_expression=pe, **kwargs)
while response.status == 'success' and response.data:
for item in response.data:
delete_response = self.delete(item['id'])
if response.status != 'success':
response = delete_response
break
n += 1
response = self.search(
query, projection_expression=pe, **kwargs)
if response.status == 'success':
response.data = {'deleted': n}
return response |
<SYSTEM_TASK:>
In addition to the methods described above, cruddy also provides a
<END_TASK>
<USER_TASK:>
Description:
def handler(self, operation=None, **kwargs):
"""
In addition to the methods described above, cruddy also provides a
generic handler interface. This is mainly useful when you want to wrap
a cruddy handler in a Lambda function and then call that Lambda
function to access the CRUD capabilities.
To call the handler, you simply put all necessary parameters into a
Python dictionary and then call the handler with that dict.
```
params = {
'operation': 'create',
'item': {'foo': 'bar', 'fie': 'baz'}
}
response = crud.handler(**params)
```
""" |
response = self._new_response()
if operation is None:
response.status = 'error'
response.error_type = 'MissingOperation'
response.error_message = 'You must pass an operation'
return response
operation = operation.lower()
self._check_supported_op(operation, response)
if response.status == 'success':
method = getattr(self, operation, None)
if callable(method):
response = method(**kwargs)
else:
response.status == 'error'
response.error_type = 'NotImplemented'
msg = 'Operation: {} is not implemented'.format(operation)
response.error_message = msg
return response |
<SYSTEM_TASK:>
Creates a new Netconf request based on the last received or if
<END_TASK>
<USER_TASK:>
Description:
def get_lldp_neighbors_request(last_ifindex, rbridge_id):
""" Creates a new Netconf request based on the last received or if
rbridge_id is specifed
ifindex when the hasMore flag is true
""" |
request_lldp = ET.Element(
'get-lldp-neighbor-detail',
xmlns="urn:brocade.com:mgmt:brocade-lldp-ext"
)
if rbridge_id is not None:
rbridge_el = ET.SubElement(request_lldp, "rbridge-id")
rbridge_el.text = rbridge_id
elif last_ifindex != '':
last_received_int = ET.SubElement(request_lldp,
"last-rcvd-ifindex")
last_received_int.text = last_ifindex
return request_lldp |
<SYSTEM_TASK:>
Gets a 201 response with the specified data.
<END_TASK>
<USER_TASK:>
Description:
def created(self, data, schema=None, envelope=None):
"""
Gets a 201 response with the specified data.
:param data: The content value.
:param schema: The schema to serialize the data.
:param envelope: The key used to envelope the data.
:return: A Flask response object.
""" |
data = marshal(data, schema, envelope)
return self.__make_response((data, 201)) |
<SYSTEM_TASK:>
Gets a 200 response with the specified data.
<END_TASK>
<USER_TASK:>
Description:
def ok(self, data, schema=None, envelope=None):
"""
Gets a 200 response with the specified data.
:param data: The content value.
:param schema: The schema to serialize the data.
:param envelope: The key used to envelope the data.
:return: A Flask response object.
""" |
data = marshal(data, schema, envelope)
return self.__make_response(data) |
<SYSTEM_TASK:>
A decorator that sets a list of authenticators for a function.
<END_TASK>
<USER_TASK:>
Description:
def authenticators(self, auths):
"""
A decorator that sets a list of authenticators for a function.
:param auths: The list of authenticator instances or classes.
:return: A function
""" |
if not isinstance(auths, (list, tuple)):
auths = [auths]
instances = []
for auth in auths:
if isclass(auth):
instances.append(auth())
else:
instances.append(auth)
def decorator(func):
func.authenticators = instances
return func
return decorator |
<SYSTEM_TASK:>
A decorator that sets a list of permissions for a function.
<END_TASK>
<USER_TASK:>
Description:
def permissions(self, perms):
"""
A decorator that sets a list of permissions for a function.
:param perms: The list of permission instances or classes.
:return: A function
""" |
if not isinstance(perms, (list, tuple)):
perms = [perms]
instances = []
for perm in perms:
if isclass(perm):
instances.append(perm())
else:
instances.append(perm)
def decorator(func):
func.permissions = instances
return func
return decorator |
<SYSTEM_TASK:>
A decorator that converts the request body into a function parameter based on the specified schema.
<END_TASK>
<USER_TASK:>
Description:
def from_body(self, param_name, schema):
"""
A decorator that converts the request body into a function parameter based on the specified schema.
:param param_name: The parameter which receives the argument.
:param schema: The schema class or instance used to deserialize the request body toa Python object.
:return: A function
""" |
schema = schema() if isclass(schema) else schema
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs[param_name] = self.__parse_body(schema)
return func(*args, **kwargs)
return wrapper
return decorator |
<SYSTEM_TASK:>
A decorator that converts a request cookie into a function parameter based on the specified field.
<END_TASK>
<USER_TASK:>
Description:
def from_cookie(self, param_name, field):
"""
A decorator that converts a request cookie into a function parameter based on the specified field.
:param str param_name: The parameter which receives the argument.
:param Field field: The field class or instance used to deserialize the request cookie to a Python object.
:return: A function
""" |
return self.__from_source(param_name, field, lambda: request.cookies, 'cookie') |
<SYSTEM_TASK:>
A decorator that converts a request form into a function parameter based on the specified field.
<END_TASK>
<USER_TASK:>
Description:
def from_form(self, param_name, field):
"""
A decorator that converts a request form into a function parameter based on the specified field.
:param str param_name: The parameter which receives the argument.
:param Field field: The field class or instance used to deserialize the request form to a Python object.
:return: A function
""" |
return self.__from_source(param_name, field, lambda: request.form, 'form') |
<SYSTEM_TASK:>
A decorator that converts a request header into a function parameter based on the specified field.
<END_TASK>
<USER_TASK:>
Description:
def from_header(self, param_name, field):
"""
A decorator that converts a request header into a function parameter based on the specified field.
:param str param_name: The parameter which receives the argument.
:param Field field: The field class or instance used to deserialize the request header to a Python object.
:return: A function
""" |
return self.__from_source(param_name, field, lambda: request.headers, 'header') |
<SYSTEM_TASK:>
A decorator that converts a query string into a function parameter based on the specified field.
<END_TASK>
<USER_TASK:>
Description:
def from_query(self, param_name, field):
"""
A decorator that converts a query string into a function parameter based on the specified field.
:param param_name: The parameter which receives the argument.
:param Field field: The field class or instance used to deserialize the request query string to a Python object.
:return: A function
""" |
return self.__from_source(param_name, field, lambda: request.args, 'query') |
<SYSTEM_TASK:>
A decorator that apply marshalling to the return values of your methods.
<END_TASK>
<USER_TASK:>
Description:
def marshal_with(self, schema, envelope=None):
"""
A decorator that apply marshalling to the return values of your methods.
:param schema: The schema class to be used to serialize the values.
:param envelope: The key used to envelope the data.
:return: A function.
""" |
# schema is pre instantiated to avoid instantiate it
# on every request
schema_is_class = isclass(schema)
schema_cache = schema() if schema_is_class else schema
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
data = func(*args, **kwargs)
if isinstance(data, self.__app.response_class):
return data
schema_instance = schema_cache
# if there is the parameter 'fields' in the url
# we cannot use the cached schema instance
# in this case we have to instantiate the schema
# on every request.
if schema_is_class:
only = get_fields_from_request(schema=schema)
if only:
schema_instance = schema(only=only)
return marshal(data, schema_instance, envelope)
return wrapper
return decorator |
<SYSTEM_TASK:>
A decorator that allows to change the trace emitter.
<END_TASK>
<USER_TASK:>
Description:
def trace_emit(self):
"""
A decorator that allows to change the trace emitter.
By default Python logging is used to emit the trace data.
""" |
def decorator(f):
self.tracer.emitter = f
return f
return decorator |
<SYSTEM_TASK:>
Creates a Flask response object from the specified data.
<END_TASK>
<USER_TASK:>
Description:
def __make_response(self, data, default_renderer=None):
"""
Creates a Flask response object from the specified data.
The appropriated encoder is taken based on the request header Accept.
If there is not data to be serialized the response status code is 204.
:param data: The Python object to be serialized.
:return: A Flask response object.
""" |
status = headers = None
if isinstance(data, tuple):
data, status, headers = unpack(data)
if data is None:
data = self.__app.response_class(status=204)
elif not isinstance(data, self.__app.response_class):
renderer, mimetype = self.content_negotiation.select_renderer(request, self.default_renderers)
if not renderer:
if not default_renderer:
raise NotAcceptable()
renderer = default_renderer
mimetype = default_renderer.mimetype
data_bytes = renderer.render(data, mimetype)
data = self.__app.response_class(data_bytes, mimetype=str(mimetype))
if status is not None:
data.status_code = status
if headers:
data.headers.extend(headers)
return data |
<SYSTEM_TASK:>
cruddy is a CLI interface to the cruddy handler. It can be used in one
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, profile, region, lambda_fn, config, debug):
"""
cruddy is a CLI interface to the cruddy handler. It can be used in one
of two ways.
First, you can pass in a ``--config`` option which is a JSON file
containing all of your cruddy parameters and the CLI will create a cruddy
handler to manipulate the DynamoDB table directly.
Alternatively, you can pass in a ``--lambda-fn`` option which is the
name of an AWS Lambda function which contains a cruddy handler. In this
case the CLI will call the Lambda function to make the changes in the
underlying DynamoDB table.
""" |
ctx.obj = CLIHandler(profile, region, lambda_fn, config, debug) |
<SYSTEM_TASK:>
Increment a counter attribute atomically
<END_TASK>
<USER_TASK:>
Description:
def increment(handler, increment, item_id, counter_name):
"""Increment a counter attribute atomically""" |
data = {'operation': 'increment_counter',
'id': item_id,
'counter_name': counter_name,
'increment': increment}
handler.invoke(data) |
<SYSTEM_TASK:>
Returns a Markdown document that describes this handler and
<END_TASK>
<USER_TASK:>
Description:
def help(handler):
"""
Returns a Markdown document that describes this handler and
it's operations.
""" |
data = {'operation': 'describe'}
response = handler.invoke(data, raw=True)
description = response.data
lines = []
lines.append('# {}'.format(handler.lambda_fn))
lines.append('## Handler Info')
lines.append('**Cruddy version**: {}'.format(
description['cruddy_version']))
lines.append('')
lines.append('**Table name**: {}'.format(description['table_name']))
lines.append('')
lines.append('**Supported operations**:')
lines.append('')
for op in description['supported_operations']:
lines.append('* {}'.format(op))
lines.append('')
lines.append('**Prototype**:')
lines.append('')
lines.append('```')
lines.append(str(description['prototype']))
lines.append('```')
lines.append('')
lines.append('## Operations')
for op_name in description['operations']:
op = description['operations'][op_name]
lines.append('### {}'.format(op_name))
lines.append('')
lines.append(_build_signature_line(
op_name, description['operations'][op_name]['argspec']))
lines.append('')
if op['docs'] is None:
lines.append('')
else:
lines.append(op['docs'])
lines.append('')
click.echo('\n'.join(lines)) |
<SYSTEM_TASK:>
Swap the byte-ordering in a packet with N=4 bytes per word
<END_TASK>
<USER_TASK:>
Description:
def byteswap(data, word_size=4):
""" Swap the byte-ordering in a packet with N=4 bytes per word
""" |
return reduce(lambda x,y: x+''.join(reversed(y)), chunks(data, word_size), '') |
<SYSTEM_TASK:>
Set VCS Virtual IP.
<END_TASK>
<USER_TASK:>
Description:
def vcs_vip(self, **kwargs):
"""Set VCS Virtual IP.
Args:
vip (str): IPv4/IPv6 Virtual IP Address.
rbridge_id (str): rbridge-id for device. Only required when type is
`ve`.
delete (bool): Deletes the virtual ip if `delete` is ``True``.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `vip` is not passed.
ValueError: if `vip` is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... dev.interface.vcs_vip(vip='10.1.1.1/24')
... dev.interface.vcs_vip(vip='fe80::cafe:beef:1000:1/64')
... dev.interface.vcs_vip(vip='10.1.1.1/24',get=True)
... dev.interface.vcs_vip(vip='fe80::cafe:beef:1000:1/64',
... get=True)
... dev.interface.vcs_vip(vip='fe80::cafe:beef:1000:1/64',
... delete=True)
... dev.interface.vcs_vip(vip='10.1.1.1/24',get=True)
... dev.interface.vcs_vip(vip='fe80::cafe:beef:1000:1/64',
... get=True)
... dev.interface.vcs_vip(vip='10.1.1.1/24',delete=True)
... dev.interface.vcs_vip(vip='fe80::cafe:beef:1000:1/64',
... delete=True)
""" |
get_config = kwargs.pop('get', False)
delete = kwargs.pop('delete', False)
callback = kwargs.pop('callback', self._callback)
method_class = self._vcs
if not get_config:
vip = str(kwargs.pop('vip'))
ipaddress = ip_interface(unicode(vip))
vcs_vip = None
if ipaddress.version == 4:
method_name = 'vcs_virtual_ip_address_address'
vcs_args = dict(address=vip)
vcs_vip = getattr(method_class, method_name)
elif ipaddress.version == 6:
method_name = 'vcs_virtual_ipv6_address_ipv6address'
vcs_args = dict(ipv6address=vip)
vcs_vip = getattr(method_class, method_name)
if not delete:
config = vcs_vip(**vcs_args)
else:
if ipaddress.version == 4:
config = vcs_vip(**vcs_args)
config.find('.//*address').set('operation', 'delete')
elif ipaddress.version == 6:
config = vcs_vip(**vcs_args)
config.find('.//*ipv6address').set('operation', 'delete')
elif get_config:
vip_info = {}
method_name = 'vcs_virtual_ip_address_address'
vcs_args = dict(address='')
vcs_vip = getattr(method_class, method_name)
config = vcs_vip(**vcs_args)
vip_info['ipv4_vip'] = callback(config, handler='get_config')
method_name = 'vcs_virtual_ipv6_address_ipv6address'
vcs_args = dict(ipv6address='')
vcs_vip = getattr(method_class, method_name)
config = vcs_vip(**vcs_args)
vip_info['ipv6_vip'] = callback(config, handler='get_config')
return vip_info
return callback(config) |
<SYSTEM_TASK:>
Get BGP neighbors configured on a device.
<END_TASK>
<USER_TASK:>
Description:
def get_bgp_neighbors(self, **kwargs):
"""Get BGP neighbors configured on a device.
Args:
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
vrf (str): The VRF for this BGP process.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
List of 0 or more BGP Neighbors on the specified
rbridge.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.bgp.local_asn(local_as='65535',
... rbridge_id='225')
... output = dev.bgp.neighbor(ip_addr='10.10.10.10',
... remote_as='65535', rbridge_id='225')
... output = dev.bgp.neighbor(remote_as='65535',
... rbridge_id='225',
... ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')
... result = dev.bgp.get_bgp_neighbors(rbridge_id='225')
... assert len(result) >= 1
... output = dev.bgp.neighbor(ip_addr='10.10.10.10',
... delete=True, rbridge_id='225')
... output = dev.bgp.neighbor(delete=True, rbridge_id='225',
... ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')
... dev.bgp.neighbor() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NotImplementedError
KeyError
""" |
callback = kwargs.pop('callback', self._callback)
neighbor_args = dict(router_bgp_neighbor_address='',
remote_as='',
vrf_name=kwargs.pop('vrf', 'default'),
rbridge_id=kwargs.pop('rbridge_id', '1'))
neighbor = getattr(self._rbridge,
'rbridge_id_router_bgp_router_bgp_cmds_holder_'
'router_bgp_attributes_neighbor_ips_'
'neighbor_addr_remote_as')
config = neighbor(**neighbor_args)
output = callback(config, handler='get_config')
result = []
urn = "{urn:brocade.com:mgmt:brocade-bgp}"
# IPv4 BGP Neighbor Handling
for item in output.data.findall(
'.//{*}neighbor-addr'):
neighbor_address = item.find(
'%srouter-bgp-neighbor-address' % urn).text
remote_as = item.find('%sremote-as' % urn).text
item_results = {'neighbor-address': neighbor_address,
'remote-as': remote_as}
result.append(item_results)
# IPv6 BGP Neighbor handling
neighbor_args['router_bgp_neighbor_ipv6_address'] = ''
neighbor = getattr(self._rbridge,
'rbridge_id_router_bgp_router_bgp_cmds_holder_'
'router_bgp_attributes_neighbor_ipv6s_neighbor_'
'ipv6_addr_remote_as')
config = neighbor(**neighbor_args)
output = callback(config, handler='get_config')
for item in output.data.findall(
'.//{*}neighbor-ipv6-addr'):
neighbor_address = item.find(
'%srouter-bgp-neighbor-ipv6-address' % urn).text
remote_as = item.find('%sremote-as' % urn).text
item_results = {'neighbor-address': neighbor_address,
'remote-as': remote_as}
result.append(item_results)
return result |
<SYSTEM_TASK:>
Set BGP multihop property for a neighbor.
<END_TASK>
<USER_TASK:>
Description:
def multihop(self, **kwargs):
"""Set BGP multihop property for a neighbor.
Args:
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
neighbor (str): Address family to configure. (ipv4, ipv6)
count (str): Number of hops to allow. (1-255)
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
``AttributeError``: When `neighbor` is not a valid IPv4 or IPv6
address.
``KeyError``: When `count` is not specified.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.230']
>>> for switch in switches:
... conn = (switch, '22')
... auth = ('admin', 'password')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... dev.bgp.local_asn(local_as='65535', rbridge_id='225')
... dev.bgp.neighbor(ip_addr='10.10.10.10',
... remote_as='65535', rbridge_id='225')
... dev.bgp.neighbor(remote_as='65535', rbridge_id='225',
... ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')
... dev.bgp.multihop(neighbor='10.10.10.10', count='5',
... rbridge_id='225')
... dev.bgp.multihop(get=True, neighbor='10.10.10.10',
... count='5', rbridge_id='225')
... dev.bgp.multihop(count='5', rbridge_id='225',
... neighbor='2001:4818:f000:1ab:cafe:beef:1000:1')
... dev.bgp.multihop(get=True, count='5', rbridge_id='225',
... neighbor='2001:4818:f000:1ab:cafe:beef:1000:1')
... dev.bgp.multihop(delete=True, neighbor='10.10.10.10',
... count='5', rbridge_id='225')
... dev.bgp.multihop(delete=True, count='5',
... rbridge_id='225',
... neighbor='2001:4818:f000:1ab:cafe:beef:1000:1')
... dev.bgp.neighbor(ip_addr='10.10.10.10', delete=True,
... rbridge_id='225')
... dev.bgp.neighbor(delete=True, rbridge_id='225',
... ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')
... output = dev.bgp.multihop(rbridge_id='225', count='5')
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NotImplementedError
KeyError
""" |
callback = kwargs.pop('callback', self._callback)
ip_addr = ip_interface(unicode(kwargs.pop('neighbor')))
config = self._multihop_xml(neighbor=ip_addr,
count=kwargs.pop('count'),
rbridge_id=kwargs.pop('rbridge_id', '1'),
vrf=kwargs.pop('vrf', 'default'))
if kwargs.pop('get', False):
return callback(config, handler='get_config')
if kwargs.pop('delete', False):
config.find('.//*ebgp-multihop').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Set BGP update source property for a neighbor.
<END_TASK>
<USER_TASK:>
Description:
def update_source(self, **kwargs):
"""Set BGP update source property for a neighbor.
This method currently only supports loopback interfaces.
Args:
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
neighbor (str): Address family to configure. (ipv4, ipv6)
int_type (str): Interface type (loopback)
int_name (str): Interface identifier (1, 5, 7, etc)
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
``AttributeError``: When `neighbor` is not a valid IPv4 or IPv6
address.
``KeyError``: When `int_type` or `int_name` are not specified.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.230']
>>> for switch in switches:
... conn = (switch, '22')
... auth = ('admin', 'password')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... dev.interface.ip_address(int_type='loopback', name='6',
... rbridge_id='225', ip_addr='6.6.6.6/32')
... dev.interface.ip_address(int_type='loopback', name='6',
... ip_addr='0:0:0:0:0:ffff:606:606/128', rbridge_id='225')
... dev.bgp.local_asn(local_as='65535', rbridge_id='225')
... dev.bgp.neighbor(ip_addr='10.10.10.10',
... remote_as='65535', rbridge_id='225')
... dev.bgp.neighbor(remote_as='65535', rbridge_id='225',
... ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')
... dev.bgp.update_source(neighbor='10.10.10.10',
... rbridge_id='225', int_type='loopback', int_name='6')
... dev.bgp.update_source(get=True, neighbor='10.10.10.10',
... rbridge_id='225', int_type='loopback', int_name='6')
... dev.bgp.update_source(rbridge_id='225', int_name='6',
... neighbor='2001:4818:f000:1ab:cafe:beef:1000:1',
... int_type='loopback')
... dev.bgp.update_source(get=True, rbridge_id='225',
... neighbor='2001:4818:f000:1ab:cafe:beef:1000:1',
... int_type='loopback', int_name='6')
... dev.bgp.update_source(neighbor='10.10.10.10',
... rbridge_id='225', delete=True, int_type='loopback',
... int_name='6')
... dev.bgp.update_source(delete=True, int_type='loopback',
... rbridge_id='225', int_name='6',
... neighbor='2001:4818:f000:1ab:cafe:beef:1000:1')
... dev.bgp.neighbor(ip_addr='10.10.10.10', delete=True,
... rbridge_id='225')
... dev.bgp.neighbor(delete=True, rbridge_id='225',
... ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')
... dev.interface.ip_address(int_type='loopback', name='6',
... rbridge_id='225', ip_addr='6.6.6.6/32', delete=True)
... dev.interface.ip_address(int_type='loopback', name='6',
... ip_addr='0:0:0:0:0:ffff:606:606/128', rbridge_id='225',
... delete=True)
... output = dev.bgp.update_source(rbridge_id='225',
... int_type='loopback')
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NotImplementedError
KeyError
""" |
callback = kwargs.pop('callback', self._callback)
ip_addr = ip_interface(unicode(kwargs.pop('neighbor')))
config = self._update_source_xml(neighbor=ip_addr,
int_type=kwargs.pop('int_type'),
int_name=kwargs.pop('int_name'),
rbridge_id=kwargs.pop('rbridge_id',
'1'),
vrf=kwargs.pop('vrf', 'default'))
if kwargs.pop('get', False):
return callback(config, handler='get_config')
if kwargs.pop('delete', False):
config.find('.//*update-source').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Encodes a Python datetime.datetime object as an ECMA-262 compliant
<END_TASK>
<USER_TASK:>
Description:
def encode_datetime(o):
""" Encodes a Python datetime.datetime object as an ECMA-262 compliant
datetime string.""" |
r = o.isoformat()
if o.microsecond:
r = r[:23] + r[26:]
if r.endswith('+00:00'):
r = r[:-6] + 'Z'
return r |
<SYSTEM_TASK:>
Encodes a Python datetime.time object as an ECMA-262 compliant
<END_TASK>
<USER_TASK:>
Description:
def encode_time(o):
""" Encodes a Python datetime.time object as an ECMA-262 compliant
time string.""" |
r = o.isoformat()
if o.microsecond:
r = r[:12]
if r.endswith('+00:00'):
r = r[:-6] + 'Z'
return r |
<SYSTEM_TASK:>
Colorize text with hex code.
<END_TASK>
<USER_TASK:>
Description:
def colorize(text, color, background=False):
"""
Colorize text with hex code.
:param text: the text you want to paint
:param color: a hex color or rgb color
:param background: decide to colorize background
::
colorize('hello', 'ff0000')
colorize('hello', '#ff0000')
colorize('hello', (255, 0, 0))
""" |
if color in _styles:
c = Color(text)
c.styles = [_styles.index(color) + 1]
return c
c = Color(text)
if background:
c.bgcolor = _color2ansi(color)
else:
c.fgcolor = _color2ansi(color)
return c |
<SYSTEM_TASK:>
Checks if the given rule matches with any filter added.
<END_TASK>
<USER_TASK:>
Description:
def match(self, rule):
"""
Checks if the given rule matches with any filter added.
:param rule: The Flask rule to be matched.
:return: True if there is a filter that matches.
""" |
if len(self.filters) == 0:
return True
for filter in self.filters:
if filter.match(rule):
return True
return False |
<SYSTEM_TASK:>
Collects the data from the given parameters and emit it.
<END_TASK>
<USER_TASK:>
Description:
def trace(self, request, response, error, latency):
"""
Collects the data from the given parameters and emit it.
:param request: The Flask request.
:param response: The Flask response.
:param error: The error occurred if any.
:param latency: The time elapsed to process the request.
""" |
data = self.__collect_trace_data(request, response, error, latency)
self.inspector(data)
self.emitter(data) |
<SYSTEM_TASK:>
Writes the given tracing data to Python Logging.
<END_TASK>
<USER_TASK:>
Description:
def __default_emit_trace(self, data):
"""
Writes the given tracing data to Python Logging.
:param data: The tracing data to be written.
""" |
message = format_trace_data(data)
self.io.logger.info(message) |
<SYSTEM_TASK:>
Checks if the given rule matches with the filter.
<END_TASK>
<USER_TASK:>
Description:
def match(self, rule):
"""
Checks if the given rule matches with the filter.
:param rule: The Flask rule to be matched.
:return: True if the filter matches.
""" |
if self.methods:
for method in self.methods:
if method in rule.methods:
return True
if self.endpoints:
for endpoint in self.endpoints:
if endpoint == rule.endpoint:
return True
return False |
<SYSTEM_TASK:>
Add SNMP Community to NOS device.
<END_TASK>
<USER_TASK:>
Description:
def add_snmp_community(self, **kwargs):
"""
Add SNMP Community to NOS device.
Args:
community (str): Community string to be added to device.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `community` is not defined.
""" |
community = kwargs.pop('community')
callback = kwargs.pop('callback', self._callback)
config = ET.Element('config')
snmp_server = ET.SubElement(config, 'snmp-server',
xmlns=("urn:brocade.com:mgmt:"
"brocade-snmp"))
community_el = ET.SubElement(snmp_server, 'community')
community_name = ET.SubElement(community_el, 'community')
community_name.text = community
return callback(config) |
<SYSTEM_TASK:>
Add SNMP host to NOS device.
<END_TASK>
<USER_TASK:>
Description:
def add_snmp_host(self, **kwargs):
"""
Add SNMP host to NOS device.
Args:
host_info (tuple(str, str)): Tuple of host IP and port.
community (str): Community string to be added to device.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `host_info` or `community` is not defined.
""" |
host_info = kwargs.pop('host_info')
community = kwargs.pop('community')
callback = kwargs.pop('callback', self._callback)
config = ET.Element('config')
snmp_server = ET.SubElement(config, 'snmp-server',
xmlns=("urn:brocade.com:mgmt:"
"brocade-snmp"))
host = ET.SubElement(snmp_server, 'host')
ip_addr = ET.SubElement(host, 'ip')
ip_addr.text = host_info[0]
com = ET.SubElement(host, 'community')
com.text = community
udp_port = ET.SubElement(host, 'udp-port')
udp_port.text = host_info[1]
return callback(config) |
<SYSTEM_TASK:>
Compiles a SASS string
<END_TASK>
<USER_TASK:>
Description:
def compile_str(contents):
"""Compiles a SASS string
:param str contents: The SASS contents to compile
:returns: The compiled CSS
""" |
ctx = SASS_CLIB.sass_new_context()
ctx.contents.source_string = c_char_p(contents)
SASS_CLIB.compile(ctx)
if ctx.contents.error_status:
print(ctx.contents.error_message)
return ctx.contents.output_string or "" |
<SYSTEM_TASK:>
Loads the libsass library if it isn't already loaded.
<END_TASK>
<USER_TASK:>
Description:
def _load(self):
"""Loads the libsass library if it isn't already loaded.""" |
if self.clib is None:
root_path = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__ )), '..'))
path1 = os.path.join(root_path, 'sass.so')
path2 = os.path.join(root_path, '..', 'sass.so')
if os.path.exists(path1):
self.clib = cdll.LoadLibrary(path1)
elif os.path.exists(path1):
self.clib = cdll.LoadLibrary(path2)
else:
raise Exception("Could not load library")
self.clib.sass_new_context.restype = POINTER(SassContext)
self.clib.sass_new_file_context.restype = POINTER(SassFileContext)
self.clib.sass_new_folder_context.restype = POINTER(SassFolderContext)
self.clib.sass_compile.restype = c_int
self.clib.sass_compile.argtypes = [POINTER(SassContext)]
self.clib.sass_compile_file.restype = c_int
self.clib.sass_compile_file.argtypes = [POINTER(SassFileContext)]
self.clib.sass_compile_folder.restype = c_int
self.clib.sass_compile_folder.argtypes = [POINTER(SassFolderContext)] |
<SYSTEM_TASK:>
Set gateway type
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_set_overlaygw_type(self, **kwargs):
"""
Set gateway type
Args:
name (str): gateway-name
type (str): gateway-type
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
name = kwargs.pop('name')
type = kwargs.pop('type')
ip_args = dict(name=name, gw_type=type)
method_name = 'overlay_gateway_gw_type'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**ip_args)
output = self._callback(config)
return output |
<SYSTEM_TASK:>
Add a range of rbridge-ids
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_add_rbridgeid(self, **kwargs):
"""
Add a range of rbridge-ids
Args:
name (str): gateway-name
vlan (str): rbridge-ids range
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
name = kwargs.pop('name')
id = kwargs.pop('rb_range')
ip_args = dict(name=name, rb_add=id)
method_name = 'overlay_gateway_attach_rbridge_id_rb_add'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**ip_args)
output = self._callback(config)
return output |
<SYSTEM_TASK:>
Add loopback interface to the overlay-gateway
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_add_loopback_interface(self, **kwargs):
"""
Add loopback interface to the overlay-gateway
Args:
name (str): gateway-name
int_id (int): loopback inteface id
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
name = kwargs.pop('name')
id = kwargs.pop('int_id')
ip_args = dict(name=name, loopback_id=id)
method_name = 'overlay_gateway_ip_interface_loopback_loopback_id'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**ip_args)
output = self._callback(config)
return output |
<SYSTEM_TASK:>
Activate the hwvtep
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_activate_hwvtep(self, **kwargs):
"""
Activate the hwvtep
Args:
name (str): overlay_gateway name
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
name = kwargs.pop('name')
name_args = dict(name=name)
method_name = 'overlay_gateway_activate'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**name_args)
output = self._callback(config)
return output |
<SYSTEM_TASK:>
Identifies exported VLANs in VXLAN gateway configurations.
<END_TASK>
<USER_TASK:>
Description:
def hwvtep_attach_vlan_vid(self, **kwargs):
"""
Identifies exported VLANs in VXLAN gateway configurations.
Args:
name (str): overlay_gateway name
vlan(str): vlan_id range
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
name = kwargs.pop('name')
mac = kwargs.pop('mac')
vlan = kwargs.pop('vlan')
name_args = dict(name=name, vid=vlan, mac=mac)
method_name = 'overlay_gateway_attach_vlan_mac'
method_class = self._brocade_tunnels
gw_attr = getattr(method_class, method_name)
config = gw_attr(**name_args)
output = self._callback(config)
return output |
<SYSTEM_TASK:>
Format the message of the logger.
<END_TASK>
<USER_TASK:>
Description:
def message(self, level, *args):
"""
Format the message of the logger.
You can rewrite this method to format your own message::
class MyLogger(Logger):
def message(self, level, *args):
msg = ' '.join(args)
if level == 'error':
return terminal.red(msg)
return msg
""" |
msg = ' '.join((str(o) for o in args))
if level not in ('start', 'end', 'debug', 'info', 'warn', 'error'):
return msg
return '%s: %s' % (level, msg) |
<SYSTEM_TASK:>
Make it the verbose log.
<END_TASK>
<USER_TASK:>
Description:
def verbose(self):
"""
Make it the verbose log.
A verbose log can be only shown when user want to see more logs.
It works as::
log.verbose.warn('this is a verbose warn')
log.verbose.info('this is a verbose info')
""" |
log = copy.copy(self)
log._is_verbose = True
return log |
<SYSTEM_TASK:>
Start a nested log.
<END_TASK>
<USER_TASK:>
Description:
def start(self, *args):
"""
Start a nested log.
""" |
if self._is_verbose:
# verbose log has no start method
return self
self.writeln('start', *args)
self._indent += 1
return self |
<SYSTEM_TASK:>
End a nested log.
<END_TASK>
<USER_TASK:>
Description:
def end(self, *args):
"""
End a nested log.
""" |
if self._is_verbose:
# verbose log has no end method
return self
if not args:
self._indent -= 1
return self
self.writeln('end', *args)
self._indent -= 1
return self |
<SYSTEM_TASK:>
A generic method to call any operation supported by the Lambda handler
<END_TASK>
<USER_TASK:>
Description:
def call_operation(self, operation, **kwargs):
"""
A generic method to call any operation supported by the Lambda handler
""" |
data = {'operation': operation}
data.update(kwargs)
return self.invoke(data) |
<SYSTEM_TASK:>
After receiving a datagram, generate the deferreds and add myself to it.
<END_TASK>
<USER_TASK:>
Description:
def datagramReceived(self, datagram, address):
"""
After receiving a datagram, generate the deferreds and add myself to it.
""" |
def write(result):
print "Writing %r" % result
self.transport.write(result, address)
d = self.d()
#d.addCallbacks(write, log.err)
d.addCallback(write) # errors are silently ignored!
d.callback(datagram) |
<SYSTEM_TASK:>
After receiving the data, generate the deferreds and add myself to it.
<END_TASK>
<USER_TASK:>
Description:
def dataReceived(self, data):
"""
After receiving the data, generate the deferreds and add myself to it.
""" |
def write(result):
print "Writing %r" % result
self.transport.write(result)
d = self.d()
d.addCallback(write) # errors are silently ignored!
d.callback(data) |
<SYSTEM_TASK:>
Configure an unnumbered interface.
<END_TASK>
<USER_TASK:>
Description:
def ip_unnumbered(self, **kwargs):
"""Configure an unnumbered interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name of interface id.
(For interface: 1/0/5, 1/0/10 etc).
delete (bool): True is the IP address is added and False if its to
be deleted (True, False). Default value will be False if not
specified.
donor_type (str): Interface type of the donor interface.
donor_name (str): Interface name of the donor interface.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, `donor_type`, or `donor_name` is
not passed.
ValueError: if `int_type`, `name`, `donor_type`, or `donor_name`
are invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.230']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.ip_address(int_type='loopback',
... name='1', ip_addr='4.4.4.4/32', rbridge_id='230')
... int_type = 'tengigabitethernet'
... name = '230/0/20'
... donor_type = 'loopback'
... donor_name = '1'
... output = dev.interface.disable_switchport(inter_type=
... int_type, inter=name)
... output = dev.interface.ip_unnumbered(int_type=int_type,
... name=name, donor_type=donor_type, donor_name=donor_name)
... output = dev.interface.ip_unnumbered(int_type=int_type,
... name=name, donor_type=donor_type, donor_name=donor_name,
... get=True)
... output = dev.interface.ip_unnumbered(int_type=int_type,
... name=name, donor_type=donor_type, donor_name=donor_name,
... delete=True)
... output = dev.interface.ip_address(int_type='loopback',
... name='1', ip_addr='4.4.4.4/32', rbridge_id='230',
... delete=True)
... output = dev.interface.ip_unnumbered(int_type='hodor',
... donor_name=donor_name, donor_type=donor_type, name=name)
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ValueError
""" |
kwargs['ip_donor_interface_name'] = kwargs.pop('donor_name')
kwargs['ip_donor_interface_type'] = kwargs.pop('donor_type')
kwargs['delete'] = kwargs.pop('delete', False)
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet']
if kwargs['int_type'] not in valid_int_types:
raise ValueError('int_type must be one of: %s' %
repr(valid_int_types))
unnumbered_type = self._ip_unnumbered_type(**kwargs)
unnumbered_name = self._ip_unnumbered_name(**kwargs)
if kwargs.pop('get', False):
return self._get_ip_unnumbered(unnumbered_type, unnumbered_name)
config = pynos.utilities.merge_xml(unnumbered_type, unnumbered_name)
return callback(config) |
<SYSTEM_TASK:>
Return the `ip unnumbered` donor name XML.
<END_TASK>
<USER_TASK:>
Description:
def _ip_unnumbered_name(self, **kwargs):
"""Return the `ip unnumbered` donor name XML.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
delete (bool): Remove the configuration if ``True``.
ip_donor_interface_name (str): The donor interface name (1, 2, etc)
Returns:
XML to be passed to the switch.
Raises:
None
""" |
method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\
'interface_name' % kwargs['int_type']
ip_unnumbered_name = getattr(self._interface, method_name)
config = ip_unnumbered_name(**kwargs)
if kwargs['delete']:
tag = 'ip-donor-interface-name'
config.find('.//*%s' % tag).set('operation', 'delete')
return config |
<SYSTEM_TASK:>
Return the `ip unnumbered` donor type XML.
<END_TASK>
<USER_TASK:>
Description:
def _ip_unnumbered_type(self, **kwargs):
"""Return the `ip unnumbered` donor type XML.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
delete (bool): Remove the configuration if ``True``.
ip_donor_interface_type (str): The donor interface type (loopback)
Returns:
XML to be passed to the switch.
Raises:
None
""" |
method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\
'interface_type' % kwargs['int_type']
ip_unnumbered_type = getattr(self._interface, method_name)
config = ip_unnumbered_type(**kwargs)
if kwargs['delete']:
tag = 'ip-donor-interface-type'
config.find('.//*%s' % tag).set('operation', 'delete')
return config |
<SYSTEM_TASK:>
Get and merge the `ip unnumbered` config from an interface.
<END_TASK>
<USER_TASK:>
Description:
def _get_ip_unnumbered(self, unnumbered_type, unnumbered_name):
"""Get and merge the `ip unnumbered` config from an interface.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
unnumbered_type: XML document with the XML to get the donor type.
unnumbered_name: XML document with the XML to get the donor name.
Returns:
Merged XML document.
Raises:
None
""" |
unnumbered_type = self._callback(unnumbered_type, handler='get_config')
unnumbered_name = self._callback(unnumbered_name, handler='get_config')
unnumbered_type = pynos.utilities.return_xml(str(unnumbered_type))
unnumbered_name = pynos.utilities.return_xml(str(unnumbered_name))
return pynos.utilities.merge_xml(unnumbered_type, unnumbered_name) |
<SYSTEM_TASK:>
Configure an anycast MAC address.
<END_TASK>
<USER_TASK:>
Description:
def anycast_mac(self, **kwargs):
"""Configure an anycast MAC address.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
mac (str): MAC address to configure
(example: '0011.2233.4455').
delete (bool): True is the IP address is added and False if its to
be deleted (True, False). Default value will be False if not
specified.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `mac` is not passed.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.230']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.services.vrrp(ip_version='6',
... enabled=True, rbridge_id='230')
... output = dev.services.vrrp(enabled=True,
... rbridge_id='230')
... output = dev.services.vrrp(ip_version='6',
... enabled=False, rbridge_id='230')
... output = dev.services.vrrp(enabled=False,
... rbridge_id='230')
... output = dev.interface.anycast_mac(rbridge_id='230',
... mac='0011.2233.4455')
... output = dev.interface.anycast_mac(rbridge_id='230',
... mac='0011.2233.4455', get=True)
... output = dev.interface.anycast_mac(rbridge_id='230',
... mac='0011.2233.4455', delete=True)
... output = dev.services.vrrp(ip_version='6', enabled=True,
... rbridge_id='230')
... output = dev.services.vrrp(enabled=True,
... rbridge_id='230')
""" |
callback = kwargs.pop('callback', self._callback)
anycast_mac = getattr(self._rbridge, 'rbridge_id_ip_static_ag_ip_'
'config_anycast_gateway_mac_ip_anycast_'
'gateway_mac')
config = anycast_mac(rbridge_id=kwargs.pop('rbridge_id', '1'),
ip_anycast_gateway_mac=kwargs.pop('mac'))
if kwargs.pop('get', False):
return callback(config, handler='get_config')
if kwargs.pop('delete', False):
config.find('.//*anycast-gateway-mac').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Configure BFD for Interface.
<END_TASK>
<USER_TASK:>
Description:
def bfd(self, **kwargs):
"""Configure BFD for Interface.
Args:
name (str): name of the interface to configure (230/0/1 etc)
int_type (str): interface type (gigabitethernet etc)
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
rx (str): BFD receive interval in milliseconds (300, 500, etc)
multiplier (str): BFD multiplier. (3, 7, 5, etc)
delete (bool): True if BFD configuration should be deleted.
Default value will be False if not specified.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `tx`, `rx`, or `multiplier` is not passed.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.230']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.bfd(name='230/0/4', rx='300',
... tx='300', multiplier='3', int_type='tengigabitethernet')
... output = dev.interface.bfd(name='230/0/4', rx='300',
... tx='300', multiplier='3',
... int_type='tengigabitethernet', get=True)
... output = dev.interface.bfd(name='230/0/4', rx='300',
... tx='300', multiplier='3',
... int_type='tengigabitethernet', delete=True)
""" |
int_type = str(kwargs.pop('int_type').lower())
kwargs['name'] = str(kwargs.pop('name'))
kwargs['min_tx'] = kwargs.pop('tx')
kwargs['min_rx'] = kwargs.pop('rx')
kwargs['delete'] = kwargs.pop('delete', False)
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet']
if int_type not in valid_int_types:
raise ValueError('int_type must be one of: %s' %
repr(valid_int_types))
kwargs['int_type'] = int_type
bfd_tx = self._bfd_tx(**kwargs)
bfd_rx = self._bfd_rx(**kwargs)
bfd_multiplier = self._bfd_multiplier(**kwargs)
if kwargs.pop('get', False):
return self._get_bfd(bfd_tx, bfd_rx, bfd_multiplier)
config = pynos.utilities.merge_xml(bfd_tx, bfd_rx)
config = pynos.utilities.merge_xml(config, bfd_multiplier)
return callback(config) |
<SYSTEM_TASK:>
Enable conversational arp learning on VDX switches
<END_TASK>
<USER_TASK:>
Description:
def conversational_arp(self, **kwargs):
"""Enable conversational arp learning on VDX switches
Args:
rbridge_id (str): rbridge-id for device.
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the conversation arp learning.
(True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `rbridge_id` is not passed.
ValueError: if `rbridge_id` is invalid.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.conversational_arp(rbridge_id="1")
... output = dev.interface.conversational_arp(rbridge_id="1",
get=True)
... output = dev.interface.conversational_arp(rbridge_id="1",
delete=True)
""" |
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
arp_config = getattr(self._rbridge,
'rbridge_id_host_table_aging_mode_conversational')
arp_args = dict(rbridge_id=rbridge_id)
config = arp_config(**arp_args)
if kwargs.pop('get', False):
output = callback(config, handler='get_config')
item = output.data.find('.//{*}aging-mode')
if item is not None:
return True
else:
return None
if kwargs.pop('delete', False):
config.find('.//*aging-mode').set('operation', 'delete')
return callback(config) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.