text stringlengths 81 112k |
|---|
Returns a specific Feed from the API
:param user: feed username
:param name: feed name
:param limit: limit the results
:param lasttime: only show >= lasttime
:return: dict
Example:
ret = feed.show('csirtgadgets', 'port-scanners', limit=5)
def show(self, use... |
Codenerix CONTEXT
def codenerix(request):
'''
Codenerix CONTEXT
'''
# Get values
DEBUG = getattr(settings, 'DEBUG', False)
VERSION = getattr(settings, 'VERSION', _('WARNING: No version set to this code, add VERSION contant to your configuration'))
# Set environment
return {
... |
Override django-bakery to skip profiles that raise 404
def build_object(self, obj):
"""Override django-bakery to skip profiles that raise 404"""
try:
build_path = self.get_build_path(obj)
self.request = self.create_request(build_path)
self.request.user = AnonymousUse... |
Create a row for the schedule table.
def make_schedule_row(schedule_day, slot, seen_items):
"""Create a row for the schedule table."""
row = ScheduleRow(schedule_day, slot)
skip = {}
expanding = {}
all_items = list(slot.scheduleitem_set
.select_related('talk', 'page', 'venue')
... |
Helper function which creates an ordered list of schedule days
def generate_schedule(today=None):
"""Helper function which creates an ordered list of schedule days"""
# We create a list of slots and schedule items
schedule_days = {}
seen_items = {}
for slot in Slot.objects.all().order_by('end_time'... |
Allow adding a 'render_description' parameter
def get_context_data(self, **kwargs):
"""Allow adding a 'render_description' parameter"""
context = super(ScheduleXmlView, self).get_context_data(**kwargs)
if self.request.GET.get('render_description', None) == '1':
context['render_descr... |
Create a iCal file from the schedule
def get(self, request):
"""Create a iCal file from the schedule"""
# Heavily inspired by https://djangosnippets.org/snippets/2223/ and
# the icalendar documentation
calendar = Calendar()
site = get_current_site(request)
calendar.add('... |
Look up a page by url (which is a tree of slugs)
def slug(request, url):
"""Look up a page by url (which is a tree of slugs)"""
page = None
if url:
for slug in url.split('/'):
if not slug:
continue
try:
page = Page.objects.get(slug=slug, pare... |
Override django-bakery to skip pages marked exclude_from_static
def build_object(self, obj):
"""Override django-bakery to skip pages marked exclude_from_static"""
if not obj.exclude_from_static:
super(ShowPage, self).build_object(obj) |
Override django-bakery to skip talks that raise 403
def build_object(self, obj):
"""Override django-bakery to skip talks that raise 403"""
try:
super(TalkView, self).build_object(obj)
except PermissionDenied:
# We cleanup the directory created
self.unbuild_ob... |
Only talk owners can see talks, unless they've been accepted
def get_object(self, *args, **kwargs):
'''Only talk owners can see talks, unless they've been accepted'''
object_ = super(TalkView, self).get_object(*args, **kwargs)
if not object_.can_view(self.request.user):
raise Permis... |
Canonicalize the URL if the slug changed
def render_to_response(self, *args, **kwargs):
'''Canonicalize the URL if the slug changed'''
if self.request.path != self.object.get_absolute_url():
return HttpResponseRedirect(self.object.get_absolute_url())
return super(TalkView, self).ren... |
Override delete to only withdraw
def delete(self, request, *args, **kwargs):
"""Override delete to only withdraw"""
talk = self.get_object()
talk.status = WITHDRAWN
talk.save()
revisions.set_user(self.request.user)
revisions.set_comment("Talk Withdrawn")
return H... |
A decorator that applies an ordering to the QuerySet returned by a
function.
def order_results_by(*fields):
"""A decorator that applies an ordering to the QuerySet returned by a
function.
"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kw):
result... |
A decorator for caching the result of a function.
def cache_result(cache_key, timeout):
"""A decorator for caching the result of a function."""
def decorator(f):
cache_name = settings.WAFER_CACHE
@functools.wraps(f)
def wrapper(*args, **kw):
cache = caches[cache_name]
... |
Override django-bakery's build logic to fake pagination.
def build_queryset(self):
"""Override django-bakery's build logic to fake pagination."""
paths = [(os.path.join(self.build_prefix, 'index.html'), {})]
self.request = None
queryset = self.get_queryset()
paginator = self.get... |
<--------------------------------------- 12 columns ------------------------------------>
<--- 6 columns ---> <--- 6 columns --->
------------------------------------------ ------------------------------------------
| Info ... |
Expose the site's info to templates
def site_info(request):
'''Expose the site's info to templates'''
site = get_current_site(request)
context = {
'WAFER_CONFERENCE_NAME': site.name,
'WAFER_CONFERENCE_DOMAIN': site.domain,
}
return context |
Expose whether to display the navigation header and footer
def navigation_info(request):
'''Expose whether to display the navigation header and footer'''
if request.GET.get('wafer_hide_navigation') == "1":
nav_class = "wafer-invisible"
else:
nav_class = "wafer-visible"
context = {
... |
Expose selected settings to templates
def registration_settings(request):
'''Expose selected settings to templates'''
context = {}
for setting in (
'WAFER_SSO',
'WAFER_HIDE_LOGIN',
'WAFER_REGISTRATION_OPEN',
'WAFER_REGISTRATION_MODE',
'WAFER_TALKS... |
return the rolls this people is related with
def profiles(self):
'''
return the rolls this people is related with
'''
limit = []
if self.is_admin():
limit.append(_("Administrator"))
limit.sort()
return limit |
r"""Matern covariance function of arbitrary dimension, for use with :py:class:`ArbitraryKernel`.
The Matern kernel has the following hyperparameters, always referenced in
the order listed:
= ===== ====================================
0 sigma prefactor
1 nu order of kernel
2 l1 le... |
r"""Evaluate the kernel directly at the given values of `tau`.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
Returns
-------
k : :py:class:`Array`, (`M`,)
:math:`k(\tau)` (less the :math... |
r"""Covert tau to :math:`y=2\nu\sum_i(\tau_i^2/l_i^2)`.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
return_r2l2 : bool, optional
Set to True to return a tuple of (`y`, `r2l2`). Default is False
(on... |
r"""Convert tau to :math:`y=\sqrt{2\nu\sum_i(\tau_i^2/l_i^2)}`.
Takes `tau` as an argument list for compatibility with :py:func:`mpmath.diff`.
Parameters
----------
tau[0] : scalar float
First element of `tau`.
tau[1] : And so on...
... |
r"""Evaluate the derivative of the outer form of the Matern kernel.
Uses the general Leibniz rule to compute the n-th derivative of:
.. math::
f(y) = \frac{2^{1-\nu}}{\Gamma(\nu)} y^{\nu/2} K_\nu(y^{1/2})
Parameters
----------
y : :... |
r"""Evaluate the derivative of the inner argument of the Matern kernel.
Take the derivative of
.. math::
y = 2 \nu \sum_i(\tau_i^2 / l_i^2)
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimen... |
Evaluate the term inside the sum of Faa di Bruno's formula for the given partition.
Overrides the version from :py:class:`gptools.kernel.core.ChainRuleKernel`
in order to get the correct behavior at the origin.
Parameters
----------
tau : :py:class:`Matrix`, (`M... |
Build an argparse argument parser to parse the command line.
def add_logging_parser(main_parser):
"Build an argparse argument parser to parse the command line."
main_parser.set_defaults(setup_logging=set_logging_level)
verbosity_group = main_parser.add_mutually_exclusive_group(required=False)
verbosi... |
Computes and sets the logging level from the parsed arguments.
def set_logging_level(args):
"Computes and sets the logging level from the parsed arguments."
root_logger = logging.getLogger()
level = logging.INFO
logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING)
if "verbose" i... |
Check if the user should or shouldn't be inside the system:
- If the user is staff or superuser: LOGIN GRANTED
- If the user has a Person and it is not "disabled": LOGIN GRANTED
- Elsewhere: LOGIN DENIED
def check_auth(user):
'''
Check if the user should or shouldn't be inside the system:
- If ... |
Handle the debugging to a file
def debug(self, msg):
'''
Handle the debugging to a file
'''
# If debug is not disabled
if self.__debug is not False:
# If never was set, try to set it up
if self.__debug is None:
# Check what do we have in... |
Authenticate the user agains LDAP
def authenticate(self, *args, **kwargs):
'''
Authenticate the user agains LDAP
'''
# Get config
username = kwargs.get("username", None)
password = kwargs.get("password", None)
# Check user in Active Directory (authorization == ... |
Get or create the given user
def get_or_create_user(self, username, password):
'''
Get or create the given user
'''
# Get the groups for this user
info = self.get_ad_info(username, password)
self.debug("INFO found: {}".format(info))
# Find the user
try:... |
It tries to do a group synchronization if possible
This methods should be redeclared by the developer
def synchronize(self, user, info):
'''
It tries to do a group synchronization if possible
This methods should be redeclared by the developer
'''
self.debug("Synchronize... |
Sets the free hyperparameters to the new parameter values in new_params.
Parameters
----------
new_params : :py:class:`Array` or other Array-like, (len(:py:attr:`self.free_params`),)
New parameter values, ordered as dictated by the docstring for the
class.
def s... |
r"""Compute the anisotropic :math:`r^2/l^2` term for the given `tau`.
Here, :math:`\tau=X_i-X_j` is the difference vector. Computes
.. math::
\frac{r^2}{l^2} = \sum_i\frac{\tau_i^2}{l_{i}^{2}}
Assumes that the length parameters are the last `num_dim` el... |
Set `enforce_bounds` for both of the kernels to a new value.
def enforce_bounds(self, v):
"""Set `enforce_bounds` for both of the kernels to a new value.
"""
self._enforce_bounds = v
self.k1.enforce_bounds = v
self.k2.enforce_bounds = v |
Returns the bounds of the free hyperparameters.
Returns
-------
free_param_bounds : :py:class:`Array`
Array of the bounds of the free parameters, in order.
def free_param_bounds(self):
"""Returns the bounds of the free hyperparameters.
Returns
... |
Returns the names of the free hyperparameters.
Returns
-------
free_param_names : :py:class:`Array`
Array of the names of the free parameters, in order.
def free_param_names(self):
"""Returns the names of the free hyperparameters.
Returns
--... |
Set the (free) hyperparameters.
Parameters
----------
new_params : :py:class:`Array` or other Array-like
New values of the free parameters.
Raises
------
ValueError
If the length of `new_params` is not consistent with :py:attr:`se... |
r"""Evaluate :math:`dk/d\tau` at the specified locations with the specified derivatives.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
n : :py:class:`Array`, (`D`,)
Degree of derivative with respect to each dime... |
Evaluate the term inside the sum of Faa di Bruno's formula for the given partition.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
p : list of :py:class:`Array`
Each element is a block of the partition representi... |
Masks the covariance function into a form usable by :py:func:`mpmath.diff`.
Parameters
----------
*args : `num_dim` * 2 floats
The individual elements of Xi and Xj to be passed to :py:attr:`cov_func`.
def _mask_cov_func(self, *args):
"""Masks the covariance function... |
Function implementing a constant mean suitable for use with :py:class:`MeanFunction`.
def constant(X, n, mu, hyper_deriv=None):
"""Function implementing a constant mean suitable for use with :py:class:`MeanFunction`.
"""
if (n == 0).all():
if hyper_deriv is not None:
return scipy.ones(X... |
Modified hyperbolic tangent function mtanh(z; alpha).
Parameters
----------
alpha : float
The core slope of the mtanh.
z : float or array
The coordinate of the mtanh.
def mtanh(alpha, z):
"""Modified hyperbolic tangent function mtanh(z; alpha).
Parameters
---------... |
Profile used with the mtanh function to fit profiles, suitable for use with :py:class:`MeanFunction`.
Only supports univariate data!
Parameters
----------
X : array, (`M`, 1)
The points to evaluate at.
n : array, (1,)
The order of derivative to compute. Only up to first der... |
Linear mean function of arbitrary dimension, suitable for use with :py:class:`MeanFunction`.
The form is :math:`m_0 * X[:, 0] + m_1 * X[:, 1] + \dots + b`.
Parameters
----------
X : array, (`M`, `D`)
The points to evaluate the model at.
n : array of non-negative int, (`D`)
... |
We save all the schedule items associated with this slot, so
the last_update time is updated to reflect any changes to the
timing of the slots
def update_schedule_items(*args, **kw):
"""We save all the schedule items associated with this slot, so
the last_update time is updated to reflect any ... |
Create the difference between the current revision and a previous version
def make_diff(current, revision):
"""Create the difference between the current revision and a previous version"""
the_diff = []
dmp = diff_match_patch()
for field in (set(current.field_dict.keys()) | set(revision.field_dict.keys... |
Actually compare two versions.
def compare_view(self, request, object_id, version_id, extra_context=None):
"""Actually compare two versions."""
opts = self.model._meta
object_id = unquote(object_id)
# get_for_object's ordering means this is always the latest revision.
# The reve... |
Allow selecting versions to compare.
def comparelist_view(self, request, object_id, extra_context=None):
"""Allow selecting versions to compare."""
opts = self.model._meta
object_id = unquote(object_id)
current = get_object_or_404(self.model, pk=object_id)
# As done by reversion... |
This function helps to convert date information for showing proper filtering
def grv(struct, position):
'''
This function helps to convert date information for showing proper filtering
'''
if position == 'year':
size = 4
else:
size = 2
if (struct[position][2]):
rightnow... |
Entry point for this class, here we decide basic stuff
def _setup(self, request):
'''
Entry point for this class, here we decide basic stuff
'''
# Get details from self
info = model_inspect(self)
self._appname = getattr(self, 'appname', info['appname'])
self._mo... |
Build the list of templates related to this user
def get_template_names(self):
'''
Build the list of templates related to this user
'''
# Get user template
template_model = getattr(self, 'template_model', "{0}/{1}_{2}".format(self._appname.lower(), self._modelname.lower(), self... |
Set a base context
def get_context_data(self, **kwargs):
'''
Set a base context
'''
# Call the base implementation first to get a context
context = super(GenBase, self).get_context_data(**kwargs)
# Update general context with the stuff we already calculated
if ... |
Entry point for this class, here we decide basic stuff
def dispatch(self, *args, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Get if this class is working as only a base render and List funcionality shouldn't be enabled
onlybase = getattr(self, "o... |
raise Exception("FOUND: {} -- __foreignkeys: {} -- __columns: {} -- autorules_keys: {} -- \
query_select_related: {} -- query_renamed: {} -- query_optimizer: {} | use_extra: {}| -- \
query: {} -- meta.fields: {} -- fields_related_model: {} -- query_verifier: {}\
-- ??? {} == {}".form... |
Generic list view with validation included and object transfering support
def get_context_data(self, **kwargs):
'''
Generic list view with validation included and object transfering support
'''
# Call the base implementation first to get a context
context = super(GenList, self)... |
Return a base answer for a json answer
def get_context_json(self, context):
'''
Return a base answer for a json answer
'''
# Initialize answer
answer = {}
# Metadata builder
answer['meta'] = self.__jcontext_metadata(context)
# Filter builder
ans... |
Get a json parameter and rebuild the context back to a dictionary (probably kwargs)
def set_context_json(self, jsonquery):
'''
Get a json parameter and rebuild the context back to a dictionary (probably kwargs)
'''
# Make sure we are getting dicts
if type(jsonquery) != dict:
... |
Entry point for this class, here we decide basic stuff
def dispatch(self, request, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Check if this is a webservice request
self.json_worker = (bool(getattr(self.request, "authtoken", False))) or (self.jso... |
Set form groups to the groups specified in the view if defined
def get_form(self, form_class=None):
'''
Set form groups to the groups specified in the view if defined
'''
formobj = super(GenModify, self).get_form(form_class)
# Set requested group to this form
selfgroups... |
Entry point for this class, here we decide basic stuff
def dispatch(self, request, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Delete method must happen with POST not with GET
if request.method == 'POST':
# Check if this is a webservi... |
Entry point for this class, here we decide basic stuff
def dispatch(self, request, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Check if this is a REST query to pusth the answer to responde in JSON
if bool(self.request.META.get('HTTP_X_REST', Fals... |
method in charged of filling an structure containing the object fields
values taking into account the 'group' attribute from the corresponding
form object, which is necesary to fill the details form as it is configured
in the 'group' attribute
def get_filled_structure(self, subgroup=None):
... |
Pilfered from `django.forms.utils`:
Convert a dictionary of attributes to a single string.
The returned string will contain a leading space followed by key="value",
XML-style pairs. In the case of a boolean value, the key will appear
without a value. Otherwise, the value is formatted through its own dic... |
r"""Evaluate the kernel directly at the given values of `tau`.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
Returns
-------
k : :py:class:`Array`, (`M`,)
:math:`k(\tau)` (less t... |
Evaluate the derivative of the outer form of the RQ kernel.
Parameters
----------
y : :py:class:`Array`, (`M`,)
`M` inputs to evaluate at.
n : non-negative scalar int
Order of derivative to compute.
Returns
-------
dk_dy :... |
Given a directory name, return the Page representing it in the menu
heirarchy.
def get_parent(self, directory):
"""
Given a directory name, return the Page representing it in the menu
heirarchy.
"""
assert settings.PAGE_DIR.startswith('/')
assert settings.PAGE_DI... |
Return the correct URL to SSO with the given method.
def wafer_sso_url(context, sso_method):
'''
Return the correct URL to SSO with the given method.
'''
request = context.request
url = reverse(getattr(views, '%s_login' % sso_method))
if 'next' in request.GET:
url += '?' + urlencode({'n... |
Authorizes Coursera's OAuth2 client for using coursera.org API servers for
a specific application
def authorize(args):
"""
Authorizes Coursera's OAuth2 client for using coursera.org API servers for
a specific application
"""
oauth2_instance = oauth2.build_oauth2(args.app, args)
oauth2_insta... |
Checks courseraoauth2client's connectivity to the coursera.org API servers
for a specific application
def check_auth(args):
"""
Checks courseraoauth2client's connectivity to the coursera.org API servers
for a specific application
"""
oauth2_instance = oauth2.build_oauth2(args.app, args)
aut... |
Writes to the screen the state of the authentication cache. (For debugging
authentication issues.) BEWARE: DO NOT email the output of this command!!!
You must keep the tokens secure. Treat them as passwords.
def display_auth_cache(args):
'''
Writes to the screen the state of the authentication cache. (... |
r"""Warps the `X` coordinate with the tanh model
.. math::
l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w}
Parameters
----------
X : :py:class:`Array`, (`M`,) or scalar float
`M` locations to evaluate length scale at.
l1 : positive float
Sma... |
r"""Warps the `X` coordinate with a Gaussian-shaped divot.
.. math::
l = l_1 - (l_1 - l_2) \exp\left ( -4\ln 2\frac{(X-x_0)^2}{l_{w}^{2}} \right )
Parameters
----------
X : :py:class:`Array`, (`M`,) or scalar float
`M` locations to evaluate length scale at.
l1 : po... |
r"""Implements a tanh warping function and its derivative.
.. math::
l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w}
Parameters
----------
x : float or array of float
Locations to evaluate the function at.
n : int
Derivative order to take. U... |
r"""Implements a sum-of-tanh warping function and its derivative.
.. math::
l = a\tanh\frac{x-x_a}{l_a} + b\tanh\frac{x-x_b}{l_b}
Parameters
----------
x : float or array of float
Locations to evaluate the function at.
n : int
Derivative order to take. Used for... |
Warps the length scale with a piecewise cubic "bucket" shape.
Parameters
----------
x : float or array-like of float
Locations to evaluate length scale at.
n : non-negative int
Derivative order to evaluate. Only first derivatives are supported.
l1 : positive float
Length... |
Warps the length scale with a piecewise quintic "bucket" shape.
Parameters
----------
x : float or array-like of float
Locations to evaluate length scale at.
n : non-negative int
Derivative order to evaluate. Only first derivatives are supported.
l1 : positive float
Length s... |
Length scale function which is an exponential of a sum of Gaussians.
The centers and widths of the Gaussians are free parameters.
The length scale function is given by
.. math::
l = l_0 \exp\left ( \sum_{i=1}^{N}\beta_i\exp\left ( -\frac{(x-\mu_i)^2}{2\sigma_i^2} \right ) \ri... |
Add only the required message, but no 'ng-required' attribute to the input fields,
otherwise all Checkboxes of a MultipleChoiceField would require the property "checked".
def get_multiple_choices_required(self):
"""
Add only the required message, but no 'ng-required' attribute to the input fiel... |
Create a user, if the provided `user` is None, from the parameters.
Then log the user in, and return it.
def sso(user, desired_username, name, email, profile_fields=None):
"""
Create a user, if the provided `user` is None, from the parameters.
Then log the user in, and return it.
"""
if not use... |
Compute matrix of the log likelihood over the parameter space in parallel.
Parameters
----------
bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters
Bounds on the range to use for each of the parameters. If a single
2-tuple is given, it will be used f... |
Constructs a plot that lets you look at slices through a multidimensional array.
Parameters
----------
vals : array, (`M`, `D`, `P`, ...)
Multidimensional array to visualize.
x_vals_1 : array, (`M`,)
Values along the first dimension.
x_vals_2 : array, (`D`,)
Values along... |
Event handler for arrow key events in plot windows.
Pass the slider object to update as a masked argument using a lambda function::
lambda evt: arrow_respond(my_slider, evt)
Parameters
----------
slider : Slider instance associated with this handler.
event : Event to be ha... |
Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively.
note amount must be non-negative.
def debit(self, amount, credit_account, description, debit_memo="", credit_memo="", datetime=None):
""" Post a debit of 'amount' and a credit of -amount against this... |
Post a credit of 'amount' and a debit of -amount against this account and credit_account respectively.
note amount must be non-negative.
def credit(self, amount, debit_account, description, debit_memo="", credit_memo="", datetime=None):
""" Post a credit of 'amount' and a debit of -amount against this... |
Post a transaction of 'amount' against this account and the negative amount against 'other_account'.
This will show as a debit or credit against this account when amount > 0 or amount < 0 respectively.
def post(self, amount, other_account, description, self_memo="", other_memo="", datetime=None):
""" ... |
returns the account balance as of 'date' (datetime stamp) or now().
def balance(self, date=None):
""" returns the account balance as of 'date' (datetime stamp) or now(). """
qs = self._entries()
if date:
qs = qs.filter(transaction__t_stamp__lt=date)
r = qs.aggregate(b=Sum(... |
Returns a Totals object containing the sum of all debits, credits
and net change over the period of time from start to end.
'start' is inclusive, 'end' is exclusive
def totals(self, start=None, end=None):
"""Returns a Totals object containing the sum of all debits, credits
and net chan... |
Returns a list of entries for this account.
Ledger returns a sequence of LedgerEntry's matching the criteria
in chronological order. The returned sequence can be boolean-tested
(ie. test that nothing was returned).
If 'start' is given, only entries on or after that datetime are
... |
Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset.
def get_third_party(self, third_party):
"""Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset."""
actual_account = third_pa... |
Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset.
def get_third_party(self, third_party):
"""Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset."""
actual_account = third_pa... |
Find any slots that overlap
def find_overlapping_slots(all_slots):
"""Find any slots that overlap"""
overlaps = set([])
for slot in all_slots:
# Because slots are ordered, we can be more efficient than this
# N^2 loop, but this is simple and, since the number of slots
# should be lo... |
Find any items that have slots that aren't contiguous
def find_non_contiguous(all_items):
"""Find any items that have slots that aren't contiguous"""
non_contiguous = []
for item in all_items:
if item.slots.count() < 2:
# No point in checking
continue
last_slot = Non... |
Find errors in the schedule. Check for:
- pending / rejected talks in the schedule
- items with both talks and pages assigned
- items with neither talks nor pages assigned
def validate_items(all_items):
"""Find errors in the schedule. Check for:
- pending / rejected talks in the... |
Find talks / pages assigned to mulitple schedule items
def find_duplicate_schedule_items(all_items):
"""Find talks / pages assigned to mulitple schedule items"""
duplicates = []
seen_talks = {}
for item in all_items:
if item.talk and item.talk in seen_talks:
duplicates.append(item)
... |
Find schedule items which clash (common slot and venue)
def find_clashes(all_items):
"""Find schedule items which clash (common slot and venue)"""
clashes = {}
seen_venue_slots = {}
for item in all_items:
for slot in item.slots.all():
pos = (item.venue, slot)
if pos in s... |
Find venues assigned slots that aren't on the allowed list
of days.
def find_invalid_venues(all_items):
"""Find venues assigned slots that aren't on the allowed list
of days."""
venues = {}
for item in all_items:
valid = False
item_days = list(item.venue.days.all())
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.