_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q256900 | parse_course_key | validation | def parse_course_key(course_identifier):
"""
Return the serialized course key given either a course run ID or course key.
"""
try:
course_run_key = CourseKey.from_string(course_identifier)
except InvalidKeyError:
# Assume | python | {
"resource": ""
} |
q256901 | EnterpriseXAPIClient.lrs | validation | def lrs(self):
"""
LRS client instance to be used for sending statements.
"""
return RemoteLRS(
version=self.lrs_configuration.version,
| python | {
"resource": ""
} |
q256902 | EnterpriseXAPIClient.save_statement | validation | def save_statement(self, statement):
"""
Save xAPI statement.
Arguments:
statement (EnterpriseStatement): xAPI Statement to send to the LRS.
Raises:
ClientError: If xAPI statement fails to save.
| python | {
"resource": ""
} |
q256903 | SapSuccessFactorsLearnerExporter.get_learner_data_records | validation | def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False):
"""
Return a SapSuccessFactorsLearnerDataTransmissionAudit with the given enrollment and course completion data.
If completed_date is None and the learner isn't passing, then course completion has not been met.
If no remote ID can be found, return None.
"""
completed_timestamp = None
course_completed = False
if completed_date is not None:
completed_timestamp = parse_datetime_to_epoch_millis(completed_date)
course_completed = is_passing
sapsf_user_id = enterprise_enrollment.enterprise_customer_user.get_remote_id()
if sapsf_user_id is not None:
SapSuccessFactorsLearnerDataTransmissionAudit = apps.get_model( # pylint: disable=invalid-name
'sap_success_factors',
'SapSuccessFactorsLearnerDataTransmissionAudit'
)
# We return two records here, one with the course key and one with the course run id, to account for
# uncertainty about the type of content (course vs. course run) that was sent to the integrated channel.
return [
SapSuccessFactorsLearnerDataTransmissionAudit(
enterprise_course_enrollment_id=enterprise_enrollment.id,
| python | {
"resource": ""
} |
q256904 | SapSuccessFactorsLearnerManger.unlink_learners | validation | def unlink_learners(self):
"""
Iterate over each learner and unlink inactive SAP channel learners.
This method iterates over each enterprise learner and unlink learner
from the enterprise if the learner is marked inactive in the related
integrated channel.
"""
sap_inactive_learners = self.client.get_inactive_sap_learners()
enterprise_customer = self.enterprise_configuration.enterprise_customer
if not sap_inactive_learners:
LOGGER.info(
'Enterprise customer {%s} has no SAPSF inactive learners',
enterprise_customer.name
)
return
provider_id = enterprise_customer.identity_provider
tpa_provider = get_identity_provider(provider_id)
if not tpa_provider:
LOGGER.info(
'Enterprise customer {%s} has no associated identity provider',
enterprise_customer.name
)
return None
for sap_inactive_learner in sap_inactive_learners:
social_auth_user = get_user_from_social_auth(tpa_provider, sap_inactive_learner['studentID'])
if not social_auth_user:
| python | {
"resource": ""
} |
q256905 | has_implicit_access_to_dashboard | validation | def has_implicit_access_to_dashboard(user, obj): # pylint: disable=unused-argument
"""
Check that if request user has implicit access to `ENTERPRISE_DASHBOARD_ADMIN_ROLE` feature role.
Returns:
boolean: whether the request user has access or not
"""
request = get_request_or_stub() | python | {
"resource": ""
} |
q256906 | has_implicit_access_to_catalog | validation | def has_implicit_access_to_catalog(user, obj): # pylint: disable=unused-argument
"""
Check that if request user has implicit access to `ENTERPRISE_CATALOG_ADMIN_ROLE` feature role.
Returns:
boolean: whether the request user has access or not
"""
request = get_request_or_stub()
| python | {
"resource": ""
} |
q256907 | has_implicit_access_to_enrollment_api | validation | def has_implicit_access_to_enrollment_api(user, obj): # pylint: disable=unused-argument
"""
Check that if request user has implicit access to `ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE` feature role.
Returns:
boolean: whether the request user has access or not
"""
request = get_request_or_stub() | python | {
"resource": ""
} |
q256908 | EnterpriseCustomerEntitlementInline.ecommerce_coupon_url | validation | def ecommerce_coupon_url(self, instance):
"""
Instance is EnterpriseCustomer. Return e-commerce coupon urls.
"""
if not instance.entitlement_id:
return "N/A"
return format_html(
| python | {
"resource": ""
} |
q256909 | dropHistoricalTable | validation | def dropHistoricalTable(apps, schema_editor):
"""
Drops the historical sap_success_factors table named herein.
"""
table_name = 'sap_success_factors_historicalsapsuccessfactorsenterprisecus80ad'
if table_name in | python | {
"resource": ""
} |
q256910 | export_as_csv_action | validation | def export_as_csv_action(description="Export selected objects as CSV file", fields=None, header=True):
"""
Return an export csv action.
Arguments:
description (string): action description
fields ([string]): list of model fields to include
header (bool): whether or not to output the column names as the first row
"""
# adapted from https://gist.github.com/mgerring/3645889
def export_as_csv(modeladmin, request, queryset): # pylint: disable=unused-argument
"""
Export model fields to CSV.
"""
opts = modeladmin.model._meta
if not fields:
field_names = [field.name for field in opts.fields]
else:
field_names = fields
response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = "attachment; filename={filename}.csv".format(
filename=str(opts).replace(".", "_")
)
writer = unicodecsv.writer(response, encoding="utf-8")
if header:
writer.writerow(field_names)
for obj in queryset:
row = []
| python | {
"resource": ""
} |
q256911 | get_clear_catalog_id_action | validation | def get_clear_catalog_id_action(description=None):
"""
Return the action method to clear the catalog ID for a EnterpriseCustomer.
"""
description = description or _("Unlink selected objects from existing course catalogs")
def clear_catalog_id(modeladmin, request, queryset): # pylint: disable=unused-argument
"""
Clear the catalog ID | python | {
"resource": ""
} |
q256912 | Account._login | validation | def _login(self, email, password):
"""
Login to pybotvac account using provided email and password.
:param email: email for pybotvac account
:param password: Password for pybotvac account
:return:
"""
response = requests.post(urljoin(self.ENDPOINT, 'sessions'),
json={'email': email,
'password': password,
'platform': 'ios',
| python | {
"resource": ""
} |
q256913 | Account.refresh_maps | validation | def refresh_maps(self):
"""
Get information about maps of the robots.
:return:
"""
for robot in self.robots:
resp2 = (
requests.get(urljoin(self.ENDPOINT, 'users/me/robots/{}/maps'.format(robot.serial)),
| python | {
"resource": ""
} |
q256914 | Account.refresh_robots | validation | def refresh_robots(self):
"""
Get information about robots connected to account.
:return:
"""
resp = requests.get(urljoin(self.ENDPOINT, 'dashboard'),
headers=self._headers)
resp.raise_for_status()
for robot in resp.json()['robots']:
if robot['mac_address'] is None:
continue # Ignore robots without mac-address
try:
self._robots.add(Robot(name=robot['name'],
serial=robot['serial'],
secret=robot['secret_key'],
| python | {
"resource": ""
} |
q256915 | Account.get_map_image | validation | def get_map_image(url, dest_path=None):
"""
Return a requested map from a robot.
:return:
"""
image = requests.get(url, stream=True, timeout=10)
if dest_path:
image_url = url.rsplit('/', 2)[1] + '-' + url.rsplit('/', 1)[1]
image_filename = image_url.split('?')[0]
dest = os.path.join(dest_path, | python | {
"resource": ""
} |
q256916 | Account.refresh_persistent_maps | validation | def refresh_persistent_maps(self):
"""
Get information about persistent maps of the robots.
:return:
"""
for robot in self._robots:
resp2 = (requests.get(urljoin(
self.ENDPOINT,
'users/me/robots/{}/persistent_maps'.format(robot.serial)), | python | {
"resource": ""
} |
q256917 | _calculate_distance | validation | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / | python | {
"resource": ""
} |
q256918 | graph2dict | validation | def graph2dict(g, return_dict_of_dict=True):
"""Takes a graph and returns an adjacency list.
Parameters
----------
g : :any:`networkx.DiGraph`, :any:`networkx.Graph`, etc.
Any object that networkx can turn into a
:any:`DiGraph<networkx.DiGraph>`.
return_dict_of_dict : bool (optional, default: ``True``)
Specifies whether this function will return a dict of dicts
or a dict of lists.
Returns
-------
adj : dict
An adjacency representation of graph as a dictionary of
dictionaries, where a key is the vertex index for a vertex
``v`` and the values are :class:`dicts<.dict>` with keys for
the vertex index and values as edge properties.
Examples
--------
>>> import queueing_tool as qt
>>> import networkx as nx
| python | {
"resource": ""
} |
q256919 | _matrix2dict | validation | def _matrix2dict(matrix, etype=False):
"""Takes an adjacency matrix and returns an adjacency list."""
n = len(matrix)
adj = {k: {} for k in range(n)}
for k in range(n):
for j in range(n):
| python | {
"resource": ""
} |
q256920 | _dict2dict | validation | def _dict2dict(adj_dict):
"""Takes a dictionary based representation of an adjacency list
and returns a dict of dicts based representation.
"""
item = adj_dict.popitem()
adj_dict[item[0]] = item[1]
if not isinstance(item[1], dict):
new_dict = {}
for key, | python | {
"resource": ""
} |
q256921 | adjacency2graph | validation | def adjacency2graph(adjacency, edge_type=None, adjust=1, **kwargs):
"""Takes an adjacency list, dict, or matrix and returns a graph.
The purpose of this function is take an adjacency list (or matrix)
and return a :class:`.QueueNetworkDiGraph` that can be used with a
:class:`.QueueNetwork` instance. The Graph returned has the
``edge_type`` edge property set for each edge. Note that the graph may
be altered.
Parameters
----------
adjacency : dict or :class:`~numpy.ndarray`
An adjacency list as either a dict, or an adjacency matrix.
adjust : int ``{1, 2}`` (optional, default: 1)
Specifies what to do when the graph has terminal vertices
(nodes with no out-edges). Note that if ``adjust`` is not 2
then it is assumed to be 1. There are two choices:
* ``adjust = 1``: A loop is added to each terminal node in the
graph, and their ``edge_type`` of that loop is set to 0.
* ``adjust = 2``: All edges leading to terminal nodes have
their ``edge_type`` set to 0.
**kwargs :
Unused.
Returns
-------
out : :any:`networkx.DiGraph`
A directed graph with the ``edge_type`` edge property.
Raises
------
TypeError
Is raised if ``adjacency`` is not a dict or
:class:`~numpy.ndarray`.
Examples
--------
If terminal nodes are such that all in-edges have edge type ``0``
then nothing is changed. However, if a node is a terminal node then
a loop is added with edge type 0.
>>> import queueing_tool as qt
>>> adj = {
... 0: {1: {}},
... 1: {2: {},
... 3: {}},
... 3: {0: {}}}
>>> eTy = {0: {1: 1}, 1: {2: 2, 3: 4}, 3: {0: 1}}
>>> # A loop will be added to vertex 2
>>> g = qt.adjacency2graph(adj, edge_type=eTy)
>>> ans = qt.graph2dict(g)
>>> sorted(ans.items()) # doctest: +NORMALIZE_WHITESPACE
[(0, {1: {'edge_type': 1}}),
(1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),
(2, {2: {'edge_type': 0}}),
(3, {0: {'edge_type': 1}})]
You can use a dict of lists to represent the adjacency list.
>>> adj = {0 : [1], 1: [2, 3], 3: [0]}
>>> g = qt.adjacency2graph(adj, edge_type=eTy)
>>> ans = qt.graph2dict(g)
>>> sorted(ans.items()) # doctest: +NORMALIZE_WHITESPACE
[(0, {1: {'edge_type': 1}}),
(1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),
(2, {2: {'edge_type': 0}}),
(3, {0: {'edge_type': 1}})]
Alternatively, you could have this function adjust the edges that
lead to terminal vertices by changing their edge | python | {
"resource": ""
} |
q256922 | QueueNetworkDiGraph.get_edge_type | validation | def get_edge_type(self, edge_type):
"""Returns all edges with the specified edge type.
Parameters
----------
edge_type : int
An integer specifying what type of edges to return.
Returns
-------
out : list of 2-tuples
A list of 2-tuples representing the edges in the graph
with the specified edge type.
Examples
--------
Lets get type 2 edges from the following graph | python | {
"resource": ""
} |
q256923 | QueueNetworkDiGraph.draw_graph | validation | def draw_graph(self, line_kwargs=None, scatter_kwargs=None, **kwargs):
"""Draws the graph.
Uses matplotlib, specifically
:class:`~matplotlib.collections.LineCollection` and
:meth:`~matplotlib.axes.Axes.scatter`. Gets the default
keyword arguments for both methods by calling
:meth:`~.QueueNetworkDiGraph.lines_scatter_args` first.
Parameters
----------
line_kwargs : dict (optional, default: ``None``)
Any keyword arguments accepted by
:class:`~matplotlib.collections.LineCollection`
scatter_kwargs : dict (optional, default: ``None``)
Any keyword arguments accepted by
:meth:`~matplotlib.axes.Axes.scatter`.
bgcolor : list (optional, keyword only)
A list with 4 floats representing a RGBA color. Defaults
to ``[1, 1, 1, 1]``.
figsize : tuple (optional, keyword only, default: ``(7, 7)``)
The width and height of the figure in inches.
kwargs :
| python | {
"resource": ""
} |
q256924 | QueueNetworkDiGraph.lines_scatter_args | validation | def lines_scatter_args(self, line_kwargs=None, scatter_kwargs=None, pos=None):
"""Returns the arguments used when plotting.
Takes any keyword arguments for
:class:`~matplotlib.collections.LineCollection` and
:meth:`~matplotlib.axes.Axes.scatter` and returns two
dictionaries with all the defaults set.
Parameters
----------
line_kwargs : dict (optional, default: ``None``)
Any keyword arguments accepted by
:class:`~matplotlib.collections.LineCollection`.
scatter_kwargs : dict (optional, default: ``None``)
Any keyword arguments accepted by
:meth:`~matplotlib.axes.Axes.scatter`.
Returns
-------
tuple
A 2-tuple of dicts. The first entry is the keyword
arguments for
:class:`~matplotlib.collections.LineCollection` and the
second is the keyword args for
:meth:`~matplotlib.axes.Axes.scatter`.
Notes
-----
If a specific keyword argument is not passed then the defaults
are used.
"""
if pos is not None:
self.set_pos(pos)
elif self.pos is None:
self.set_pos()
edge_pos = [0 for e in self.edges()]
for e in self.edges():
ei = self.edge_index[e]
edge_pos[ei] = (self.pos[e[0]], self.pos[e[1]])
line_collecton_kwargs = {
'segments': edge_pos,
'colors': self.edge_color,
'linewidths': (1,),
'antialiaseds': (1,),
'linestyle': 'solid',
'transOffset': None,
'cmap': plt.cm.ocean_r,
'pickradius': 5,
'zorder': 0,
'facecolors': None,
'norm': None,
'offsets': None,
'offset_position': 'screen',
'hatch': None, | python | {
"resource": ""
} |
q256925 | poisson_random_measure | validation | def poisson_random_measure(t, rate, rate_max):
"""A function that returns the arrival time of the next arrival for
a Poisson random measure.
Parameters
----------
t : float
The start time from which to simulate the next arrival time.
rate : function
The *intensity function* for the measure, where ``rate(t)`` is
the expected arrival rate at time ``t``.
rate_max : float
The maximum value of the ``rate`` function.
Returns
-------
out : float
The time of the next arrival.
Notes
-----
This function returns the time of the next arrival, where the
distribution of the number of arrivals between times :math:`t` and
:math:`t+s` is Poisson with mean
.. math::
\int_{t}^{t+s} dx \, r(x)
where :math:`r(t)` is the supplied ``rate`` function. This function
can only simulate processes that have bounded intensity functions.
| python | {
"resource": ""
} |
q256926 | QueueServer._current_color | validation | def _current_color(self, which=0):
"""Returns a color for the queue.
Parameters
----------
which : int (optional, default: ``0``)
Specifies the type of color to return.
Returns
-------
color : list
Returns a RGBA color that is represented as a list with 4
entries where each entry can be any floating point number
between 0 and 1.
* If ``which`` is 1 then it returns the color of the edge
as if it were a self loop. This is specified in
``colors['edge_loop_color']``.
* If ``which`` is 2 then it returns the color of the vertex
pen color (defined as color/vertex_color in
:meth:`.QueueNetworkDiGraph.graph_draw`). This is
specified in ``colors['vertex_color']``.
* If ``which`` is anything else, then it returns the a
shade of the edge that is proportional to the number of
agents in the system -- which includes those being
servered and those waiting to be served. More agents
correspond to darker edge colors. Uses
| python | {
"resource": ""
} |
q256927 | QueueServer.fetch_data | validation | def fetch_data(self, return_header=False):
"""Fetches data from the queue.
Parameters
----------
return_header : bool (optonal, default: ``False``)
Determines whether the column headers are returned.
Returns
-------
data : :class:`~numpy.ndarray`
A six column :class:`~numpy.ndarray` of all the data. The
columns are:
* 1st: The arrival time of an agent.
* 2nd: The service start time of an agent.
* 3rd: The departure time of an agent.
* 4th: The length of the queue upon the agents arrival.
* 5th: The total number of :class:`Agents<.Agent>` in the
:class:`.QueueServer`.
* 6th: The :class:`QueueServer's<.QueueServer>` edge index.
headers : str (optional)
A comma seperated string of the column headers. Returns
``'arrival,service,departure,num_queued,num_total,q_id'``
"""
qdata = []
for d in self.data.values():
qdata.extend(d)
dat = np.zeros((len(qdata), 6))
| python | {
"resource": ""
} |
q256928 | QueueServer.next_event_description | validation | def next_event_description(self):
"""Returns an integer representing whether the next event is
an arrival, a departure, or nothing.
Returns
-------
out : int
An integer representing whether the next event is an
| python | {
"resource": ""
} |
q256929 | QueueServer.set_num_servers | validation | def set_num_servers(self, n):
"""Change the number of servers in the queue to ``n``.
Parameters
----------
n : int or :const:`numpy.infty`
A positive integer (or ``numpy.infty``) to set the number
of queues in the system to.
Raises
------
TypeError
If ``n`` is not an integer or positive infinity then this
error is raised.
ValueError
If ``n`` is not positive.
"""
if not isinstance(n, numbers.Integral) and n | python | {
"resource": ""
} |
q256930 | QueueServer.simulate | validation | def simulate(self, n=1, t=None, nA=None, nD=None):
"""This method simulates the queue forward for a specified
amount of simulation time, or for a specific number of
events.
Parameters
----------
n : int (optional, default: ``1``)
The number of events to simulate. If ``t``, ``nA``, and
``nD`` are not given then this parameter is used.
t : float (optional)
The minimum amount of simulation time to simulate forward.
nA : int (optional)
Simulate until ``nA`` additional arrivals are observed.
nD : int (optional)
Simulate until ``nD`` additional departures are observed.
Examples
--------
Before any simulations can take place the ``QueueServer`` must
be activated:
>>> import queueing_tool as qt
>>> import numpy as np
>>> rate = lambda t: 2 + 16 * np.sin(np.pi * t / 8)**2
>>> arr = lambda t: qt.poisson_random_measure(t, rate, 18)
>>> ser = lambda t: t + np.random.gamma(4, 0.1)
>>> q = qt.QueueServer(5, arrival_f=arr, service_f=ser, seed=54)
>>> q.set_active()
| python | {
"resource": ""
} |
q256931 | _get_queues | validation | def _get_queues(g, queues, edge, edge_type):
"""Used to specify edge indices from different types of arguments."""
INT = numbers.Integral
if isinstance(queues, INT):
queues = [queues]
elif queues is None:
if edge is not None:
if isinstance(edge, tuple):
if isinstance(edge[0], INT) and isinstance(edge[1], INT):
queues = [g.edge_index[edge]]
elif isinstance(edge[0], collections.Iterable):
| python | {
"resource": ""
} |
q256932 | QueueNetwork.animate | validation | def animate(self, out=None, t=None, line_kwargs=None,
scatter_kwargs=None, **kwargs):
"""Animates the network as it's simulating.
The animations can be saved to disk or viewed in interactive
mode. Closing the window ends the animation if viewed in
interactive mode. This method calls
:meth:`~matplotlib.axes.scatter`, and
:class:`~matplotlib.collections.LineCollection`, and any
keyword arguments they accept can be passed to them.
Parameters
----------
out : str (optional)
The location where the frames for the images will be saved.
If this parameter is not given, then the animation is shown
in interactive mode.
t : float (optional)
The amount of simulation time to simulate forward. If
given, and ``out`` is given, ``t`` is used instead of
``n``.
line_kwargs : dict (optional, default: None)
Any keyword arguments accepted by
:class:`~matplotlib.collections.LineCollection`.
scatter_kwargs : dict (optional, default: None)
Any keyword arguments accepted by
:meth:`~matplotlib.axes.Axes.scatter`.
bgcolor : list (optional, keyword only)
A list with 4 floats representing a RGBA color. The
default is defined in ``self.colors['bgcolor']``.
figsize : tuple (optional, keyword only, default: ``(7, 7)``)
The width and height of the figure in inches.
**kwargs :
This method calls
:class:`~matplotlib.animation.FuncAnimation` and
optionally :meth:`.matplotlib.animation.FuncAnimation.save`.
Any keyword that can be passed to these functions are
passed via ``kwargs``.
Notes
-----
There are several parameters automatically set and passed to
matplotlib's :meth:`~matplotlib.axes.Axes.scatter`,
:class:`~matplotlib.collections.LineCollection`, and
:class:`~matplotlib.animation.FuncAnimation` by default.
These include:
* :class:`~matplotlib.animation.FuncAnimation`: Uses the
defaults for that function. Saving the animation is done
by passing the 'filename' keyword argument to this method.
This method also accepts any keyword arguments accepted
by :meth:`~matplotlib.animation.FuncAnimation.save`.
* :class:`~matplotlib.collections.LineCollection`: The default
arguments are taken from
:meth:`.QueueNetworkDiGraph.lines_scatter_args`.
* :meth:`~matplotlib.axes.Axes.scatter`: The default
arguments are taken from
:meth:`.QueueNetworkDiGraph.lines_scatter_args`.
Raises
------
QueueingToolError
Will raise a :exc:`.QueueingToolError` if the
``QueueNetwork`` has not been initialized. Call
:meth:`.initialize` before running.
Examples
--------
This function works similarly to ``QueueNetwork's``
:meth:`.draw` method.
>>> import queueing_tool as qt
>>> g = qt.generate_pagerank_graph(100, seed=13)
>>> net = qt.QueueNetwork(g, seed=13)
>>> net.initialize()
>>> net.animate(figsize=(4, 4)) # doctest: +SKIP
To stop the animation just close the window. If you want to
write the animation to disk run something like the following:
>>> kwargs = {
... 'filename': 'test.mp4',
... 'frames': 300,
... 'fps': 30,
... 'writer': 'mencoder',
... 'figsize': (4, 4),
... 'vertex_size': 15
... }
>>> net.animate(**kwargs) # doctest: +SKIP
"""
if not self._initialized:
msg = ("Network has not been initialized. "
"Call '.initialize()' first.")
raise QueueingToolError(msg)
if not HAS_MATPLOTLIB:
msg = "Matplotlib is necessary to animate a simulation."
raise ImportError(msg)
self._update_all_colors()
kwargs.setdefault('bgcolor', self.colors['bgcolor'])
fig = plt.figure(figsize=kwargs.get('figsize', (7, 7)))
ax = fig.gca()
mpl_kwargs | python | {
"resource": ""
} |
q256933 | QueueNetwork.clear | validation | def clear(self):
"""Resets the queue to its initial state.
The attributes ``t``, ``num_events``, ``num_agents`` are set to
zero, :meth:`.reset_colors` is called, and the
:meth:`.QueueServer.clear` method is called for each queue in
the network.
Notes
-----
``QueueNetwork`` must be re-initialized before any simulations
can run.
"""
self._t = 0
self.num_events | python | {
"resource": ""
} |
q256934 | QueueNetwork.clear_data | validation | def clear_data(self, queues=None, edge=None, edge_type=None):
"""Clears data from all queues.
If none of the parameters are given then every queue's data is
cleared.
Parameters
----------
queues : int or an iterable of int (optional)
The edge index (or an iterable of edge indices) identifying
the :class:`QueueServer(s)<.QueueServer>` whose data will
be cleared.
edge : 2-tuple of int or *array_like* (optional)
Explicitly specify which queues' data to clear. Must be
either:
* A 2-tuple of the edge's source and target vertex | python | {
"resource": ""
} |
q256935 | QueueNetwork.copy | validation | def copy(self):
"""Returns a deep copy of itself."""
net = QueueNetwork(None)
net.g = self.g.copy()
net.max_agents = copy.deepcopy(self.max_agents)
net.nV = copy.deepcopy(self.nV)
net.nE = copy.deepcopy(self.nE)
net.num_agents = copy.deepcopy(self.num_agents)
net.num_events = copy.deepcopy(self.num_events)
net._t = copy.deepcopy(self._t)
net._initialized = copy.deepcopy(self._initialized)
net._prev_edge = copy.deepcopy(self._prev_edge)
net._blocking = copy.deepcopy(self._blocking)
| python | {
"resource": ""
} |
q256936 | QueueNetwork.draw | validation | def draw(self, update_colors=True, line_kwargs=None,
scatter_kwargs=None, **kwargs):
"""Draws the network. The coloring of the network corresponds
to the number of agents at each queue.
Parameters
----------
update_colors : ``bool`` (optional, default: ``True``).
Specifies whether all the colors are updated.
line_kwargs : dict (optional, default: None)
Any keyword arguments accepted by
:class:`~matplotlib.collections.LineCollection`
scatter_kwargs : dict (optional, default: None)
Any keyword arguments accepted by
:meth:`~matplotlib.axes.Axes.scatter`.
bgcolor : list (optional, keyword only)
A list with 4 floats representing a RGBA color. The
default is defined in ``self.colors['bgcolor']``.
figsize : tuple (optional, keyword only, default: ``(7, 7)``)
The width and height of the canvas in inches.
**kwargs
Any parameters to pass to
:meth:`.QueueNetworkDiGraph.draw_graph`.
Notes
-----
This method relies heavily on
:meth:`.QueueNetworkDiGraph.draw_graph`. Also, there is a
parameter that sets the background | python | {
"resource": ""
} |
q256937 | QueueNetwork.get_agent_data | validation | def get_agent_data(self, queues=None, edge=None, edge_type=None, return_header=False):
"""Gets data from queues and organizes it by agent.
If none of the parameters are given then data from every
:class:`.QueueServer` is retrieved.
Parameters
----------
queues : int or *array_like* (optional)
The edge index (or an iterable of edge indices) identifying
the :class:`QueueServer(s)<.QueueServer>` whose data will
be retrieved.
edge : 2-tuple of int or *array_like* (optional)
Explicitly specify which queues to retrieve agent data
from. Must be either:
* A 2-tuple of the edge's source and target vertex
indices, or
* An iterable of 2-tuples of the edge's source and
target vertex indices.
edge_type : int or an iterable of int (optional)
A integer, or a collection of integers identifying which
edge types to retrieve agent data from.
return_header : bool (optonal, default: False)
Determines whether the column headers are returned.
Returns
-------
dict
Returns a ``dict`` where the keys are the
:class:`Agent's<.Agent>` ``agent_id`` and the values are
:class:`ndarrays<~numpy.ndarray>` for that
:class:`Agent's<.Agent>` data. The columns of this array
are as follows:
* First: The arrival time of an agent.
* Second: The service start time of an agent.
* Third: The departure time of an agent.
* Fourth: The length of the queue upon the agents arrival.
* Fifth: The total number of :class:`Agents<.Agent>` in the
:class:`.QueueServer`.
* Sixth: the :class:`QueueServer's<.QueueServer>` id
(its edge index).
headers : str (optional)
A comma seperated string of the column headers. Returns
``'arrival,service,departure,num_queued,num_total,q_id'``
"""
queues = _get_queues(self.g, queues, | python | {
"resource": ""
} |
q256938 | QueueNetwork.get_queue_data | validation | def get_queue_data(self, queues=None, edge=None, edge_type=None, return_header=False):
"""Gets data from all the queues.
If none of the parameters are given then data from every
:class:`.QueueServer` is retrieved.
Parameters
----------
queues : int or an *array_like* of int, (optional)
The edge index (or an iterable of edge indices) identifying
the :class:`QueueServer(s)<.QueueServer>` whose data will
be retrieved.
edge : 2-tuple of int or *array_like* (optional)
Explicitly specify which queues to retrieve data from. Must
be either:
* A 2-tuple of the edge's source and target vertex
indices, or
* An iterable of 2-tuples of the edge's source and
target vertex indices.
edge_type : int or an iterable of int (optional)
A integer, or a collection of integers identifying which
edge types to retrieve data from.
return_header : bool (optonal, default: False)
Determines whether the column headers are returned.
Returns
-------
out : :class:`~numpy.ndarray`
* 1st: The arrival time of an agent.
| python | {
"resource": ""
} |
q256939 | QueueNetwork.initialize | validation | def initialize(self, nActive=1, queues=None, edges=None, edge_type=None):
"""Prepares the ``QueueNetwork`` for simulation.
Each :class:`.QueueServer` in the network starts inactive,
which means they do not accept arrivals from outside the
network, and they have no agents in their system. This method
sets queues to active, which then allows agents to arrive from
outside the network.
Parameters
----------
nActive : int (optional, default: ``1``)
The number of queues to set as active. The queues are
selected randomly.
queues : int *array_like* (optional)
The edge index (or an iterable of edge indices) identifying
the :class:`QueueServer(s)<.QueueServer>` to make active by.
edges : 2-tuple of int or *array_like* (optional)
Explicitly specify which queues to make active. Must be
either:
* A 2-tuple of the edge's source and target vertex
indices, or
* An iterable of 2-tuples of the edge's source and
target vertex indices.
edge_type : int or an iterable of int (optional)
A integer, or a collection of integers identifying which
edge types will be set active.
Raises
------
ValueError
If ``queues``, ``egdes``, and ``edge_type`` are all ``None``
and ``nActive`` is an integer less than 1
:exc:`~ValueError` is raised.
TypeError
If ``queues``, ``egdes``, and ``edge_type`` are all ``None``
and ``nActive`` is not an integer then a :exc:`~TypeError`
is raised.
QueueingToolError
Raised if all the queues specified are
:class:`NullQueues<.NullQueue>`.
Notes
-----
:class:`NullQueues<.NullQueue>` cannot be activated, and are
sifted out if they are specified. More specifically, every edge
with edge type 0 is sifted out.
"""
if queues is None and edges is None and edge_type is None:
if nActive >= 1 and isinstance(nActive, numbers.Integral):
| python | {
"resource": ""
} |
q256940 | QueueNetwork.next_event_description | validation | def next_event_description(self):
"""Returns whether the next event is an arrival or a departure
and the queue the event is accuring at.
Returns
-------
des : str
Indicates whether the next event is an arrival, a
departure, or nothing; returns ``'Arrival'``,
``'Departure'``, or ``'Nothing'``.
edge : int or ``None``
The edge index of the edge that this event will occur at.
If there are no events then ``None`` is returned.
"""
if self._fancy_heap.size == 0:
| python | {
"resource": ""
} |
q256941 | QueueNetwork.reset_colors | validation | def reset_colors(self):
"""Resets all edge and vertex colors to their default values."""
for k, e in enumerate(self.g.edges()):
self.g.set_ep(e, 'edge_color', self.edge2queue[k].colors['edge_color'])
| python | {
"resource": ""
} |
q256942 | QueueNetwork.set_transitions | validation | def set_transitions(self, mat):
"""Change the routing transitions probabilities for the
network.
Parameters
----------
mat : dict or :class:`~numpy.ndarray`
A transition routing matrix or transition dictionary. If
passed a dictionary, the keys are source vertex indices and
the values are dictionaries with target vertex indicies
as the keys and the probabilities of routing from the
source to the target as the values.
Raises
------
ValueError
A :exc:`.ValueError` is raised if: the keys in the dict
don't match with a vertex index in the graph; or if the
:class:`~numpy.ndarray` is passed with the wrong shape,
must be (``num_vertices``, ``num_vertices``); or the values
passed are not probabilities (for each vertex they are
positive and sum to 1);
TypeError
A :exc:`.TypeError` is raised if mat is not a dict or
:class:`~numpy.ndarray`.
Examples
--------
The default transition matrix is every out edge being equally
likely:
>>> import queueing_tool as qt
>>> adjacency = {
... 0: [2],
... 1: [2, 3],
... 2: [0, 1, 2, 4],
... 3: [1],
... 4: [2],
... }
>>> g = qt.adjacency2graph(adjacency)
>>> net = qt.QueueNetwork(g)
>>> net.transitions(False) # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
{0: {2: 1.0},
1: {2: 0.5, 3: 0.5},
2: {0: 0.25, 1: 0.25, 2: 0.25, 4: 0.25},
3: {1: 1.0},
4: {2: 1.0}}
If you want to change only one vertex's transition
probabilities, you can do so with the following:
>>> net.set_transitions({1 : {2: 0.75, 3: 0.25}})
>>> net.transitions(False) # doctest: +ELLIPSIS
| python | {
"resource": ""
} |
q256943 | QueueNetwork.show_active | validation | def show_active(self, **kwargs):
"""Draws the network, highlighting active queues.
The colored vertices represent vertices that have at least one
queue on an in-edge that is active. Dark edges represent
queues that are active, light edges represent queues that are
inactive.
Parameters
----------
**kwargs
Any additional parameters to pass to :meth:`.draw`, and
:meth:`.QueueNetworkDiGraph.draw_graph`.
Notes
-----
Active queues are :class:`QueueServers<.QueueServer>` that
accept arrivals from outside the network. The colors are
defined by the class attribute ``colors``. The relevant keys
are ``vertex_active``, ``vertex_inactive``, ``edge_active``,
and ``edge_inactive``.
"""
g = self.g
for v in g.nodes():
self.g.set_vp(v, 'vertex_color', [0, 0, 0, 0.9])
is_active = False
my_iter = g.in_edges(v) if g.is_directed() else g.out_edges(v)
for e in my_iter:
ei = g.edge_index[e]
| python | {
"resource": ""
} |
q256944 | QueueNetwork.show_type | validation | def show_type(self, edge_type, **kwargs):
"""Draws the network, highlighting queues of a certain type.
The colored vertices represent self loops of type ``edge_type``.
Dark edges represent queues of type ``edge_type``.
Parameters
----------
edge_type : int
The type of vertices and edges to be shown.
**kwargs
Any additional parameters to pass to :meth:`.draw`, and
:meth:`.QueueNetworkDiGraph.draw_graph`
Notes
-----
The colors are defined by the class attribute ``colors``. The
relevant colors are ``vertex_active``, ``vertex_inactive``,
``vertex_highlight``, ``edge_active``, and ``edge_inactive``.
Examples
--------
The following code highlights all edges with edge type ``2``.
If the edge is a loop then the vertex is highlighted as well.
In this case all edges with edge type ``2`` happen to be loops.
>>> import queueing_tool as qt
>>> g = qt.generate_pagerank_graph(100, seed=13)
>>> net = qt.QueueNetwork(g, seed=13)
>>> fname = 'edge_type_2.png'
>>> net.show_type(2, fname=fname) # doctest: +SKIP
.. figure:: edge_type_2-1.png
:align: center
"""
for v in self.g.nodes():
| python | {
"resource": ""
} |
q256945 | QueueNetwork.simulate | validation | def simulate(self, n=1, t=None):
"""Simulates the network forward.
Simulates either a specific number of events or for a specified
amount of simulation time.
Parameters
----------
n : int (optional, default: 1)
The number of events to simulate. If ``t`` is not given
then this parameter is used.
t : float (optional)
The amount of simulation time to simulate forward. If
given, ``t`` is used instead of ``n``.
Raises
------
QueueingToolError
Will raise a :exc:`.QueueingToolError` if the
``QueueNetwork`` has not been initialized. Call
:meth:`.initialize` before calling this method.
Examples
--------
Let ``net`` denote your instance of a ``QueueNetwork``. Before
you simulate, you need to initialize the network, which allows
arrivals from outside the network. To initialize with 2 (random
chosen) edges accepting arrivals run:
>>> import queueing_tool as qt
>>> g = qt.generate_pagerank_graph(100, seed=50)
>>> net = qt.QueueNetwork(g, seed=50)
>>> net.initialize(2)
To simulate the network 50000 events run:
>>> net.num_events
0
| python | {
"resource": ""
} |
q256946 | QueueNetwork.start_collecting_data | validation | def start_collecting_data(self, queues=None, edge=None, edge_type=None):
"""Tells the queues to collect data on agents' arrival, service
start, and departure times.
If none of the parameters are given then every
:class:`.QueueServer` will start collecting data.
Parameters
----------
queues : :any:`int`, *array_like* (optional)
The edge index (or an iterable of edge indices) identifying
the :class:`QueueServer(s)<.QueueServer>` that will start
collecting data.
edge : 2-tuple of int or *array_like* (optional)
Explicitly specify which queues will collect data. Must be
either:
| python | {
"resource": ""
} |
q256947 | QueueNetwork.stop_collecting_data | validation | def stop_collecting_data(self, queues=None, edge=None, edge_type=None):
"""Tells the queues to stop collecting data on agents.
If none of the parameters are given then every
:class:`.QueueServer` will stop collecting data.
Parameters
----------
queues : int, *array_like* (optional)
The edge index (or an iterable of edge indices) identifying
the :class:`QueueServer(s)<.QueueServer>` that will stop
| python | {
"resource": ""
} |
q256948 | QueueNetwork.transitions | validation | def transitions(self, return_matrix=True):
"""Returns the routing probabilities for each vertex in the
graph.
Parameters
----------
return_matrix : bool (optional, the default is ``True``)
Specifies whether an :class:`~numpy.ndarray` is returned.
If ``False``, a dict is returned instead.
Returns
-------
out : a dict or :class:`~numpy.ndarray`
The transition probabilities for each vertex in the graph.
If ``out`` is an :class:`~numpy.ndarray`, then
``out[v, u]`` returns the probability of a transition from
vertex ``v`` to vertex ``u``. If ``out`` is a dict
then ``out_edge[v][u]`` is the probability of moving from
vertex ``v`` to the vertex ``u``.
Examples
--------
Lets change the routing probabilities:
>>> import queueing_tool as qt
>>> import networkx as nx
>>> g = nx.sedgewick_maze_graph()
>>> net = qt.QueueNetwork(g)
Below is an adjacency list for the graph ``g``.
>>> ans = qt.graph2dict(g, False)
>>> {k: sorted(v) for k, v in ans.items()}
... # doctest: +NORMALIZE_WHITESPACE
{0: [2, 5, 7],
1: [7],
2: [0, 6],
3: [4, 5],
4: [3, 5, 6, 7],
5: [0, 3, 4],
6: [2, 4],
7: [0, 1, 4]}
The default transition matrix is every out edge being equally
likely:
>>> net.transitions(False) # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
{0: {2: 0.333..., 5: 0.333..., 7: 0.333...},
1: {7: 1.0},
2: {0: 0.5, 6: 0.5},
3: {4: 0.5, 5: 0.5},
4: {3: 0.25, 5: 0.25, 6: 0.25, 7: 0.25},
5: {0: 0.333..., 3: 0.333..., 4: 0.333...},
6: {2: 0.5, 4: 0.5},
7: {0: 0.333..., 1: 0.333..., 4: 0.333...}}
Now we will generate a random routing matrix:
>>> mat = qt.generate_transition_matrix(g, seed=96)
>>> net.set_transitions(mat)
>>> net.transitions(False) # doctest: +ELLIPSIS
| python | {
"resource": ""
} |
q256949 | UnionFind.size | validation | def size(self, s):
"""Returns the number of elements in the set that ``s`` belongs to.
Parameters
----------
s : object
An object
Returns
-------
| python | {
"resource": ""
} |
q256950 | UnionFind.find | validation | def find(self, s):
"""Locates the leader of the set to which the element ``s`` belongs.
Parameters
----------
s : object
An object that the ``UnionFind`` contains.
Returns
-------
object
The leader of the set that contains ``s``.
"""
pSet = [s]
parent = self._leader[s]
while parent != self._leader[parent]:
| python | {
"resource": ""
} |
q256951 | UnionFind.union | validation | def union(self, a, b):
"""Merges the set that contains ``a`` with the set that contains ``b``.
Parameters
----------
a, b : objects
Two objects whose sets are to be merged.
"""
s1, s2 = self.find(a), self.find(b)
if s1 != s2:
r1, r2 = self._rank[s1], self._rank[s2]
if r2 > r1:
r1, r2 = r2, r1
| python | {
"resource": ""
} |
q256952 | generate_transition_matrix | validation | def generate_transition_matrix(g, seed=None):
"""Generates a random transition matrix for the graph ``g``.
Parameters
----------
g : :any:`networkx.DiGraph`, :class:`numpy.ndarray`, dict, etc.
Any object that :any:`DiGraph<networkx.DiGraph>` accepts.
seed : int (optional)
An integer used to initialize numpy's psuedo-random number
generator.
Returns
-------
mat : :class:`~numpy.ndarray`
Returns a transition matrix where ``mat[i, j]`` is the
probability of transitioning from vertex ``i`` to vertex ``j``.
If there is no edge connecting vertex ``i`` to vertex ``j``
then ``mat[i, j] = 0``.
"""
g = _test_graph(g)
if isinstance(seed, numbers.Integral):
| python | {
"resource": ""
} |
q256953 | generate_random_graph | validation | def generate_random_graph(num_vertices=250, prob_loop=0.5, **kwargs):
"""Creates a random graph where the edges have different types.
This method calls :func:`.minimal_random_graph`, and then adds
a loop to each vertex with ``prob_loop`` probability. It then
calls :func:`.set_types_random` on the resulting graph.
Parameters
----------
num_vertices : int (optional, default: 250)
The number of vertices in the graph.
prob_loop : float (optional, default: 0.5)
The probability that a loop gets added to a vertex.
**kwargs :
Any parameters to send to :func:`.minimal_random_graph` or
:func:`.set_types_random`.
Returns
-------
:class:`.QueueNetworkDiGraph`
A graph with the position of the vertex set as a property.
The position property is called ``pos``. Also, the ``edge_type``
edge property is set for each edge.
Examples
--------
The following generates a directed graph with 50 vertices where half
the edges are type 1 and 1/4th are type 2 and 1/4th are type 3:
>>> import queueing_tool as qt
>>> pTypes = {1: 0.5, 2: 0.25, 3: 0.25}
>>> g = qt.generate_random_graph(100, proportions=pTypes, seed=17)
>>> non_loops = [e for e in g.edges() if e[0] != e[1]]
>>> p1 = np.sum([g.ep(e, 'edge_type') == 1 for e in non_loops])
>>> float(p1) / len(non_loops) # doctest: +ELLIPSIS
0.486...
>>> p2 = np.sum([g.ep(e, 'edge_type') == 2 for e in non_loops])
>>> float(p2) / len(non_loops) # doctest: +ELLIPSIS
0.249...
>>> p3 = np.sum([g.ep(e, 'edge_type') == | python | {
"resource": ""
} |
q256954 | generate_pagerank_graph | validation | def generate_pagerank_graph(num_vertices=250, **kwargs):
"""Creates a random graph where the vertex types are
selected using their pagerank.
Calls :func:`.minimal_random_graph` and then
:func:`.set_types_rank` where the ``rank`` keyword argument
is given by :func:`networkx.pagerank`.
Parameters
----------
num_vertices : int (optional, the default is 250)
The number of vertices in the graph.
**kwargs :
Any parameters to send to :func:`.minimal_random_graph` or
:func:`.set_types_rank`.
Returns
-------
:class:`.QueueNetworkDiGraph`
A graph with a ``pos`` vertex property and the ``edge_type``
edge property.
Notes
-----
This function sets the edge types of a graph to be either 1, 2, or
3. It sets the vertices to type 2 by selecting the | python | {
"resource": ""
} |
q256955 | minimal_random_graph | validation | def minimal_random_graph(num_vertices, seed=None, **kwargs):
"""Creates a connected graph with random vertex locations.
Parameters
----------
num_vertices : int
The number of vertices in the graph.
seed : int (optional)
An integer used to initialize numpy's psuedorandom number
generators.
**kwargs :
Unused.
Returns
-------
:class:`.QueueNetworkDiGraph`
A graph with a ``pos`` vertex property for each vertex's
position.
Notes
-----
This function first places ``num_vertices`` points in the unit square
randomly (using the uniform distribution). Then, for every vertex
``v``, all other vertices | python | {
"resource": ""
} |
q256956 | get_class_traits | validation | def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of | python | {
"resource": ""
} |
q256957 | NonComment.add | validation | def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
| python | {
"resource": ""
} |
q256958 | CommentBlocker.process_file | validation | def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
| python | {
"resource": ""
} |
q256959 | CommentBlocker.process_token | validation | def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
| python | {
"resource": ""
} |
q256960 | CommentBlocker.new_noncomment | validation | def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
| python | {
"resource": ""
} |
q256961 | CommentBlocker.new_comment | validation | def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a | python | {
"resource": ""
} |
q256962 | CommentBlocker.make_index | validation | def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for | python | {
"resource": ""
} |
q256963 | CommentBlocker.search_for_comment | validation | def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
| python | {
"resource": ""
} |
q256964 | BaseBackend._load | validation | def _load(self, config):
"""
Loads config from string or dict
"""
if isinstance(config, six.string_types):
try:
config = json.loads(config)
except ValueError:
pass
| python | {
"resource": ""
} |
q256965 | BaseBackend._merge_config | validation | def _merge_config(self, config, templates):
"""
Merges config with templates
"""
if not templates:
return config
# type check
if not isinstance(templates, list):
raise TypeError('templates argument must be an instance of list')
# merge templates with main configuration
| python | {
"resource": ""
} |
q256966 | BaseBackend.render | validation | def render(self, files=True):
"""
Converts the configuration dictionary into the corresponding configuration format
:param files: whether to include "additional files" in the output or not;
defaults to ``True``
:returns: string with output
"""
self.validate()
# convert NetJSON config to intermediate data structure
if self.intermediate_data is None:
self.to_intermediate()
# support multiple renderers
renderers = getattr(self, 'renderers', None) or [self.renderer]
# convert intermediate data structure to native configuration
output = ''
for renderer_class in renderers:
renderer = renderer_class(self)
| python | {
"resource": ""
} |
q256967 | BaseBackend.generate | validation | def generate(self):
"""
Returns a ``BytesIO`` instance representing an in-memory tar.gz archive
containing the native router configuration.
:returns: in-memory tar.gz archive, instance of ``BytesIO``
"""
tar_bytes = BytesIO()
tar = tarfile.open(fileobj=tar_bytes, mode='w')
self._generate_contents(tar)
self._process_files(tar)
tar.close()
tar_bytes.seek(0) # set pointer to beginning of stream
# `mtime` parameter of gzip file must be 0, otherwise any checksum operation
# would return a different digest even when content is the same.
# to achieve this we must use the python `gzip` library | python | {
"resource": ""
} |
q256968 | BaseBackend.write | validation | def write(self, name, path='./'):
"""
Like ``generate`` but writes to disk.
:param name: file name, the tar.gz extension will be added automatically
:param path: directory where the file will be written to, defaults to ``./``
:returns: None
"""
byte_object = self.generate() | python | {
"resource": ""
} |
q256969 | BaseBackend._add_file | validation | def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE):
"""
Adds a single file in tarfile instance.
:param tar: tarfile instance
:param name: string representing filename or path
:param contents: string representing file contents
:param mode: string representing file mode, defaults to 644
:returns: None
"""
byte_contents = BytesIO(contents.encode('utf8'))
info = tarfile.TarInfo(name=name)
info.size = len(contents)
# mtime must be 0 or any checksum operation
| python | {
"resource": ""
} |
q256970 | BaseBackend.parse | validation | def parse(self, native):
"""
Parses a native configuration and converts
it to a NetJSON configuration dictionary
"""
if not hasattr(self, 'parser') or not self.parser:
raise NotImplementedError('Parser | python | {
"resource": ""
} |
q256971 | merge_config | validation | def merge_config(template, config, list_identifiers=None):
"""
Merges ``config`` on top of ``template``.
Conflicting keys are handled in the following way:
* simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
overwrite the ones in ``template``
* values of type ``list`` in both ``config`` and ``template`` will be
merged using to the ``merge_list`` function
* values of type ``dict`` will be merged recursively
:param template: template ``dict``
:param config: config ``dict``
:param list_identifiers: ``list`` or ``None``
:returns: merged ``dict``
"""
result = template.copy()
for key, value in config.items():
if isinstance(value, dict):
| python | {
"resource": ""
} |
q256972 | merge_list | validation | def merge_list(list1, list2, identifiers=None):
"""
Merges ``list2`` on top of ``list1``.
If both lists contain dictionaries which have keys specified
in ``identifiers`` which have equal values, those dicts will
be merged (dicts in ``list2`` will override dicts in ``list1``).
The remaining elements will be summed in order to create a list
which contains elements of both lists.
:param list1: ``list`` from template
:param list2: ``list`` from config
:param identifiers: ``list`` or ``None``
:returns: merged ``list``
"""
identifiers = identifiers or []
dict_map = {'list1': OrderedDict(), 'list2': OrderedDict()}
counter = 1
for list_ in [list1, list2]:
container = dict_map['list{0}'.format(counter)]
for el in list_:
| python | {
"resource": ""
} |
q256973 | evaluate_vars | validation | def evaluate_vars(data, context=None):
"""
Evaluates variables in ``data``
:param data: data structure containing variables, may be
``str``, ``dict`` or ``list``
:param context: ``dict`` containing variables
:returns: modified data structure
"""
context = context or {}
if isinstance(data, (dict, list)):
if isinstance(data, dict):
loop_items = data.items()
elif isinstance(data, list):
loop_items = enumerate(data)
for key, value in loop_items:
data[key] = evaluate_vars(value, context)
elif isinstance(data, six.string_types):
vars_found = var_pattern.findall(data)
for var in vars_found:
var = var.strip()
| python | {
"resource": ""
} |
q256974 | get_copy | validation | def get_copy(dict_, key, default=None):
"""
Looks for a key in a dictionary, if found returns
a deepcopied value, otherwise returns default value
"""
| python | {
"resource": ""
} |
q256975 | BaseConverter.type_cast | validation | def type_cast(self, item, schema=None):
"""
Loops over item and performs type casting
according to supplied schema fragment
"""
if schema is None:
schema = self._schema
properties = schema['properties']
for key, value in item.items():
if key not in properties:
continue
try:
json_type = properties[key]['type']
| python | {
"resource": ""
} |
q256976 | OpenWisp._get_install_context | validation | def _get_install_context(self):
"""
returns the template context for install.sh and uninstall.sh
"""
config = self.config
# layer2 VPN list
l2vpn = []
for vpn in self.config.get('openvpn', []):
if vpn.get('dev_type') != 'tap':
continue
tap = vpn.copy()
l2vpn.append(tap)
# bridge list
bridges = []
for interface in self.config.get('interfaces', []):
if interface['type'] != 'bridge':
continue
| python | {
"resource": ""
} |
q256977 | OpenWisp._add_install | validation | def _add_install(self, context):
"""
generates install.sh and adds it to included files
"""
contents = self._render_template('install.sh', context)
self.config.setdefault('files', []) # file list might be empty
# add install.sh to list of included files
| python | {
"resource": ""
} |
q256978 | OpenWisp._add_uninstall | validation | def _add_uninstall(self, context):
"""
generates uninstall.sh and adds it to included files
"""
contents = self._render_template('uninstall.sh', context)
self.config.setdefault('files', []) # file list might be empty
# add uninstall.sh to list of included files
| python | {
"resource": ""
} |
q256979 | OpenWisp._add_tc_script | validation | def _add_tc_script(self):
"""
generates tc_script.sh and adds it to included files
"""
# fill context
context = dict(tc_options=self.config.get('tc_options', []))
# import pdb; pdb.set_trace()
contents = self._render_template('tc_script.sh', context)
self.config.setdefault('files', []) # file list might be empty
| python | {
"resource": ""
} |
q256980 | BaseRenderer.render | validation | def render(self):
"""
Renders configuration by using the jinja2 templating engine
"""
# get jinja2 template
template_name = '{0}.jinja2'.format(self.get_name())
| python | {
"resource": ""
} |
q256981 | Interfaces.__intermediate_addresses | validation | def __intermediate_addresses(self, interface):
"""
converts NetJSON address to
UCI intermediate data structure
"""
address_list = self.get_copy(interface, 'addresses')
# do not ignore interfaces if they do not contain any address
if not address_list:
return [{'proto': 'none'}]
result = []
static = {}
dhcp = []
for address in address_list:
family = address.get('family')
# dhcp
if address['proto'] == 'dhcp':
address['proto'] = 'dhcp' if family == 'ipv4' else 'dhcpv6'
dhcp.append(self.__intermediate_address(address))
continue
if 'gateway' in address:
uci_key = 'gateway' if family == 'ipv4' else 'ip6gw'
interface[uci_key] = address['gateway']
# static
address_key = 'ipaddr' if family == 'ipv4' else 'ip6addr'
static.setdefault(address_key, [])
static[address_key].append('{address}/{mask}'.format(**address))
static.update(self.__intermediate_address(address))
if static:
# do not use CIDR notation when | python | {
"resource": ""
} |
q256982 | Interfaces.__intermediate_interface | validation | def __intermediate_interface(self, interface, uci_name):
"""
converts NetJSON interface to
UCI intermediate data structure
"""
interface.update({
'.type': 'interface',
'.name': uci_name,
'ifname': interface.pop('name')
})
if 'network' in interface:
del interface['network']
if 'mac' in interface:
# mac address of wireless interface must
# be set in /etc/config/wireless, therfore
# we can skip this in /etc/config/network
if interface.get('type') != 'wireless':
interface['macaddr'] = interface['mac']
| python | {
"resource": ""
} |
q256983 | Interfaces.__intermediate_address | validation | def __intermediate_address(self, address):
"""
deletes NetJSON address keys
| python | {
"resource": ""
} |
q256984 | Interfaces.__intermediate_bridge | validation | def __intermediate_bridge(self, interface, i):
"""
converts NetJSON bridge to
UCI intermediate data structure
"""
# ensure type "bridge" is only given to one logical interface
if interface['type'] == 'bridge' and i < 2:
bridge_members = ' '.join(interface.pop('bridge_members'))
# put bridge members in ifname attribute
if bridge_members:
interface['ifname'] = bridge_members
# if no members, this is an empty bridge
else:
interface['bridge_empty'] = True
del interface['ifname']
# bridge has already been defined
# but we need to add more references to it
elif interface['type'] == 'bridge' and i >= 2:
# openwrt adds "br-" prefix to bridge interfaces
# we need to take this into account when referring
# to these physical names
if 'br-' not | python | {
"resource": ""
} |
q256985 | Interfaces.__intermediate_proto | validation | def __intermediate_proto(self, interface, address):
"""
determines UCI interface "proto" option
"""
# proto defaults to static
address_proto = address.pop('proto', 'static')
if 'proto' not in interface:
| python | {
"resource": ""
} |
q256986 | Interfaces.__intermediate_dns_servers | validation | def __intermediate_dns_servers(self, uci, address):
"""
determines UCI interface "dns" option
"""
# allow override
if 'dns' in uci:
return uci['dns']
# ignore if using DHCP or if "proto" is none
| python | {
"resource": ""
} |
q256987 | Interfaces.__intermediate_dns_search | validation | def __intermediate_dns_search(self, uci, address):
"""
determines UCI interface "dns_search" option
"""
# allow override
if 'dns_search' in uci:
return uci['dns_search']
# ignore if "proto" is none
| python | {
"resource": ""
} |
q256988 | Radios.__intermediate_htmode | validation | def __intermediate_htmode(self, radio):
"""
only for mac80211 driver
"""
protocol = radio.pop('protocol')
channel_width = radio.pop('channel_width')
# allow overriding htmode
if 'htmode' in radio:
return radio['htmode']
| python | {
"resource": ""
} |
q256989 | Radios.__netjson_protocol | validation | def __netjson_protocol(self, radio):
"""
determines NetJSON protocol radio attribute
"""
htmode = radio.get('htmode')
| python | {
"resource": ""
} |
q256990 | Radios.__netjson_channel_width | validation | def __netjson_channel_width(self, radio):
"""
determines NetJSON channel_width radio attribute
"""
htmode = radio.pop('htmode')
if htmode == 'NONE':
return 20
channel_width = htmode.replace('VHT', '').replace('HT', '')
# we need to override htmode
| python | {
"resource": ""
} |
q256991 | OpenVpn.auto_client | validation | def auto_client(cls, host, server, ca_path=None, ca_contents=None,
cert_path=None, cert_contents=None, key_path=None,
key_contents=None):
"""
Returns a configuration dictionary representing an OpenVPN client configuration
that is compatible with the passed server configuration.
:param host: remote VPN server
:param server: dictionary representing a single OpenVPN server configuration
:param ca_path: optional string representing path to CA, will consequently add
a file in the resulting configuration dictionary
:param ca_contents: optional string representing contents of CA file
:param cert_path: optional string representing path to certificate, will consequently add
a file in the resulting configuration dictionary
:param cert_contents: optional string representing contents of cert file
:param key_path: optional string representing path to key, will consequently add
a file in the resulting configuration dictionary
:param key_contents: optional string representing contents of key file
:returns: dictionary representing a single OpenVPN client configuration
"""
# client defaults
client = {
"mode": "p2p",
"nobind": True,
"resolv_retry": "infinite",
"tls_client": True
}
# remote
port = server.get('port') or 1195
client['remote'] = [{'host': host, 'port': port}]
# proto
if server.get('proto') == 'tcp-server':
client['proto'] = 'tcp-client'
else:
client['proto'] = 'udp'
# determine if pull must be True
if 'server' in server or 'server_bridge' in server:
client['pull'] = True
# tls_client
if 'tls_server' not in server or not server['tls_server']:
client['tls_client'] = False
# ns_cert_type
ns_cert_type = {None: '',
| python | {
"resource": ""
} |
q256992 | OpenVpn._auto_client_files | validation | def _auto_client_files(cls, client, ca_path=None, ca_contents=None, cert_path=None,
cert_contents=None, key_path=None, key_contents=None):
"""
returns a list of NetJSON extra files for automatically generated clients
produces side effects in ``client`` dictionary
"""
files = []
if ca_path and ca_contents:
client['ca'] = ca_path
| python | {
"resource": ""
} |
q256993 | get_install_requires | validation | def get_install_requires():
"""
parse requirements.txt, ignore links, exclude comments
"""
requirements = []
for line in open('requirements.txt').readlines():
# skip to next iteration if comment or empty line
if line.startswith('#') or line == '' or line.startswith('http') or line.startswith('git'):
continue
| python | {
"resource": ""
} |
q256994 | Report.events | validation | def events(self, **kwargs):
"""Get all events for this report. Additional arguments may also be
specified that will be passed to the query function.
"""
| python | {
"resource": ""
} |
q256995 | Node.facts | validation | def facts(self, **kwargs):
"""Get all facts of this node. Additional arguments may also be
specified that will be passed to the query function.
"""
| python | {
"resource": ""
} |
q256996 | Node.fact | validation | def fact(self, name):
"""Get a single fact from this node."""
| python | {
"resource": ""
} |
q256997 | Node.resources | validation | def resources(self, type_=None, title=None, **kwargs):
"""Get all resources of this node or all resources of the specified
type. Additional arguments may also be specified that will be passed
to the query function.
"""
if type_ is None:
resources = self.__api.resources(
query=EqualsOperator("certname", self.name),
**kwargs)
elif type_ is not None and title is None:
resources = self.__api.resources(
type_=type_,
| python | {
"resource": ""
} |
q256998 | Node.resource | validation | def resource(self, type_, title, **kwargs):
"""Get a resource matching the supplied type and title. Additional
arguments may also be specified that will be passed to the query
function.
"""
resources = self.__api.resources(
| python | {
"resource": ""
} |
q256999 | Node.reports | validation | def reports(self, **kwargs):
"""Get all reports for this node. Additional arguments may also be
specified that will be passed to the query function.
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.