Search is not available for this dataset
text stringlengths 75 104k |
|---|
def checkRequirements(sender,**kwargs):
'''
Check that the customer meets all prerequisites for the items in the registration.
'''
if not getConstant('requirements__enableRequirements'):
return
logger.debug('Signal to check RegistrationContactForm handled by prerequisites app.')
... |
def email_recipient(self, subject, content, **kwargs):
'''
This method allows for direct emailing of an object's recipient(s)
(default or manually specified), with both object-specific context
provided using the get_email_context() method. This is used, for example,
to emai... |
def get_email_context(self,**kwargs):
'''
This method can be overridden in classes that inherit from this mixin
so that additional object-specific context is provided to the email
template. This should return a dictionary. By default, only general
financial context variabl... |
def get_group_required(self):
''' Get the group_required value from the object '''
this_object = self.model_object
if hasattr(this_object,self.group_required_field):
if hasattr(getattr(this_object,self.group_required_field),'name'):
return [getattr(this_object,se... |
def check_membership(self, groups):
''' Allows for objects with no required groups '''
if not groups or groups == ['']:
return True
if self.request.user.is_superuser:
return True
user_groups = self.request.user.groups.values_list("name", flat=True)
... |
def dispatch(self, request, *args, **kwargs):
'''
This override of dispatch ensures that if no group is required, then
the request still goes through without being logged in.
'''
self.request = request
in_group = False
required_group = self.get_group_requir... |
def validate(self,value):
'''
Check for empty values, and for an existing template, but do not check if
this is one of the initial choices provided.
'''
super(ChoiceField,self).validate(value)
try:
get_template(value)
except TemplateDoesNotEx... |
def render(self, context, instance, placeholder):
''' Permits setting of the template in the plugin instance configuration '''
if instance and instance.template:
self.render_template = instance.template
return super(PluginTemplateMixin,self).render(context,instance,placeholder) |
def get_annotations(self):
'''
This method gets the annotations for the queryset. Unlike get_ordering() below, it
passes the actual Case() and F() objects that will be evaluated with the queryset, returned
in a dictionary that is compatible with get_ordering().
'''
... |
def get_ordering(self, reverseTime=False):
'''
This method provides the tuple for ordering of querysets. However, this will only
work if the annotations generated by the get_annotations() method above have been
added to the queryset. Otherwise, the use of this ordering tuple will f... |
def get_return_page(self,prior=False):
''' This is just a wrapper for the getReturnPage helper function. '''
siteHistory = self.request.session.get('SITE_HISTORY',{})
return getReturnPage(siteHistory,prior=prior) |
def is_valid(self):
'''
For this form to be considered valid, there must be not only no errors, but also no messages on
the request that need to be shown.
'''
valid = super(RegistrationContactForm,self).is_valid()
msgs = messages.get_messages(self._request)
# We... |
def clean_total_refund_amount(self):
'''
The Javascript should ensure that the hidden input is updated, but double check it here.
'''
initial = self.cleaned_data.get('initial_refund_amount', 0)
total = self.cleaned_data['total_refund_amount']
summed_refunds = sum([v for k... |
def _check_values(self, value):
"""
Given a list of possible PK values, returns a QuerySet of the
corresponding objects. Raises a ValidationError if a given value is
invalid (not a valid PK, not in the queryset, etc.)
"""
key = self.to_field_name or 'pk'
# dedupli... |
def clean(self):
'''
This code prevents multiple individuals from substituting for the
same class and class teacher. It also prevents an individual from
substituting for a class in which they are a teacher.
'''
super(SubstituteReportingForm,self).clean()
occurre... |
def save(self, commit=True):
'''
If a staff member is reporting substitute teaching for a second time, then we should update
the list of occurrences for which they are a substitute on their existing EventStaffMember
record, rather than creating a new record and creating database issues.
... |
def save(self, commit=True):
''' If the staff member is an instructor, also update the availableForPrivates field on the Instructor record. '''
if getattr(self.instance,'instructor',None):
self.instance.instructor.availableForPrivates = self.cleaned_data.pop('availableForPrivates',self.insta... |
def save(self, *args, **kwargs):
''' Just add "s" if no plural name given. '''
if not self.pluralName:
self.pluralName = self.name + 's'
super(self.__class__, self).save(*args, **kwargs) |
def lastOfferedMonth(self):
'''
Sometimes a Series is associated with a month other than the one
in which the first class begins, so this returns a (year,month) tuple
that can be used in admin instead.
'''
lastOfferedSeries = self.event_set.order_by('-startTime').first()
... |
def getBasePrice(self,**kwargs):
'''
This handles the logic of finding the correct price. If more sophisticated
discounting systems are needed, then this PricingTier model can be subclassed,
or the discounts and vouchers apps can be used.
'''
payAtDoor = kwargs.get('payA... |
def getMonthName(self):
'''
This exists as a separate method because sometimes events should really
belong to more than one month (e.g. class series that persist over multiple months).
'''
class_counter = Counter([(x.startTime.year, x.startTime.month) for x in self.eventoccurrenc... |
def name(self):
'''
Since other types of events (PublicEvents, class Series, etc.) are subclasses
of this class, it is a good idea to override this method for those subclasses,
to provide a more intuitive name. However, defining this property at the
event level ensures that <obj... |
def organizer(self):
'''
Since events can be organized for registration in different ways (e.g. by month,
by session, or the interaction of the two), this property is used to make it easy
for templates to include necessary organizing information. Note that this method
has nothin... |
def get_default_recipients(self):
''' Overrides EmailRecipientMixin '''
return [x.registration.customer.email for x in self.eventregistration_set.filter(cancelled=False)] |
def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
context = super(Event,self).get_email_context(**kwargs)
context.update({
'id': self.id,
'name': self.__str__(),
'title': self.name,
'start': self.firstOccurrenceTime,
... |
def registrationEnabled(self):
''' Just checks if this event ever permits/permitted registration '''
return self.status in [self.RegStatus.enabled,self.RegStatus.heldOpen,self.RegStatus.heldClosed] |
def getNumRegistered(self, includeTemporaryRegs=False, dateTime=None):
'''
Method allows the inclusion of temporary registrations, as well as exclusion of
temporary registrations that are too new (e.g. for discounts based on the first
X registrants, we don't want to include people who st... |
def availableRoles(self):
'''
Returns the set of roles for this event. Since roles are not always custom specified for
event, this looks for the set of available roles in multiple places. If no roles are found,
then the method returns an empty list, in which case it can be assumed that... |
def numRegisteredForRole(self, role, includeTemporaryRegs=False):
'''
Accepts a DanceRole object and returns the number of registrations of that role.
'''
count = self.eventregistration_set.filter(cancelled=False,dropIn=False,role=role).count()
if includeTemporaryRegs:
... |
def numRegisteredByRole(self):
'''
Return a dictionary listing registrations by all available roles (including no role)
'''
role_list = list(self.availableRoles) + [None,]
return {getattr(x,'name',None):self.numRegisteredForRole(x) for x in role_list} |
def capacityForRole(self,role):
'''
Accepts a DanceRole object and determines the capacity for that role at this event.this
Since roles are not always custom specified for events, this looks for the set of
available roles in multiple places, and only returns the overall capacity of the e... |
def soldOutForRole(self,role,includeTemporaryRegs=False):
'''
Accepts a DanceRole object and responds if the number of registrations for that
role exceeds the capacity for that role at this event.
'''
return self.numRegisteredForRole(
role,includeTemporaryRegs=include... |
def updateRegistrationStatus(self, saveMethod=False):
'''
If called via cron job or otherwise, then update the registrationOpen
property for this series to reflect any manual override and/or the automatic
closing of this series for registration.
'''
logger.debug('Beginnin... |
def allDayForDate(self,this_date,timeZone=None):
'''
This method determines whether the occurrence lasts the entirety of
a specified day in the specified time zone. If no time zone is specified,
then it uses the default time zone). Also, give a grace period of a few
minutes to ... |
def netHours(self):
'''
For regular event staff, this is the net hours worked for financial purposes.
For Instructors, netHours is caclulated net of any substitutes.
'''
if self.specifiedHours is not None:
return self.specifiedHours
elif self.category in [getC... |
def shortDescription(self):
'''
Overrides property from Event base class.
'''
cd = getattr(self,'classDescription',None)
if cd:
sd = getattr(cd,'shortDescription','')
d = getattr(cd,'description','')
return sd if sd else d
return '' |
def netHours(self):
'''
For regular event staff, this is the net hours worked for financial purposes.
For Instructors, netHours is calculated net of any substitutes.
'''
if self.specifiedHours is not None:
return self.specifiedHours
return self.event.duration ... |
def getSeriesRegistered(self,q_filter=Q(),distinct=True,counter=False,**kwargs):
'''
Return a list that indicates each series the person has registered for
and how many registrations they have for that series (because of couples).
This can be filtered by any keyword arguments passed (e.g... |
def getMultiSeriesRegistrations(self,q_filter=Q(),name_series=False,**kwargs):
'''
Use the getSeriesRegistered method above to get a list of each series the
person has registered for. The return only indicates whether they are
registered more than once for the same series (e.g. for keep... |
def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
context = super(Customer,self).get_email_context(**kwargs)
context.update({
'first_name': self.first_name,
'last_name': self.last_name,
'email': self.email,
'fullName': sel... |
def getTimeOfClassesRemaining(self,numClasses=0):
'''
For checking things like prerequisites, it's useful to check if a requirement is 'almost' met
'''
occurrences = EventOccurrence.objects.filter(
cancelled=False,
event__in=[x.event for x in self.temporaryeventre... |
def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
context = super(TemporaryRegistration,self).get_email_context(**kwargs)
context.update({
'first_name': self.firstName,
'last_name': self.lastName,
'registrationComments': self.comments... |
def finalize(self,**kwargs):
'''
This method is called when the payment process has been completed and a registration
is ready to be finalized. It also fires the post-registration signal
'''
dateTime = kwargs.pop('dateTime', timezone.now())
# If sendEmail is passed as F... |
def warningFlag(self):
'''
When viewing individual event registrations, there are a large number of potential
issues that can arise that may warrant scrutiny. This property just checks all of
these conditions and indicates if anything is amiss so that the template need not
check ... |
def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
context = super(Registration,self).get_email_context(**kwargs)
context.update({
'first_name': self.customer.first_name,
'last_name': self.customer.last_name,
'registrationComments': se... |
def warningFlag(self):
'''
When viewing individual event registrations, there are a large number of potential
issues that can arise that may warrant scrutiny. This property just checks all of
these conditions and indicates if anything is amiss so that the template need not
check ... |
def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
includeName = kwargs.pop('includeName',True)
context = super(EventRegistration,self).get_email_context(**kwargs)
context.update({
'title': self.event.name,
'start': self.event.firstOccurre... |
def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
includeName = kwargs.pop('includeName',True)
context = super(TemporaryEventRegistration,self).get_email_context(**kwargs)
context.update({
'title': self.event.name,
'start': self.event.f... |
def save(self, *args, **kwargs):
'''
If this is an HTML template, then set the non-HTML content to be the stripped version of the HTML.
If this is a plain text template, then set the HTML content to be null.
'''
if self.send_html:
self.content = get_text_for_html(self... |
def create_from_item(cls, amount, item_description, **kwargs):
'''
Creates an Invoice as well as a single associated InvoiceItem
with the passed description (for things like gift certificates)
'''
submissionUser = kwargs.pop('submissionUser', None)
collectedByUser = kwarg... |
def create_from_registration(cls, reg, **kwargs):
'''
Handles the creation of an Invoice as well as one InvoiceItem per
assodciated TemporaryEventRegistration or registration. Also handles taxes
appropriately.
'''
submissionUser = kwargs.pop('submissionUser', None)
... |
def url(self):
'''
Because invoice URLs are generally emailed, this
includes the default site URL and the protocol specified in
settings.
'''
if self.id:
return '%s://%s%s' % (
getConstant('email__linkProtocol'),
Site.objects.ge... |
def get_default_recipients(self):
''' Overrides EmailRecipientMixin '''
if self.email:
return [self.email,]
if self.finalRegistration:
return [self.finalRegistration.customer.email,]
elif self.temporaryRegistration:
return [self.temporaryRegistration.e... |
def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
context = super(Invoice,self).get_email_context(**kwargs)
context.update({
'id': self.id,
'url': '%s?v=%s' % (self.url, self.validationString),
'amountPaid': self.amountPaid,
... |
def calculateTaxes(self):
'''
Updates the tax field to reflect the amount of taxes depending on
the local rate as well as whether the buyer or seller pays sales tax.
'''
tax_rate = (getConstant('registration__salesTaxRate') or 0) / 100
if tax_rate > 0:
if se... |
def processPayment(self, amount, fees, paidOnline=True, methodName=None, methodTxn=None, submissionUser=None, collectedByUser=None, forceFinalize=False, status=None, notify=None):
'''
When a payment processor makes a successful payment against an invoice, it can call this method
which handles st... |
def allocateFees(self):
'''
Fees are allocated across invoice items based on their discounted
total price net of adjustments as a proportion of the overall
invoice's total price
'''
items = list(self.invoiceitem_set.all())
# Check that totals and adjusments match... |
def createPaypalPayment(request):
'''
This view handles the creation of Paypal Express Checkout Payment objects.
All Express Checkout payments must either be associated with a pre-existing Invoice
or a registration, or they must have an amount and type passed in the post data
(such as gift certific... |
def applyAndAllocate(self,allocatedPrices,tieredTuples,payAtDoor=False):
'''
This method takes an initial allocation of prices across events, and
an identical length list of allocation tuples. It applies the rule
specified by this discount, allocates the discount across the listed
... |
def getFlatPrice(self,payAtDoor=False):
'''
Rather than embedding logic re: door pricing,
other code can call this method.
'''
if self.discountType is not DiscountCombo.DiscountType.flatPrice:
return None
if payAtDoor:
return self.doorPrice
... |
def getComponentList(self):
'''
This function just returns a list with items that are supposed to
be present in the the list multiple times as multiple elements
of the list. It simplifies checking whether a discount's conditions
are satisfied.
'''
component_list... |
def save(self, *args, **kwargs):
'''
Don't save any passed values related to a type of discount
that is not the specified type
'''
if self.discountType != self.DiscountType.flatPrice:
self.onlinePrice = None
self.doorPrice = None
if self.discount... |
def getBestDiscount(sender,**kwargs):
'''
When a customer registers for events, discounts may need to be
automatically applied. A given shopping cart may, in fact,
be eligible for multiple different types of discounts (e.g. hours-based
discounts for increasing numbers of class hours), but typically... |
def render(self, context, instance, placeholder):
''' Add the cart-specific context to this form '''
context = super(SquareCheckoutFormPlugin, self).render(context, instance, placeholder)
context.update({
'squareApplicationId': getattr(settings,'SQUARE_APPLICATION_ID',''),
... |
def checkVoucherCode(sender,**kwargs):
'''
Check that the given voucher code is valid
'''
logger.debug('Signal to check RegistrationContactForm handled by vouchers app.')
formData = kwargs.get('formData',{})
request = kwargs.get('request',{})
registration = kwargs.get('registration'... |
def applyVoucherCodeTemporarily(sender,**kwargs):
'''
When the core registration system creates a temporary registration with a voucher code,
the voucher app looks for vouchers that match that code and creates TemporaryVoucherUse
objects to keep track of the fact that the voucher may be used.
'... |
def applyReferrerVouchersTemporarily(sender,**kwargs):
'''
Unlike voucher codes which have to be manually supplied, referrer discounts are
automatically applied here, assuming that the referral program is enabled.
'''
# Only continue if the referral program is enabled
if not getConstant(... |
def applyVoucherCodesFinal(sender,**kwargs):
'''
Once a registration has been completed, vouchers are used and referrers are awarded
'''
logger.debug('Signal fired to mark voucher codes as applied.')
finalReg = kwargs.pop('registration')
tr = finalReg.temporaryRegistration
tvus = ... |
def provideCustomerReferralCode(sender,**kwargs):
'''
If the vouchers app is installed and referrals are enabled, then the customer's profile page can show their voucher referral code.
'''
customer = kwargs.pop('customer')
if getConstant('vouchers__enableVouchers') and getConstant('referrals__e... |
def getConstant(name):
'''
This is a convenience function that makes it easy to access the value of a preference/constant
without needing to check if the django_dynamic_preferences app has been set up and without
needing to load from that model directly.
'''
# We instantiate a manager for our g... |
def updateConstant(name,value,fail_silently=False):
'''
This is a convenience function that makes it easy to update the value of a preference/constant
without needing to check if the django_dynamic_preferences app has been set up, without
needing to load from that model directly, and with the option to ... |
def processSquarePayment(request):
'''
This view handles the charging of approved Square Checkout payments.
All Checkout payments must either be associated with a pre-existing Invoice
or a registration, or they must have an amount and type passed in the post data
(such as gift certificate payment r... |
def processPointOfSalePayment(request):
'''
This view handles the callbacks from point-of-sale transactions.
Please note that this will only work if you have set up your callback
URL in Square to point to this view.
'''
print('Request data is: %s' % request.GET)
# iOS transactions put all r... |
def get_prep_lookup(self):
"""Raise errors for unsupported lookups"""
raise FieldError("{} '{}' does not support lookups".format(
self.lhs.field.__class__.__name__, self.lookup_name)) |
def derive_fernet_key(input_key):
"""Derive a 32-bit b64-encoded Fernet key from arbitrary input key."""
hkdf = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
info=info,
backend=backend,
)
return base64.urlsafe_b64encode(hkdf.derive(force_bytes(input_key))... |
def reduce_cpu(f, x, axes, dtype):
"""NumPy's reduce in terms of fold."""
axes = _get_axes(axes, x.ndim)
if not axes:
return x
permute = [n for n in range(x.ndim) if n not in axes]
permute = axes + permute
T = x.transpose(permute=permute)
N = len(axes)
t = T.type.at(N, dtype=d... |
def reduce_cuda(g, x, axes, dtype):
"""Reductions in CUDA use the thrust library for speed and have limited
functionality."""
if axes != 0:
raise NotImplementedError("'axes' keyword is not implemented for CUDA")
return g(x, dtype=dtype) |
def maxlevel(lst):
"""Return maximum nesting depth"""
maxlev = 0
def f(lst, level):
nonlocal maxlev
if isinstance(lst, list):
level += 1
maxlev = max(level, maxlev)
for item in lst:
f(item, level)
f(lst, 0)
return maxlev |
def getitem(lst, indices):
"""Definition for multidimensional slicing and indexing on arbitrarily
shaped nested lists.
"""
if not indices:
return lst
i, indices = indices[0], indices[1:]
item = list.__getitem__(lst, i)
if isinstance(i, int):
return getitem(item, indices)... |
def genslices(n):
"""Generate all possible slices for a single dimension."""
def range_with_none():
yield None
yield from range(-n, n+1)
for t in product(range_with_none(), range_with_none(), range_with_none()):
s = slice(*t)
if s.step != 0:
yield s |
def genslices_ndim(ndim, shape):
"""Generate all possible slice tuples for 'shape'."""
iterables = [genslices(shape[n]) for n in range(ndim)]
yield from product(*iterables) |
def mutator(mutate):
"""Return an inspyred mutator function based on the given function.
This function generator takes a function that operates on only
one candidate to produce a single mutated candidate. The generator
handles the iteration over each candidate in the set to be mutated.
The gi... |
def bit_flip_mutation(random, candidate, args):
"""Return the mutants produced by bit-flip mutation on the candidates.
This function performs bit-flip mutation. If a candidate solution contains
non-binary values, this function leaves it unchanged.
.. Arguments:
random -- the random number gener... |
def random_reset_mutation(random, candidate, args):
"""Return the mutants produced by randomly choosing new values.
This function performs random-reset mutation. It assumes that
candidate solutions are composed of discrete values. This function
makes use of the bounder function as specified in the EC'... |
def scramble_mutation(random, candidate, args):
"""Return the mutants created by scramble mutation on the candidates.
This function performs scramble mutation. It randomly chooses two
locations along the candidate and scrambles the values within that
slice.
.. Arguments:
random -- the rand... |
def gaussian_mutation(random, candidate, args):
"""Return the mutants created by Gaussian mutation on the candidates.
This function performs Gaussian mutation. This function
makes use of the bounder function as specified in the EC's
``evolve`` method.
.. Arguments:
random -- the random n... |
def nonuniform_mutation(random, candidate, args):
"""Return the mutants produced by nonuniform mutation on the candidates.
The function performs nonuniform mutation as specified in
(Michalewicz, "Genetic Algorithms + Data Structures = Evolution
Programs," Springer, 1996). This function also makes use o... |
def population_archiver(random, population, archive, args):
"""Archive the current population.
This function replaces the archive with the individuals
of the current population.
.. Arguments:
random -- the random number generator object
population -- the population of individual... |
def best_archiver(random, population, archive, args):
"""Archive only the best individual(s).
This function archives the best solutions and removes inferior ones.
If the comparison operators have been overloaded to define Pareto
preference (as in the ``Pareto`` class), then this archiver will form ... |
def adaptive_grid_archiver(random, population, archive, args):
"""Archive only the best individual(s) using a fixed size grid.
This function archives the best solutions by using a fixed-size grid
to determine which existing solutions should be removed in order to
make room for new ones. This archiv... |
def ring_topology(random, population, args):
"""Returns the neighbors using a ring topology.
This function sets all particles in a specified sized neighborhood
as neighbors for a given particle. This is known as a ring
topology. The resulting list of lists of neighbors is returned.
.. Arg... |
def evolve(self, generator, evaluator, pop_size=100, seeds=None, maximize=True, bounder=None, **args):
"""Perform the evolution.
This function creates a population and then runs it through a series
of evolutionary epochs until the terminator is satisfied. The general
outline of ... |
def truncation_selection(random, population, args):
"""Selects the best individuals from the population.
This function performs truncation selection, which means that only
the best individuals from the current population are selected. This
is a completely deterministic selection mechanism.
... |
def uniform_selection(random, population, args):
"""Return a uniform sampling of individuals from the population.
This function performs uniform selection by randomly choosing
members of the population with replacement.
.. Arguments:
random -- the random number generator object
p... |
def fitness_proportionate_selection(random, population, args):
"""Return fitness proportionate sampling of individuals from the population.
This function stochastically chooses individuals from the population
with probability proportional to their fitness. This is often
referred to as "roulette wh... |
def rank_selection(random, population, args):
"""Return a rank-based sampling of individuals from the population.
This function behaves similarly to fitness proportionate selection,
except that it uses the individual's rank in the population, rather
than its raw fitness value, to determine its prob... |
def tournament_selection(random, population, args):
"""Return a tournament sampling of individuals from the population.
This function selects ``num_selected`` individuals from the population.
It selects each one by using random sampling without replacement
to pull ``tournament_size`` individuals a... |
def best_observer(population, num_generations, num_evaluations, args):
"""Print the best individual in the population to the screen.
This function displays the best individual in the population to
the screen.
.. Arguments:
population -- the population of Individuals
num_generat... |
def stats_observer(population, num_generations, num_evaluations, args):
"""Print the statistics of the evolutionary computation to the screen.
This function displays the statistics of the evolutionary computation
to the screen. The output includes the generation number, the current
number of evalua... |
def population_observer(population, num_generations, num_evaluations, args):
"""Print the current population of the evolutionary computation to the screen.
This function displays the current population of the evolutionary
computation to the screen in fitness-sorted order.
.. Arguments:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.