repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
django-danceschool/django-danceschool
danceschool/prerequisites/handlers.py
checkRequirements
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.') formData = kwargs.get('formData',{}) first = formData.get('firstName') last = formData.get('lastName') email = formData.get('email') request = kwargs.get('request',{}) registration = kwargs.get('registration',None) customer = Customer.objects.filter( first_name=first, last_name=last, email=email).first() requirement_warnings = [] requirement_errors = [] for ter in registration.temporaryeventregistration_set.all(): if hasattr(ter.event,'getRequirements'): for req in ter.event.getRequirements(): if not req.customerMeetsRequirement( customer=customer, danceRole=ter.role ): if req.enforcementMethod == Requirement.EnforcementChoice.error: requirement_errors.append((ter.event.name, req.name)) if req.enforcementMethod == Requirement.EnforcementChoice.warning: requirement_warnings.append((ter.event.name,req.name)) if requirement_errors: raise ValidationError(format_html( '<p>{}</p> <ul>{}</ul> <p>{}</p>', ugettext('Unfortunately, you do not meet the following requirements/prerequisites for the items you have chosen:\n'), mark_safe(''.join(['<li><em>%s:</em> %s</li>\n' % x for x in requirement_errors])), getConstant('requirements__errorMessage') or '', )) if requirement_warnings: messages.warning(request,format_html( '<p>{}</p> <ul>{}</ul> <p>{}</p>', mark_safe(ugettext('<strong>Please Note:</strong> It appears that you do not meet the following requirements/prerequisites for the items you have chosen:\n')), mark_safe(''.join(['<li><em>%s:</em> %s</li>\n' % x for x in requirement_warnings])), getConstant('requirements__warningMessage') or '', ))
python
def checkRequirements(sender,**kwargs): if not getConstant('requirements__enableRequirements'): return logger.debug('Signal to check RegistrationContactForm handled by prerequisites app.') formData = kwargs.get('formData',{}) first = formData.get('firstName') last = formData.get('lastName') email = formData.get('email') request = kwargs.get('request',{}) registration = kwargs.get('registration',None) customer = Customer.objects.filter( first_name=first, last_name=last, email=email).first() requirement_warnings = [] requirement_errors = [] for ter in registration.temporaryeventregistration_set.all(): if hasattr(ter.event,'getRequirements'): for req in ter.event.getRequirements(): if not req.customerMeetsRequirement( customer=customer, danceRole=ter.role ): if req.enforcementMethod == Requirement.EnforcementChoice.error: requirement_errors.append((ter.event.name, req.name)) if req.enforcementMethod == Requirement.EnforcementChoice.warning: requirement_warnings.append((ter.event.name,req.name)) if requirement_errors: raise ValidationError(format_html( '<p>{}</p> <ul>{}</ul> <p>{}</p>', ugettext('Unfortunately, you do not meet the following requirements/prerequisites for the items you have chosen:\n'), mark_safe(''.join(['<li><em>%s:</em> %s</li>\n' % x for x in requirement_errors])), getConstant('requirements__errorMessage') or '', )) if requirement_warnings: messages.warning(request,format_html( '<p>{}</p> <ul>{}</ul> <p>{}</p>', mark_safe(ugettext('<strong>Please Note:</strong> It appears that you do not meet the following requirements/prerequisites for the items you have chosen:\n')), mark_safe(''.join(['<li><em>%s:</em> %s</li>\n' % x for x in requirement_warnings])), getConstant('requirements__warningMessage') or '', ))
[ "def", "checkRequirements", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "getConstant", "(", "'requirements__enableRequirements'", ")", ":", "return", "logger", ".", "debug", "(", "'Signal to check RegistrationContactForm handled by prerequisites app.'", ")", "formData", "=", "kwargs", ".", "get", "(", "'formData'", ",", "{", "}", ")", "first", "=", "formData", ".", "get", "(", "'firstName'", ")", "last", "=", "formData", ".", "get", "(", "'lastName'", ")", "email", "=", "formData", ".", "get", "(", "'email'", ")", "request", "=", "kwargs", ".", "get", "(", "'request'", ",", "{", "}", ")", "registration", "=", "kwargs", ".", "get", "(", "'registration'", ",", "None", ")", "customer", "=", "Customer", ".", "objects", ".", "filter", "(", "first_name", "=", "first", ",", "last_name", "=", "last", ",", "email", "=", "email", ")", ".", "first", "(", ")", "requirement_warnings", "=", "[", "]", "requirement_errors", "=", "[", "]", "for", "ter", "in", "registration", ".", "temporaryeventregistration_set", ".", "all", "(", ")", ":", "if", "hasattr", "(", "ter", ".", "event", ",", "'getRequirements'", ")", ":", "for", "req", "in", "ter", ".", "event", ".", "getRequirements", "(", ")", ":", "if", "not", "req", ".", "customerMeetsRequirement", "(", "customer", "=", "customer", ",", "danceRole", "=", "ter", ".", "role", ")", ":", "if", "req", ".", "enforcementMethod", "==", "Requirement", ".", "EnforcementChoice", ".", "error", ":", "requirement_errors", ".", "append", "(", "(", "ter", ".", "event", ".", "name", ",", "req", ".", "name", ")", ")", "if", "req", ".", "enforcementMethod", "==", "Requirement", ".", "EnforcementChoice", ".", "warning", ":", "requirement_warnings", ".", "append", "(", "(", "ter", ".", "event", ".", "name", ",", "req", ".", "name", ")", ")", "if", "requirement_errors", ":", "raise", "ValidationError", "(", "format_html", "(", "'<p>{}</p> <ul>{}</ul> <p>{}</p>'", ",", "ugettext", "(", "'Unfortunately, you do not meet the following requirements/prerequisites for the items you have chosen:\\n'", ")", ",", "mark_safe", "(", "''", ".", "join", "(", "[", "'<li><em>%s:</em> %s</li>\\n'", "%", "x", "for", "x", "in", "requirement_errors", "]", ")", ")", ",", "getConstant", "(", "'requirements__errorMessage'", ")", "or", "''", ",", ")", ")", "if", "requirement_warnings", ":", "messages", ".", "warning", "(", "request", ",", "format_html", "(", "'<p>{}</p> <ul>{}</ul> <p>{}</p>'", ",", "mark_safe", "(", "ugettext", "(", "'<strong>Please Note:</strong> It appears that you do not meet the following requirements/prerequisites for the items you have chosen:\\n'", ")", ")", ",", "mark_safe", "(", "''", ".", "join", "(", "[", "'<li><em>%s:</em> %s</li>\\n'", "%", "x", "for", "x", "in", "requirement_warnings", "]", ")", ")", ",", "getConstant", "(", "'requirements__warningMessage'", ")", "or", "''", ",", ")", ")" ]
Check that the customer meets all prerequisites for the items in the registration.
[ "Check", "that", "the", "customer", "meets", "all", "prerequisites", "for", "the", "items", "in", "the", "registration", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/prerequisites/handlers.py#L22-L74
django-danceschool/django-danceschool
danceschool/core/mixins.py
EmailRecipientMixin.email_recipient
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 email an individual registrant or the recipient of an individual invoice. ''' email_kwargs = {} for list_arg in [ 'to','cc','bcc', ]: email_kwargs[list_arg] = kwargs.pop(list_arg,[]) or [] if isinstance(email_kwargs[list_arg],string_types): email_kwargs[list_arg] = [email_kwargs[list_arg],] for none_arg in ['attachment_name','attachment']: email_kwargs[none_arg] = kwargs.pop(none_arg,None) or None # Ignore any passed HTML content unless explicitly told to send as HTML if kwargs.pop('send_html',False) and kwargs.get('html_message'): email_kwargs['html_content'] = render_to_string( 'email/html_email_base.html', context={'html_content': kwargs.get('html_message'),'subject': subject} ) email_kwargs['from_name'] = kwargs.pop('from_name',getConstant('email__defaultEmailName')) or \ getConstant('email__defaultEmailName') email_kwargs['from_address'] = kwargs.pop('from_name',getConstant('email__defaultEmailFrom')) or \ getConstant('email__defaultEmailFrom') # Add the object's default recipients if they are provided default_recipients = self.get_default_recipients() or [] if isinstance(default_recipients,string_types): default_recipients = [default_recipients,] email_kwargs['bcc'] += default_recipients if not (email_kwargs['bcc'] or email_kwargs['cc'] or email_kwargs['to']): raise ValueError(_('Email must have a recipient.')) # In situations where there are no context # variables to be rendered, send a mass email has_tags = re.search('\{\{.+\}\}',content) if not has_tags: t = Template(content) rendered_content = t.render(Context(kwargs)) sendEmail(subject,rendered_content,**email_kwargs) return # Otherwise, get the object-specific email context and email # each recipient template_context = self.get_email_context() or {} template_context.update(kwargs) # For security reasons, the following tags are removed from the template before parsing: # {% extends %}{% load %}{% debug %}{% include %}{% ssi %} content = re.sub( '\{%\s*((extends)|(load)|(debug)|(include)|(ssi))\s+.*?\s*%\}', '', content ) t = Template(content) rendered_content = t.render(Context(template_context)) if email_kwargs.get('html_content'): html_content = re.sub( '\{%\s*((extends)|(load)|(debug)|(include)|(ssi))\s+.*?\s*%\}', '', email_kwargs.get('html_content') ) t = Template(html_content) email_kwargs['html_content'] = t.render(Context(template_context)) sendEmail(subject,rendered_content,**email_kwargs)
python
def email_recipient(self, subject, content, **kwargs): email_kwargs = {} for list_arg in [ 'to','cc','bcc', ]: email_kwargs[list_arg] = kwargs.pop(list_arg,[]) or [] if isinstance(email_kwargs[list_arg],string_types): email_kwargs[list_arg] = [email_kwargs[list_arg],] for none_arg in ['attachment_name','attachment']: email_kwargs[none_arg] = kwargs.pop(none_arg,None) or None if kwargs.pop('send_html',False) and kwargs.get('html_message'): email_kwargs['html_content'] = render_to_string( 'email/html_email_base.html', context={'html_content': kwargs.get('html_message'),'subject': subject} ) email_kwargs['from_name'] = kwargs.pop('from_name',getConstant('email__defaultEmailName')) or \ getConstant('email__defaultEmailName') email_kwargs['from_address'] = kwargs.pop('from_name',getConstant('email__defaultEmailFrom')) or \ getConstant('email__defaultEmailFrom') default_recipients = self.get_default_recipients() or [] if isinstance(default_recipients,string_types): default_recipients = [default_recipients,] email_kwargs['bcc'] += default_recipients if not (email_kwargs['bcc'] or email_kwargs['cc'] or email_kwargs['to']): raise ValueError(_('Email must have a recipient.')) has_tags = re.search('\{\{.+\}\}',content) if not has_tags: t = Template(content) rendered_content = t.render(Context(kwargs)) sendEmail(subject,rendered_content,**email_kwargs) return template_context = self.get_email_context() or {} template_context.update(kwargs) content = re.sub( '\{%\s*((extends)|(load)|(debug)|(include)|(ssi))\s+.*?\s*%\}', '', content ) t = Template(content) rendered_content = t.render(Context(template_context)) if email_kwargs.get('html_content'): html_content = re.sub( '\{%\s*((extends)|(load)|(debug)|(include)|(ssi))\s+.*?\s*%\}', '', email_kwargs.get('html_content') ) t = Template(html_content) email_kwargs['html_content'] = t.render(Context(template_context)) sendEmail(subject,rendered_content,**email_kwargs)
[ "def", "email_recipient", "(", "self", ",", "subject", ",", "content", ",", "*", "*", "kwargs", ")", ":", "email_kwargs", "=", "{", "}", "for", "list_arg", "in", "[", "'to'", ",", "'cc'", ",", "'bcc'", ",", "]", ":", "email_kwargs", "[", "list_arg", "]", "=", "kwargs", ".", "pop", "(", "list_arg", ",", "[", "]", ")", "or", "[", "]", "if", "isinstance", "(", "email_kwargs", "[", "list_arg", "]", ",", "string_types", ")", ":", "email_kwargs", "[", "list_arg", "]", "=", "[", "email_kwargs", "[", "list_arg", "]", ",", "]", "for", "none_arg", "in", "[", "'attachment_name'", ",", "'attachment'", "]", ":", "email_kwargs", "[", "none_arg", "]", "=", "kwargs", ".", "pop", "(", "none_arg", ",", "None", ")", "or", "None", "# Ignore any passed HTML content unless explicitly told to send as HTML\r", "if", "kwargs", ".", "pop", "(", "'send_html'", ",", "False", ")", "and", "kwargs", ".", "get", "(", "'html_message'", ")", ":", "email_kwargs", "[", "'html_content'", "]", "=", "render_to_string", "(", "'email/html_email_base.html'", ",", "context", "=", "{", "'html_content'", ":", "kwargs", ".", "get", "(", "'html_message'", ")", ",", "'subject'", ":", "subject", "}", ")", "email_kwargs", "[", "'from_name'", "]", "=", "kwargs", ".", "pop", "(", "'from_name'", ",", "getConstant", "(", "'email__defaultEmailName'", ")", ")", "or", "getConstant", "(", "'email__defaultEmailName'", ")", "email_kwargs", "[", "'from_address'", "]", "=", "kwargs", ".", "pop", "(", "'from_name'", ",", "getConstant", "(", "'email__defaultEmailFrom'", ")", ")", "or", "getConstant", "(", "'email__defaultEmailFrom'", ")", "# Add the object's default recipients if they are provided\r", "default_recipients", "=", "self", ".", "get_default_recipients", "(", ")", "or", "[", "]", "if", "isinstance", "(", "default_recipients", ",", "string_types", ")", ":", "default_recipients", "=", "[", "default_recipients", ",", "]", "email_kwargs", "[", "'bcc'", "]", "+=", "default_recipients", "if", "not", "(", "email_kwargs", "[", "'bcc'", "]", "or", "email_kwargs", "[", "'cc'", "]", "or", "email_kwargs", "[", "'to'", "]", ")", ":", "raise", "ValueError", "(", "_", "(", "'Email must have a recipient.'", ")", ")", "# In situations where there are no context\r", "# variables to be rendered, send a mass email\r", "has_tags", "=", "re", ".", "search", "(", "'\\{\\{.+\\}\\}'", ",", "content", ")", "if", "not", "has_tags", ":", "t", "=", "Template", "(", "content", ")", "rendered_content", "=", "t", ".", "render", "(", "Context", "(", "kwargs", ")", ")", "sendEmail", "(", "subject", ",", "rendered_content", ",", "*", "*", "email_kwargs", ")", "return", "# Otherwise, get the object-specific email context and email\r", "# each recipient\r", "template_context", "=", "self", ".", "get_email_context", "(", ")", "or", "{", "}", "template_context", ".", "update", "(", "kwargs", ")", "# For security reasons, the following tags are removed from the template before parsing:\r", "# {% extends %}{% load %}{% debug %}{% include %}{% ssi %}\r", "content", "=", "re", ".", "sub", "(", "'\\{%\\s*((extends)|(load)|(debug)|(include)|(ssi))\\s+.*?\\s*%\\}'", ",", "''", ",", "content", ")", "t", "=", "Template", "(", "content", ")", "rendered_content", "=", "t", ".", "render", "(", "Context", "(", "template_context", ")", ")", "if", "email_kwargs", ".", "get", "(", "'html_content'", ")", ":", "html_content", "=", "re", ".", "sub", "(", "'\\{%\\s*((extends)|(load)|(debug)|(include)|(ssi))\\s+.*?\\s*%\\}'", ",", "''", ",", "email_kwargs", ".", "get", "(", "'html_content'", ")", ")", "t", "=", "Template", "(", "html_content", ")", "email_kwargs", "[", "'html_content'", "]", "=", "t", ".", "render", "(", "Context", "(", "template_context", ")", ")", "sendEmail", "(", "subject", ",", "rendered_content", ",", "*", "*", "email_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 email an individual registrant or the recipient of an individual invoice.
[ "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", "email", "an", "individual", "registrant", "or", "the", "recipient", "of", "an", "individual", "invoice", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L30-L105
django-danceschool/django-danceschool
danceschool/core/mixins.py
EmailRecipientMixin.get_email_context
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 variables are added to the dictionary, and kwargs are just passed directly. Note also that it is in general not a good idea for security reasons to pass model instances in the context here, since these methods can be accessed by logged in users who use the SendEmailView. So, In the default models of this app, the values of fields and properties are passed directly instead. ''' context = kwargs context.update({ 'currencyCode': getConstant('general__currencyCode'), 'currencySymbol': getConstant('general__currencySymbol'), 'businessName': getConstant('contact__businessName'), 'site_url': getConstant('email__linkProtocol') + '://' + Site.objects.get_current().domain, }) return context
python
def get_email_context(self,**kwargs): context = kwargs context.update({ 'currencyCode': getConstant('general__currencyCode'), 'currencySymbol': getConstant('general__currencySymbol'), 'businessName': getConstant('contact__businessName'), 'site_url': getConstant('email__linkProtocol') + '://' + Site.objects.get_current().domain, }) return context
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "kwargs", "context", ".", "update", "(", "{", "'currencyCode'", ":", "getConstant", "(", "'general__currencyCode'", ")", ",", "'currencySymbol'", ":", "getConstant", "(", "'general__currencySymbol'", ")", ",", "'businessName'", ":", "getConstant", "(", "'contact__businessName'", ")", ",", "'site_url'", ":", "getConstant", "(", "'email__linkProtocol'", ")", "+", "'://'", "+", "Site", ".", "objects", ".", "get_current", "(", ")", ".", "domain", ",", "}", ")", "return", "context" ]
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 variables are added to the dictionary, and kwargs are just passed directly. Note also that it is in general not a good idea for security reasons to pass model instances in the context here, since these methods can be accessed by logged in users who use the SendEmailView. So, In the default models of this app, the values of fields and properties are passed directly instead.
[ "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", "variables", "are", "added", "to", "the", "dictionary", "and", "kwargs", "are", "just", "passed", "directly", ".", "Note", "also", "that", "it", "is", "in", "general", "not", "a", "good", "idea", "for", "security", "reasons", "to", "pass", "model", "instances", "in", "the", "context", "here", "since", "these", "methods", "can", "be", "accessed", "by", "logged", "in", "users", "who", "use", "the", "SendEmailView", ".", "So", "In", "the", "default", "models", "of", "this", "app", "the", "values", "of", "fields", "and", "properties", "are", "passed", "directly", "instead", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L107-L128
django-danceschool/django-danceschool
danceschool/core/mixins.py
GroupRequiredByFieldMixin.get_group_required
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,self.group_required_field).name] return ['']
python
def get_group_required(self): 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,self.group_required_field).name] return ['']
[ "def", "get_group_required", "(", "self", ")", ":", "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", ",", "self", ".", "group_required_field", ")", ".", "name", "]", "return", "[", "''", "]" ]
Get the group_required value from the object
[ "Get", "the", "group_required", "value", "from", "the", "object" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L179-L185
django-danceschool/django-danceschool
danceschool/core/mixins.py
GroupRequiredByFieldMixin.check_membership
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) return set(groups).intersection(set(user_groups))
python
def check_membership(self, 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) return set(groups).intersection(set(user_groups))
[ "def", "check_membership", "(", "self", ",", "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", ")", "return", "set", "(", "groups", ")", ".", "intersection", "(", "set", "(", "user_groups", ")", ")" ]
Allows for objects with no required groups
[ "Allows", "for", "objects", "with", "no", "required", "groups" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L187-L194
django-danceschool/django-danceschool
danceschool/core/mixins.py
GroupRequiredByFieldMixin.dispatch
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_required() if not required_group or required_group == ['']: in_group = True elif self.request.user.is_authenticated(): in_group = self.check_membership(required_group) if not in_group: if self.raise_exception: raise PermissionDenied else: return redirect_to_login( request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) return super(GroupRequiredMixin, self).dispatch( request, *args, **kwargs)
python
def dispatch(self, request, *args, **kwargs): self.request = request in_group = False required_group = self.get_group_required() if not required_group or required_group == ['']: in_group = True elif self.request.user.is_authenticated(): in_group = self.check_membership(required_group) if not in_group: if self.raise_exception: raise PermissionDenied else: return redirect_to_login( request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) return super(GroupRequiredMixin, self).dispatch( request, *args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "request", "=", "request", "in_group", "=", "False", "required_group", "=", "self", ".", "get_group_required", "(", ")", "if", "not", "required_group", "or", "required_group", "==", "[", "''", "]", ":", "in_group", "=", "True", "elif", "self", ".", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "in_group", "=", "self", ".", "check_membership", "(", "required_group", ")", "if", "not", "in_group", ":", "if", "self", ".", "raise_exception", ":", "raise", "PermissionDenied", "else", ":", "return", "redirect_to_login", "(", "request", ".", "get_full_path", "(", ")", ",", "self", ".", "get_login_url", "(", ")", ",", "self", ".", "get_redirect_field_name", "(", ")", ")", "return", "super", "(", "GroupRequiredMixin", ",", "self", ")", ".", "dispatch", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
This override of dispatch ensures that if no group is required, then the request still goes through without being logged in.
[ "This", "override", "of", "dispatch", "ensures", "that", "if", "no", "group", "is", "required", "then", "the", "request", "still", "goes", "through", "without", "being", "logged", "in", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L196-L218
django-danceschool/django-danceschool
danceschool/core/mixins.py
TemplateChoiceField.validate
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 TemplateDoesNotExist: raise ValidationError(_('%s is not a valid template.' % value))
python
def validate(self,value): super(ChoiceField,self).validate(value) try: get_template(value) except TemplateDoesNotExist: raise ValidationError(_('%s is not a valid template.' % value))
[ "def", "validate", "(", "self", ",", "value", ")", ":", "super", "(", "ChoiceField", ",", "self", ")", ".", "validate", "(", "value", ")", "try", ":", "get_template", "(", "value", ")", "except", "TemplateDoesNotExist", ":", "raise", "ValidationError", "(", "_", "(", "'%s is not a valid template.'", "%", "value", ")", ")" ]
Check for empty values, and for an existing template, but do not check if this is one of the initial choices provided.
[ "Check", "for", "empty", "values", "and", "for", "an", "existing", "template", "but", "do", "not", "check", "if", "this", "is", "one", "of", "the", "initial", "choices", "provided", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L242-L252
django-danceschool/django-danceschool
danceschool/core/mixins.py
PluginTemplateMixin.render
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)
python
def render(self, context, instance, placeholder): if instance and instance.template: self.render_template = instance.template return super(PluginTemplateMixin,self).render(context,instance,placeholder)
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "if", "instance", "and", "instance", ".", "template", ":", "self", ".", "render_template", "=", "instance", ".", "template", "return", "super", "(", "PluginTemplateMixin", ",", "self", ")", ".", "render", "(", "context", ",", "instance", ",", "placeholder", ")" ]
Permits setting of the template in the plugin instance configuration
[ "Permits", "setting", "of", "the", "template", "in", "the", "plugin", "instance", "configuration" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L261-L265
django-danceschool/django-danceschool
danceschool/core/mixins.py
EventOrderMixin.get_annotations
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(). ''' rule = getConstant('registration__orgRule') # Initialize with null values that get filled in based on the logic below. annotations = { 'nullParam': Case(default_value=None,output_field=IntegerField()), 'paramOne': Case(default_value=None,output_field=IntegerField()), 'paramTwo': Case(default_value=None,output_field=IntegerField()), } if rule == 'SessionFirst': annotations.update({ 'nullParam': Case( When(session__startTime__isnull=False, then=0), When(month__isnull=False, then=1), default_value=2, output_field=IntegerField() ), 'paramOne': F('session__startTime'), 'paramTwo': ExpressionWrapper(12 * F('year') + F('month'), output_field=IntegerField()), }) elif rule == 'SessionAlphaFirst': annotations.update({ 'nullParam': Case( When(session__name__isnull=False, then=0), When(month__isnull=False, then=1), default_value=2, output_field=IntegerField() ), 'paramOne': F('session__name'), 'paramTwo': ExpressionWrapper(12 * F('year') + F('month'), output_field=IntegerField()), }) elif rule == 'Month': annotations.update({ 'nullParam': Case( When(month__isnull=False, then=0), default_value=1, output_field=IntegerField() ), 'paramOne': ExpressionWrapper(12*F('year') + F('month'), output_field=IntegerField()), }) elif rule == 'Session': annotations.update({ 'nullParam': Case( When(session__startTime__isnull=False, then=0), default_value=1, output_field=IntegerField() ), 'paramOne': F('session__startTime'), }) elif rule == 'SessionAlpha': annotations.update({ 'nullParam': Case( When(session__name__isnull=False, then=0), default_value=1, output_field=IntegerField() ), 'paramOne': F('session__name'), }) elif rule == 'SessionMonth': annotations.update({ 'nullParam': Case( When(Q(session__startTime__isnull=False) & Q(month__isnull=False), then=0), When(Q(session__startTime__isnull=True) & Q(month__isnull=False), then=1), When(Q(session__startTime__isnull=False) & Q(month__isnull=True), then=2), default_value=3, output_field=IntegerField() ), 'paramOne': ExpressionWrapper(12 * F('year') + F('month'), output_field=IntegerField()), 'paramTwo': F('session__startTime'), }) elif rule == 'SessionAlphaMonth': annotations.update({ 'nullParam': Case( When(Q(session__name__isnull=False) & Q(month__isnull=False), then=0), When(Q(session__name__isnull=True) & Q(month__isnull=False), then=1), When(Q(session__name__isnull=False) & Q(month__isnull=True), then=2), default_value=3, output_field=IntegerField() ), 'paramOne': ExpressionWrapper(12*F('year') + F('month'), output_field=IntegerField()), 'paramTwo': F('session__name'), }) elif rule == 'Weekday': annotations.update({ 'nullParam': Case( When(startTime__week_day__isnull=False, then=0), default_value=1, output_field=IntegerField() ), 'paramOne': ExtractWeekDay('startTime'), }) elif rule == 'MonthWeekday': annotations.update({ 'nullParam': Case( When(Q(month__isnull=False) & Q(startTime__week_day__isnull=False), then=0), default_value=1, output_field=IntegerField() ), 'paramOne': ExpressionWrapper(12*F('year') + F('month'), output_field=IntegerField()), 'paramTwo': ExtractWeekDay('startTime'), }) return annotations
python
def get_annotations(self): rule = getConstant('registration__orgRule') annotations = { 'nullParam': Case(default_value=None,output_field=IntegerField()), 'paramOne': Case(default_value=None,output_field=IntegerField()), 'paramTwo': Case(default_value=None,output_field=IntegerField()), } if rule == 'SessionFirst': annotations.update({ 'nullParam': Case( When(session__startTime__isnull=False, then=0), When(month__isnull=False, then=1), default_value=2, output_field=IntegerField() ), 'paramOne': F('session__startTime'), 'paramTwo': ExpressionWrapper(12 * F('year') + F('month'), output_field=IntegerField()), }) elif rule == 'SessionAlphaFirst': annotations.update({ 'nullParam': Case( When(session__name__isnull=False, then=0), When(month__isnull=False, then=1), default_value=2, output_field=IntegerField() ), 'paramOne': F('session__name'), 'paramTwo': ExpressionWrapper(12 * F('year') + F('month'), output_field=IntegerField()), }) elif rule == 'Month': annotations.update({ 'nullParam': Case( When(month__isnull=False, then=0), default_value=1, output_field=IntegerField() ), 'paramOne': ExpressionWrapper(12*F('year') + F('month'), output_field=IntegerField()), }) elif rule == 'Session': annotations.update({ 'nullParam': Case( When(session__startTime__isnull=False, then=0), default_value=1, output_field=IntegerField() ), 'paramOne': F('session__startTime'), }) elif rule == 'SessionAlpha': annotations.update({ 'nullParam': Case( When(session__name__isnull=False, then=0), default_value=1, output_field=IntegerField() ), 'paramOne': F('session__name'), }) elif rule == 'SessionMonth': annotations.update({ 'nullParam': Case( When(Q(session__startTime__isnull=False) & Q(month__isnull=False), then=0), When(Q(session__startTime__isnull=True) & Q(month__isnull=False), then=1), When(Q(session__startTime__isnull=False) & Q(month__isnull=True), then=2), default_value=3, output_field=IntegerField() ), 'paramOne': ExpressionWrapper(12 * F('year') + F('month'), output_field=IntegerField()), 'paramTwo': F('session__startTime'), }) elif rule == 'SessionAlphaMonth': annotations.update({ 'nullParam': Case( When(Q(session__name__isnull=False) & Q(month__isnull=False), then=0), When(Q(session__name__isnull=True) & Q(month__isnull=False), then=1), When(Q(session__name__isnull=False) & Q(month__isnull=True), then=2), default_value=3, output_field=IntegerField() ), 'paramOne': ExpressionWrapper(12*F('year') + F('month'), output_field=IntegerField()), 'paramTwo': F('session__name'), }) elif rule == 'Weekday': annotations.update({ 'nullParam': Case( When(startTime__week_day__isnull=False, then=0), default_value=1, output_field=IntegerField() ), 'paramOne': ExtractWeekDay('startTime'), }) elif rule == 'MonthWeekday': annotations.update({ 'nullParam': Case( When(Q(month__isnull=False) & Q(startTime__week_day__isnull=False), then=0), default_value=1, output_field=IntegerField() ), 'paramOne': ExpressionWrapper(12*F('year') + F('month'), output_field=IntegerField()), 'paramTwo': ExtractWeekDay('startTime'), }) return annotations
[ "def", "get_annotations", "(", "self", ")", ":", "rule", "=", "getConstant", "(", "'registration__orgRule'", ")", "# Initialize with null values that get filled in based on the logic below.\r", "annotations", "=", "{", "'nullParam'", ":", "Case", "(", "default_value", "=", "None", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "Case", "(", "default_value", "=", "None", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramTwo'", ":", "Case", "(", "default_value", "=", "None", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "}", "if", "rule", "==", "'SessionFirst'", ":", "annotations", ".", "update", "(", "{", "'nullParam'", ":", "Case", "(", "When", "(", "session__startTime__isnull", "=", "False", ",", "then", "=", "0", ")", ",", "When", "(", "month__isnull", "=", "False", ",", "then", "=", "1", ")", ",", "default_value", "=", "2", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "F", "(", "'session__startTime'", ")", ",", "'paramTwo'", ":", "ExpressionWrapper", "(", "12", "*", "F", "(", "'year'", ")", "+", "F", "(", "'month'", ")", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "}", ")", "elif", "rule", "==", "'SessionAlphaFirst'", ":", "annotations", ".", "update", "(", "{", "'nullParam'", ":", "Case", "(", "When", "(", "session__name__isnull", "=", "False", ",", "then", "=", "0", ")", ",", "When", "(", "month__isnull", "=", "False", ",", "then", "=", "1", ")", ",", "default_value", "=", "2", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "F", "(", "'session__name'", ")", ",", "'paramTwo'", ":", "ExpressionWrapper", "(", "12", "*", "F", "(", "'year'", ")", "+", "F", "(", "'month'", ")", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "}", ")", "elif", "rule", "==", "'Month'", ":", "annotations", ".", "update", "(", "{", "'nullParam'", ":", "Case", "(", "When", "(", "month__isnull", "=", "False", ",", "then", "=", "0", ")", ",", "default_value", "=", "1", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "ExpressionWrapper", "(", "12", "*", "F", "(", "'year'", ")", "+", "F", "(", "'month'", ")", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "}", ")", "elif", "rule", "==", "'Session'", ":", "annotations", ".", "update", "(", "{", "'nullParam'", ":", "Case", "(", "When", "(", "session__startTime__isnull", "=", "False", ",", "then", "=", "0", ")", ",", "default_value", "=", "1", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "F", "(", "'session__startTime'", ")", ",", "}", ")", "elif", "rule", "==", "'SessionAlpha'", ":", "annotations", ".", "update", "(", "{", "'nullParam'", ":", "Case", "(", "When", "(", "session__name__isnull", "=", "False", ",", "then", "=", "0", ")", ",", "default_value", "=", "1", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "F", "(", "'session__name'", ")", ",", "}", ")", "elif", "rule", "==", "'SessionMonth'", ":", "annotations", ".", "update", "(", "{", "'nullParam'", ":", "Case", "(", "When", "(", "Q", "(", "session__startTime__isnull", "=", "False", ")", "&", "Q", "(", "month__isnull", "=", "False", ")", ",", "then", "=", "0", ")", ",", "When", "(", "Q", "(", "session__startTime__isnull", "=", "True", ")", "&", "Q", "(", "month__isnull", "=", "False", ")", ",", "then", "=", "1", ")", ",", "When", "(", "Q", "(", "session__startTime__isnull", "=", "False", ")", "&", "Q", "(", "month__isnull", "=", "True", ")", ",", "then", "=", "2", ")", ",", "default_value", "=", "3", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "ExpressionWrapper", "(", "12", "*", "F", "(", "'year'", ")", "+", "F", "(", "'month'", ")", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramTwo'", ":", "F", "(", "'session__startTime'", ")", ",", "}", ")", "elif", "rule", "==", "'SessionAlphaMonth'", ":", "annotations", ".", "update", "(", "{", "'nullParam'", ":", "Case", "(", "When", "(", "Q", "(", "session__name__isnull", "=", "False", ")", "&", "Q", "(", "month__isnull", "=", "False", ")", ",", "then", "=", "0", ")", ",", "When", "(", "Q", "(", "session__name__isnull", "=", "True", ")", "&", "Q", "(", "month__isnull", "=", "False", ")", ",", "then", "=", "1", ")", ",", "When", "(", "Q", "(", "session__name__isnull", "=", "False", ")", "&", "Q", "(", "month__isnull", "=", "True", ")", ",", "then", "=", "2", ")", ",", "default_value", "=", "3", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "ExpressionWrapper", "(", "12", "*", "F", "(", "'year'", ")", "+", "F", "(", "'month'", ")", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramTwo'", ":", "F", "(", "'session__name'", ")", ",", "}", ")", "elif", "rule", "==", "'Weekday'", ":", "annotations", ".", "update", "(", "{", "'nullParam'", ":", "Case", "(", "When", "(", "startTime__week_day__isnull", "=", "False", ",", "then", "=", "0", ")", ",", "default_value", "=", "1", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "ExtractWeekDay", "(", "'startTime'", ")", ",", "}", ")", "elif", "rule", "==", "'MonthWeekday'", ":", "annotations", ".", "update", "(", "{", "'nullParam'", ":", "Case", "(", "When", "(", "Q", "(", "month__isnull", "=", "False", ")", "&", "Q", "(", "startTime__week_day__isnull", "=", "False", ")", ",", "then", "=", "0", ")", ",", "default_value", "=", "1", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramOne'", ":", "ExpressionWrapper", "(", "12", "*", "F", "(", "'year'", ")", "+", "F", "(", "'month'", ")", ",", "output_field", "=", "IntegerField", "(", ")", ")", ",", "'paramTwo'", ":", "ExtractWeekDay", "(", "'startTime'", ")", ",", "}", ")", "return", "annotations" ]
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().
[ "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", "()", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L336-L444
django-danceschool/django-danceschool
danceschool/core/mixins.py
EventOrderMixin.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 fail because the appropriate column names will not exist to sort with. ''' # Reverse ordering can be optionally specified in the view class definition. reverseTime = getattr(self,'reverse_time_ordering',reverseTime) timeParameter = '-startTime' if reverseTime is True else 'startTime' return ('nullParam', 'paramOne', 'paramTwo', timeParameter)
python
def get_ordering(self, reverseTime=False): reverseTime = getattr(self,'reverse_time_ordering',reverseTime) timeParameter = '-startTime' if reverseTime is True else 'startTime' return ('nullParam', 'paramOne', 'paramTwo', timeParameter)
[ "def", "get_ordering", "(", "self", ",", "reverseTime", "=", "False", ")", ":", "# Reverse ordering can be optionally specified in the view class definition.\r", "reverseTime", "=", "getattr", "(", "self", ",", "'reverse_time_ordering'", ",", "reverseTime", ")", "timeParameter", "=", "'-startTime'", "if", "reverseTime", "is", "True", "else", "'startTime'", "return", "(", "'nullParam'", ",", "'paramOne'", ",", "'paramTwo'", ",", "timeParameter", ")" ]
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 fail because the appropriate column names will not exist to sort with.
[ "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", "fail", "because", "the", "appropriate", "column", "names", "will", "not", "exist", "to", "sort", "with", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L446-L457
django-danceschool/django-danceschool
danceschool/core/mixins.py
SiteHistoryMixin.get_return_page
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)
python
def get_return_page(self,prior=False): siteHistory = self.request.session.get('SITE_HISTORY',{}) return getReturnPage(siteHistory,prior=prior)
[ "def", "get_return_page", "(", "self", ",", "prior", "=", "False", ")", ":", "siteHistory", "=", "self", ".", "request", ".", "session", ".", "get", "(", "'SITE_HISTORY'", ",", "{", "}", ")", "return", "getReturnPage", "(", "siteHistory", ",", "prior", "=", "prior", ")" ]
This is just a wrapper for the getReturnPage helper function.
[ "This", "is", "just", "a", "wrapper", "for", "the", "getReturnPage", "helper", "function", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L487-L490
django-danceschool/django-danceschool
danceschool/core/forms.py
RegistrationContactForm.is_valid
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 only want validation messages to show up once, so pop messages that have already show up # before checking to see if any messages remain to be shown. prior_messages = self._session.pop('prior_messages',[]) remaining_messages = [] for m in msgs: m_dict = {'message': m.message, 'level': m.level, 'extra_tags': m.extra_tags} if m_dict not in prior_messages: remaining_messages.append(m_dict) if remaining_messages: self._session['prior_messages'] = remaining_messages self._request.session.modified = True return False return valid
python
def is_valid(self): valid = super(RegistrationContactForm,self).is_valid() msgs = messages.get_messages(self._request) prior_messages = self._session.pop('prior_messages',[]) remaining_messages = [] for m in msgs: m_dict = {'message': m.message, 'level': m.level, 'extra_tags': m.extra_tags} if m_dict not in prior_messages: remaining_messages.append(m_dict) if remaining_messages: self._session['prior_messages'] = remaining_messages self._request.session.modified = True return False return valid
[ "def", "is_valid", "(", "self", ")", ":", "valid", "=", "super", "(", "RegistrationContactForm", ",", "self", ")", ".", "is_valid", "(", ")", "msgs", "=", "messages", ".", "get_messages", "(", "self", ".", "_request", ")", "# We only want validation messages to show up once, so pop messages that have already show up", "# before checking to see if any messages remain to be shown.", "prior_messages", "=", "self", ".", "_session", ".", "pop", "(", "'prior_messages'", ",", "[", "]", ")", "remaining_messages", "=", "[", "]", "for", "m", "in", "msgs", ":", "m_dict", "=", "{", "'message'", ":", "m", ".", "message", ",", "'level'", ":", "m", ".", "level", ",", "'extra_tags'", ":", "m", ".", "extra_tags", "}", "if", "m_dict", "not", "in", "prior_messages", ":", "remaining_messages", ".", "append", "(", "m_dict", ")", "if", "remaining_messages", ":", "self", ".", "_session", "[", "'prior_messages'", "]", "=", "remaining_messages", "self", ".", "_request", ".", "session", ".", "modified", "=", "True", "return", "False", "return", "valid" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L378-L401
django-danceschool/django-danceschool
danceschool/core/forms.py
RefundForm.clean_total_refund_amount
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,v in self.cleaned_data.items() if k.startswith('item_refundamount_')]) if not self.cleaned_data.get('id'): raise ValidationError('ID not in cleaned data') if summed_refunds != total: raise ValidationError(_('Passed value does not match sum of allocated refunds.')) elif summed_refunds > self.cleaned_data['id'].amountPaid + self.cleaned_data['id'].refunds: raise ValidationError(_('Total refunds allocated exceed revenue received.')) elif total < initial: raise ValidationError(_('Cannot reduce the total amount of the refund.')) return total
python
def clean_total_refund_amount(self): initial = self.cleaned_data.get('initial_refund_amount', 0) total = self.cleaned_data['total_refund_amount'] summed_refunds = sum([v for k,v in self.cleaned_data.items() if k.startswith('item_refundamount_')]) if not self.cleaned_data.get('id'): raise ValidationError('ID not in cleaned data') if summed_refunds != total: raise ValidationError(_('Passed value does not match sum of allocated refunds.')) elif summed_refunds > self.cleaned_data['id'].amountPaid + self.cleaned_data['id'].refunds: raise ValidationError(_('Total refunds allocated exceed revenue received.')) elif total < initial: raise ValidationError(_('Cannot reduce the total amount of the refund.')) return total
[ "def", "clean_total_refund_amount", "(", "self", ")", ":", "initial", "=", "self", ".", "cleaned_data", ".", "get", "(", "'initial_refund_amount'", ",", "0", ")", "total", "=", "self", ".", "cleaned_data", "[", "'total_refund_amount'", "]", "summed_refunds", "=", "sum", "(", "[", "v", "for", "k", ",", "v", "in", "self", ".", "cleaned_data", ".", "items", "(", ")", "if", "k", ".", "startswith", "(", "'item_refundamount_'", ")", "]", ")", "if", "not", "self", ".", "cleaned_data", ".", "get", "(", "'id'", ")", ":", "raise", "ValidationError", "(", "'ID not in cleaned data'", ")", "if", "summed_refunds", "!=", "total", ":", "raise", "ValidationError", "(", "_", "(", "'Passed value does not match sum of allocated refunds.'", ")", ")", "elif", "summed_refunds", ">", "self", ".", "cleaned_data", "[", "'id'", "]", ".", "amountPaid", "+", "self", ".", "cleaned_data", "[", "'id'", "]", ".", "refunds", ":", "raise", "ValidationError", "(", "_", "(", "'Total refunds allocated exceed revenue received.'", ")", ")", "elif", "total", "<", "initial", ":", "raise", "ValidationError", "(", "_", "(", "'Cannot reduce the total amount of the refund.'", ")", ")", "return", "total" ]
The Javascript should ensure that the hidden input is updated, but double check it here.
[ "The", "Javascript", "should", "ensure", "that", "the", "hidden", "input", "is", "updated", "but", "double", "check", "it", "here", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L662-L679
django-danceschool/django-danceschool
danceschool/core/forms.py
SeriesClassesChoiceField._check_values
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' # deduplicate given values to avoid creating many querysets or # requiring the database backend deduplicate efficiently. try: value = frozenset(value) except TypeError: # list of lists isn't hashable, for example raise ValidationError( self.error_messages['list'], code='list', ) for pk in value: try: self.queryset.filter(**{key: pk}) except (ValueError, TypeError): raise ValidationError( self.error_messages['invalid_pk_value'], code='invalid_pk_value', params={'pk': pk}, ) qs = EventOccurrence.objects.filter(**{'%s__in' % key: value}) pks = set(force_text(getattr(o, key)) for o in qs) for val in value: if force_text(val) not in pks: raise ValidationError( self.error_messages['invalid_choice'], code='invalid_choice', params={'value': val}, ) return qs
python
def _check_values(self, value): key = self.to_field_name or 'pk' try: value = frozenset(value) except TypeError: raise ValidationError( self.error_messages['list'], code='list', ) for pk in value: try: self.queryset.filter(**{key: pk}) except (ValueError, TypeError): raise ValidationError( self.error_messages['invalid_pk_value'], code='invalid_pk_value', params={'pk': pk}, ) qs = EventOccurrence.objects.filter(**{'%s__in' % key: value}) pks = set(force_text(getattr(o, key)) for o in qs) for val in value: if force_text(val) not in pks: raise ValidationError( self.error_messages['invalid_choice'], code='invalid_choice', params={'value': val}, ) return qs
[ "def", "_check_values", "(", "self", ",", "value", ")", ":", "key", "=", "self", ".", "to_field_name", "or", "'pk'", "# deduplicate given values to avoid creating many querysets or", "# requiring the database backend deduplicate efficiently.", "try", ":", "value", "=", "frozenset", "(", "value", ")", "except", "TypeError", ":", "# list of lists isn't hashable, for example", "raise", "ValidationError", "(", "self", ".", "error_messages", "[", "'list'", "]", ",", "code", "=", "'list'", ",", ")", "for", "pk", "in", "value", ":", "try", ":", "self", ".", "queryset", ".", "filter", "(", "*", "*", "{", "key", ":", "pk", "}", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "raise", "ValidationError", "(", "self", ".", "error_messages", "[", "'invalid_pk_value'", "]", ",", "code", "=", "'invalid_pk_value'", ",", "params", "=", "{", "'pk'", ":", "pk", "}", ",", ")", "qs", "=", "EventOccurrence", ".", "objects", ".", "filter", "(", "*", "*", "{", "'%s__in'", "%", "key", ":", "value", "}", ")", "pks", "=", "set", "(", "force_text", "(", "getattr", "(", "o", ",", "key", ")", ")", "for", "o", "in", "qs", ")", "for", "val", "in", "value", ":", "if", "force_text", "(", "val", ")", "not", "in", "pks", ":", "raise", "ValidationError", "(", "self", ".", "error_messages", "[", "'invalid_choice'", "]", ",", "code", "=", "'invalid_choice'", ",", "params", "=", "{", "'value'", ":", "val", "}", ",", ")", "return", "qs" ]
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.)
[ "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", ".", ")" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L798-L833
django-danceschool/django-danceschool
danceschool/core/forms.py
SubstituteReportingForm.clean
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() occurrences = self.cleaned_data.get('occurrences',[]) staffMember = self.cleaned_data.get('staffMember') replacementFor = self.cleaned_data.get('replacedStaffMember',[]) event = self.cleaned_data.get('event') for occ in occurrences: for this_sub in occ.eventstaffmember_set.all(): if this_sub.replacedStaffMember == replacementFor: self.add_error('occurrences',ValidationError(_('One or more classes you have selected already has a substitute teacher for that class.'),code='invalid')) if event and staffMember: if staffMember in [x.staffMember for x in event.eventstaffmember_set.filter(category__in=[getConstant('general__eventStaffCategoryAssistant'),getConstant('general__eventStaffCategoryInstructor')])]: self.add_error('event',ValidationError(_('You cannot substitute teach for a class in which you were an instructor.'),code='invalid'))
python
def clean(self): super(SubstituteReportingForm,self).clean() occurrences = self.cleaned_data.get('occurrences',[]) staffMember = self.cleaned_data.get('staffMember') replacementFor = self.cleaned_data.get('replacedStaffMember',[]) event = self.cleaned_data.get('event') for occ in occurrences: for this_sub in occ.eventstaffmember_set.all(): if this_sub.replacedStaffMember == replacementFor: self.add_error('occurrences',ValidationError(_('One or more classes you have selected already has a substitute teacher for that class.'),code='invalid')) if event and staffMember: if staffMember in [x.staffMember for x in event.eventstaffmember_set.filter(category__in=[getConstant('general__eventStaffCategoryAssistant'),getConstant('general__eventStaffCategoryInstructor')])]: self.add_error('event',ValidationError(_('You cannot substitute teach for a class in which you were an instructor.'),code='invalid'))
[ "def", "clean", "(", "self", ")", ":", "super", "(", "SubstituteReportingForm", ",", "self", ")", ".", "clean", "(", ")", "occurrences", "=", "self", ".", "cleaned_data", ".", "get", "(", "'occurrences'", ",", "[", "]", ")", "staffMember", "=", "self", ".", "cleaned_data", ".", "get", "(", "'staffMember'", ")", "replacementFor", "=", "self", ".", "cleaned_data", ".", "get", "(", "'replacedStaffMember'", ",", "[", "]", ")", "event", "=", "self", ".", "cleaned_data", ".", "get", "(", "'event'", ")", "for", "occ", "in", "occurrences", ":", "for", "this_sub", "in", "occ", ".", "eventstaffmember_set", ".", "all", "(", ")", ":", "if", "this_sub", ".", "replacedStaffMember", "==", "replacementFor", ":", "self", ".", "add_error", "(", "'occurrences'", ",", "ValidationError", "(", "_", "(", "'One or more classes you have selected already has a substitute teacher for that class.'", ")", ",", "code", "=", "'invalid'", ")", ")", "if", "event", "and", "staffMember", ":", "if", "staffMember", "in", "[", "x", ".", "staffMember", "for", "x", "in", "event", ".", "eventstaffmember_set", ".", "filter", "(", "category__in", "=", "[", "getConstant", "(", "'general__eventStaffCategoryAssistant'", ")", ",", "getConstant", "(", "'general__eventStaffCategoryInstructor'", ")", "]", ")", "]", ":", "self", ".", "add_error", "(", "'event'", ",", "ValidationError", "(", "_", "(", "'You cannot substitute teach for a class in which you were an instructor.'", ")", ",", "code", "=", "'invalid'", ")", ")" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L868-L888
django-danceschool/django-danceschool
danceschool/core/forms.py
SubstituteReportingForm.save
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. ''' existing_record = EventStaffMember.objects.filter( staffMember=self.cleaned_data.get('staffMember'), event=self.cleaned_data.get('event'), category=getConstant('general__eventStaffCategorySubstitute'), replacedStaffMember=self.cleaned_data.get('replacedStaffMember'), ) if existing_record.exists(): record = existing_record.first() for x in self.cleaned_data.get('occurrences'): record.occurrences.add(x) record.save() return record else: return super(SubstituteReportingForm,self).save()
python
def save(self, commit=True): existing_record = EventStaffMember.objects.filter( staffMember=self.cleaned_data.get('staffMember'), event=self.cleaned_data.get('event'), category=getConstant('general__eventStaffCategorySubstitute'), replacedStaffMember=self.cleaned_data.get('replacedStaffMember'), ) if existing_record.exists(): record = existing_record.first() for x in self.cleaned_data.get('occurrences'): record.occurrences.add(x) record.save() return record else: return super(SubstituteReportingForm,self).save()
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "existing_record", "=", "EventStaffMember", ".", "objects", ".", "filter", "(", "staffMember", "=", "self", ".", "cleaned_data", ".", "get", "(", "'staffMember'", ")", ",", "event", "=", "self", ".", "cleaned_data", ".", "get", "(", "'event'", ")", ",", "category", "=", "getConstant", "(", "'general__eventStaffCategorySubstitute'", ")", ",", "replacedStaffMember", "=", "self", ".", "cleaned_data", ".", "get", "(", "'replacedStaffMember'", ")", ",", ")", "if", "existing_record", ".", "exists", "(", ")", ":", "record", "=", "existing_record", ".", "first", "(", ")", "for", "x", "in", "self", ".", "cleaned_data", ".", "get", "(", "'occurrences'", ")", ":", "record", ".", "occurrences", ".", "add", "(", "x", ")", "record", ".", "save", "(", ")", "return", "record", "else", ":", "return", "super", "(", "SubstituteReportingForm", ",", "self", ")", ".", "save", "(", ")" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L898-L917
django-danceschool/django-danceschool
danceschool/core/forms.py
StaffMemberBioChangeForm.save
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.instance.instructor.availableForPrivates) self.instance.instructor.save(update_fields=['availableForPrivates',]) super(StaffMemberBioChangeForm,self).save(commit=True)
python
def save(self, commit=True): if getattr(self.instance,'instructor',None): self.instance.instructor.availableForPrivates = self.cleaned_data.pop('availableForPrivates',self.instance.instructor.availableForPrivates) self.instance.instructor.save(update_fields=['availableForPrivates',]) super(StaffMemberBioChangeForm,self).save(commit=True)
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "if", "getattr", "(", "self", ".", "instance", ",", "'instructor'", ",", "None", ")", ":", "self", ".", "instance", ".", "instructor", ".", "availableForPrivates", "=", "self", ".", "cleaned_data", ".", "pop", "(", "'availableForPrivates'", ",", "self", ".", "instance", ".", "instructor", ".", "availableForPrivates", ")", "self", ".", "instance", ".", "instructor", ".", "save", "(", "update_fields", "=", "[", "'availableForPrivates'", ",", "]", ")", "super", "(", "StaffMemberBioChangeForm", ",", "self", ")", ".", "save", "(", "commit", "=", "True", ")" ]
If the staff member is an instructor, also update the availableForPrivates field on the Instructor record.
[ "If", "the", "staff", "member", "is", "an", "instructor", "also", "update", "the", "availableForPrivates", "field", "on", "the", "Instructor", "record", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L942-L947
django-danceschool/django-danceschool
danceschool/core/models.py
DanceRole.save
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)
python
def save(self, *args, **kwargs): if not self.pluralName: self.pluralName = self.name + 's' super(self.__class__, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pluralName", ":", "self", ".", "pluralName", "=", "self", ".", "name", "+", "'s'", "super", "(", "self", ".", "__class__", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Just add "s" if no plural name given.
[ "Just", "add", "s", "if", "no", "plural", "name", "given", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L83-L89
django-danceschool/django-danceschool
danceschool/core/models.py
ClassDescription.lastOfferedMonth
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() return (lastOfferedSeries.year,lastOfferedSeries.month)
python
def lastOfferedMonth(self): lastOfferedSeries = self.event_set.order_by('-startTime').first() return (lastOfferedSeries.year,lastOfferedSeries.month)
[ "def", "lastOfferedMonth", "(", "self", ")", ":", "lastOfferedSeries", "=", "self", ".", "event_set", ".", "order_by", "(", "'-startTime'", ")", ".", "first", "(", ")", "return", "(", "lastOfferedSeries", ".", "year", ",", "lastOfferedSeries", ".", "month", ")" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L317-L324
django-danceschool/django-danceschool
danceschool/core/models.py
PricingTier.getBasePrice
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('payAtDoor', False) dropIns = kwargs.get('dropIns', 0) if dropIns: return dropIns * self.dropinPrice if payAtDoor: return self.doorPrice return self.onlinePrice
python
def getBasePrice(self,**kwargs): payAtDoor = kwargs.get('payAtDoor', False) dropIns = kwargs.get('dropIns', 0) if dropIns: return dropIns * self.dropinPrice if payAtDoor: return self.doorPrice return self.onlinePrice
[ "def", "getBasePrice", "(", "self", ",", "*", "*", "kwargs", ")", ":", "payAtDoor", "=", "kwargs", ".", "get", "(", "'payAtDoor'", ",", "False", ")", "dropIns", "=", "kwargs", ".", "get", "(", "'dropIns'", ",", "0", ")", "if", "dropIns", ":", "return", "dropIns", "*", "self", ".", "dropinPrice", "if", "payAtDoor", ":", "return", "self", ".", "doorPrice", "return", "self", ".", "onlinePrice" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L432-L445
django-danceschool/django-danceschool
danceschool/core/models.py
Event.getMonthName
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.eventoccurrence_set.all()]) multiclass_months = [x[0] for x in class_counter.items() if x[1] > 1] all_months = [x[0] for x in class_counter.items()] if multiclass_months: multiclass_months.sort() return '/'.join([month_name[x[1]] for x in multiclass_months]) else: return month_name[min(all_months)[1]]
python
def getMonthName(self): class_counter = Counter([(x.startTime.year, x.startTime.month) for x in self.eventoccurrence_set.all()]) multiclass_months = [x[0] for x in class_counter.items() if x[1] > 1] all_months = [x[0] for x in class_counter.items()] if multiclass_months: multiclass_months.sort() return '/'.join([month_name[x[1]] for x in multiclass_months]) else: return month_name[min(all_months)[1]]
[ "def", "getMonthName", "(", "self", ")", ":", "class_counter", "=", "Counter", "(", "[", "(", "x", ".", "startTime", ".", "year", ",", "x", ".", "startTime", ".", "month", ")", "for", "x", "in", "self", ".", "eventoccurrence_set", ".", "all", "(", ")", "]", ")", "multiclass_months", "=", "[", "x", "[", "0", "]", "for", "x", "in", "class_counter", ".", "items", "(", ")", "if", "x", "[", "1", "]", ">", "1", "]", "all_months", "=", "[", "x", "[", "0", "]", "for", "x", "in", "class_counter", ".", "items", "(", ")", "]", "if", "multiclass_months", ":", "multiclass_months", ".", "sort", "(", ")", "return", "'/'", ".", "join", "(", "[", "month_name", "[", "x", "[", "1", "]", "]", "for", "x", "in", "multiclass_months", "]", ")", "else", ":", "return", "month_name", "[", "min", "(", "all_months", ")", "[", "1", "]", "]" ]
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).
[ "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", ")", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L622-L636
django-danceschool/django-danceschool
danceschool/core/models.py
Event.name
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 <object>.name can always be used to access a readable name for describing the event. ''' if self.startTime: return _('Event, begins %s' % (self.startTime.strftime('%a., %B %d, %Y, %I:%M %p'))) else: return _('Event #%s' % (self.id))
python
def name(self): if self.startTime: return _('Event, begins %s' % (self.startTime.strftime('%a., %B %d, %Y, %I:%M %p'))) else: return _('Event
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "startTime", ":", "return", "_", "(", "'Event, begins %s'", "%", "(", "self", ".", "startTime", ".", "strftime", "(", "'%a., %B %d, %Y, %I:%M %p'", ")", ")", ")", "else", ":", "return", "_", "(", "'Event #%s'", "%", "(", "self", ".", "id", ")", ")" ]
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 <object>.name can always be used to access a readable name for describing the event.
[ "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", "<object", ">", ".", "name", "can", "always", "be", "used", "to", "access", "a", "readable", "name", "for", "describing", "the", "event", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L640-L651
django-danceschool/django-danceschool
danceschool/core/models.py
Event.organizer
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 nothing to do with the sorting of any queryset in use, which still has to be handled elsewhere. ''' rule = getConstant('registration__orgRule') # Default grouping is "Other", in case session, month, or weekday are not specified. org = { 'name': _('Other'), 'nameFirst': {'name': _('Other'), 'sorter': _('Other')}, 'nameSecond': {'name': '', 'sorter': ''}, 'id': None, } def updateForMonth(self, org): ''' Function to avoid repeated code ''' if self.month: org.update({ 'name': _(month_name[self.month]), 'nameFirst': {'name': _(month_name[self.month]), 'sorter': self.month}, 'id': 'month_%s' % self.month, }) return org def updateForSession(self, org): ''' Function to avoid repeated code ''' if self.session: org.update({ 'name': self.session.name, 'nameFirst': {'name': _(self.session.name), 'sorter': _(self.session.name)}, 'id': self.session.pk, }) return org if rule in ['SessionFirst', 'SessionAlphaFirst']: org = updateForSession(self, org) if not org.get('id'): org = updateForMonth(self, org) elif rule == 'Month': org = updateForMonth(self, org) elif rule in ['Session','SessionAlpha']: org = updateForSession(self, org) elif rule in ['SessionMonth','SessionAlphaMonth']: if self.session and self.month: org.update({ 'name': _('%s: %s' % (month_name[self.month], self.session.name)), 'nameFirst': {'name': _(month_name[self.month]), 'sorter': self.month}, 'nameSecond': {'name': _(self.session.name), 'sorter': _(self.session.name)}, 'id': 'month_%s_session_%s' % (self.month, self.session.pk), }) elif not self.month: org = updateForSession(self, org) elif not self.session: org = updateForMonth(self, org) elif rule == 'Weekday': w = self.weekday d = day_name[w] if w is not None: org.update({ 'name': _(d), 'nameFirst': {'name': _(d), 'sorter': w}, 'id': w, }) elif rule == 'MonthWeekday': w = self.weekday d = day_name[w] m = self.month mn = month_name[m] if w is not None and m: org.update({ 'name': _('%ss in %s' % (d, mn)), 'nameFirst': {'name': _(mn), 'sorter': m}, 'nameSecond': {'name': _('%ss' % d), 'sorter': w}, 'id': 'month_%s_weekday_%s' % (m, w) }) return org
python
def organizer(self): rule = getConstant('registration__orgRule') org = { 'name': _('Other'), 'nameFirst': {'name': _('Other'), 'sorter': _('Other')}, 'nameSecond': {'name': '', 'sorter': ''}, 'id': None, } def updateForMonth(self, org): if self.month: org.update({ 'name': _(month_name[self.month]), 'nameFirst': {'name': _(month_name[self.month]), 'sorter': self.month}, 'id': 'month_%s' % self.month, }) return org def updateForSession(self, org): if self.session: org.update({ 'name': self.session.name, 'nameFirst': {'name': _(self.session.name), 'sorter': _(self.session.name)}, 'id': self.session.pk, }) return org if rule in ['SessionFirst', 'SessionAlphaFirst']: org = updateForSession(self, org) if not org.get('id'): org = updateForMonth(self, org) elif rule == 'Month': org = updateForMonth(self, org) elif rule in ['Session','SessionAlpha']: org = updateForSession(self, org) elif rule in ['SessionMonth','SessionAlphaMonth']: if self.session and self.month: org.update({ 'name': _('%s: %s' % (month_name[self.month], self.session.name)), 'nameFirst': {'name': _(month_name[self.month]), 'sorter': self.month}, 'nameSecond': {'name': _(self.session.name), 'sorter': _(self.session.name)}, 'id': 'month_%s_session_%s' % (self.month, self.session.pk), }) elif not self.month: org = updateForSession(self, org) elif not self.session: org = updateForMonth(self, org) elif rule == 'Weekday': w = self.weekday d = day_name[w] if w is not None: org.update({ 'name': _(d), 'nameFirst': {'name': _(d), 'sorter': w}, 'id': w, }) elif rule == 'MonthWeekday': w = self.weekday d = day_name[w] m = self.month mn = month_name[m] if w is not None and m: org.update({ 'name': _('%ss in %s' % (d, mn)), 'nameFirst': {'name': _(mn), 'sorter': m}, 'nameSecond': {'name': _('%ss' % d), 'sorter': w}, 'id': 'month_%s_weekday_%s' % (m, w) }) return org
[ "def", "organizer", "(", "self", ")", ":", "rule", "=", "getConstant", "(", "'registration__orgRule'", ")", "# Default grouping is \"Other\", in case session, month, or weekday are not specified.", "org", "=", "{", "'name'", ":", "_", "(", "'Other'", ")", ",", "'nameFirst'", ":", "{", "'name'", ":", "_", "(", "'Other'", ")", ",", "'sorter'", ":", "_", "(", "'Other'", ")", "}", ",", "'nameSecond'", ":", "{", "'name'", ":", "''", ",", "'sorter'", ":", "''", "}", ",", "'id'", ":", "None", ",", "}", "def", "updateForMonth", "(", "self", ",", "org", ")", ":", "''' Function to avoid repeated code '''", "if", "self", ".", "month", ":", "org", ".", "update", "(", "{", "'name'", ":", "_", "(", "month_name", "[", "self", ".", "month", "]", ")", ",", "'nameFirst'", ":", "{", "'name'", ":", "_", "(", "month_name", "[", "self", ".", "month", "]", ")", ",", "'sorter'", ":", "self", ".", "month", "}", ",", "'id'", ":", "'month_%s'", "%", "self", ".", "month", ",", "}", ")", "return", "org", "def", "updateForSession", "(", "self", ",", "org", ")", ":", "''' Function to avoid repeated code '''", "if", "self", ".", "session", ":", "org", ".", "update", "(", "{", "'name'", ":", "self", ".", "session", ".", "name", ",", "'nameFirst'", ":", "{", "'name'", ":", "_", "(", "self", ".", "session", ".", "name", ")", ",", "'sorter'", ":", "_", "(", "self", ".", "session", ".", "name", ")", "}", ",", "'id'", ":", "self", ".", "session", ".", "pk", ",", "}", ")", "return", "org", "if", "rule", "in", "[", "'SessionFirst'", ",", "'SessionAlphaFirst'", "]", ":", "org", "=", "updateForSession", "(", "self", ",", "org", ")", "if", "not", "org", ".", "get", "(", "'id'", ")", ":", "org", "=", "updateForMonth", "(", "self", ",", "org", ")", "elif", "rule", "==", "'Month'", ":", "org", "=", "updateForMonth", "(", "self", ",", "org", ")", "elif", "rule", "in", "[", "'Session'", ",", "'SessionAlpha'", "]", ":", "org", "=", "updateForSession", "(", "self", ",", "org", ")", "elif", "rule", "in", "[", "'SessionMonth'", ",", "'SessionAlphaMonth'", "]", ":", "if", "self", ".", "session", "and", "self", ".", "month", ":", "org", ".", "update", "(", "{", "'name'", ":", "_", "(", "'%s: %s'", "%", "(", "month_name", "[", "self", ".", "month", "]", ",", "self", ".", "session", ".", "name", ")", ")", ",", "'nameFirst'", ":", "{", "'name'", ":", "_", "(", "month_name", "[", "self", ".", "month", "]", ")", ",", "'sorter'", ":", "self", ".", "month", "}", ",", "'nameSecond'", ":", "{", "'name'", ":", "_", "(", "self", ".", "session", ".", "name", ")", ",", "'sorter'", ":", "_", "(", "self", ".", "session", ".", "name", ")", "}", ",", "'id'", ":", "'month_%s_session_%s'", "%", "(", "self", ".", "month", ",", "self", ".", "session", ".", "pk", ")", ",", "}", ")", "elif", "not", "self", ".", "month", ":", "org", "=", "updateForSession", "(", "self", ",", "org", ")", "elif", "not", "self", ".", "session", ":", "org", "=", "updateForMonth", "(", "self", ",", "org", ")", "elif", "rule", "==", "'Weekday'", ":", "w", "=", "self", ".", "weekday", "d", "=", "day_name", "[", "w", "]", "if", "w", "is", "not", "None", ":", "org", ".", "update", "(", "{", "'name'", ":", "_", "(", "d", ")", ",", "'nameFirst'", ":", "{", "'name'", ":", "_", "(", "d", ")", ",", "'sorter'", ":", "w", "}", ",", "'id'", ":", "w", ",", "}", ")", "elif", "rule", "==", "'MonthWeekday'", ":", "w", "=", "self", ".", "weekday", "d", "=", "day_name", "[", "w", "]", "m", "=", "self", ".", "month", "mn", "=", "month_name", "[", "m", "]", "if", "w", "is", "not", "None", "and", "m", ":", "org", ".", "update", "(", "{", "'name'", ":", "_", "(", "'%ss in %s'", "%", "(", "d", ",", "mn", ")", ")", ",", "'nameFirst'", ":", "{", "'name'", ":", "_", "(", "mn", ")", ",", "'sorter'", ":", "m", "}", ",", "'nameSecond'", ":", "{", "'name'", ":", "_", "(", "'%ss'", "%", "d", ")", ",", "'sorter'", ":", "w", "}", ",", "'id'", ":", "'month_%s_weekday_%s'", "%", "(", "m", ",", "w", ")", "}", ")", "return", "org" ]
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 nothing to do with the sorting of any queryset in use, which still has to be handled elsewhere.
[ "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", "nothing", "to", "do", "with", "the", "sorting", "of", "any", "queryset", "in", "use", "which", "still", "has", "to", "be", "handled", "elsewhere", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L679-L758
django-danceschool/django-danceschool
danceschool/core/models.py
Event.get_default_recipients
def get_default_recipients(self): ''' Overrides EmailRecipientMixin ''' return [x.registration.customer.email for x in self.eventregistration_set.filter(cancelled=False)]
python
def get_default_recipients(self): return [x.registration.customer.email for x in self.eventregistration_set.filter(cancelled=False)]
[ "def", "get_default_recipients", "(", "self", ")", ":", "return", "[", "x", ".", "registration", ".", "customer", ".", "email", "for", "x", "in", "self", ".", "eventregistration_set", ".", "filter", "(", "cancelled", "=", "False", ")", "]" ]
Overrides EmailRecipientMixin
[ "Overrides", "EmailRecipientMixin" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L776-L778
django-danceschool/django-danceschool
danceschool/core/models.py
Event.get_email_context
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, 'next': self.nextOccurrenceTime, 'last': self.lastOccurrenceTime, 'url': self.url, }) return context
python
def get_email_context(self,**kwargs): context = super(Event,self).get_email_context(**kwargs) context.update({ 'id': self.id, 'name': self.__str__(), 'title': self.name, 'start': self.firstOccurrenceTime, 'next': self.nextOccurrenceTime, 'last': self.lastOccurrenceTime, 'url': self.url, }) return context
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "Event", ",", "self", ")", ".", "get_email_context", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'id'", ":", "self", ".", "id", ",", "'name'", ":", "self", ".", "__str__", "(", ")", ",", "'title'", ":", "self", ".", "name", ",", "'start'", ":", "self", ".", "firstOccurrenceTime", ",", "'next'", ":", "self", ".", "nextOccurrenceTime", ",", "'last'", ":", "self", ".", "lastOccurrenceTime", ",", "'url'", ":", "self", ".", "url", ",", "}", ")", "return", "context" ]
Overrides EmailRecipientMixin
[ "Overrides", "EmailRecipientMixin" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L780-L792
django-danceschool/django-danceschool
danceschool/core/models.py
Event.registrationEnabled
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]
python
def registrationEnabled(self): return self.status in [self.RegStatus.enabled,self.RegStatus.heldOpen,self.RegStatus.heldClosed]
[ "def", "registrationEnabled", "(", "self", ")", ":", "return", "self", ".", "status", "in", "[", "self", ".", "RegStatus", ".", "enabled", ",", "self", ".", "RegStatus", ".", "heldOpen", ",", "self", ".", "RegStatus", ".", "heldClosed", "]" ]
Just checks if this event ever permits/permitted registration
[ "Just", "checks", "if", "this", "event", "ever", "permits", "/", "permitted", "registration" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L911-L913
django-danceschool/django-danceschool
danceschool/core/models.py
Event.getNumRegistered
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 started tp register later than the person in question. ''' count = self.eventregistration_set.filter(cancelled=False,dropIn=False).count() if includeTemporaryRegs: excludes = Q(registration__expirationDate__lte=timezone.now()) if isinstance(dateTime,datetime): excludes = exclude | Q(registration__dateTime__gte=dateTime) count += self.temporaryeventregistration_set.filter(dropIn=False).exclude(excludes).count() return count
python
def getNumRegistered(self, includeTemporaryRegs=False, dateTime=None): count = self.eventregistration_set.filter(cancelled=False,dropIn=False).count() if includeTemporaryRegs: excludes = Q(registration__expirationDate__lte=timezone.now()) if isinstance(dateTime,datetime): excludes = exclude | Q(registration__dateTime__gte=dateTime) count += self.temporaryeventregistration_set.filter(dropIn=False).exclude(excludes).count() return count
[ "def", "getNumRegistered", "(", "self", ",", "includeTemporaryRegs", "=", "False", ",", "dateTime", "=", "None", ")", ":", "count", "=", "self", ".", "eventregistration_set", ".", "filter", "(", "cancelled", "=", "False", ",", "dropIn", "=", "False", ")", ".", "count", "(", ")", "if", "includeTemporaryRegs", ":", "excludes", "=", "Q", "(", "registration__expirationDate__lte", "=", "timezone", ".", "now", "(", ")", ")", "if", "isinstance", "(", "dateTime", ",", "datetime", ")", ":", "excludes", "=", "exclude", "|", "Q", "(", "registration__dateTime__gte", "=", "dateTime", ")", "count", "+=", "self", ".", "temporaryeventregistration_set", ".", "filter", "(", "dropIn", "=", "False", ")", ".", "exclude", "(", "excludes", ")", ".", "count", "(", ")", "return", "count" ]
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 started tp register later than the person in question.
[ "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", "started", "tp", "register", "later", "than", "the", "person", "in", "question", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L930-L944
django-danceschool/django-danceschool
danceschool/core/models.py
Event.availableRoles
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 the event's registration is not role-specific. ''' eventRoles = self.eventrole_set.filter(capacity__gt=0) if eventRoles.count() > 0: return [x.role for x in eventRoles] elif isinstance(self,Series): return self.classDescription.danceTypeLevel.danceType.roles.all() return []
python
def availableRoles(self): eventRoles = self.eventrole_set.filter(capacity__gt=0) if eventRoles.count() > 0: return [x.role for x in eventRoles] elif isinstance(self,Series): return self.classDescription.danceTypeLevel.danceType.roles.all() return []
[ "def", "availableRoles", "(", "self", ")", ":", "eventRoles", "=", "self", ".", "eventrole_set", ".", "filter", "(", "capacity__gt", "=", "0", ")", "if", "eventRoles", ".", "count", "(", ")", ">", "0", ":", "return", "[", "x", ".", "role", "for", "x", "in", "eventRoles", "]", "elif", "isinstance", "(", "self", ",", "Series", ")", ":", "return", "self", ".", "classDescription", ".", "danceTypeLevel", ".", "danceType", ".", "roles", ".", "all", "(", ")", "return", "[", "]" ]
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 the event's registration is not role-specific.
[ "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", "the", "event", "s", "registration", "is", "not", "role", "-", "specific", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L952-L964
django-danceschool/django-danceschool
danceschool/core/models.py
Event.numRegisteredForRole
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: count += self.temporaryeventregistration_set.filter(dropIn=False,role=role).exclude( registration__expirationDate__lte=timezone.now()).count() return count
python
def numRegisteredForRole(self, role, includeTemporaryRegs=False): count = self.eventregistration_set.filter(cancelled=False,dropIn=False,role=role).count() if includeTemporaryRegs: count += self.temporaryeventregistration_set.filter(dropIn=False,role=role).exclude( registration__expirationDate__lte=timezone.now()).count() return count
[ "def", "numRegisteredForRole", "(", "self", ",", "role", ",", "includeTemporaryRegs", "=", "False", ")", ":", "count", "=", "self", ".", "eventregistration_set", ".", "filter", "(", "cancelled", "=", "False", ",", "dropIn", "=", "False", ",", "role", "=", "role", ")", ".", "count", "(", ")", "if", "includeTemporaryRegs", ":", "count", "+=", "self", ".", "temporaryeventregistration_set", ".", "filter", "(", "dropIn", "=", "False", ",", "role", "=", "role", ")", ".", "exclude", "(", "registration__expirationDate__lte", "=", "timezone", ".", "now", "(", ")", ")", ".", "count", "(", ")", "return", "count" ]
Accepts a DanceRole object and returns the number of registrations of that role.
[ "Accepts", "a", "DanceRole", "object", "and", "returns", "the", "number", "of", "registrations", "of", "that", "role", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L967-L975
django-danceschool/django-danceschool
danceschool/core/models.py
Event.numRegisteredByRole
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}
python
def numRegisteredByRole(self): role_list = list(self.availableRoles) + [None,] return {getattr(x,'name',None):self.numRegisteredForRole(x) for x in role_list}
[ "def", "numRegisteredByRole", "(", "self", ")", ":", "role_list", "=", "list", "(", "self", ".", "availableRoles", ")", "+", "[", "None", ",", "]", "return", "{", "getattr", "(", "x", ",", "'name'", ",", "None", ")", ":", "self", ".", "numRegisteredForRole", "(", "x", ")", "for", "x", "in", "role_list", "}" ]
Return a dictionary listing registrations by all available roles (including no role)
[ "Return", "a", "dictionary", "listing", "registrations", "by", "all", "available", "roles", "(", "including", "no", "role", ")" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L978-L983
django-danceschool/django-danceschool
danceschool/core/models.py
Event.capacityForRole
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 event if roles are not found elsewhere. ''' if isinstance(role, DanceRole): role_id = role.id else: role_id = role eventRoles = self.eventrole_set.filter(capacity__gt=0) if eventRoles.count() > 0 and role_id not in [x.role.id for x in eventRoles]: ''' Custom role capacities exist but role this is not one of them. ''' return 0 elif eventRoles.count() > 0: ''' The role is a match to custom roles, so check the capacity. ''' return eventRoles.get(role=role).capacity # No custom roles for this event, so get the danceType roles and use the overall # capacity divided by the number of roles if isinstance(self,Series): try: availableRoles = self.classDescription.danceTypeLevel.danceType.roles.all() if availableRoles.count() > 0 and role_id not in [x.id for x in availableRoles]: ''' DanceType roles specified and this is not one of them ''' return 0 elif availableRoles.count() > 0 and self.capacity: # Divide the total capacity by the number of roles and round up. return ceil(self.capacity / availableRoles.count()) except ObjectDoesNotExist as e: logger.error('Error in calculating capacity for role: %s' % e) # No custom roles and no danceType to get roles from, so return the overall capacity return self.capacity
python
def capacityForRole(self,role): if isinstance(role, DanceRole): role_id = role.id else: role_id = role eventRoles = self.eventrole_set.filter(capacity__gt=0) if eventRoles.count() > 0 and role_id not in [x.role.id for x in eventRoles]: return 0 elif eventRoles.count() > 0: return eventRoles.get(role=role).capacity if isinstance(self,Series): try: availableRoles = self.classDescription.danceTypeLevel.danceType.roles.all() if availableRoles.count() > 0 and role_id not in [x.id for x in availableRoles]: return 0 elif availableRoles.count() > 0 and self.capacity: return ceil(self.capacity / availableRoles.count()) except ObjectDoesNotExist as e: logger.error('Error in calculating capacity for role: %s' % e) return self.capacity
[ "def", "capacityForRole", "(", "self", ",", "role", ")", ":", "if", "isinstance", "(", "role", ",", "DanceRole", ")", ":", "role_id", "=", "role", ".", "id", "else", ":", "role_id", "=", "role", "eventRoles", "=", "self", ".", "eventrole_set", ".", "filter", "(", "capacity__gt", "=", "0", ")", "if", "eventRoles", ".", "count", "(", ")", ">", "0", "and", "role_id", "not", "in", "[", "x", ".", "role", ".", "id", "for", "x", "in", "eventRoles", "]", ":", "''' Custom role capacities exist but role this is not one of them. '''", "return", "0", "elif", "eventRoles", ".", "count", "(", ")", ">", "0", ":", "''' The role is a match to custom roles, so check the capacity. '''", "return", "eventRoles", ".", "get", "(", "role", "=", "role", ")", ".", "capacity", "# No custom roles for this event, so get the danceType roles and use the overall", "# capacity divided by the number of roles", "if", "isinstance", "(", "self", ",", "Series", ")", ":", "try", ":", "availableRoles", "=", "self", ".", "classDescription", ".", "danceTypeLevel", ".", "danceType", ".", "roles", ".", "all", "(", ")", "if", "availableRoles", ".", "count", "(", ")", ">", "0", "and", "role_id", "not", "in", "[", "x", ".", "id", "for", "x", "in", "availableRoles", "]", ":", "''' DanceType roles specified and this is not one of them '''", "return", "0", "elif", "availableRoles", ".", "count", "(", ")", ">", "0", "and", "self", ".", "capacity", ":", "# Divide the total capacity by the number of roles and round up.", "return", "ceil", "(", "self", ".", "capacity", "/", "availableRoles", ".", "count", "(", ")", ")", "except", "ObjectDoesNotExist", "as", "e", ":", "logger", ".", "error", "(", "'Error in calculating capacity for role: %s'", "%", "e", ")", "# No custom roles and no danceType to get roles from, so return the overall capacity", "return", "self", ".", "capacity" ]
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 event if roles are not found elsewhere.
[ "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", "event", "if", "roles", "are", "not", "found", "elsewhere", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L986-L1022
django-danceschool/django-danceschool
danceschool/core/models.py
Event.soldOutForRole
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=includeTemporaryRegs) >= (self.capacityForRole(role) or 0)
python
def soldOutForRole(self,role,includeTemporaryRegs=False): return self.numRegisteredForRole( role,includeTemporaryRegs=includeTemporaryRegs) >= (self.capacityForRole(role) or 0)
[ "def", "soldOutForRole", "(", "self", ",", "role", ",", "includeTemporaryRegs", "=", "False", ")", ":", "return", "self", ".", "numRegisteredForRole", "(", "role", ",", "includeTemporaryRegs", "=", "includeTemporaryRegs", ")", ">=", "(", "self", ".", "capacityForRole", "(", "role", ")", "or", "0", ")" ]
Accepts a DanceRole object and responds if the number of registrations for that role exceeds the capacity for that role at this event.
[ "Accepts", "a", "DanceRole", "object", "and", "responds", "if", "the", "number", "of", "registrations", "for", "that", "role", "exceeds", "the", "capacity", "for", "that", "role", "at", "this", "event", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1024-L1030
django-danceschool/django-danceschool
danceschool/core/models.py
Event.updateRegistrationStatus
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('Beginning update registration status. saveMethod=%s' % saveMethod) modified = False open = self.registrationOpen startTime = self.startTime or getattr(self.eventoccurrence_set.order_by('startTime').first(),'startTime',None) endTime = self.endTime or getattr(self.eventoccurrence_set.order_by('-endTime').first(),'endTime',None) # If set to these codes, then registration will be held closed force_closed_codes = [ self.RegStatus.disabled, self.RegStatus.heldClosed, self.RegStatus.regHidden, self.RegStatus.hidden ] # If set to these codes, then registration will be held open force_open_codes = [ self.RegStatus.heldOpen, ] # If set to these codes, then registration will be open or closed # automatically depending on the value of closeAfterDays automatic_codes = [ self.RegStatus.enabled, self.RegStatus.linkOnly, ] if (self.status in force_closed_codes or not self.pricingTier) and open is True: open = False modified = True elif not self.pricingTier: open = False modified = False elif (self.status in force_open_codes and self.pricingTier) and open is False: open = True modified = True elif ( startTime and self.status in automatic_codes and (( self.closeAfterDays and timezone.now() > startTime + timedelta(days=self.closeAfterDays)) or timezone.now() > endTime) and open is True): open = False modified = True elif startTime and self.status in automatic_codes and (( timezone.now() < endTime and not self.closeAfterDays) or ( self.closeAfterDays and timezone.now() < startTime + timedelta(days=self.closeAfterDays))) and open is False: open = True modified = True # Save if something has changed, otherwise, do nothing if modified and not saveMethod: logger.debug('Attempting to save Series object with status: %s' % open) self.registrationOpen = open self.save(fromUpdateRegistrationStatus=True) logger.debug('Returning value: %s' % open) return (modified, open)
python
def updateRegistrationStatus(self, saveMethod=False): logger.debug('Beginning update registration status. saveMethod=%s' % saveMethod) modified = False open = self.registrationOpen startTime = self.startTime or getattr(self.eventoccurrence_set.order_by('startTime').first(),'startTime',None) endTime = self.endTime or getattr(self.eventoccurrence_set.order_by('-endTime').first(),'endTime',None) force_closed_codes = [ self.RegStatus.disabled, self.RegStatus.heldClosed, self.RegStatus.regHidden, self.RegStatus.hidden ] force_open_codes = [ self.RegStatus.heldOpen, ] automatic_codes = [ self.RegStatus.enabled, self.RegStatus.linkOnly, ] if (self.status in force_closed_codes or not self.pricingTier) and open is True: open = False modified = True elif not self.pricingTier: open = False modified = False elif (self.status in force_open_codes and self.pricingTier) and open is False: open = True modified = True elif ( startTime and self.status in automatic_codes and (( self.closeAfterDays and timezone.now() > startTime + timedelta(days=self.closeAfterDays)) or timezone.now() > endTime) and open is True): open = False modified = True elif startTime and self.status in automatic_codes and (( timezone.now() < endTime and not self.closeAfterDays) or ( self.closeAfterDays and timezone.now() < startTime + timedelta(days=self.closeAfterDays))) and open is False: open = True modified = True if modified and not saveMethod: logger.debug('Attempting to save Series object with status: %s' % open) self.registrationOpen = open self.save(fromUpdateRegistrationStatus=True) logger.debug('Returning value: %s' % open) return (modified, open)
[ "def", "updateRegistrationStatus", "(", "self", ",", "saveMethod", "=", "False", ")", ":", "logger", ".", "debug", "(", "'Beginning update registration status. saveMethod=%s'", "%", "saveMethod", ")", "modified", "=", "False", "open", "=", "self", ".", "registrationOpen", "startTime", "=", "self", ".", "startTime", "or", "getattr", "(", "self", ".", "eventoccurrence_set", ".", "order_by", "(", "'startTime'", ")", ".", "first", "(", ")", ",", "'startTime'", ",", "None", ")", "endTime", "=", "self", ".", "endTime", "or", "getattr", "(", "self", ".", "eventoccurrence_set", ".", "order_by", "(", "'-endTime'", ")", ".", "first", "(", ")", ",", "'endTime'", ",", "None", ")", "# If set to these codes, then registration will be held closed", "force_closed_codes", "=", "[", "self", ".", "RegStatus", ".", "disabled", ",", "self", ".", "RegStatus", ".", "heldClosed", ",", "self", ".", "RegStatus", ".", "regHidden", ",", "self", ".", "RegStatus", ".", "hidden", "]", "# If set to these codes, then registration will be held open", "force_open_codes", "=", "[", "self", ".", "RegStatus", ".", "heldOpen", ",", "]", "# If set to these codes, then registration will be open or closed", "# automatically depending on the value of closeAfterDays", "automatic_codes", "=", "[", "self", ".", "RegStatus", ".", "enabled", ",", "self", ".", "RegStatus", ".", "linkOnly", ",", "]", "if", "(", "self", ".", "status", "in", "force_closed_codes", "or", "not", "self", ".", "pricingTier", ")", "and", "open", "is", "True", ":", "open", "=", "False", "modified", "=", "True", "elif", "not", "self", ".", "pricingTier", ":", "open", "=", "False", "modified", "=", "False", "elif", "(", "self", ".", "status", "in", "force_open_codes", "and", "self", ".", "pricingTier", ")", "and", "open", "is", "False", ":", "open", "=", "True", "modified", "=", "True", "elif", "(", "startTime", "and", "self", ".", "status", "in", "automatic_codes", "and", "(", "(", "self", ".", "closeAfterDays", "and", "timezone", ".", "now", "(", ")", ">", "startTime", "+", "timedelta", "(", "days", "=", "self", ".", "closeAfterDays", ")", ")", "or", "timezone", ".", "now", "(", ")", ">", "endTime", ")", "and", "open", "is", "True", ")", ":", "open", "=", "False", "modified", "=", "True", "elif", "startTime", "and", "self", ".", "status", "in", "automatic_codes", "and", "(", "(", "timezone", ".", "now", "(", ")", "<", "endTime", "and", "not", "self", ".", "closeAfterDays", ")", "or", "(", "self", ".", "closeAfterDays", "and", "timezone", ".", "now", "(", ")", "<", "startTime", "+", "timedelta", "(", "days", "=", "self", ".", "closeAfterDays", ")", ")", ")", "and", "open", "is", "False", ":", "open", "=", "True", "modified", "=", "True", "# Save if something has changed, otherwise, do nothing", "if", "modified", "and", "not", "saveMethod", ":", "logger", ".", "debug", "(", "'Attempting to save Series object with status: %s'", "%", "open", ")", "self", ".", "registrationOpen", "=", "open", "self", ".", "save", "(", "fromUpdateRegistrationStatus", "=", "True", ")", "logger", ".", "debug", "(", "'Returning value: %s'", "%", "open", ")", "return", "(", "modified", ",", "open", ")" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1051-L1111
django-danceschool/django-danceschool
danceschool/core/models.py
EventOccurrence.allDayForDate
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 account for issues with the way events are sometimes entered. ''' if isinstance(this_date,datetime): d = this_date.date() else: d = this_date date_start = datetime(d.year,d.month,d.day) naive_start = self.startTime if timezone.is_naive(self.startTime) else timezone.make_naive(self.startTime, timezone=timeZone) naive_end = self.endTime if timezone.is_naive(self.endTime) else timezone.make_naive(self.endTime, timezone=timeZone) return ( # Ensure that all comparisons are done in local time naive_start <= date_start and naive_end >= date_start + timedelta(days=1,minutes=-30) )
python
def allDayForDate(self,this_date,timeZone=None): if isinstance(this_date,datetime): d = this_date.date() else: d = this_date date_start = datetime(d.year,d.month,d.day) naive_start = self.startTime if timezone.is_naive(self.startTime) else timezone.make_naive(self.startTime, timezone=timeZone) naive_end = self.endTime if timezone.is_naive(self.endTime) else timezone.make_naive(self.endTime, timezone=timeZone) return ( naive_start <= date_start and naive_end >= date_start + timedelta(days=1,minutes=-30) )
[ "def", "allDayForDate", "(", "self", ",", "this_date", ",", "timeZone", "=", "None", ")", ":", "if", "isinstance", "(", "this_date", ",", "datetime", ")", ":", "d", "=", "this_date", ".", "date", "(", ")", "else", ":", "d", "=", "this_date", "date_start", "=", "datetime", "(", "d", ".", "year", ",", "d", ".", "month", ",", "d", ".", "day", ")", "naive_start", "=", "self", ".", "startTime", "if", "timezone", ".", "is_naive", "(", "self", ".", "startTime", ")", "else", "timezone", ".", "make_naive", "(", "self", ".", "startTime", ",", "timezone", "=", "timeZone", ")", "naive_end", "=", "self", ".", "endTime", "if", "timezone", ".", "is_naive", "(", "self", ".", "endTime", ")", "else", "timezone", ".", "make_naive", "(", "self", ".", "endTime", ",", "timezone", "=", "timeZone", ")", "return", "(", "# Ensure that all comparisons are done in local time", "naive_start", "<=", "date_start", "and", "naive_end", ">=", "date_start", "+", "timedelta", "(", "days", "=", "1", ",", "minutes", "=", "-", "30", ")", ")" ]
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 account for issues with the way events are sometimes entered.
[ "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", "account", "for", "issues", "with", "the", "way", "events", "are", "sometimes", "entered", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1191-L1211
django-danceschool/django-danceschool
danceschool/core/models.py
EventStaffMember.netHours
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 [getConstant('general__eventStaffCategoryAssistant'),getConstant('general__eventStaffCategoryInstructor')]: return self.event.duration - sum([sub.netHours for sub in self.replacementFor.all()]) else: return sum([x.duration for x in self.occurrences.filter(cancelled=False)])
python
def netHours(self): if self.specifiedHours is not None: return self.specifiedHours elif self.category in [getConstant('general__eventStaffCategoryAssistant'),getConstant('general__eventStaffCategoryInstructor')]: return self.event.duration - sum([sub.netHours for sub in self.replacementFor.all()]) else: return sum([x.duration for x in self.occurrences.filter(cancelled=False)])
[ "def", "netHours", "(", "self", ")", ":", "if", "self", ".", "specifiedHours", "is", "not", "None", ":", "return", "self", ".", "specifiedHours", "elif", "self", ".", "category", "in", "[", "getConstant", "(", "'general__eventStaffCategoryAssistant'", ")", ",", "getConstant", "(", "'general__eventStaffCategoryInstructor'", ")", "]", ":", "return", "self", ".", "event", ".", "duration", "-", "sum", "(", "[", "sub", ".", "netHours", "for", "sub", "in", "self", ".", "replacementFor", ".", "all", "(", ")", "]", ")", "else", ":", "return", "sum", "(", "[", "x", ".", "duration", "for", "x", "in", "self", ".", "occurrences", ".", "filter", "(", "cancelled", "=", "False", ")", "]", ")" ]
For regular event staff, this is the net hours worked for financial purposes. For Instructors, netHours is caclulated net of any substitutes.
[ "For", "regular", "event", "staff", "this", "is", "the", "net", "hours", "worked", "for", "financial", "purposes", ".", "For", "Instructors", "netHours", "is", "caclulated", "net", "of", "any", "substitutes", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1284-L1294
django-danceschool/django-danceschool
danceschool/core/models.py
Series.shortDescription
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 ''
python
def shortDescription(self): cd = getattr(self,'classDescription',None) if cd: sd = getattr(cd,'shortDescription','') d = getattr(cd,'description','') return sd if sd else d return ''
[ "def", "shortDescription", "(", "self", ")", ":", "cd", "=", "getattr", "(", "self", ",", "'classDescription'", ",", "None", ")", "if", "cd", ":", "sd", "=", "getattr", "(", "cd", ",", "'shortDescription'", ",", "''", ")", "d", "=", "getattr", "(", "cd", ",", "'description'", ",", "''", ")", "return", "sd", "if", "sd", "else", "d", "return", "''" ]
Overrides property from Event base class.
[ "Overrides", "property", "from", "Event", "base", "class", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1360-L1369
django-danceschool/django-danceschool
danceschool/core/models.py
SeriesTeacher.netHours
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 - sum([sub.netHours for sub in self.replacementFor.all()])
python
def netHours(self): if self.specifiedHours is not None: return self.specifiedHours return self.event.duration - sum([sub.netHours for sub in self.replacementFor.all()])
[ "def", "netHours", "(", "self", ")", ":", "if", "self", ".", "specifiedHours", "is", "not", "None", ":", "return", "self", ".", "specifiedHours", "return", "self", ".", "event", ".", "duration", "-", "sum", "(", "[", "sub", ".", "netHours", "for", "sub", "in", "self", ".", "replacementFor", ".", "all", "(", ")", "]", ")" ]
For regular event staff, this is the net hours worked for financial purposes. For Instructors, netHours is calculated net of any substitutes.
[ "For", "regular", "event", "staff", "this", "is", "the", "net", "hours", "worked", "for", "financial", "purposes", ".", "For", "Instructors", "netHours", "is", "calculated", "net", "of", "any", "substitutes", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1466-L1473
django-danceschool/django-danceschool
danceschool/core/models.py
Customer.getSeriesRegistered
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. year and month). ''' series_set = Series.objects.filter(q_filter,eventregistration__registration__customer=self,**kwargs) if not distinct: return series_set elif distinct and not counter: return series_set.distinct() elif 'year' in kwargs or 'month' in kwargs: return [str(x[1]) + 'x: ' + x[0].classDescription.title for x in Counter(series_set).items()] else: return [str(x[1]) + 'x: ' + x[0].__str__() for x in Counter(series_set).items()]
python
def getSeriesRegistered(self,q_filter=Q(),distinct=True,counter=False,**kwargs): series_set = Series.objects.filter(q_filter,eventregistration__registration__customer=self,**kwargs) if not distinct: return series_set elif distinct and not counter: return series_set.distinct() elif 'year' in kwargs or 'month' in kwargs: return [str(x[1]) + 'x: ' + x[0].classDescription.title for x in Counter(series_set).items()] else: return [str(x[1]) + 'x: ' + x[0].__str__() for x in Counter(series_set).items()]
[ "def", "getSeriesRegistered", "(", "self", ",", "q_filter", "=", "Q", "(", ")", ",", "distinct", "=", "True", ",", "counter", "=", "False", ",", "*", "*", "kwargs", ")", ":", "series_set", "=", "Series", ".", "objects", ".", "filter", "(", "q_filter", ",", "eventregistration__registration__customer", "=", "self", ",", "*", "*", "kwargs", ")", "if", "not", "distinct", ":", "return", "series_set", "elif", "distinct", "and", "not", "counter", ":", "return", "series_set", ".", "distinct", "(", ")", "elif", "'year'", "in", "kwargs", "or", "'month'", "in", "kwargs", ":", "return", "[", "str", "(", "x", "[", "1", "]", ")", "+", "'x: '", "+", "x", "[", "0", "]", ".", "classDescription", ".", "title", "for", "x", "in", "Counter", "(", "series_set", ")", ".", "items", "(", ")", "]", "else", ":", "return", "[", "str", "(", "x", "[", "1", "]", ")", "+", "'x: '", "+", "x", "[", "0", "]", ".", "__str__", "(", ")", "for", "x", "in", "Counter", "(", "series_set", ")", ".", "items", "(", ")", "]" ]
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. year and month).
[ "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", ".", "year", "and", "month", ")", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1787-L1802
django-danceschool/django-danceschool
danceschool/core/models.py
Customer.getMultiSeriesRegistrations
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 keeping track of dance admissions for couples who register under one name). ''' series_registered = self.getSeriesRegistered(q_filter,distinct=False,counter=False,**kwargs) counter_items = Counter(series_registered).items() multireg_list = [x for x in counter_items if x[1] > 1] if name_series and multireg_list: if 'year' in kwargs or 'month' in kwargs: return [str(x[1]) + 'x: ' + x[0].classDescription.title for x in multireg_list] else: return [str(x[1]) + 'x: ' + x[0].__str__() for x in multireg_list] elif multireg_list: return '%sx registration' % max([x[1] for x in multireg_list])
python
def getMultiSeriesRegistrations(self,q_filter=Q(),name_series=False,**kwargs): series_registered = self.getSeriesRegistered(q_filter,distinct=False,counter=False,**kwargs) counter_items = Counter(series_registered).items() multireg_list = [x for x in counter_items if x[1] > 1] if name_series and multireg_list: if 'year' in kwargs or 'month' in kwargs: return [str(x[1]) + 'x: ' + x[0].classDescription.title for x in multireg_list] else: return [str(x[1]) + 'x: ' + x[0].__str__() for x in multireg_list] elif multireg_list: return '%sx registration' % max([x[1] for x in multireg_list])
[ "def", "getMultiSeriesRegistrations", "(", "self", ",", "q_filter", "=", "Q", "(", ")", ",", "name_series", "=", "False", ",", "*", "*", "kwargs", ")", ":", "series_registered", "=", "self", ".", "getSeriesRegistered", "(", "q_filter", ",", "distinct", "=", "False", ",", "counter", "=", "False", ",", "*", "*", "kwargs", ")", "counter_items", "=", "Counter", "(", "series_registered", ")", ".", "items", "(", ")", "multireg_list", "=", "[", "x", "for", "x", "in", "counter_items", "if", "x", "[", "1", "]", ">", "1", "]", "if", "name_series", "and", "multireg_list", ":", "if", "'year'", "in", "kwargs", "or", "'month'", "in", "kwargs", ":", "return", "[", "str", "(", "x", "[", "1", "]", ")", "+", "'x: '", "+", "x", "[", "0", "]", ".", "classDescription", ".", "title", "for", "x", "in", "multireg_list", "]", "else", ":", "return", "[", "str", "(", "x", "[", "1", "]", ")", "+", "'x: '", "+", "x", "[", "0", "]", ".", "__str__", "(", ")", "for", "x", "in", "multireg_list", "]", "elif", "multireg_list", ":", "return", "'%sx registration'", "%", "max", "(", "[", "x", "[", "1", "]", "for", "x", "in", "multireg_list", "]", ")" ]
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 keeping track of dance admissions for couples who register under one name).
[ "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", "keeping", "track", "of", "dance", "admissions", "for", "couples", "who", "register", "under", "one", "name", ")", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1804-L1821
django-danceschool/django-danceschool
danceschool/core/models.py
Customer.get_email_context
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': self.fullName, 'phone': self.phone, }) return context
python
def get_email_context(self,**kwargs): context = super(Customer,self).get_email_context(**kwargs) context.update({ 'first_name': self.first_name, 'last_name': self.last_name, 'email': self.email, 'fullName': self.fullName, 'phone': self.phone, }) return context
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "Customer", ",", "self", ")", ".", "get_email_context", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'first_name'", ":", "self", ".", "first_name", ",", "'last_name'", ":", "self", ".", "last_name", ",", "'email'", ":", "self", ".", "email", ",", "'fullName'", ":", "self", ".", "fullName", ",", "'phone'", ":", "self", ".", "phone", ",", "}", ")", "return", "context" ]
Overrides EmailRecipientMixin
[ "Overrides", "EmailRecipientMixin" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1827-L1837
django-danceschool/django-danceschool
danceschool/core/models.py
TemporaryRegistration.getTimeOfClassesRemaining
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.temporaryeventregistration_set.filter(event__series__isnull=False)], ).order_by('-endTime') if occurrences.count() > numClasses: return occurrences[numClasses].endTime else: return occurrences.last().startTime
python
def getTimeOfClassesRemaining(self,numClasses=0): occurrences = EventOccurrence.objects.filter( cancelled=False, event__in=[x.event for x in self.temporaryeventregistration_set.filter(event__series__isnull=False)], ).order_by('-endTime') if occurrences.count() > numClasses: return occurrences[numClasses].endTime else: return occurrences.last().startTime
[ "def", "getTimeOfClassesRemaining", "(", "self", ",", "numClasses", "=", "0", ")", ":", "occurrences", "=", "EventOccurrence", ".", "objects", ".", "filter", "(", "cancelled", "=", "False", ",", "event__in", "=", "[", "x", ".", "event", "for", "x", "in", "self", ".", "temporaryeventregistration_set", ".", "filter", "(", "event__series__isnull", "=", "False", ")", "]", ",", ")", ".", "order_by", "(", "'-endTime'", ")", "if", "occurrences", ".", "count", "(", ")", ">", "numClasses", ":", "return", "occurrences", "[", "numClasses", "]", ".", "endTime", "else", ":", "return", "occurrences", ".", "last", "(", ")", ".", "startTime" ]
For checking things like prerequisites, it's useful to check if a requirement is 'almost' met
[ "For", "checking", "things", "like", "prerequisites", "it", "s", "useful", "to", "check", "if", "a", "requirement", "is", "almost", "met" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1952-L1963
django-danceschool/django-danceschool
danceschool/core/models.py
TemporaryRegistration.get_email_context
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, 'registrationHowHeardAboutUs': self.howHeardAboutUs, 'eventList': [x.get_email_context(includeName=False) for x in self.temporaryeventregistration_set.all()], }) if hasattr(self,'invoice') and self.invoice: context.update({ 'invoice': self.invoice.get_email_context(), }) return context
python
def get_email_context(self,**kwargs): context = super(TemporaryRegistration,self).get_email_context(**kwargs) context.update({ 'first_name': self.firstName, 'last_name': self.lastName, 'registrationComments': self.comments, 'registrationHowHeardAboutUs': self.howHeardAboutUs, 'eventList': [x.get_email_context(includeName=False) for x in self.temporaryeventregistration_set.all()], }) if hasattr(self,'invoice') and self.invoice: context.update({ 'invoice': self.invoice.get_email_context(), }) return context
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "TemporaryRegistration", ",", "self", ")", ".", "get_email_context", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'first_name'", ":", "self", ".", "firstName", ",", "'last_name'", ":", "self", ".", "lastName", ",", "'registrationComments'", ":", "self", ".", "comments", ",", "'registrationHowHeardAboutUs'", ":", "self", ".", "howHeardAboutUs", ",", "'eventList'", ":", "[", "x", ".", "get_email_context", "(", "includeName", "=", "False", ")", "for", "x", "in", "self", ".", "temporaryeventregistration_set", ".", "all", "(", ")", "]", ",", "}", ")", "if", "hasattr", "(", "self", ",", "'invoice'", ")", "and", "self", ".", "invoice", ":", "context", ".", "update", "(", "{", "'invoice'", ":", "self", ".", "invoice", ".", "get_email_context", "(", ")", ",", "}", ")", "return", "context" ]
Overrides EmailRecipientMixin
[ "Overrides", "EmailRecipientMixin" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1969-L1985
django-danceschool/django-danceschool
danceschool/core/models.py
TemporaryRegistration.finalize
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 False, then we won't send an email sendEmail = kwargs.pop('sendEmail', True) customer, created = Customer.objects.update_or_create( first_name=self.firstName,last_name=self.lastName, email=self.email,defaults={'phone': self.phone} ) regArgs = { 'customer': customer, 'firstName': self.firstName, 'lastName': self.lastName, 'dateTime': dateTime, 'temporaryRegistration': self } for key in ['comments', 'howHeardAboutUs', 'student', 'priceWithDiscount','payAtDoor']: regArgs[key] = kwargs.pop(key, getattr(self,key,None)) # All other passed kwargs are put into the data JSON regArgs['data'] = self.data regArgs['data'].update(kwargs) realreg = Registration(**regArgs) realreg.save() logger.debug('Created registration with id: ' + str(realreg.id)) for er in self.temporaryeventregistration_set.all(): logger.debug('Creating eventreg for event: ' + str(er.event.id)) realer = EventRegistration(registration=realreg,event=er.event, customer=customer,role=er.role, price=er.price, dropIn=er.dropIn, data=er.data ) realer.save() # Mark this temporary registration as expired, so that it won't # be counted twice against the number of in-progress registrations # in the future when another customer tries to register. self.expirationDate = timezone.now() self.save() # This signal can, for example, be caught by the vouchers app to keep track of any vouchers # that were applied post_registration.send( sender=TemporaryRegistration, registration=realreg ) if sendEmail: if getConstant('email__disableSiteEmails'): logger.info('Sending of confirmation emails is disabled.') else: logger.info('Sending confirmation email.') template = getConstant('email__registrationSuccessTemplate') realreg.email_recipient( subject=template.subject, content=template.content, html_content=template.html_content, send_html=template.send_html, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, ) # Return the newly-created finalized registration object return realreg
python
def finalize(self,**kwargs): dateTime = kwargs.pop('dateTime', timezone.now()) sendEmail = kwargs.pop('sendEmail', True) customer, created = Customer.objects.update_or_create( first_name=self.firstName,last_name=self.lastName, email=self.email,defaults={'phone': self.phone} ) regArgs = { 'customer': customer, 'firstName': self.firstName, 'lastName': self.lastName, 'dateTime': dateTime, 'temporaryRegistration': self } for key in ['comments', 'howHeardAboutUs', 'student', 'priceWithDiscount','payAtDoor']: regArgs[key] = kwargs.pop(key, getattr(self,key,None)) regArgs['data'] = self.data regArgs['data'].update(kwargs) realreg = Registration(**regArgs) realreg.save() logger.debug('Created registration with id: ' + str(realreg.id)) for er in self.temporaryeventregistration_set.all(): logger.debug('Creating eventreg for event: ' + str(er.event.id)) realer = EventRegistration(registration=realreg,event=er.event, customer=customer,role=er.role, price=er.price, dropIn=er.dropIn, data=er.data ) realer.save() self.expirationDate = timezone.now() self.save() post_registration.send( sender=TemporaryRegistration, registration=realreg ) if sendEmail: if getConstant('email__disableSiteEmails'): logger.info('Sending of confirmation emails is disabled.') else: logger.info('Sending confirmation email.') template = getConstant('email__registrationSuccessTemplate') realreg.email_recipient( subject=template.subject, content=template.content, html_content=template.html_content, send_html=template.send_html, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, ) return realreg
[ "def", "finalize", "(", "self", ",", "*", "*", "kwargs", ")", ":", "dateTime", "=", "kwargs", ".", "pop", "(", "'dateTime'", ",", "timezone", ".", "now", "(", ")", ")", "# If sendEmail is passed as False, then we won't send an email", "sendEmail", "=", "kwargs", ".", "pop", "(", "'sendEmail'", ",", "True", ")", "customer", ",", "created", "=", "Customer", ".", "objects", ".", "update_or_create", "(", "first_name", "=", "self", ".", "firstName", ",", "last_name", "=", "self", ".", "lastName", ",", "email", "=", "self", ".", "email", ",", "defaults", "=", "{", "'phone'", ":", "self", ".", "phone", "}", ")", "regArgs", "=", "{", "'customer'", ":", "customer", ",", "'firstName'", ":", "self", ".", "firstName", ",", "'lastName'", ":", "self", ".", "lastName", ",", "'dateTime'", ":", "dateTime", ",", "'temporaryRegistration'", ":", "self", "}", "for", "key", "in", "[", "'comments'", ",", "'howHeardAboutUs'", ",", "'student'", ",", "'priceWithDiscount'", ",", "'payAtDoor'", "]", ":", "regArgs", "[", "key", "]", "=", "kwargs", ".", "pop", "(", "key", ",", "getattr", "(", "self", ",", "key", ",", "None", ")", ")", "# All other passed kwargs are put into the data JSON", "regArgs", "[", "'data'", "]", "=", "self", ".", "data", "regArgs", "[", "'data'", "]", ".", "update", "(", "kwargs", ")", "realreg", "=", "Registration", "(", "*", "*", "regArgs", ")", "realreg", ".", "save", "(", ")", "logger", ".", "debug", "(", "'Created registration with id: '", "+", "str", "(", "realreg", ".", "id", ")", ")", "for", "er", "in", "self", ".", "temporaryeventregistration_set", ".", "all", "(", ")", ":", "logger", ".", "debug", "(", "'Creating eventreg for event: '", "+", "str", "(", "er", ".", "event", ".", "id", ")", ")", "realer", "=", "EventRegistration", "(", "registration", "=", "realreg", ",", "event", "=", "er", ".", "event", ",", "customer", "=", "customer", ",", "role", "=", "er", ".", "role", ",", "price", "=", "er", ".", "price", ",", "dropIn", "=", "er", ".", "dropIn", ",", "data", "=", "er", ".", "data", ")", "realer", ".", "save", "(", ")", "# Mark this temporary registration as expired, so that it won't", "# be counted twice against the number of in-progress registrations", "# in the future when another customer tries to register.", "self", ".", "expirationDate", "=", "timezone", ".", "now", "(", ")", "self", ".", "save", "(", ")", "# This signal can, for example, be caught by the vouchers app to keep track of any vouchers", "# that were applied", "post_registration", ".", "send", "(", "sender", "=", "TemporaryRegistration", ",", "registration", "=", "realreg", ")", "if", "sendEmail", ":", "if", "getConstant", "(", "'email__disableSiteEmails'", ")", ":", "logger", ".", "info", "(", "'Sending of confirmation emails is disabled.'", ")", "else", ":", "logger", ".", "info", "(", "'Sending confirmation email.'", ")", "template", "=", "getConstant", "(", "'email__registrationSuccessTemplate'", ")", "realreg", ".", "email_recipient", "(", "subject", "=", "template", ".", "subject", ",", "content", "=", "template", ".", "content", ",", "html_content", "=", "template", ".", "html_content", ",", "send_html", "=", "template", ".", "send_html", ",", "from_address", "=", "template", ".", "defaultFromAddress", ",", "from_name", "=", "template", ".", "defaultFromName", ",", "cc", "=", "template", ".", "defaultCC", ",", ")", "# Return the newly-created finalized registration object", "return", "realreg" ]
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
[ "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" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1987-L2061
django-danceschool/django-danceschool
danceschool/core/models.py
Registration.warningFlag
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 each of these conditions individually repeatedly. ''' if not hasattr(self,'invoice'): return True if apps.is_installed('danceschool.financial'): ''' If the financial app is installed, then we can also check additional properties set by that app to ensure that there are no inconsistencies ''' if self.invoice.revenueNotYetReceived != 0 or self.invoice.revenueMismatch: return True return ( self.priceWithDiscount != self.invoice.total or self.invoice.unpaid or self.invoice.outstandingBalance != 0 )
python
def warningFlag(self): if not hasattr(self,'invoice'): return True if apps.is_installed('danceschool.financial'): if self.invoice.revenueNotYetReceived != 0 or self.invoice.revenueMismatch: return True return ( self.priceWithDiscount != self.invoice.total or self.invoice.unpaid or self.invoice.outstandingBalance != 0 )
[ "def", "warningFlag", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'invoice'", ")", ":", "return", "True", "if", "apps", ".", "is_installed", "(", "'danceschool.financial'", ")", ":", "'''\n If the financial app is installed, then we can also check additional\n properties set by that app to ensure that there are no inconsistencies\n '''", "if", "self", ".", "invoice", ".", "revenueNotYetReceived", "!=", "0", "or", "self", ".", "invoice", ".", "revenueMismatch", ":", "return", "True", "return", "(", "self", ".", "priceWithDiscount", "!=", "self", ".", "invoice", ".", "total", "or", "self", ".", "invoice", ".", "unpaid", "or", "self", ".", "invoice", ".", "outstandingBalance", "!=", "0", ")" ]
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 each of these conditions individually repeatedly.
[ "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", "each", "of", "these", "conditions", "individually", "repeatedly", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2102-L2121
django-danceschool/django-danceschool
danceschool/core/models.py
Registration.get_email_context
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': self.comments, 'registrationHowHeardAboutUs': self.howHeardAboutUs, 'eventList': [x.get_email_context(includeName=False) for x in self.eventregistration_set.all()], }) if hasattr(self,'invoice') and self.invoice: context.update({ 'invoice': self.invoice.get_email_context(), }) return context
python
def get_email_context(self,**kwargs): context = super(Registration,self).get_email_context(**kwargs) context.update({ 'first_name': self.customer.first_name, 'last_name': self.customer.last_name, 'registrationComments': self.comments, 'registrationHowHeardAboutUs': self.howHeardAboutUs, 'eventList': [x.get_email_context(includeName=False) for x in self.eventregistration_set.all()], }) if hasattr(self,'invoice') and self.invoice: context.update({ 'invoice': self.invoice.get_email_context(), }) return context
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "Registration", ",", "self", ")", ".", "get_email_context", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'first_name'", ":", "self", ".", "customer", ".", "first_name", ",", "'last_name'", ":", "self", ".", "customer", ".", "last_name", ",", "'registrationComments'", ":", "self", ".", "comments", ",", "'registrationHowHeardAboutUs'", ":", "self", ".", "howHeardAboutUs", ",", "'eventList'", ":", "[", "x", ".", "get_email_context", "(", "includeName", "=", "False", ")", "for", "x", "in", "self", ".", "eventregistration_set", ".", "all", "(", ")", "]", ",", "}", ")", "if", "hasattr", "(", "self", ",", "'invoice'", ")", "and", "self", ".", "invoice", ":", "context", ".", "update", "(", "{", "'invoice'", ":", "self", ".", "invoice", ".", "get_email_context", "(", ")", ",", "}", ")", "return", "context" ]
Overrides EmailRecipientMixin
[ "Overrides", "EmailRecipientMixin" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2262-L2278
django-danceschool/django-danceschool
danceschool/core/models.py
EventRegistration.warningFlag
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 each of these conditions individually repeatedly. ''' if not hasattr(self,'invoiceitem'): return True if apps.is_installed('danceschool.financial'): ''' If the financial app is installed, then we can also check additional properties set by that app to ensure that there are no inconsistencies ''' if self.invoiceitem.revenueNotYetReceived != 0 or self.invoiceitem.revenueMismatch: return True return ( self.price != self.invoiceitem.grossTotal or self.invoiceitem.invoice.unpaid or self.invoiceitem.invoice.outstandingBalance != 0 )
python
def warningFlag(self): if not hasattr(self,'invoiceitem'): return True if apps.is_installed('danceschool.financial'): if self.invoiceitem.revenueNotYetReceived != 0 or self.invoiceitem.revenueMismatch: return True return ( self.price != self.invoiceitem.grossTotal or self.invoiceitem.invoice.unpaid or self.invoiceitem.invoice.outstandingBalance != 0 )
[ "def", "warningFlag", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'invoiceitem'", ")", ":", "return", "True", "if", "apps", ".", "is_installed", "(", "'danceschool.financial'", ")", ":", "'''\n If the financial app is installed, then we can also check additional\n properties set by that app to ensure that there are no inconsistencies\n '''", "if", "self", ".", "invoiceitem", ".", "revenueNotYetReceived", "!=", "0", "or", "self", ".", "invoiceitem", ".", "revenueMismatch", ":", "return", "True", "return", "(", "self", ".", "price", "!=", "self", ".", "invoiceitem", ".", "grossTotal", "or", "self", ".", "invoiceitem", ".", "invoice", ".", "unpaid", "or", "self", ".", "invoiceitem", ".", "invoice", ".", "outstandingBalance", "!=", "0", ")" ]
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 each of these conditions individually repeatedly.
[ "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", "each", "of", "these", "conditions", "individually", "repeatedly", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2340-L2359
django-danceschool/django-danceschool
danceschool/core/models.py
EventRegistration.get_email_context
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.firstOccurrenceTime, 'end': self.event.lastOccurrenceTime, }) if includeName: context.update({ 'first_name': self.registration.customer.first_name, 'last_name': self.registration.customer.last_name, }) return context
python
def get_email_context(self,**kwargs): includeName = kwargs.pop('includeName',True) context = super(EventRegistration,self).get_email_context(**kwargs) context.update({ 'title': self.event.name, 'start': self.event.firstOccurrenceTime, 'end': self.event.lastOccurrenceTime, }) if includeName: context.update({ 'first_name': self.registration.customer.first_name, 'last_name': self.registration.customer.last_name, }) return context
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "includeName", "=", "kwargs", ".", "pop", "(", "'includeName'", ",", "True", ")", "context", "=", "super", "(", "EventRegistration", ",", "self", ")", ".", "get_email_context", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'title'", ":", "self", ".", "event", ".", "name", ",", "'start'", ":", "self", ".", "event", ".", "firstOccurrenceTime", ",", "'end'", ":", "self", ".", "event", ".", "lastOccurrenceTime", ",", "}", ")", "if", "includeName", ":", "context", ".", "update", "(", "{", "'first_name'", ":", "self", ".", "registration", ".", "customer", ".", "first_name", ",", "'last_name'", ":", "self", ".", "registration", ".", "customer", ".", "last_name", ",", "}", ")", "return", "context" ]
Overrides EmailRecipientMixin
[ "Overrides", "EmailRecipientMixin" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2377-L2392
django-danceschool/django-danceschool
danceschool/core/models.py
TemporaryEventRegistration.get_email_context
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.firstOccurrenceTime, 'end': self.event.lastOccurrenceTime, }) if includeName: context.update({ 'first_name': self.registration.firstName, 'last_name': self.registration.lastName, }) return context
python
def get_email_context(self,**kwargs): includeName = kwargs.pop('includeName',True) context = super(TemporaryEventRegistration,self).get_email_context(**kwargs) context.update({ 'title': self.event.name, 'start': self.event.firstOccurrenceTime, 'end': self.event.lastOccurrenceTime, }) if includeName: context.update({ 'first_name': self.registration.firstName, 'last_name': self.registration.lastName, }) return context
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "includeName", "=", "kwargs", ".", "pop", "(", "'includeName'", ",", "True", ")", "context", "=", "super", "(", "TemporaryEventRegistration", ",", "self", ")", ".", "get_email_context", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'title'", ":", "self", ".", "event", ".", "name", ",", "'start'", ":", "self", ".", "event", ".", "firstOccurrenceTime", ",", "'end'", ":", "self", ".", "event", ".", "lastOccurrenceTime", ",", "}", ")", "if", "includeName", ":", "context", ".", "update", "(", "{", "'first_name'", ":", "self", ".", "registration", ".", "firstName", ",", "'last_name'", ":", "self", ".", "registration", ".", "lastName", ",", "}", ")", "return", "context" ]
Overrides EmailRecipientMixin
[ "Overrides", "EmailRecipientMixin" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2421-L2438
django-danceschool/django-danceschool
danceschool/core/models.py
EmailTemplate.save
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.html_content) else: self.html_content = None super(EmailTemplate, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): if self.send_html: self.content = get_text_for_html(self.html_content) else: self.html_content = None super(EmailTemplate, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "send_html", ":", "self", ".", "content", "=", "get_text_for_html", "(", "self", ".", "html_content", ")", "else", ":", "self", ".", "html_content", "=", "None", "super", "(", "EmailTemplate", ",", "self", ")", ".", "save", "(", "*", "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", "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2469-L2479
django-danceschool/django-danceschool
danceschool/core/models.py
Invoice.create_from_item
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 = kwargs.pop('collectedByUser', None) calculate_taxes = kwargs.pop('calculate_taxes', False) grossTotal = kwargs.pop('grossTotal',None) new_invoice = cls( grossTotal=grossTotal or amount, total=amount, submissionUser=submissionUser, collectedByUser=collectedByUser, buyerPaysSalesTax=getConstant('registration__buyerPaysSalesTax'), data=kwargs, ) if calculate_taxes: new_invoice.calculateTaxes() new_invoice.save() InvoiceItem.objects.create( invoice=new_invoice, grossTotal=grossTotal or amount, total=amount, taxes=new_invoice.taxes, description=item_description, ) return new_invoice
python
def create_from_item(cls, amount, item_description, **kwargs): submissionUser = kwargs.pop('submissionUser', None) collectedByUser = kwargs.pop('collectedByUser', None) calculate_taxes = kwargs.pop('calculate_taxes', False) grossTotal = kwargs.pop('grossTotal',None) new_invoice = cls( grossTotal=grossTotal or amount, total=amount, submissionUser=submissionUser, collectedByUser=collectedByUser, buyerPaysSalesTax=getConstant('registration__buyerPaysSalesTax'), data=kwargs, ) if calculate_taxes: new_invoice.calculateTaxes() new_invoice.save() InvoiceItem.objects.create( invoice=new_invoice, grossTotal=grossTotal or amount, total=amount, taxes=new_invoice.taxes, description=item_description, ) return new_invoice
[ "def", "create_from_item", "(", "cls", ",", "amount", ",", "item_description", ",", "*", "*", "kwargs", ")", ":", "submissionUser", "=", "kwargs", ".", "pop", "(", "'submissionUser'", ",", "None", ")", "collectedByUser", "=", "kwargs", ".", "pop", "(", "'collectedByUser'", ",", "None", ")", "calculate_taxes", "=", "kwargs", ".", "pop", "(", "'calculate_taxes'", ",", "False", ")", "grossTotal", "=", "kwargs", ".", "pop", "(", "'grossTotal'", ",", "None", ")", "new_invoice", "=", "cls", "(", "grossTotal", "=", "grossTotal", "or", "amount", ",", "total", "=", "amount", ",", "submissionUser", "=", "submissionUser", ",", "collectedByUser", "=", "collectedByUser", ",", "buyerPaysSalesTax", "=", "getConstant", "(", "'registration__buyerPaysSalesTax'", ")", ",", "data", "=", "kwargs", ",", ")", "if", "calculate_taxes", ":", "new_invoice", ".", "calculateTaxes", "(", ")", "new_invoice", ".", "save", "(", ")", "InvoiceItem", ".", "objects", ".", "create", "(", "invoice", "=", "new_invoice", ",", "grossTotal", "=", "grossTotal", "or", "amount", ",", "total", "=", "amount", ",", "taxes", "=", "new_invoice", ".", "taxes", ",", "description", "=", "item_description", ",", ")", "return", "new_invoice" ]
Creates an Invoice as well as a single associated InvoiceItem with the passed description (for things like gift certificates)
[ "Creates", "an", "Invoice", "as", "well", "as", "a", "single", "associated", "InvoiceItem", "with", "the", "passed", "description", "(", "for", "things", "like", "gift", "certificates", ")" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2547-L2578
django-danceschool/django-danceschool
danceschool/core/models.py
Invoice.create_from_registration
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) collectedByUser = kwargs.pop('collectedByUser', None) status = kwargs.pop('status',Invoice.PaymentStatus.unpaid) new_invoice = cls( firstName=reg.firstName, lastName=reg.lastName, email=reg.email, grossTotal=reg.totalPrice, total=reg.priceWithDiscount, submissionUser=submissionUser, collectedByUser=collectedByUser, buyerPaysSalesTax=getConstant('registration__buyerPaysSalesTax'), status=status, data=kwargs, ) if isinstance(reg, Registration): new_invoice.finalRegistration = reg ter_set = reg.eventregistration_set.all() elif isinstance(reg, TemporaryRegistration): new_invoice.temporaryRegistration = reg ter_set = reg.temporaryeventregistration_set.all() else: raise ValueError('Object passed is not a registration.') new_invoice.calculateTaxes() new_invoice.save() # Now, create InvoiceItem records for each EventRegistration for ter in ter_set: # Discounts and vouchers are always applied equally to all items at initial # invoice creation. item_kwargs = { 'invoice': new_invoice, 'grossTotal': ter.price, } if new_invoice.grossTotal > 0: item_kwargs.update({ 'total': ter.price * (new_invoice.total / new_invoice.grossTotal), 'taxes': new_invoice.taxes * (ter.price / new_invoice.grossTotal), 'fees': new_invoice.fees * (ter.price / new_invoice.grossTotal), }) else: item_kwargs.update({ 'total': ter.price, 'taxes': new_invoice.taxes, 'fees': new_invoice.fees, }) if isinstance(ter,TemporaryEventRegistration): item_kwargs['temporaryEventRegistration'] = ter elif isinstance(ter,EventRegistration): item_kwargs['finalEventRegistration'] = ter this_item = InvoiceItem(**item_kwargs) this_item.save() return new_invoice
python
def create_from_registration(cls, reg, **kwargs): submissionUser = kwargs.pop('submissionUser', None) collectedByUser = kwargs.pop('collectedByUser', None) status = kwargs.pop('status',Invoice.PaymentStatus.unpaid) new_invoice = cls( firstName=reg.firstName, lastName=reg.lastName, email=reg.email, grossTotal=reg.totalPrice, total=reg.priceWithDiscount, submissionUser=submissionUser, collectedByUser=collectedByUser, buyerPaysSalesTax=getConstant('registration__buyerPaysSalesTax'), status=status, data=kwargs, ) if isinstance(reg, Registration): new_invoice.finalRegistration = reg ter_set = reg.eventregistration_set.all() elif isinstance(reg, TemporaryRegistration): new_invoice.temporaryRegistration = reg ter_set = reg.temporaryeventregistration_set.all() else: raise ValueError('Object passed is not a registration.') new_invoice.calculateTaxes() new_invoice.save() for ter in ter_set: item_kwargs = { 'invoice': new_invoice, 'grossTotal': ter.price, } if new_invoice.grossTotal > 0: item_kwargs.update({ 'total': ter.price * (new_invoice.total / new_invoice.grossTotal), 'taxes': new_invoice.taxes * (ter.price / new_invoice.grossTotal), 'fees': new_invoice.fees * (ter.price / new_invoice.grossTotal), }) else: item_kwargs.update({ 'total': ter.price, 'taxes': new_invoice.taxes, 'fees': new_invoice.fees, }) if isinstance(ter,TemporaryEventRegistration): item_kwargs['temporaryEventRegistration'] = ter elif isinstance(ter,EventRegistration): item_kwargs['finalEventRegistration'] = ter this_item = InvoiceItem(**item_kwargs) this_item.save() return new_invoice
[ "def", "create_from_registration", "(", "cls", ",", "reg", ",", "*", "*", "kwargs", ")", ":", "submissionUser", "=", "kwargs", ".", "pop", "(", "'submissionUser'", ",", "None", ")", "collectedByUser", "=", "kwargs", ".", "pop", "(", "'collectedByUser'", ",", "None", ")", "status", "=", "kwargs", ".", "pop", "(", "'status'", ",", "Invoice", ".", "PaymentStatus", ".", "unpaid", ")", "new_invoice", "=", "cls", "(", "firstName", "=", "reg", ".", "firstName", ",", "lastName", "=", "reg", ".", "lastName", ",", "email", "=", "reg", ".", "email", ",", "grossTotal", "=", "reg", ".", "totalPrice", ",", "total", "=", "reg", ".", "priceWithDiscount", ",", "submissionUser", "=", "submissionUser", ",", "collectedByUser", "=", "collectedByUser", ",", "buyerPaysSalesTax", "=", "getConstant", "(", "'registration__buyerPaysSalesTax'", ")", ",", "status", "=", "status", ",", "data", "=", "kwargs", ",", ")", "if", "isinstance", "(", "reg", ",", "Registration", ")", ":", "new_invoice", ".", "finalRegistration", "=", "reg", "ter_set", "=", "reg", ".", "eventregistration_set", ".", "all", "(", ")", "elif", "isinstance", "(", "reg", ",", "TemporaryRegistration", ")", ":", "new_invoice", ".", "temporaryRegistration", "=", "reg", "ter_set", "=", "reg", ".", "temporaryeventregistration_set", ".", "all", "(", ")", "else", ":", "raise", "ValueError", "(", "'Object passed is not a registration.'", ")", "new_invoice", ".", "calculateTaxes", "(", ")", "new_invoice", ".", "save", "(", ")", "# Now, create InvoiceItem records for each EventRegistration", "for", "ter", "in", "ter_set", ":", "# Discounts and vouchers are always applied equally to all items at initial", "# invoice creation.", "item_kwargs", "=", "{", "'invoice'", ":", "new_invoice", ",", "'grossTotal'", ":", "ter", ".", "price", ",", "}", "if", "new_invoice", ".", "grossTotal", ">", "0", ":", "item_kwargs", ".", "update", "(", "{", "'total'", ":", "ter", ".", "price", "*", "(", "new_invoice", ".", "total", "/", "new_invoice", ".", "grossTotal", ")", ",", "'taxes'", ":", "new_invoice", ".", "taxes", "*", "(", "ter", ".", "price", "/", "new_invoice", ".", "grossTotal", ")", ",", "'fees'", ":", "new_invoice", ".", "fees", "*", "(", "ter", ".", "price", "/", "new_invoice", ".", "grossTotal", ")", ",", "}", ")", "else", ":", "item_kwargs", ".", "update", "(", "{", "'total'", ":", "ter", ".", "price", ",", "'taxes'", ":", "new_invoice", ".", "taxes", ",", "'fees'", ":", "new_invoice", ".", "fees", ",", "}", ")", "if", "isinstance", "(", "ter", ",", "TemporaryEventRegistration", ")", ":", "item_kwargs", "[", "'temporaryEventRegistration'", "]", "=", "ter", "elif", "isinstance", "(", "ter", ",", "EventRegistration", ")", ":", "item_kwargs", "[", "'finalEventRegistration'", "]", "=", "ter", "this_item", "=", "InvoiceItem", "(", "*", "*", "item_kwargs", ")", "this_item", ".", "save", "(", ")", "return", "new_invoice" ]
Handles the creation of an Invoice as well as one InvoiceItem per assodciated TemporaryEventRegistration or registration. Also handles taxes appropriately.
[ "Handles", "the", "creation", "of", "an", "Invoice", "as", "well", "as", "one", "InvoiceItem", "per", "assodciated", "TemporaryEventRegistration", "or", "registration", ".", "Also", "handles", "taxes", "appropriately", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2591-L2656
django-danceschool/django-danceschool
danceschool/core/models.py
Invoice.url
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.get_current().domain, reverse('viewInvoice', args=[self.id,]), )
python
def url(self): if self.id: return '%s://%s%s' % ( getConstant('email__linkProtocol'), Site.objects.get_current().domain, reverse('viewInvoice', args=[self.id,]), )
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "id", ":", "return", "'%s://%s%s'", "%", "(", "getConstant", "(", "'email__linkProtocol'", ")", ",", "Site", ".", "objects", ".", "get_current", "(", ")", ".", "domain", ",", "reverse", "(", "'viewInvoice'", ",", "args", "=", "[", "self", ".", "id", ",", "]", ")", ",", ")" ]
Because invoice URLs are generally emailed, this includes the default site URL and the protocol specified in settings.
[ "Because", "invoice", "URLs", "are", "generally", "emailed", "this", "includes", "the", "default", "site", "URL", "and", "the", "protocol", "specified", "in", "settings", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2710-L2721
django-danceschool/django-danceschool
danceschool/core/models.py
Invoice.get_default_recipients
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.email,] return []
python
def get_default_recipients(self): if self.email: return [self.email,] if self.finalRegistration: return [self.finalRegistration.customer.email,] elif self.temporaryRegistration: return [self.temporaryRegistration.email,] return []
[ "def", "get_default_recipients", "(", "self", ")", ":", "if", "self", ".", "email", ":", "return", "[", "self", ".", "email", ",", "]", "if", "self", ".", "finalRegistration", ":", "return", "[", "self", ".", "finalRegistration", ".", "customer", ".", "email", ",", "]", "elif", "self", ".", "temporaryRegistration", ":", "return", "[", "self", ".", "temporaryRegistration", ".", "email", ",", "]", "return", "[", "]" ]
Overrides EmailRecipientMixin
[ "Overrides", "EmailRecipientMixin" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2730-L2738
django-danceschool/django-danceschool
danceschool/core/models.py
Invoice.get_email_context
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, 'outstandingBalance': self.outstandingBalance, 'status': self.statusLabel, 'creationDate': self.creationDate, 'modifiedDate': self.modifiedDate, 'paidOnline': self.paidOnline, 'grossTotal': self.grossTotal, 'total': self.total, 'adjustments': self.adjustments, 'taxes': self.taxes, 'fees': self.fees, 'comments': self.comments, }) return context
python
def get_email_context(self,**kwargs): context = super(Invoice,self).get_email_context(**kwargs) context.update({ 'id': self.id, 'url': '%s?v=%s' % (self.url, self.validationString), 'amountPaid': self.amountPaid, 'outstandingBalance': self.outstandingBalance, 'status': self.statusLabel, 'creationDate': self.creationDate, 'modifiedDate': self.modifiedDate, 'paidOnline': self.paidOnline, 'grossTotal': self.grossTotal, 'total': self.total, 'adjustments': self.adjustments, 'taxes': self.taxes, 'fees': self.fees, 'comments': self.comments, }) return context
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "Invoice", ",", "self", ")", ".", "get_email_context", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'id'", ":", "self", ".", "id", ",", "'url'", ":", "'%s?v=%s'", "%", "(", "self", ".", "url", ",", "self", ".", "validationString", ")", ",", "'amountPaid'", ":", "self", ".", "amountPaid", ",", "'outstandingBalance'", ":", "self", ".", "outstandingBalance", ",", "'status'", ":", "self", ".", "statusLabel", ",", "'creationDate'", ":", "self", ".", "creationDate", ",", "'modifiedDate'", ":", "self", ".", "modifiedDate", ",", "'paidOnline'", ":", "self", ".", "paidOnline", ",", "'grossTotal'", ":", "self", ".", "grossTotal", ",", "'total'", ":", "self", ".", "total", ",", "'adjustments'", ":", "self", ".", "adjustments", ",", "'taxes'", ":", "self", ".", "taxes", ",", "'fees'", ":", "self", ".", "fees", ",", "'comments'", ":", "self", ".", "comments", ",", "}", ")", "return", "context" ]
Overrides EmailRecipientMixin
[ "Overrides", "EmailRecipientMixin" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2740-L2759
django-danceschool/django-danceschool
danceschool/core/models.py
Invoice.calculateTaxes
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 self.buyerPaysSalesTax: # If the buyer pays taxes, then taxes are just added as a fraction of the price self.taxes = self.total * tax_rate else: # If the seller pays sales taxes, then adjusted_total will be their net revenue, # and under this calculation adjusted_total + taxes = the price charged adjusted_total = self.total / (1 + tax_rate) self.taxes = adjusted_total * tax_rate
python
def calculateTaxes(self): tax_rate = (getConstant('registration__salesTaxRate') or 0) / 100 if tax_rate > 0: if self.buyerPaysSalesTax: self.taxes = self.total * tax_rate else: adjusted_total = self.total / (1 + tax_rate) self.taxes = adjusted_total * tax_rate
[ "def", "calculateTaxes", "(", "self", ")", ":", "tax_rate", "=", "(", "getConstant", "(", "'registration__salesTaxRate'", ")", "or", "0", ")", "/", "100", "if", "tax_rate", ">", "0", ":", "if", "self", ".", "buyerPaysSalesTax", ":", "# If the buyer pays taxes, then taxes are just added as a fraction of the price", "self", ".", "taxes", "=", "self", ".", "total", "*", "tax_rate", "else", ":", "# If the seller pays sales taxes, then adjusted_total will be their net revenue,", "# and under this calculation adjusted_total + taxes = the price charged", "adjusted_total", "=", "self", ".", "total", "/", "(", "1", "+", "tax_rate", ")", "self", ".", "taxes", "=", "adjusted_total", "*", "tax_rate" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2777-L2793
django-danceschool/django-danceschool
danceschool/core/models.py
Invoice.processPayment
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 status updates, the creation of a final registration object (if applicable), and the firing of appropriate registration-related signals. ''' epsilon = .01 paymentTime = timezone.now() logger.info('Processing payment and creating registration objects if applicable.') # The payment history record is primarily for convenience, and passed values are not # validated. Payment processing apps should keep individual transaction records with # a ForeignKey to the Invoice object. paymentHistory = self.data.get('paymentHistory',[]) paymentHistory.append({ 'dateTime': paymentTime.isoformat(), 'amount': amount, 'fees': fees, 'paidOnline': paidOnline, 'methodName': methodName, 'methodTxn': methodTxn, 'submissionUser': getattr(submissionUser,'id',None), 'collectedByUser': getattr(collectedByUser,'id',None), }) self.data['paymentHistory'] = paymentHistory self.amountPaid += amount self.fees += fees self.paidOnline = paidOnline if submissionUser and not self.submissionUser: self.submissionUser = submissionUser if collectedByUser and not self.collectedByUser: self.collectedByUser = collectedByUser # if this completed the payment, then finalize the registration and mark # the invoice as Paid unless told to do otherwise. if forceFinalize or abs(self.outstandingBalance) < epsilon: self.status = status or self.PaymentStatus.paid if not self.finalRegistration and self.temporaryRegistration: self.finalRegistration = self.temporaryRegistration.finalize(dateTime=paymentTime) else: self.sendNotification(invoicePaid=True,thisPaymentAmount=amount,payerEmail=notify) self.save() if self.finalRegistration: for eventReg in self.finalRegistration.eventregistration_set.filter(cancelled=False): # There can only be one eventreg per event in a registration, so we # can filter on temporaryRegistration event to get the invoiceItem # to which we should attach a finalEventRegistration this_invoice_item = self.invoiceitem_set.filter( temporaryEventRegistration__event=eventReg.event, finalEventRegistration__isnull=True ).first() if this_invoice_item: this_invoice_item.finalEventRegistration = eventReg this_invoice_item.save() else: # The payment wasn't completed so don't finalize, but do send a notification recording the payment. if notify: self.sendNotification(invoicePaid=True,thisPaymentAmount=amount,payerEmail=notify) else: self.sendNotification(invoicePaid=True,thisPaymentAmount=amount) self.save() # If there were transaction fees, then these also need to be allocated among the InvoiceItems # All fees from payments are allocated proportionately. self.allocateFees()
python
def processPayment(self, amount, fees, paidOnline=True, methodName=None, methodTxn=None, submissionUser=None, collectedByUser=None, forceFinalize=False, status=None, notify=None): epsilon = .01 paymentTime = timezone.now() logger.info('Processing payment and creating registration objects if applicable.') paymentHistory = self.data.get('paymentHistory',[]) paymentHistory.append({ 'dateTime': paymentTime.isoformat(), 'amount': amount, 'fees': fees, 'paidOnline': paidOnline, 'methodName': methodName, 'methodTxn': methodTxn, 'submissionUser': getattr(submissionUser,'id',None), 'collectedByUser': getattr(collectedByUser,'id',None), }) self.data['paymentHistory'] = paymentHistory self.amountPaid += amount self.fees += fees self.paidOnline = paidOnline if submissionUser and not self.submissionUser: self.submissionUser = submissionUser if collectedByUser and not self.collectedByUser: self.collectedByUser = collectedByUser if forceFinalize or abs(self.outstandingBalance) < epsilon: self.status = status or self.PaymentStatus.paid if not self.finalRegistration and self.temporaryRegistration: self.finalRegistration = self.temporaryRegistration.finalize(dateTime=paymentTime) else: self.sendNotification(invoicePaid=True,thisPaymentAmount=amount,payerEmail=notify) self.save() if self.finalRegistration: for eventReg in self.finalRegistration.eventregistration_set.filter(cancelled=False): this_invoice_item = self.invoiceitem_set.filter( temporaryEventRegistration__event=eventReg.event, finalEventRegistration__isnull=True ).first() if this_invoice_item: this_invoice_item.finalEventRegistration = eventReg this_invoice_item.save() else: if notify: self.sendNotification(invoicePaid=True,thisPaymentAmount=amount,payerEmail=notify) else: self.sendNotification(invoicePaid=True,thisPaymentAmount=amount) self.save() self.allocateFees()
[ "def", "processPayment", "(", "self", ",", "amount", ",", "fees", ",", "paidOnline", "=", "True", ",", "methodName", "=", "None", ",", "methodTxn", "=", "None", ",", "submissionUser", "=", "None", ",", "collectedByUser", "=", "None", ",", "forceFinalize", "=", "False", ",", "status", "=", "None", ",", "notify", "=", "None", ")", ":", "epsilon", "=", ".01", "paymentTime", "=", "timezone", ".", "now", "(", ")", "logger", ".", "info", "(", "'Processing payment and creating registration objects if applicable.'", ")", "# The payment history record is primarily for convenience, and passed values are not", "# validated. Payment processing apps should keep individual transaction records with", "# a ForeignKey to the Invoice object.", "paymentHistory", "=", "self", ".", "data", ".", "get", "(", "'paymentHistory'", ",", "[", "]", ")", "paymentHistory", ".", "append", "(", "{", "'dateTime'", ":", "paymentTime", ".", "isoformat", "(", ")", ",", "'amount'", ":", "amount", ",", "'fees'", ":", "fees", ",", "'paidOnline'", ":", "paidOnline", ",", "'methodName'", ":", "methodName", ",", "'methodTxn'", ":", "methodTxn", ",", "'submissionUser'", ":", "getattr", "(", "submissionUser", ",", "'id'", ",", "None", ")", ",", "'collectedByUser'", ":", "getattr", "(", "collectedByUser", ",", "'id'", ",", "None", ")", ",", "}", ")", "self", ".", "data", "[", "'paymentHistory'", "]", "=", "paymentHistory", "self", ".", "amountPaid", "+=", "amount", "self", ".", "fees", "+=", "fees", "self", ".", "paidOnline", "=", "paidOnline", "if", "submissionUser", "and", "not", "self", ".", "submissionUser", ":", "self", ".", "submissionUser", "=", "submissionUser", "if", "collectedByUser", "and", "not", "self", ".", "collectedByUser", ":", "self", ".", "collectedByUser", "=", "collectedByUser", "# if this completed the payment, then finalize the registration and mark", "# the invoice as Paid unless told to do otherwise.", "if", "forceFinalize", "or", "abs", "(", "self", ".", "outstandingBalance", ")", "<", "epsilon", ":", "self", ".", "status", "=", "status", "or", "self", ".", "PaymentStatus", ".", "paid", "if", "not", "self", ".", "finalRegistration", "and", "self", ".", "temporaryRegistration", ":", "self", ".", "finalRegistration", "=", "self", ".", "temporaryRegistration", ".", "finalize", "(", "dateTime", "=", "paymentTime", ")", "else", ":", "self", ".", "sendNotification", "(", "invoicePaid", "=", "True", ",", "thisPaymentAmount", "=", "amount", ",", "payerEmail", "=", "notify", ")", "self", ".", "save", "(", ")", "if", "self", ".", "finalRegistration", ":", "for", "eventReg", "in", "self", ".", "finalRegistration", ".", "eventregistration_set", ".", "filter", "(", "cancelled", "=", "False", ")", ":", "# There can only be one eventreg per event in a registration, so we", "# can filter on temporaryRegistration event to get the invoiceItem", "# to which we should attach a finalEventRegistration", "this_invoice_item", "=", "self", ".", "invoiceitem_set", ".", "filter", "(", "temporaryEventRegistration__event", "=", "eventReg", ".", "event", ",", "finalEventRegistration__isnull", "=", "True", ")", ".", "first", "(", ")", "if", "this_invoice_item", ":", "this_invoice_item", ".", "finalEventRegistration", "=", "eventReg", "this_invoice_item", ".", "save", "(", ")", "else", ":", "# The payment wasn't completed so don't finalize, but do send a notification recording the payment.", "if", "notify", ":", "self", ".", "sendNotification", "(", "invoicePaid", "=", "True", ",", "thisPaymentAmount", "=", "amount", ",", "payerEmail", "=", "notify", ")", "else", ":", "self", ".", "sendNotification", "(", "invoicePaid", "=", "True", ",", "thisPaymentAmount", "=", "amount", ")", "self", ".", "save", "(", ")", "# If there were transaction fees, then these also need to be allocated among the InvoiceItems", "# All fees from payments are allocated proportionately.", "self", ".", "allocateFees", "(", ")" ]
When a payment processor makes a successful payment against an invoice, it can call this method which handles status updates, the creation of a final registration object (if applicable), and the firing of appropriate registration-related signals.
[ "When", "a", "payment", "processor", "makes", "a", "successful", "payment", "against", "an", "invoice", "it", "can", "call", "this", "method", "which", "handles", "status", "updates", "the", "creation", "of", "a", "final", "registration", "object", "(", "if", "applicable", ")", "and", "the", "firing", "of", "appropriate", "registration", "-", "related", "signals", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2795-L2863
django-danceschool/django-danceschool
danceschool/core/models.py
Invoice.allocateFees
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. If they do not, raise an error. if self.total != sum([x.total for x in items]): msg = _('Invoice item totals do not match invoice total. Unable to allocate fees.') logger.error(str(msg)) raise ValidationError(msg) if self.adjustments != sum([x.adjustments for x in items]): msg = _('Invoice item adjustments do not match invoice adjustments. Unable to allocate fees.') logger.error(str(msg)) raise ValidationError(msg) for item in items: saveFlag = False if self.total - self.adjustments > 0: item.fees = self.fees * ((item.total - item.adjustments) / (self.total - self.adjustments)) saveFlag = True # In the case of full refunds, allocate fees according to the # initial total price of the item only. elif self.total - self.adjustments == 0 and self.total > 0: item.fees = self.fees * (item.total / self.total) saveFlag = True # In the unexpected event of fees with no total, just divide # the fees equally among the items. elif self.fees: item.fees = self.fees * (1 / len(items)) saveFlag = True if saveFlag: item.save()
python
def allocateFees(self): items = list(self.invoiceitem_set.all()) if self.total != sum([x.total for x in items]): msg = _('Invoice item totals do not match invoice total. Unable to allocate fees.') logger.error(str(msg)) raise ValidationError(msg) if self.adjustments != sum([x.adjustments for x in items]): msg = _('Invoice item adjustments do not match invoice adjustments. Unable to allocate fees.') logger.error(str(msg)) raise ValidationError(msg) for item in items: saveFlag = False if self.total - self.adjustments > 0: item.fees = self.fees * ((item.total - item.adjustments) / (self.total - self.adjustments)) saveFlag = True elif self.total - self.adjustments == 0 and self.total > 0: item.fees = self.fees * (item.total / self.total) saveFlag = True elif self.fees: item.fees = self.fees * (1 / len(items)) saveFlag = True if saveFlag: item.save()
[ "def", "allocateFees", "(", "self", ")", ":", "items", "=", "list", "(", "self", ".", "invoiceitem_set", ".", "all", "(", ")", ")", "# Check that totals and adjusments match. If they do not, raise an error.", "if", "self", ".", "total", "!=", "sum", "(", "[", "x", ".", "total", "for", "x", "in", "items", "]", ")", ":", "msg", "=", "_", "(", "'Invoice item totals do not match invoice total. Unable to allocate fees.'", ")", "logger", ".", "error", "(", "str", "(", "msg", ")", ")", "raise", "ValidationError", "(", "msg", ")", "if", "self", ".", "adjustments", "!=", "sum", "(", "[", "x", ".", "adjustments", "for", "x", "in", "items", "]", ")", ":", "msg", "=", "_", "(", "'Invoice item adjustments do not match invoice adjustments. Unable to allocate fees.'", ")", "logger", ".", "error", "(", "str", "(", "msg", ")", ")", "raise", "ValidationError", "(", "msg", ")", "for", "item", "in", "items", ":", "saveFlag", "=", "False", "if", "self", ".", "total", "-", "self", ".", "adjustments", ">", "0", ":", "item", ".", "fees", "=", "self", ".", "fees", "*", "(", "(", "item", ".", "total", "-", "item", ".", "adjustments", ")", "/", "(", "self", ".", "total", "-", "self", ".", "adjustments", ")", ")", "saveFlag", "=", "True", "# In the case of full refunds, allocate fees according to the", "# initial total price of the item only.", "elif", "self", ".", "total", "-", "self", ".", "adjustments", "==", "0", "and", "self", ".", "total", ">", "0", ":", "item", ".", "fees", "=", "self", ".", "fees", "*", "(", "item", ".", "total", "/", "self", ".", "total", ")", "saveFlag", "=", "True", "# In the unexpected event of fees with no total, just divide", "# the fees equally among the items.", "elif", "self", ".", "fees", ":", "item", ".", "fees", "=", "self", ".", "fees", "*", "(", "1", "/", "len", "(", "items", ")", ")", "saveFlag", "=", "True", "if", "saveFlag", ":", "item", ".", "save", "(", ")" ]
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
[ "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" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2865-L2903
django-danceschool/django-danceschool
danceschool/payments/paypal/views.py
createPaypalPayment
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 certificate payment requests). ''' logger.info('Received request for Paypal Express Checkout payment.') invoice_id = request.POST.get('invoice_id') tr_id = request.POST.get('reg_id') amount = request.POST.get('amount') submissionUserId = request.POST.get('user_id') transactionType = request.POST.get('transaction_type') taxable = request.POST.get('taxable', False) # If a specific amount to pay has been passed, then allow payment # of that amount. if amount: try: amount = float(amount) except ValueError: logger.error('Invalid amount passed') return HttpResponseBadRequest() # Parse if a specific submission user is indicated submissionUser = None if submissionUserId: try: submissionUser = User.objects.get(id=int(submissionUserId)) except (ValueError, ObjectDoesNotExist): logger.warning('Invalid user passed, submissionUser will not be recorded.') try: # Invoice transactions are usually payment on an existing invoice. if invoice_id: this_invoice = Invoice.objects.get(id=invoice_id) this_description = _('Invoice Payment: %s' % this_invoice.id) if not amount: amount = this_invoice.outstandingBalance # This is typical of payment at the time of registration elif tr_id: tr = TemporaryRegistration.objects.get(id=int(tr_id)) tr.expirationDate = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) tr.save() this_invoice = Invoice.get_or_create_from_registration(tr, submissionUser=submissionUser) this_description = _('Registration Payment: #%s' % tr_id) if not amount: amount = this_invoice.outstandingBalance # All other transactions require both a transaction type and an amount to be specified elif not transactionType or not amount: logger.error('Insufficient information passed to createPaypalPayment view.') raise ValueError else: # Gift certificates automatically get a nicer invoice description if transactionType == 'Gift Certificate': this_description = _('Gift Certificate Purchase') else: this_description = transactionType this_invoice = Invoice.create_from_item( float(amount), this_description, submissionUser=submissionUser, calculate_taxes=(taxable is not False), transactionType=transactionType, ) except (ValueError, ObjectDoesNotExist) as e: logger.error('Invalid registration information passed to createPaypalPayment view: (%s, %s, %s)' % (invoice_id, tr_id, amount)) logger.error(e) return HttpResponseBadRequest() this_currency = getConstant('general__currencyCode') this_total = min(this_invoice.outstandingBalance, amount) this_subtotal = this_total - this_invoice.taxes this_transaction = { 'amount': { 'total': round(this_total,2), 'currency': this_currency, 'details': { 'subtotal': round(this_subtotal,2), 'tax': round(this_invoice.taxes,2), }, }, 'description': str(this_description), 'item_list': { 'items': [] } } for item in this_invoice.invoiceitem_set.all(): if not getConstant('registration__buyerPaysSalesTax'): this_item_price = item.grossTotal - item.taxes else: this_item_price = item.grossTotal this_transaction['item_list']['items'].append({ 'name': str(item.name), 'price': round(this_item_price,2), 'tax': round(item.taxes,2), 'currency': this_currency, 'quantity': 1, }) # Because the Paypal API requires that the subtotal add up to the sum of the item # totals, we must add a negative line item for discounts applied, and a line item # for the remaining balance if there is to be one. if this_invoice.grossTotal != this_invoice.total: this_transaction['item_list']['items'].append({ 'name': str(_('Total Discounts')), 'price': round(this_invoice.total,2) - round(this_invoice.grossTotal,2), 'currency': this_currency, 'quantity': 1, }) if this_invoice.amountPaid > 0: this_transaction['item_list']['items'].append({ 'name': str(_('Previously Paid')), 'price': -1 * round(this_invoice.amountPaid,2), 'currency': this_currency, 'quantity': 1, }) if amount != this_invoice.outstandingBalance: this_transaction['item_list']['items'].append({ 'name': str(_('Remaining Balance After Payment')), 'price': round(amount,2) - round(this_invoice.outstandingBalance,2), 'currency': this_currency, 'quantity': 1, }) # Paypal requires the Payment request to include redirect URLs. Since # the plugin can handle actual redirects, we just pass the base URL for # the current site. site = SimpleLazyObject(lambda: get_current_site(request)) protocol = 'https' if request.is_secure() else 'http' base_url = SimpleLazyObject(lambda: "{0}://{1}".format(protocol, site.domain)) payment = Payment({ 'intent': 'sale', 'payer': { 'payment_method': 'paypal' }, 'transactions': [this_transaction], 'redirect_urls': { 'return_url': str(base_url), 'cancel_url': str(base_url), } }) if payment.create(): logger.info('Paypal payment object created.') if this_invoice: this_invoice.status = Invoice.PaymentStatus.authorized this_invoice.save() # We just keep a record of the ID and the status, because the # API can be used to look up everything else. PaypalPaymentRecord.objects.create( paymentId=payment.id, invoice=this_invoice, status=payment.state, ) return JsonResponse(payment.to_dict()) else: logger.error('Paypal payment object not created.') logger.error(payment) logger.error(payment.error) if this_invoice: this_invoice.status = Invoice.PaymentStatus.error this_invoice.save() return HttpResponseBadRequest()
python
def createPaypalPayment(request): logger.info('Received request for Paypal Express Checkout payment.') invoice_id = request.POST.get('invoice_id') tr_id = request.POST.get('reg_id') amount = request.POST.get('amount') submissionUserId = request.POST.get('user_id') transactionType = request.POST.get('transaction_type') taxable = request.POST.get('taxable', False) if amount: try: amount = float(amount) except ValueError: logger.error('Invalid amount passed') return HttpResponseBadRequest() submissionUser = None if submissionUserId: try: submissionUser = User.objects.get(id=int(submissionUserId)) except (ValueError, ObjectDoesNotExist): logger.warning('Invalid user passed, submissionUser will not be recorded.') try: if invoice_id: this_invoice = Invoice.objects.get(id=invoice_id) this_description = _('Invoice Payment: %s' % this_invoice.id) if not amount: amount = this_invoice.outstandingBalance elif tr_id: tr = TemporaryRegistration.objects.get(id=int(tr_id)) tr.expirationDate = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) tr.save() this_invoice = Invoice.get_or_create_from_registration(tr, submissionUser=submissionUser) this_description = _('Registration Payment: if not amount: amount = this_invoice.outstandingBalance elif not transactionType or not amount: logger.error('Insufficient information passed to createPaypalPayment view.') raise ValueError else: if transactionType == 'Gift Certificate': this_description = _('Gift Certificate Purchase') else: this_description = transactionType this_invoice = Invoice.create_from_item( float(amount), this_description, submissionUser=submissionUser, calculate_taxes=(taxable is not False), transactionType=transactionType, ) except (ValueError, ObjectDoesNotExist) as e: logger.error('Invalid registration information passed to createPaypalPayment view: (%s, %s, %s)' % (invoice_id, tr_id, amount)) logger.error(e) return HttpResponseBadRequest() this_currency = getConstant('general__currencyCode') this_total = min(this_invoice.outstandingBalance, amount) this_subtotal = this_total - this_invoice.taxes this_transaction = { 'amount': { 'total': round(this_total,2), 'currency': this_currency, 'details': { 'subtotal': round(this_subtotal,2), 'tax': round(this_invoice.taxes,2), }, }, 'description': str(this_description), 'item_list': { 'items': [] } } for item in this_invoice.invoiceitem_set.all(): if not getConstant('registration__buyerPaysSalesTax'): this_item_price = item.grossTotal - item.taxes else: this_item_price = item.grossTotal this_transaction['item_list']['items'].append({ 'name': str(item.name), 'price': round(this_item_price,2), 'tax': round(item.taxes,2), 'currency': this_currency, 'quantity': 1, }) if this_invoice.grossTotal != this_invoice.total: this_transaction['item_list']['items'].append({ 'name': str(_('Total Discounts')), 'price': round(this_invoice.total,2) - round(this_invoice.grossTotal,2), 'currency': this_currency, 'quantity': 1, }) if this_invoice.amountPaid > 0: this_transaction['item_list']['items'].append({ 'name': str(_('Previously Paid')), 'price': -1 * round(this_invoice.amountPaid,2), 'currency': this_currency, 'quantity': 1, }) if amount != this_invoice.outstandingBalance: this_transaction['item_list']['items'].append({ 'name': str(_('Remaining Balance After Payment')), 'price': round(amount,2) - round(this_invoice.outstandingBalance,2), 'currency': this_currency, 'quantity': 1, }) site = SimpleLazyObject(lambda: get_current_site(request)) protocol = 'https' if request.is_secure() else 'http' base_url = SimpleLazyObject(lambda: "{0}://{1}".format(protocol, site.domain)) payment = Payment({ 'intent': 'sale', 'payer': { 'payment_method': 'paypal' }, 'transactions': [this_transaction], 'redirect_urls': { 'return_url': str(base_url), 'cancel_url': str(base_url), } }) if payment.create(): logger.info('Paypal payment object created.') if this_invoice: this_invoice.status = Invoice.PaymentStatus.authorized this_invoice.save() PaypalPaymentRecord.objects.create( paymentId=payment.id, invoice=this_invoice, status=payment.state, ) return JsonResponse(payment.to_dict()) else: logger.error('Paypal payment object not created.') logger.error(payment) logger.error(payment.error) if this_invoice: this_invoice.status = Invoice.PaymentStatus.error this_invoice.save() return HttpResponseBadRequest()
[ "def", "createPaypalPayment", "(", "request", ")", ":", "logger", ".", "info", "(", "'Received request for Paypal Express Checkout payment.'", ")", "invoice_id", "=", "request", ".", "POST", ".", "get", "(", "'invoice_id'", ")", "tr_id", "=", "request", ".", "POST", ".", "get", "(", "'reg_id'", ")", "amount", "=", "request", ".", "POST", ".", "get", "(", "'amount'", ")", "submissionUserId", "=", "request", ".", "POST", ".", "get", "(", "'user_id'", ")", "transactionType", "=", "request", ".", "POST", ".", "get", "(", "'transaction_type'", ")", "taxable", "=", "request", ".", "POST", ".", "get", "(", "'taxable'", ",", "False", ")", "# If a specific amount to pay has been passed, then allow payment", "# of that amount.", "if", "amount", ":", "try", ":", "amount", "=", "float", "(", "amount", ")", "except", "ValueError", ":", "logger", ".", "error", "(", "'Invalid amount passed'", ")", "return", "HttpResponseBadRequest", "(", ")", "# Parse if a specific submission user is indicated", "submissionUser", "=", "None", "if", "submissionUserId", ":", "try", ":", "submissionUser", "=", "User", ".", "objects", ".", "get", "(", "id", "=", "int", "(", "submissionUserId", ")", ")", "except", "(", "ValueError", ",", "ObjectDoesNotExist", ")", ":", "logger", ".", "warning", "(", "'Invalid user passed, submissionUser will not be recorded.'", ")", "try", ":", "# Invoice transactions are usually payment on an existing invoice.", "if", "invoice_id", ":", "this_invoice", "=", "Invoice", ".", "objects", ".", "get", "(", "id", "=", "invoice_id", ")", "this_description", "=", "_", "(", "'Invoice Payment: %s'", "%", "this_invoice", ".", "id", ")", "if", "not", "amount", ":", "amount", "=", "this_invoice", ".", "outstandingBalance", "# This is typical of payment at the time of registration", "elif", "tr_id", ":", "tr", "=", "TemporaryRegistration", ".", "objects", ".", "get", "(", "id", "=", "int", "(", "tr_id", ")", ")", "tr", ".", "expirationDate", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "minutes", "=", "getConstant", "(", "'registration__sessionExpiryMinutes'", ")", ")", "tr", ".", "save", "(", ")", "this_invoice", "=", "Invoice", ".", "get_or_create_from_registration", "(", "tr", ",", "submissionUser", "=", "submissionUser", ")", "this_description", "=", "_", "(", "'Registration Payment: #%s'", "%", "tr_id", ")", "if", "not", "amount", ":", "amount", "=", "this_invoice", ".", "outstandingBalance", "# All other transactions require both a transaction type and an amount to be specified", "elif", "not", "transactionType", "or", "not", "amount", ":", "logger", ".", "error", "(", "'Insufficient information passed to createPaypalPayment view.'", ")", "raise", "ValueError", "else", ":", "# Gift certificates automatically get a nicer invoice description", "if", "transactionType", "==", "'Gift Certificate'", ":", "this_description", "=", "_", "(", "'Gift Certificate Purchase'", ")", "else", ":", "this_description", "=", "transactionType", "this_invoice", "=", "Invoice", ".", "create_from_item", "(", "float", "(", "amount", ")", ",", "this_description", ",", "submissionUser", "=", "submissionUser", ",", "calculate_taxes", "=", "(", "taxable", "is", "not", "False", ")", ",", "transactionType", "=", "transactionType", ",", ")", "except", "(", "ValueError", ",", "ObjectDoesNotExist", ")", "as", "e", ":", "logger", ".", "error", "(", "'Invalid registration information passed to createPaypalPayment view: (%s, %s, %s)'", "%", "(", "invoice_id", ",", "tr_id", ",", "amount", ")", ")", "logger", ".", "error", "(", "e", ")", "return", "HttpResponseBadRequest", "(", ")", "this_currency", "=", "getConstant", "(", "'general__currencyCode'", ")", "this_total", "=", "min", "(", "this_invoice", ".", "outstandingBalance", ",", "amount", ")", "this_subtotal", "=", "this_total", "-", "this_invoice", ".", "taxes", "this_transaction", "=", "{", "'amount'", ":", "{", "'total'", ":", "round", "(", "this_total", ",", "2", ")", ",", "'currency'", ":", "this_currency", ",", "'details'", ":", "{", "'subtotal'", ":", "round", "(", "this_subtotal", ",", "2", ")", ",", "'tax'", ":", "round", "(", "this_invoice", ".", "taxes", ",", "2", ")", ",", "}", ",", "}", ",", "'description'", ":", "str", "(", "this_description", ")", ",", "'item_list'", ":", "{", "'items'", ":", "[", "]", "}", "}", "for", "item", "in", "this_invoice", ".", "invoiceitem_set", ".", "all", "(", ")", ":", "if", "not", "getConstant", "(", "'registration__buyerPaysSalesTax'", ")", ":", "this_item_price", "=", "item", ".", "grossTotal", "-", "item", ".", "taxes", "else", ":", "this_item_price", "=", "item", ".", "grossTotal", "this_transaction", "[", "'item_list'", "]", "[", "'items'", "]", ".", "append", "(", "{", "'name'", ":", "str", "(", "item", ".", "name", ")", ",", "'price'", ":", "round", "(", "this_item_price", ",", "2", ")", ",", "'tax'", ":", "round", "(", "item", ".", "taxes", ",", "2", ")", ",", "'currency'", ":", "this_currency", ",", "'quantity'", ":", "1", ",", "}", ")", "# Because the Paypal API requires that the subtotal add up to the sum of the item", "# totals, we must add a negative line item for discounts applied, and a line item", "# for the remaining balance if there is to be one.", "if", "this_invoice", ".", "grossTotal", "!=", "this_invoice", ".", "total", ":", "this_transaction", "[", "'item_list'", "]", "[", "'items'", "]", ".", "append", "(", "{", "'name'", ":", "str", "(", "_", "(", "'Total Discounts'", ")", ")", ",", "'price'", ":", "round", "(", "this_invoice", ".", "total", ",", "2", ")", "-", "round", "(", "this_invoice", ".", "grossTotal", ",", "2", ")", ",", "'currency'", ":", "this_currency", ",", "'quantity'", ":", "1", ",", "}", ")", "if", "this_invoice", ".", "amountPaid", ">", "0", ":", "this_transaction", "[", "'item_list'", "]", "[", "'items'", "]", ".", "append", "(", "{", "'name'", ":", "str", "(", "_", "(", "'Previously Paid'", ")", ")", ",", "'price'", ":", "-", "1", "*", "round", "(", "this_invoice", ".", "amountPaid", ",", "2", ")", ",", "'currency'", ":", "this_currency", ",", "'quantity'", ":", "1", ",", "}", ")", "if", "amount", "!=", "this_invoice", ".", "outstandingBalance", ":", "this_transaction", "[", "'item_list'", "]", "[", "'items'", "]", ".", "append", "(", "{", "'name'", ":", "str", "(", "_", "(", "'Remaining Balance After Payment'", ")", ")", ",", "'price'", ":", "round", "(", "amount", ",", "2", ")", "-", "round", "(", "this_invoice", ".", "outstandingBalance", ",", "2", ")", ",", "'currency'", ":", "this_currency", ",", "'quantity'", ":", "1", ",", "}", ")", "# Paypal requires the Payment request to include redirect URLs. Since", "# the plugin can handle actual redirects, we just pass the base URL for", "# the current site.", "site", "=", "SimpleLazyObject", "(", "lambda", ":", "get_current_site", "(", "request", ")", ")", "protocol", "=", "'https'", "if", "request", ".", "is_secure", "(", ")", "else", "'http'", "base_url", "=", "SimpleLazyObject", "(", "lambda", ":", "\"{0}://{1}\"", ".", "format", "(", "protocol", ",", "site", ".", "domain", ")", ")", "payment", "=", "Payment", "(", "{", "'intent'", ":", "'sale'", ",", "'payer'", ":", "{", "'payment_method'", ":", "'paypal'", "}", ",", "'transactions'", ":", "[", "this_transaction", "]", ",", "'redirect_urls'", ":", "{", "'return_url'", ":", "str", "(", "base_url", ")", ",", "'cancel_url'", ":", "str", "(", "base_url", ")", ",", "}", "}", ")", "if", "payment", ".", "create", "(", ")", ":", "logger", ".", "info", "(", "'Paypal payment object created.'", ")", "if", "this_invoice", ":", "this_invoice", ".", "status", "=", "Invoice", ".", "PaymentStatus", ".", "authorized", "this_invoice", ".", "save", "(", ")", "# We just keep a record of the ID and the status, because the", "# API can be used to look up everything else.", "PaypalPaymentRecord", ".", "objects", ".", "create", "(", "paymentId", "=", "payment", ".", "id", ",", "invoice", "=", "this_invoice", ",", "status", "=", "payment", ".", "state", ",", ")", "return", "JsonResponse", "(", "payment", ".", "to_dict", "(", ")", ")", "else", ":", "logger", ".", "error", "(", "'Paypal payment object not created.'", ")", "logger", ".", "error", "(", "payment", ")", "logger", ".", "error", "(", "payment", ".", "error", ")", "if", "this_invoice", ":", "this_invoice", ".", "status", "=", "Invoice", ".", "PaymentStatus", ".", "error", "this_invoice", ".", "save", "(", ")", "return", "HttpResponseBadRequest", "(", ")" ]
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 certificate payment requests).
[ "This", "view", "handles", "the", "creation", "of", "Paypal", "Express", "Checkout", "Payment", "objects", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/paypal/views.py#L24-L198
django-danceschool/django-danceschool
danceschool/discounts/models.py
DiscountCombo.applyAndAllocate
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 items, and returns both the price and the allocation ''' initial_net_price = sum([x for x in allocatedPrices]) if self.discountType == self.DiscountType.flatPrice: # Flat-price for all applicable items (partial application for items which are # only partially needed to apply the discount). Flat prices ignore any previous discounts # in other categories which may have been the best, but they only are applied if they are # lower than the price that would be feasible by applying those prior discounts alone. applicable_price = self.getFlatPrice(payAtDoor) or 0 this_price = applicable_price \ + sum([x[0].event.getBasePrice(payAtDoor=payAtDoor) * x[1] if x[1] != 1 else x[0].price for x in tieredTuples]) # Flat prices are allocated equally across all events this_allocated_prices = [x * (this_price / initial_net_price) for x in allocatedPrices] elif self.discountType == self.DiscountType.dollarDiscount: # Discount the set of applicable items by a specific number of dollars (currency units) # Dollar discounts are allocated equally across all events. this_price = initial_net_price - self.dollarDiscount this_allocated_prices = [x * (this_price / initial_net_price) for x in allocatedPrices] elif self.discountType == DiscountCombo.DiscountType.percentDiscount: # Percentage off discounts, which may be applied to all items in the cart, # or just to the items that were needed to apply the discount if self.percentUniversallyApplied: this_price = \ initial_net_price * (1 - (max(min(self.percentDiscount or 0,100),0) / 100)) this_allocated_prices = [x * (this_price / initial_net_price) for x in allocatedPrices] else: # Allocate the percentage discount based on the prior allocation from the prior category this_price = 0 this_allocated_prices = [] for idx, val in enumerate(tieredTuples): this_val = ( allocatedPrices[idx] * (1 - val[1]) * (1 - (max(min(self.percentDiscount or 0,100),0) / 100)) + allocatedPrices[idx] * val[1] ) this_allocated_prices.append(this_val) this_price += this_val else: raise KeyError(_('Invalid discount type.')) if this_price < initial_net_price: # Ensure no negative prices this_price = max(this_price, 0) return self.DiscountInfo(self, this_price, initial_net_price - this_price, this_allocated_prices)
python
def applyAndAllocate(self,allocatedPrices,tieredTuples,payAtDoor=False): initial_net_price = sum([x for x in allocatedPrices]) if self.discountType == self.DiscountType.flatPrice: applicable_price = self.getFlatPrice(payAtDoor) or 0 this_price = applicable_price \ + sum([x[0].event.getBasePrice(payAtDoor=payAtDoor) * x[1] if x[1] != 1 else x[0].price for x in tieredTuples]) this_allocated_prices = [x * (this_price / initial_net_price) for x in allocatedPrices] elif self.discountType == self.DiscountType.dollarDiscount: this_price = initial_net_price - self.dollarDiscount this_allocated_prices = [x * (this_price / initial_net_price) for x in allocatedPrices] elif self.discountType == DiscountCombo.DiscountType.percentDiscount: if self.percentUniversallyApplied: this_price = \ initial_net_price * (1 - (max(min(self.percentDiscount or 0,100),0) / 100)) this_allocated_prices = [x * (this_price / initial_net_price) for x in allocatedPrices] else: this_price = 0 this_allocated_prices = [] for idx, val in enumerate(tieredTuples): this_val = ( allocatedPrices[idx] * (1 - val[1]) * (1 - (max(min(self.percentDiscount or 0,100),0) / 100)) + allocatedPrices[idx] * val[1] ) this_allocated_prices.append(this_val) this_price += this_val else: raise KeyError(_('Invalid discount type.')) if this_price < initial_net_price: this_price = max(this_price, 0) return self.DiscountInfo(self, this_price, initial_net_price - this_price, this_allocated_prices)
[ "def", "applyAndAllocate", "(", "self", ",", "allocatedPrices", ",", "tieredTuples", ",", "payAtDoor", "=", "False", ")", ":", "initial_net_price", "=", "sum", "(", "[", "x", "for", "x", "in", "allocatedPrices", "]", ")", "if", "self", ".", "discountType", "==", "self", ".", "DiscountType", ".", "flatPrice", ":", "# Flat-price for all applicable items (partial application for items which are", "# only partially needed to apply the discount). Flat prices ignore any previous discounts", "# in other categories which may have been the best, but they only are applied if they are", "# lower than the price that would be feasible by applying those prior discounts alone.", "applicable_price", "=", "self", ".", "getFlatPrice", "(", "payAtDoor", ")", "or", "0", "this_price", "=", "applicable_price", "+", "sum", "(", "[", "x", "[", "0", "]", ".", "event", ".", "getBasePrice", "(", "payAtDoor", "=", "payAtDoor", ")", "*", "x", "[", "1", "]", "if", "x", "[", "1", "]", "!=", "1", "else", "x", "[", "0", "]", ".", "price", "for", "x", "in", "tieredTuples", "]", ")", "# Flat prices are allocated equally across all events", "this_allocated_prices", "=", "[", "x", "*", "(", "this_price", "/", "initial_net_price", ")", "for", "x", "in", "allocatedPrices", "]", "elif", "self", ".", "discountType", "==", "self", ".", "DiscountType", ".", "dollarDiscount", ":", "# Discount the set of applicable items by a specific number of dollars (currency units)", "# Dollar discounts are allocated equally across all events.", "this_price", "=", "initial_net_price", "-", "self", ".", "dollarDiscount", "this_allocated_prices", "=", "[", "x", "*", "(", "this_price", "/", "initial_net_price", ")", "for", "x", "in", "allocatedPrices", "]", "elif", "self", ".", "discountType", "==", "DiscountCombo", ".", "DiscountType", ".", "percentDiscount", ":", "# Percentage off discounts, which may be applied to all items in the cart,", "# or just to the items that were needed to apply the discount", "if", "self", ".", "percentUniversallyApplied", ":", "this_price", "=", "initial_net_price", "*", "(", "1", "-", "(", "max", "(", "min", "(", "self", ".", "percentDiscount", "or", "0", ",", "100", ")", ",", "0", ")", "/", "100", ")", ")", "this_allocated_prices", "=", "[", "x", "*", "(", "this_price", "/", "initial_net_price", ")", "for", "x", "in", "allocatedPrices", "]", "else", ":", "# Allocate the percentage discount based on the prior allocation from the prior category", "this_price", "=", "0", "this_allocated_prices", "=", "[", "]", "for", "idx", ",", "val", "in", "enumerate", "(", "tieredTuples", ")", ":", "this_val", "=", "(", "allocatedPrices", "[", "idx", "]", "*", "(", "1", "-", "val", "[", "1", "]", ")", "*", "(", "1", "-", "(", "max", "(", "min", "(", "self", ".", "percentDiscount", "or", "0", ",", "100", ")", ",", "0", ")", "/", "100", ")", ")", "+", "allocatedPrices", "[", "idx", "]", "*", "val", "[", "1", "]", ")", "this_allocated_prices", ".", "append", "(", "this_val", ")", "this_price", "+=", "this_val", "else", ":", "raise", "KeyError", "(", "_", "(", "'Invalid discount type.'", ")", ")", "if", "this_price", "<", "initial_net_price", ":", "# Ensure no negative prices", "this_price", "=", "max", "(", "this_price", ",", "0", ")", "return", "self", ".", "DiscountInfo", "(", "self", ",", "this_price", ",", "initial_net_price", "-", "this_price", ",", "this_allocated_prices", ")" ]
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 items, and returns both the price and the allocation
[ "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", "items", "and", "returns", "both", "the", "price", "and", "the", "allocation" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/discounts/models.py#L146-L201
django-danceschool/django-danceschool
danceschool/discounts/models.py
DiscountCombo.getFlatPrice
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 else: return self.onlinePrice
python
def getFlatPrice(self,payAtDoor=False): if self.discountType is not DiscountCombo.DiscountType.flatPrice: return None if payAtDoor: return self.doorPrice else: return self.onlinePrice
[ "def", "getFlatPrice", "(", "self", ",", "payAtDoor", "=", "False", ")", ":", "if", "self", ".", "discountType", "is", "not", "DiscountCombo", ".", "DiscountType", ".", "flatPrice", ":", "return", "None", "if", "payAtDoor", ":", "return", "self", ".", "doorPrice", "else", ":", "return", "self", ".", "onlinePrice" ]
Rather than embedding logic re: door pricing, other code can call this method.
[ "Rather", "than", "embedding", "logic", "re", ":", "door", "pricing", "other", "code", "can", "call", "this", "method", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/discounts/models.py#L203-L213
django-danceschool/django-danceschool
danceschool/discounts/models.py
DiscountCombo.getComponentList
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 = [] for x in self.discountcombocomponent_set.all(): for y in range(0,x.quantity): component_list += [x] component_list.sort(key=lambda x: x.quantity, reverse=True) return component_list
python
def getComponentList(self): component_list = [] for x in self.discountcombocomponent_set.all(): for y in range(0,x.quantity): component_list += [x] component_list.sort(key=lambda x: x.quantity, reverse=True) return component_list
[ "def", "getComponentList", "(", "self", ")", ":", "component_list", "=", "[", "]", "for", "x", "in", "self", ".", "discountcombocomponent_set", ".", "all", "(", ")", ":", "for", "y", "in", "range", "(", "0", ",", "x", ".", "quantity", ")", ":", "component_list", "+=", "[", "x", "]", "component_list", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "quantity", ",", "reverse", "=", "True", ")", "return", "component_list" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/discounts/models.py#L215-L230
django-danceschool/django-danceschool
danceschool/discounts/models.py
DiscountCombo.save
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.discountType != self.DiscountType.dollarDiscount: self.dollarDiscount = None if self.discountType != self.DiscountType.percentDiscount: self.percentDiscount = None self.percentUniversallyApplied = False super(DiscountCombo, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): if self.discountType != self.DiscountType.flatPrice: self.onlinePrice = None self.doorPrice = None if self.discountType != self.DiscountType.dollarDiscount: self.dollarDiscount = None if self.discountType != self.DiscountType.percentDiscount: self.percentDiscount = None self.percentUniversallyApplied = False super(DiscountCombo, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "discountType", "!=", "self", ".", "DiscountType", ".", "flatPrice", ":", "self", ".", "onlinePrice", "=", "None", "self", ".", "doorPrice", "=", "None", "if", "self", ".", "discountType", "!=", "self", ".", "DiscountType", ".", "dollarDiscount", ":", "self", ".", "dollarDiscount", "=", "None", "if", "self", ".", "discountType", "!=", "self", ".", "DiscountType", ".", "percentDiscount", ":", "self", ".", "percentDiscount", "=", "None", "self", ".", "percentUniversallyApplied", "=", "False", "super", "(", "DiscountCombo", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Don't save any passed values related to a type of discount that is not the specified type
[ "Don", "t", "save", "any", "passed", "values", "related", "to", "a", "type", "of", "discount", "that", "is", "not", "the", "specified", "type" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/discounts/models.py#L232-L249
django-danceschool/django-danceschool
danceschool/discounts/handlers.py
getBestDiscount
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, only one discount should be applied. Therefore, this handler loops through all potential discounts, finds the ones that are applicable to the passed registration or set of items, and returns the code and discounted price of the best available discount, in a tuple of the form (code, discounted_price). ''' if not getConstant('general__discountsEnabled'): return logger.debug('Signal fired to request discounts.') reg = kwargs.pop('registration',None) if not reg: logger.warning('No registration passed, discounts not applied.') return payAtDoor = reg.payAtDoor # Check if this is a new customer, who may be eligible for special discounts newCustomer = True customer = Customer.objects.filter(email=reg.email,first_name=reg.firstName,last_name=reg.lastName).first() if (customer and customer.numClassSeries > 0) or sender != RegistrationSummaryView: newCustomer = False eligible_filter = ( Q(event__series__pricingTier__isnull=False) | Q(event__publicevent__pricingTier__isnull=False) ) ineligible_filter = ( (Q(event__series__isnull=False) & Q(event__series__pricingTier__isnull=True)) | (Q(event__publicevent__isnull=False) & Q(event__publicevent__pricingTier__isnull=True)) | Q(dropIn=True) ) if apps.is_installed('danceschool.private_lessons'): eligible_filter = eligible_filter | Q(event__privatelessonevent__pricingTier__isnull=False) ineligible_filter = ineligible_filter | ( Q(event__privatelessonevent__isnull=False) & Q(event__privatelessonevent__pricingTier__isnull=True) ) # The items for which the customer registered. eventregs_list = reg.temporaryeventregistration_set.all() eligible_list = eventregs_list.filter(dropIn=False).filter(eligible_filter) ineligible_list = eventregs_list.filter(ineligible_filter) ineligible_total = sum( [x.event.getBasePrice(payAtDoor=payAtDoor) for x in ineligible_list.exclude(dropIn=True)] + [x.price for x in ineligible_list.filter(dropIn=True)] ) # Get the applicable discounts and sort them in ascending category order # so that the best discounts are always listed in the order that they will # be applied. discountCodesApplicable = getApplicableDiscountCombos(eligible_list, newCustomer, reg.student, customer=customer, addOn=False, cannotCombine=False, dateTime=reg.dateTime) discountCodesApplicable.sort(key=lambda x: x.code.category.order) # Once we have a list of codes to try, calculate the discounted price for each possibility, # and pick the one in each category that has the lowest total price. We also need to keep track # of the way in which some discounts are allocated across individual events. best_discounts = OrderedDict() initial_prices = [x.event.getBasePrice(payAtDoor=payAtDoor) for x in eligible_list] initial_total = sum(initial_prices) if discountCodesApplicable: net_allocated_prices = initial_prices net_precategory_price = initial_total last_category = discountCodesApplicable[0].code.category for discount in discountCodesApplicable: # If the category has changed, then the new net_allocated_prices and the # new net_precategory price are whatever was found to be best in the last category. if (discount.code.category != last_category): last_category = discount.code.category if best_discounts: # Since this is an OrderedDict, we can get the last element of the dict from # the iterator, which is the last category for which there was a valid discount. last_discount = best_discounts.get(next(reversed(best_discounts))) net_allocated_prices = last_discount.net_allocated_prices net_precategory_price = last_discount.net_price # The second item in each tuple is now adjusted, so that each item that is wholly or partially # applied against the discount will be wholly (value goes to 0) or partially subtracted from the # remaining value to be calculated at full price. tieredTuples = [(x,1) for x in eligible_list[:]] for itemTuple in discount.itemTuples: tieredTuples = [(p,q) if p != itemTuple[0] else (p,q - itemTuple[1]) for (p,q) in tieredTuples] response = discount.code.applyAndAllocate(net_allocated_prices,tieredTuples,payAtDoor) # Once the final price has been calculated, apply it iff it is less than # the previously best discount found. current_code = best_discounts.get(discount.code.category.name, None) if ( response and ( (not current_code and response.net_price < net_precategory_price) or (current_code and response.net_price < current_code.net_price) ) ): best_discounts[discount.code.category.name] = response # Now, repeat the basic process for codes that cannot be combined. These codes are always # compared against the base price, and there is no need to allocate across items since # only one code will potentially be applied. uncombinedCodesApplicable = getApplicableDiscountCombos( eligible_list, newCustomer, reg.student, customer=customer, addOn=False, cannotCombine=True, dateTime=reg.dateTime ) for discount in uncombinedCodesApplicable: # The second item in each tuple is now adjusted, so that each item that is wholly or partially # applied against the discount will be wholly (value goes to 0) or partially subtracted from the # remaining value to be calculated at full price. tieredTuples = [(x,1) for x in eligible_list[:]] for itemTuple in discount.itemTuples: tieredTuples = [(p,q) if p != itemTuple[0] else (p,q - itemTuple[1]) for (p,q) in tieredTuples] response = discount.code.applyAndAllocate(initial_prices,tieredTuples,payAtDoor) # Once the final price has been calculated, apply it iff it is less than # the previously best discount or combination of discounts found. if ( response and response.net_price < min([x.net_price for x in best_discounts.values()] + [initial_total]) ): best_discounts = OrderedDict({discount.code.category.name: response}) if not best_discounts: logger.debug('No applicable discounts found.') # Return the list of discounts to be applied (in DiscountInfo tuples), along with the additional # price of ineligible items to be added. return DiscountCombo.DiscountApplication([x for x in best_discounts.values()], ineligible_total)
python
def getBestDiscount(sender,**kwargs): if not getConstant('general__discountsEnabled'): return logger.debug('Signal fired to request discounts.') reg = kwargs.pop('registration',None) if not reg: logger.warning('No registration passed, discounts not applied.') return payAtDoor = reg.payAtDoor newCustomer = True customer = Customer.objects.filter(email=reg.email,first_name=reg.firstName,last_name=reg.lastName).first() if (customer and customer.numClassSeries > 0) or sender != RegistrationSummaryView: newCustomer = False eligible_filter = ( Q(event__series__pricingTier__isnull=False) | Q(event__publicevent__pricingTier__isnull=False) ) ineligible_filter = ( (Q(event__series__isnull=False) & Q(event__series__pricingTier__isnull=True)) | (Q(event__publicevent__isnull=False) & Q(event__publicevent__pricingTier__isnull=True)) | Q(dropIn=True) ) if apps.is_installed('danceschool.private_lessons'): eligible_filter = eligible_filter | Q(event__privatelessonevent__pricingTier__isnull=False) ineligible_filter = ineligible_filter | ( Q(event__privatelessonevent__isnull=False) & Q(event__privatelessonevent__pricingTier__isnull=True) ) eventregs_list = reg.temporaryeventregistration_set.all() eligible_list = eventregs_list.filter(dropIn=False).filter(eligible_filter) ineligible_list = eventregs_list.filter(ineligible_filter) ineligible_total = sum( [x.event.getBasePrice(payAtDoor=payAtDoor) for x in ineligible_list.exclude(dropIn=True)] + [x.price for x in ineligible_list.filter(dropIn=True)] ) discountCodesApplicable = getApplicableDiscountCombos(eligible_list, newCustomer, reg.student, customer=customer, addOn=False, cannotCombine=False, dateTime=reg.dateTime) discountCodesApplicable.sort(key=lambda x: x.code.category.order) best_discounts = OrderedDict() initial_prices = [x.event.getBasePrice(payAtDoor=payAtDoor) for x in eligible_list] initial_total = sum(initial_prices) if discountCodesApplicable: net_allocated_prices = initial_prices net_precategory_price = initial_total last_category = discountCodesApplicable[0].code.category for discount in discountCodesApplicable: if (discount.code.category != last_category): last_category = discount.code.category if best_discounts: last_discount = best_discounts.get(next(reversed(best_discounts))) net_allocated_prices = last_discount.net_allocated_prices net_precategory_price = last_discount.net_price tieredTuples = [(x,1) for x in eligible_list[:]] for itemTuple in discount.itemTuples: tieredTuples = [(p,q) if p != itemTuple[0] else (p,q - itemTuple[1]) for (p,q) in tieredTuples] response = discount.code.applyAndAllocate(net_allocated_prices,tieredTuples,payAtDoor) current_code = best_discounts.get(discount.code.category.name, None) if ( response and ( (not current_code and response.net_price < net_precategory_price) or (current_code and response.net_price < current_code.net_price) ) ): best_discounts[discount.code.category.name] = response uncombinedCodesApplicable = getApplicableDiscountCombos( eligible_list, newCustomer, reg.student, customer=customer, addOn=False, cannotCombine=True, dateTime=reg.dateTime ) for discount in uncombinedCodesApplicable: tieredTuples = [(x,1) for x in eligible_list[:]] for itemTuple in discount.itemTuples: tieredTuples = [(p,q) if p != itemTuple[0] else (p,q - itemTuple[1]) for (p,q) in tieredTuples] response = discount.code.applyAndAllocate(initial_prices,tieredTuples,payAtDoor) if ( response and response.net_price < min([x.net_price for x in best_discounts.values()] + [initial_total]) ): best_discounts = OrderedDict({discount.code.category.name: response}) if not best_discounts: logger.debug('No applicable discounts found.') return DiscountCombo.DiscountApplication([x for x in best_discounts.values()], ineligible_total)
[ "def", "getBestDiscount", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "getConstant", "(", "'general__discountsEnabled'", ")", ":", "return", "logger", ".", "debug", "(", "'Signal fired to request discounts.'", ")", "reg", "=", "kwargs", ".", "pop", "(", "'registration'", ",", "None", ")", "if", "not", "reg", ":", "logger", ".", "warning", "(", "'No registration passed, discounts not applied.'", ")", "return", "payAtDoor", "=", "reg", ".", "payAtDoor", "# Check if this is a new customer, who may be eligible for special discounts", "newCustomer", "=", "True", "customer", "=", "Customer", ".", "objects", ".", "filter", "(", "email", "=", "reg", ".", "email", ",", "first_name", "=", "reg", ".", "firstName", ",", "last_name", "=", "reg", ".", "lastName", ")", ".", "first", "(", ")", "if", "(", "customer", "and", "customer", ".", "numClassSeries", ">", "0", ")", "or", "sender", "!=", "RegistrationSummaryView", ":", "newCustomer", "=", "False", "eligible_filter", "=", "(", "Q", "(", "event__series__pricingTier__isnull", "=", "False", ")", "|", "Q", "(", "event__publicevent__pricingTier__isnull", "=", "False", ")", ")", "ineligible_filter", "=", "(", "(", "Q", "(", "event__series__isnull", "=", "False", ")", "&", "Q", "(", "event__series__pricingTier__isnull", "=", "True", ")", ")", "|", "(", "Q", "(", "event__publicevent__isnull", "=", "False", ")", "&", "Q", "(", "event__publicevent__pricingTier__isnull", "=", "True", ")", ")", "|", "Q", "(", "dropIn", "=", "True", ")", ")", "if", "apps", ".", "is_installed", "(", "'danceschool.private_lessons'", ")", ":", "eligible_filter", "=", "eligible_filter", "|", "Q", "(", "event__privatelessonevent__pricingTier__isnull", "=", "False", ")", "ineligible_filter", "=", "ineligible_filter", "|", "(", "Q", "(", "event__privatelessonevent__isnull", "=", "False", ")", "&", "Q", "(", "event__privatelessonevent__pricingTier__isnull", "=", "True", ")", ")", "# The items for which the customer registered.", "eventregs_list", "=", "reg", ".", "temporaryeventregistration_set", ".", "all", "(", ")", "eligible_list", "=", "eventregs_list", ".", "filter", "(", "dropIn", "=", "False", ")", ".", "filter", "(", "eligible_filter", ")", "ineligible_list", "=", "eventregs_list", ".", "filter", "(", "ineligible_filter", ")", "ineligible_total", "=", "sum", "(", "[", "x", ".", "event", ".", "getBasePrice", "(", "payAtDoor", "=", "payAtDoor", ")", "for", "x", "in", "ineligible_list", ".", "exclude", "(", "dropIn", "=", "True", ")", "]", "+", "[", "x", ".", "price", "for", "x", "in", "ineligible_list", ".", "filter", "(", "dropIn", "=", "True", ")", "]", ")", "# Get the applicable discounts and sort them in ascending category order", "# so that the best discounts are always listed in the order that they will", "# be applied.", "discountCodesApplicable", "=", "getApplicableDiscountCombos", "(", "eligible_list", ",", "newCustomer", ",", "reg", ".", "student", ",", "customer", "=", "customer", ",", "addOn", "=", "False", ",", "cannotCombine", "=", "False", ",", "dateTime", "=", "reg", ".", "dateTime", ")", "discountCodesApplicable", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "code", ".", "category", ".", "order", ")", "# Once we have a list of codes to try, calculate the discounted price for each possibility,", "# and pick the one in each category that has the lowest total price. We also need to keep track", "# of the way in which some discounts are allocated across individual events.", "best_discounts", "=", "OrderedDict", "(", ")", "initial_prices", "=", "[", "x", ".", "event", ".", "getBasePrice", "(", "payAtDoor", "=", "payAtDoor", ")", "for", "x", "in", "eligible_list", "]", "initial_total", "=", "sum", "(", "initial_prices", ")", "if", "discountCodesApplicable", ":", "net_allocated_prices", "=", "initial_prices", "net_precategory_price", "=", "initial_total", "last_category", "=", "discountCodesApplicable", "[", "0", "]", ".", "code", ".", "category", "for", "discount", "in", "discountCodesApplicable", ":", "# If the category has changed, then the new net_allocated_prices and the", "# new net_precategory price are whatever was found to be best in the last category.", "if", "(", "discount", ".", "code", ".", "category", "!=", "last_category", ")", ":", "last_category", "=", "discount", ".", "code", ".", "category", "if", "best_discounts", ":", "# Since this is an OrderedDict, we can get the last element of the dict from", "# the iterator, which is the last category for which there was a valid discount.", "last_discount", "=", "best_discounts", ".", "get", "(", "next", "(", "reversed", "(", "best_discounts", ")", ")", ")", "net_allocated_prices", "=", "last_discount", ".", "net_allocated_prices", "net_precategory_price", "=", "last_discount", ".", "net_price", "# The second item in each tuple is now adjusted, so that each item that is wholly or partially", "# applied against the discount will be wholly (value goes to 0) or partially subtracted from the", "# remaining value to be calculated at full price.", "tieredTuples", "=", "[", "(", "x", ",", "1", ")", "for", "x", "in", "eligible_list", "[", ":", "]", "]", "for", "itemTuple", "in", "discount", ".", "itemTuples", ":", "tieredTuples", "=", "[", "(", "p", ",", "q", ")", "if", "p", "!=", "itemTuple", "[", "0", "]", "else", "(", "p", ",", "q", "-", "itemTuple", "[", "1", "]", ")", "for", "(", "p", ",", "q", ")", "in", "tieredTuples", "]", "response", "=", "discount", ".", "code", ".", "applyAndAllocate", "(", "net_allocated_prices", ",", "tieredTuples", ",", "payAtDoor", ")", "# Once the final price has been calculated, apply it iff it is less than", "# the previously best discount found.", "current_code", "=", "best_discounts", ".", "get", "(", "discount", ".", "code", ".", "category", ".", "name", ",", "None", ")", "if", "(", "response", "and", "(", "(", "not", "current_code", "and", "response", ".", "net_price", "<", "net_precategory_price", ")", "or", "(", "current_code", "and", "response", ".", "net_price", "<", "current_code", ".", "net_price", ")", ")", ")", ":", "best_discounts", "[", "discount", ".", "code", ".", "category", ".", "name", "]", "=", "response", "# Now, repeat the basic process for codes that cannot be combined. These codes are always", "# compared against the base price, and there is no need to allocate across items since", "# only one code will potentially be applied.", "uncombinedCodesApplicable", "=", "getApplicableDiscountCombos", "(", "eligible_list", ",", "newCustomer", ",", "reg", ".", "student", ",", "customer", "=", "customer", ",", "addOn", "=", "False", ",", "cannotCombine", "=", "True", ",", "dateTime", "=", "reg", ".", "dateTime", ")", "for", "discount", "in", "uncombinedCodesApplicable", ":", "# The second item in each tuple is now adjusted, so that each item that is wholly or partially", "# applied against the discount will be wholly (value goes to 0) or partially subtracted from the", "# remaining value to be calculated at full price.", "tieredTuples", "=", "[", "(", "x", ",", "1", ")", "for", "x", "in", "eligible_list", "[", ":", "]", "]", "for", "itemTuple", "in", "discount", ".", "itemTuples", ":", "tieredTuples", "=", "[", "(", "p", ",", "q", ")", "if", "p", "!=", "itemTuple", "[", "0", "]", "else", "(", "p", ",", "q", "-", "itemTuple", "[", "1", "]", ")", "for", "(", "p", ",", "q", ")", "in", "tieredTuples", "]", "response", "=", "discount", ".", "code", ".", "applyAndAllocate", "(", "initial_prices", ",", "tieredTuples", ",", "payAtDoor", ")", "# Once the final price has been calculated, apply it iff it is less than", "# the previously best discount or combination of discounts found.", "if", "(", "response", "and", "response", ".", "net_price", "<", "min", "(", "[", "x", ".", "net_price", "for", "x", "in", "best_discounts", ".", "values", "(", ")", "]", "+", "[", "initial_total", "]", ")", ")", ":", "best_discounts", "=", "OrderedDict", "(", "{", "discount", ".", "code", ".", "category", ".", "name", ":", "response", "}", ")", "if", "not", "best_discounts", ":", "logger", ".", "debug", "(", "'No applicable discounts found.'", ")", "# Return the list of discounts to be applied (in DiscountInfo tuples), along with the additional", "# price of ineligible items to be added.", "return", "DiscountCombo", ".", "DiscountApplication", "(", "[", "x", "for", "x", "in", "best_discounts", ".", "values", "(", ")", "]", ",", "ineligible_total", ")" ]
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, only one discount should be applied. Therefore, this handler loops through all potential discounts, finds the ones that are applicable to the passed registration or set of items, and returns the code and discounted price of the best available discount, in a tuple of the form (code, discounted_price).
[ "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", "only", "one", "discount", "should", "be", "applied", ".", "Therefore", "this", "handler", "loops", "through", "all", "potential", "discounts", "finds", "the", "ones", "that", "are", "applicable", "to", "the", "passed", "registration", "or", "set", "of", "items", "and", "returns", "the", "code", "and", "discounted", "price", "of", "the", "best", "available", "discount", "in", "a", "tuple", "of", "the", "form", "(", "code", "discounted_price", ")", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/discounts/handlers.py#L22-L163
django-danceschool/django-danceschool
danceschool/payments/square/cms_plugins.py
SquareCheckoutFormPlugin.render
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',''), }) return context
python
def render(self, context, instance, placeholder): context = super(SquareCheckoutFormPlugin, self).render(context, instance, placeholder) context.update({ 'squareApplicationId': getattr(settings,'SQUARE_APPLICATION_ID',''), }) return context
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "context", "=", "super", "(", "SquareCheckoutFormPlugin", ",", "self", ")", ".", "render", "(", "context", ",", "instance", ",", "placeholder", ")", "context", ".", "update", "(", "{", "'squareApplicationId'", ":", "getattr", "(", "settings", ",", "'SQUARE_APPLICATION_ID'", ",", "''", ")", ",", "}", ")", "return", "context" ]
Add the cart-specific context to this form
[ "Add", "the", "cart", "-", "specific", "context", "to", "this", "form" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/square/cms_plugins.py#L18-L26
django-danceschool/django-danceschool
danceschool/vouchers/handlers.py
checkVoucherCode
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',None) session = getattr(request,'session',{}).get(REG_VALIDATION_STR,{}) id = formData.get('gift','') first = formData.get('firstName') last = formData.get('lastName') email = formData.get('email') # Clean out the session data relating to vouchers so that we can revalidate it. session.pop('total_voucher_amount',0) session.pop('voucher_names',None) session.pop('gift',None) if id == '': return if not getConstant('vouchers__enableVouchers'): raise ValidationError({'gift': _('Vouchers are disabled.')}) if session.get('gift','') != '': raise ValidationError({'gift': _('Can\'t have more than one voucher')}) eventids = [x.event.id for x in registration.temporaryeventregistration_set.exclude(dropIn=True)] seriess = Series.objects.filter(id__in=eventids) obj = Voucher.objects.filter(voucherId=id).first() if not obj: raise ValidationError({'gift':_('Invalid Voucher Id')}) else: customer = Customer.objects.filter( first_name=first, last_name=last, email=email).first() # This will raise any other errors that may be relevant try: obj.validateForCustomerAndSeriess(customer,seriess) except ValidationError as e: # Ensures that the error is applied to the correct field raise ValidationError({'gift': e}) # If we got this far, then the voucher is determined to be valid, so the registration # can proceed with no errors. return
python
def checkVoucherCode(sender,**kwargs): logger.debug('Signal to check RegistrationContactForm handled by vouchers app.') formData = kwargs.get('formData',{}) request = kwargs.get('request',{}) registration = kwargs.get('registration',None) session = getattr(request,'session',{}).get(REG_VALIDATION_STR,{}) id = formData.get('gift','') first = formData.get('firstName') last = formData.get('lastName') email = formData.get('email') session.pop('total_voucher_amount',0) session.pop('voucher_names',None) session.pop('gift',None) if id == '': return if not getConstant('vouchers__enableVouchers'): raise ValidationError({'gift': _('Vouchers are disabled.')}) if session.get('gift','') != '': raise ValidationError({'gift': _('Can\'t have more than one voucher')}) eventids = [x.event.id for x in registration.temporaryeventregistration_set.exclude(dropIn=True)] seriess = Series.objects.filter(id__in=eventids) obj = Voucher.objects.filter(voucherId=id).first() if not obj: raise ValidationError({'gift':_('Invalid Voucher Id')}) else: customer = Customer.objects.filter( first_name=first, last_name=last, email=email).first() try: obj.validateForCustomerAndSeriess(customer,seriess) except ValidationError as e: raise ValidationError({'gift': e}) return
[ "def", "checkVoucherCode", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Signal to check RegistrationContactForm handled by vouchers app.'", ")", "formData", "=", "kwargs", ".", "get", "(", "'formData'", ",", "{", "}", ")", "request", "=", "kwargs", ".", "get", "(", "'request'", ",", "{", "}", ")", "registration", "=", "kwargs", ".", "get", "(", "'registration'", ",", "None", ")", "session", "=", "getattr", "(", "request", ",", "'session'", ",", "{", "}", ")", ".", "get", "(", "REG_VALIDATION_STR", ",", "{", "}", ")", "id", "=", "formData", ".", "get", "(", "'gift'", ",", "''", ")", "first", "=", "formData", ".", "get", "(", "'firstName'", ")", "last", "=", "formData", ".", "get", "(", "'lastName'", ")", "email", "=", "formData", ".", "get", "(", "'email'", ")", "# Clean out the session data relating to vouchers so that we can revalidate it.\r", "session", ".", "pop", "(", "'total_voucher_amount'", ",", "0", ")", "session", ".", "pop", "(", "'voucher_names'", ",", "None", ")", "session", ".", "pop", "(", "'gift'", ",", "None", ")", "if", "id", "==", "''", ":", "return", "if", "not", "getConstant", "(", "'vouchers__enableVouchers'", ")", ":", "raise", "ValidationError", "(", "{", "'gift'", ":", "_", "(", "'Vouchers are disabled.'", ")", "}", ")", "if", "session", ".", "get", "(", "'gift'", ",", "''", ")", "!=", "''", ":", "raise", "ValidationError", "(", "{", "'gift'", ":", "_", "(", "'Can\\'t have more than one voucher'", ")", "}", ")", "eventids", "=", "[", "x", ".", "event", ".", "id", "for", "x", "in", "registration", ".", "temporaryeventregistration_set", ".", "exclude", "(", "dropIn", "=", "True", ")", "]", "seriess", "=", "Series", ".", "objects", ".", "filter", "(", "id__in", "=", "eventids", ")", "obj", "=", "Voucher", ".", "objects", ".", "filter", "(", "voucherId", "=", "id", ")", ".", "first", "(", ")", "if", "not", "obj", ":", "raise", "ValidationError", "(", "{", "'gift'", ":", "_", "(", "'Invalid Voucher Id'", ")", "}", ")", "else", ":", "customer", "=", "Customer", ".", "objects", ".", "filter", "(", "first_name", "=", "first", ",", "last_name", "=", "last", ",", "email", "=", "email", ")", ".", "first", "(", ")", "# This will raise any other errors that may be relevant\r", "try", ":", "obj", ".", "validateForCustomerAndSeriess", "(", "customer", ",", "seriess", ")", "except", "ValidationError", "as", "e", ":", "# Ensures that the error is applied to the correct field\r", "raise", "ValidationError", "(", "{", "'gift'", ":", "e", "}", ")", "# If we got this far, then the voucher is determined to be valid, so the registration\r", "# can proceed with no errors.\r", "return" ]
Check that the given voucher code is valid
[ "Check", "that", "the", "given", "voucher", "code", "is", "valid" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L20-L71
django-danceschool/django-danceschool
danceschool/vouchers/handlers.py
applyVoucherCodeTemporarily
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. ''' logger.debug('Signal fired to apply temporary vouchers.') reg = kwargs.pop('registration') voucherId = reg.data.get('gift','') try: voucher = Voucher.objects.get(voucherId=voucherId) except ObjectDoesNotExist: logger.debug('No applicable vouchers found.') return tvu = TemporaryVoucherUse(voucher=voucher,registration=reg,amount=0) tvu.save() logger.debug('Temporary voucher use object created.')
python
def applyVoucherCodeTemporarily(sender,**kwargs): logger.debug('Signal fired to apply temporary vouchers.') reg = kwargs.pop('registration') voucherId = reg.data.get('gift','') try: voucher = Voucher.objects.get(voucherId=voucherId) except ObjectDoesNotExist: logger.debug('No applicable vouchers found.') return tvu = TemporaryVoucherUse(voucher=voucher,registration=reg,amount=0) tvu.save() logger.debug('Temporary voucher use object created.')
[ "def", "applyVoucherCodeTemporarily", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Signal fired to apply temporary vouchers.'", ")", "reg", "=", "kwargs", ".", "pop", "(", "'registration'", ")", "voucherId", "=", "reg", ".", "data", ".", "get", "(", "'gift'", ",", "''", ")", "try", ":", "voucher", "=", "Voucher", ".", "objects", ".", "get", "(", "voucherId", "=", "voucherId", ")", "except", "ObjectDoesNotExist", ":", "logger", ".", "debug", "(", "'No applicable vouchers found.'", ")", "return", "tvu", "=", "TemporaryVoucherUse", "(", "voucher", "=", "voucher", ",", "registration", "=", "reg", ",", "amount", "=", "0", ")", "tvu", ".", "save", "(", ")", "logger", ".", "debug", "(", "'Temporary voucher use object created.'", ")" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L75-L94
django-danceschool/django-danceschool
danceschool/vouchers/handlers.py
applyReferrerVouchersTemporarily
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('referrals__enableReferralProgram'): return logger.debug('Signal fired to temporarily apply referrer vouchers.') reg = kwargs.pop('registration') # Email address is unique for users, so use that try: c = Customer.objects.get(user__email=reg.email) vouchers = c.getReferralVouchers() except ObjectDoesNotExist: vouchers = None if not vouchers: logger.debug('No referral vouchers found.') return for v in vouchers: TemporaryVoucherUse(voucher=v,registration=reg,amount=0).save()
python
def applyReferrerVouchersTemporarily(sender,**kwargs): if not getConstant('referrals__enableReferralProgram'): return logger.debug('Signal fired to temporarily apply referrer vouchers.') reg = kwargs.pop('registration') try: c = Customer.objects.get(user__email=reg.email) vouchers = c.getReferralVouchers() except ObjectDoesNotExist: vouchers = None if not vouchers: logger.debug('No referral vouchers found.') return for v in vouchers: TemporaryVoucherUse(voucher=v,registration=reg,amount=0).save()
[ "def", "applyReferrerVouchersTemporarily", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "# Only continue if the referral program is enabled\r", "if", "not", "getConstant", "(", "'referrals__enableReferralProgram'", ")", ":", "return", "logger", ".", "debug", "(", "'Signal fired to temporarily apply referrer vouchers.'", ")", "reg", "=", "kwargs", ".", "pop", "(", "'registration'", ")", "# Email address is unique for users, so use that\r", "try", ":", "c", "=", "Customer", ".", "objects", ".", "get", "(", "user__email", "=", "reg", ".", "email", ")", "vouchers", "=", "c", ".", "getReferralVouchers", "(", ")", "except", "ObjectDoesNotExist", ":", "vouchers", "=", "None", "if", "not", "vouchers", ":", "logger", ".", "debug", "(", "'No referral vouchers found.'", ")", "return", "for", "v", "in", "vouchers", ":", "TemporaryVoucherUse", "(", "voucher", "=", "v", ",", "registration", "=", "reg", ",", "amount", "=", "0", ")", ".", "save", "(", ")" ]
Unlike voucher codes which have to be manually supplied, referrer discounts are automatically applied here, assuming that the referral program is enabled.
[ "Unlike", "voucher", "codes", "which", "have", "to", "be", "manually", "supplied", "referrer", "discounts", "are", "automatically", "applied", "here", "assuming", "that", "the", "referral", "program", "is", "enabled", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L98-L124
django-danceschool/django-danceschool
danceschool/vouchers/handlers.py
applyVoucherCodesFinal
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 = TemporaryVoucherUse.objects.filter(registration=tr) for tvu in tvus: vu = VoucherUse(voucher=tvu.voucher,registration=finalReg,amount=tvu.amount) vu.save() if getConstant('referrals__enableReferralProgram'): awardReferrers(vu)
python
def applyVoucherCodesFinal(sender,**kwargs): logger.debug('Signal fired to mark voucher codes as applied.') finalReg = kwargs.pop('registration') tr = finalReg.temporaryRegistration tvus = TemporaryVoucherUse.objects.filter(registration=tr) for tvu in tvus: vu = VoucherUse(voucher=tvu.voucher,registration=finalReg,amount=tvu.amount) vu.save() if getConstant('referrals__enableReferralProgram'): awardReferrers(vu)
[ "def", "applyVoucherCodesFinal", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Signal fired to mark voucher codes as applied.'", ")", "finalReg", "=", "kwargs", ".", "pop", "(", "'registration'", ")", "tr", "=", "finalReg", ".", "temporaryRegistration", "tvus", "=", "TemporaryVoucherUse", ".", "objects", ".", "filter", "(", "registration", "=", "tr", ")", "for", "tvu", "in", "tvus", ":", "vu", "=", "VoucherUse", "(", "voucher", "=", "tvu", ".", "voucher", ",", "registration", "=", "finalReg", ",", "amount", "=", "tvu", ".", "amount", ")", "vu", ".", "save", "(", ")", "if", "getConstant", "(", "'referrals__enableReferralProgram'", ")", ":", "awardReferrers", "(", "vu", ")" ]
Once a registration has been completed, vouchers are used and referrers are awarded
[ "Once", "a", "registration", "has", "been", "completed", "vouchers", "are", "used", "and", "referrers", "are", "awarded" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L170-L185
django-danceschool/django-danceschool
danceschool/vouchers/handlers.py
provideCustomerReferralCode
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__enableReferralProgram'): vrd = ensureReferralVouchersExist(customer) return { 'referralVoucherId': vrd.referreeVoucher.voucherId }
python
def provideCustomerReferralCode(sender,**kwargs): customer = kwargs.pop('customer') if getConstant('vouchers__enableVouchers') and getConstant('referrals__enableReferralProgram'): vrd = ensureReferralVouchersExist(customer) return { 'referralVoucherId': vrd.referreeVoucher.voucherId }
[ "def", "provideCustomerReferralCode", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "customer", "=", "kwargs", ".", "pop", "(", "'customer'", ")", "if", "getConstant", "(", "'vouchers__enableVouchers'", ")", "and", "getConstant", "(", "'referrals__enableReferralProgram'", ")", ":", "vrd", "=", "ensureReferralVouchersExist", "(", "customer", ")", "return", "{", "'referralVoucherId'", ":", "vrd", ".", "referreeVoucher", ".", "voucherId", "}" ]
If the vouchers app is installed and referrals are enabled, then the customer's profile page can show their voucher referral code.
[ "If", "the", "vouchers", "app", "is", "installed", "and", "referrals", "are", "enabled", "then", "the", "customer", "s", "profile", "page", "can", "show", "their", "voucher", "referral", "code", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L189-L199
django-danceschool/django-danceschool
danceschool/core/constants.py
getConstant
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 global preferences if 'dynamic_preferences_globalpreferencemodel' in connection.introspection.table_names() and not isPreliminaryRun(): params = global_preferences_registry.manager() try: return params.get(name) except NotFoundInRegistry as e: logger.error('Error in getting constant: %s' % e) return None
python
def getConstant(name): if 'dynamic_preferences_globalpreferencemodel' in connection.introspection.table_names() and not isPreliminaryRun(): params = global_preferences_registry.manager() try: return params.get(name) except NotFoundInRegistry as e: logger.error('Error in getting constant: %s' % e) return None
[ "def", "getConstant", "(", "name", ")", ":", "# We instantiate a manager for our global preferences", "if", "'dynamic_preferences_globalpreferencemodel'", "in", "connection", ".", "introspection", ".", "table_names", "(", ")", "and", "not", "isPreliminaryRun", "(", ")", ":", "params", "=", "global_preferences_registry", ".", "manager", "(", ")", "try", ":", "return", "params", ".", "get", "(", "name", ")", "except", "NotFoundInRegistry", "as", "e", ":", "logger", ".", "error", "(", "'Error in getting constant: %s'", "%", "e", ")", "return", "None" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/constants.py#L15-L29
django-danceschool/django-danceschool
danceschool/core/constants.py
updateConstant
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 suppress any errors (e.g. KeyErrors resulting from the order in which apps are loaded). ''' # We instantiate a manager for our global preferences if 'dynamic_preferences_globalpreferencemodel' in connection.introspection.table_names() and not isPreliminaryRun(): params = global_preferences_registry.manager() try: params[name] = value return True except Exception as e: logger.error('Error in updating constant: %s' % e) if not fail_silently: raise return False
python
def updateConstant(name,value,fail_silently=False): if 'dynamic_preferences_globalpreferencemodel' in connection.introspection.table_names() and not isPreliminaryRun(): params = global_preferences_registry.manager() try: params[name] = value return True except Exception as e: logger.error('Error in updating constant: %s' % e) if not fail_silently: raise return False
[ "def", "updateConstant", "(", "name", ",", "value", ",", "fail_silently", "=", "False", ")", ":", "# We instantiate a manager for our global preferences", "if", "'dynamic_preferences_globalpreferencemodel'", "in", "connection", ".", "introspection", ".", "table_names", "(", ")", "and", "not", "isPreliminaryRun", "(", ")", ":", "params", "=", "global_preferences_registry", ".", "manager", "(", ")", "try", ":", "params", "[", "name", "]", "=", "value", "return", "True", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Error in updating constant: %s'", "%", "e", ")", "if", "not", "fail_silently", ":", "raise", "return", "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 suppress any errors (e.g. KeyErrors resulting from the order in which apps are loaded).
[ "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", "suppress", "any", "errors", "(", "e", ".", "g", ".", "KeyErrors", "resulting", "from", "the", "order", "in", "which", "apps", "are", "loaded", ")", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/constants.py#L32-L50
django-danceschool/django-danceschool
danceschool/payments/square/views.py
processSquarePayment
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 requests). ''' logger.info('Received request for Square Checkout payment.') nonce_id = request.POST.get('nonce') invoice_id = request.POST.get('invoice_id') tr_id = request.POST.get('reg_id') amount = request.POST.get('amount') submissionUserId = request.POST.get('user_id') transactionType = request.POST.get('transaction_type') taxable = request.POST.get('taxable', False) sourceUrl = request.POST.get('sourceUrl', reverse('showRegSummary')) addSessionInfo = request.POST.get('addSessionInfo',False) successUrl = request.POST.get('successUrl',reverse('registration')) customerEmail = request.POST.get('customerEmail') # If a specific amount to pay has been passed, then allow payment # of that amount. if amount: try: amount = float(amount) except ValueError: logger.error('Invalid amount passed') messages.error( request, format_html( '<p>{}</p><ul><li>{}</li></ul>', str(_('ERROR: Error with Square checkout transaction attempt.')), str(_('Invalid amount passed.')) ) ) return HttpResponseRedirect(sourceUrl) # Parse if a specific submission user is indicated submissionUser = None if submissionUserId: try: submissionUser = User.objects.get(id=int(submissionUserId)) except (ValueError, ObjectDoesNotExist): logger.warning('Invalid user passed, submissionUser will not be recorded.') try: # Invoice transactions are usually payment on an existing invoice. if invoice_id: this_invoice = Invoice.objects.get(id=invoice_id) this_description = _('Invoice Payment: %s' % this_invoice.id) if not amount: amount = this_invoice.outstandingBalance # This is typical of payment at the time of registration elif tr_id: tr = TemporaryRegistration.objects.get(id=int(tr_id)) tr.expirationDate = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) tr.save() this_invoice = Invoice.get_or_create_from_registration(tr, submissionUser=submissionUser) this_description = _('Registration Payment: #%s' % tr_id) if not amount: amount = this_invoice.outstandingBalance # All other transactions require both a transaction type and an amount to be specified elif not transactionType or not amount: logger.error('Insufficient information passed to createSquarePayment view.') messages.error( request, format_html( '<p>{}</p><ul><li>{}</li></ul>', str(_('ERROR: Error with Square checkout transaction attempt.')), str(_('Insufficient information passed to createSquarePayment view.')) ) ) return HttpResponseRedirect(sourceUrl) else: # Gift certificates automatically get a nicer invoice description if transactionType == 'Gift Certificate': this_description = _('Gift Certificate Purchase') else: this_description = transactionType this_invoice = Invoice.create_from_item( float(amount), this_description, submissionUser=submissionUser, calculate_taxes=(taxable is not False), transactionType=transactionType, ) except (ValueError, ObjectDoesNotExist) as e: logger.error('Invalid registration information passed to createSquarePayment view: (%s, %s, %s)' % (invoice_id, tr_id, amount)) messages.error( request, format_html( '<p>{}</p><ul><li>{}</li></ul>', str(_('ERROR: Error with Square checkout transaction attempt.')), str(_('Invalid registration information passed to createSquarePayment view: (%s, %s, %s)' % (invoice_id, tr_id, amount))) ) ) return HttpResponseRedirect(sourceUrl) this_currency = getConstant('general__currencyCode') this_total = min(this_invoice.outstandingBalance, amount) api_instance = TransactionsApi() api_instance.api_client.configuration.access_token = getattr(settings,'SQUARE_ACCESS_TOKEN','') idempotency_key = str(uuid.uuid1()) location_id = getattr(settings,'SQUARE_LOCATION_ID','') amount = {'amount': int(100 * this_total), 'currency': this_currency} body = {'idempotency_key': idempotency_key, 'card_nonce': nonce_id, 'amount_money': amount} errors_list = [] try: # Charge api_response = api_instance.charge(location_id, body) if api_response.errors: logger.error('Error in charging Square transaction: %s' % api_response.errors) errors_list = api_response.errors except ApiException as e: logger.error('Exception when calling TransactionApi->charge: %s\n' % e) errors_list = json.loads(e.body).get('errors',[]) if errors_list: this_invoice.status = Invoice.PaymentStatus.error this_invoice.save() errors_string = '' for err in errors_list: errors_string += '<li><strong>CODE:</strong> %s, %s</li>' % ( err.get('code',str(_('Unknown'))), err.get('detail',str(_('Unknown'))) ) messages.error( request, format_html( '<p>{}</p><ul>{}</ul>', str(_('ERROR: Error with Square checkout transaction attempt.')), mark_safe(errors_list), ) ) return HttpResponseRedirect(sourceUrl) else: logger.info('Square charge successfully created.') transaction = api_response.transaction paymentRecord = SquarePaymentRecord.objects.create( invoice=this_invoice, transactionId=transaction.id, locationId=transaction.location_id, ) # We process the payment now, and enqueue the job to retrieve the # transaction again once fees have been calculated by Square this_invoice.processPayment( amount=this_total, fees=0, paidOnline=True, methodName='Square Checkout', methodTxn=transaction.id, notify=customerEmail, ) updateSquareFees.schedule(args=(paymentRecord,), delay=60) if addSessionInfo: paymentSession = request.session.get(INVOICE_VALIDATION_STR, {}) paymentSession.update({ 'invoiceID': str(this_invoice.id), 'amount': this_total, 'successUrl': successUrl, }) request.session[INVOICE_VALIDATION_STR] = paymentSession return HttpResponseRedirect(successUrl)
python
def processSquarePayment(request): logger.info('Received request for Square Checkout payment.') nonce_id = request.POST.get('nonce') invoice_id = request.POST.get('invoice_id') tr_id = request.POST.get('reg_id') amount = request.POST.get('amount') submissionUserId = request.POST.get('user_id') transactionType = request.POST.get('transaction_type') taxable = request.POST.get('taxable', False) sourceUrl = request.POST.get('sourceUrl', reverse('showRegSummary')) addSessionInfo = request.POST.get('addSessionInfo',False) successUrl = request.POST.get('successUrl',reverse('registration')) customerEmail = request.POST.get('customerEmail') if amount: try: amount = float(amount) except ValueError: logger.error('Invalid amount passed') messages.error( request, format_html( '<p>{}</p><ul><li>{}</li></ul>', str(_('ERROR: Error with Square checkout transaction attempt.')), str(_('Invalid amount passed.')) ) ) return HttpResponseRedirect(sourceUrl) submissionUser = None if submissionUserId: try: submissionUser = User.objects.get(id=int(submissionUserId)) except (ValueError, ObjectDoesNotExist): logger.warning('Invalid user passed, submissionUser will not be recorded.') try: if invoice_id: this_invoice = Invoice.objects.get(id=invoice_id) this_description = _('Invoice Payment: %s' % this_invoice.id) if not amount: amount = this_invoice.outstandingBalance elif tr_id: tr = TemporaryRegistration.objects.get(id=int(tr_id)) tr.expirationDate = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) tr.save() this_invoice = Invoice.get_or_create_from_registration(tr, submissionUser=submissionUser) this_description = _('Registration Payment: if not amount: amount = this_invoice.outstandingBalance elif not transactionType or not amount: logger.error('Insufficient information passed to createSquarePayment view.') messages.error( request, format_html( '<p>{}</p><ul><li>{}</li></ul>', str(_('ERROR: Error with Square checkout transaction attempt.')), str(_('Insufficient information passed to createSquarePayment view.')) ) ) return HttpResponseRedirect(sourceUrl) else: if transactionType == 'Gift Certificate': this_description = _('Gift Certificate Purchase') else: this_description = transactionType this_invoice = Invoice.create_from_item( float(amount), this_description, submissionUser=submissionUser, calculate_taxes=(taxable is not False), transactionType=transactionType, ) except (ValueError, ObjectDoesNotExist) as e: logger.error('Invalid registration information passed to createSquarePayment view: (%s, %s, %s)' % (invoice_id, tr_id, amount)) messages.error( request, format_html( '<p>{}</p><ul><li>{}</li></ul>', str(_('ERROR: Error with Square checkout transaction attempt.')), str(_('Invalid registration information passed to createSquarePayment view: (%s, %s, %s)' % (invoice_id, tr_id, amount))) ) ) return HttpResponseRedirect(sourceUrl) this_currency = getConstant('general__currencyCode') this_total = min(this_invoice.outstandingBalance, amount) api_instance = TransactionsApi() api_instance.api_client.configuration.access_token = getattr(settings,'SQUARE_ACCESS_TOKEN','') idempotency_key = str(uuid.uuid1()) location_id = getattr(settings,'SQUARE_LOCATION_ID','') amount = {'amount': int(100 * this_total), 'currency': this_currency} body = {'idempotency_key': idempotency_key, 'card_nonce': nonce_id, 'amount_money': amount} errors_list = [] try: api_response = api_instance.charge(location_id, body) if api_response.errors: logger.error('Error in charging Square transaction: %s' % api_response.errors) errors_list = api_response.errors except ApiException as e: logger.error('Exception when calling TransactionApi->charge: %s\n' % e) errors_list = json.loads(e.body).get('errors',[]) if errors_list: this_invoice.status = Invoice.PaymentStatus.error this_invoice.save() errors_string = '' for err in errors_list: errors_string += '<li><strong>CODE:</strong> %s, %s</li>' % ( err.get('code',str(_('Unknown'))), err.get('detail',str(_('Unknown'))) ) messages.error( request, format_html( '<p>{}</p><ul>{}</ul>', str(_('ERROR: Error with Square checkout transaction attempt.')), mark_safe(errors_list), ) ) return HttpResponseRedirect(sourceUrl) else: logger.info('Square charge successfully created.') transaction = api_response.transaction paymentRecord = SquarePaymentRecord.objects.create( invoice=this_invoice, transactionId=transaction.id, locationId=transaction.location_id, ) this_invoice.processPayment( amount=this_total, fees=0, paidOnline=True, methodName='Square Checkout', methodTxn=transaction.id, notify=customerEmail, ) updateSquareFees.schedule(args=(paymentRecord,), delay=60) if addSessionInfo: paymentSession = request.session.get(INVOICE_VALIDATION_STR, {}) paymentSession.update({ 'invoiceID': str(this_invoice.id), 'amount': this_total, 'successUrl': successUrl, }) request.session[INVOICE_VALIDATION_STR] = paymentSession return HttpResponseRedirect(successUrl)
[ "def", "processSquarePayment", "(", "request", ")", ":", "logger", ".", "info", "(", "'Received request for Square Checkout payment.'", ")", "nonce_id", "=", "request", ".", "POST", ".", "get", "(", "'nonce'", ")", "invoice_id", "=", "request", ".", "POST", ".", "get", "(", "'invoice_id'", ")", "tr_id", "=", "request", ".", "POST", ".", "get", "(", "'reg_id'", ")", "amount", "=", "request", ".", "POST", ".", "get", "(", "'amount'", ")", "submissionUserId", "=", "request", ".", "POST", ".", "get", "(", "'user_id'", ")", "transactionType", "=", "request", ".", "POST", ".", "get", "(", "'transaction_type'", ")", "taxable", "=", "request", ".", "POST", ".", "get", "(", "'taxable'", ",", "False", ")", "sourceUrl", "=", "request", ".", "POST", ".", "get", "(", "'sourceUrl'", ",", "reverse", "(", "'showRegSummary'", ")", ")", "addSessionInfo", "=", "request", ".", "POST", ".", "get", "(", "'addSessionInfo'", ",", "False", ")", "successUrl", "=", "request", ".", "POST", ".", "get", "(", "'successUrl'", ",", "reverse", "(", "'registration'", ")", ")", "customerEmail", "=", "request", ".", "POST", ".", "get", "(", "'customerEmail'", ")", "# If a specific amount to pay has been passed, then allow payment", "# of that amount.", "if", "amount", ":", "try", ":", "amount", "=", "float", "(", "amount", ")", "except", "ValueError", ":", "logger", ".", "error", "(", "'Invalid amount passed'", ")", "messages", ".", "error", "(", "request", ",", "format_html", "(", "'<p>{}</p><ul><li>{}</li></ul>'", ",", "str", "(", "_", "(", "'ERROR: Error with Square checkout transaction attempt.'", ")", ")", ",", "str", "(", "_", "(", "'Invalid amount passed.'", ")", ")", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "# Parse if a specific submission user is indicated", "submissionUser", "=", "None", "if", "submissionUserId", ":", "try", ":", "submissionUser", "=", "User", ".", "objects", ".", "get", "(", "id", "=", "int", "(", "submissionUserId", ")", ")", "except", "(", "ValueError", ",", "ObjectDoesNotExist", ")", ":", "logger", ".", "warning", "(", "'Invalid user passed, submissionUser will not be recorded.'", ")", "try", ":", "# Invoice transactions are usually payment on an existing invoice.", "if", "invoice_id", ":", "this_invoice", "=", "Invoice", ".", "objects", ".", "get", "(", "id", "=", "invoice_id", ")", "this_description", "=", "_", "(", "'Invoice Payment: %s'", "%", "this_invoice", ".", "id", ")", "if", "not", "amount", ":", "amount", "=", "this_invoice", ".", "outstandingBalance", "# This is typical of payment at the time of registration", "elif", "tr_id", ":", "tr", "=", "TemporaryRegistration", ".", "objects", ".", "get", "(", "id", "=", "int", "(", "tr_id", ")", ")", "tr", ".", "expirationDate", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "minutes", "=", "getConstant", "(", "'registration__sessionExpiryMinutes'", ")", ")", "tr", ".", "save", "(", ")", "this_invoice", "=", "Invoice", ".", "get_or_create_from_registration", "(", "tr", ",", "submissionUser", "=", "submissionUser", ")", "this_description", "=", "_", "(", "'Registration Payment: #%s'", "%", "tr_id", ")", "if", "not", "amount", ":", "amount", "=", "this_invoice", ".", "outstandingBalance", "# All other transactions require both a transaction type and an amount to be specified", "elif", "not", "transactionType", "or", "not", "amount", ":", "logger", ".", "error", "(", "'Insufficient information passed to createSquarePayment view.'", ")", "messages", ".", "error", "(", "request", ",", "format_html", "(", "'<p>{}</p><ul><li>{}</li></ul>'", ",", "str", "(", "_", "(", "'ERROR: Error with Square checkout transaction attempt.'", ")", ")", ",", "str", "(", "_", "(", "'Insufficient information passed to createSquarePayment view.'", ")", ")", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "else", ":", "# Gift certificates automatically get a nicer invoice description", "if", "transactionType", "==", "'Gift Certificate'", ":", "this_description", "=", "_", "(", "'Gift Certificate Purchase'", ")", "else", ":", "this_description", "=", "transactionType", "this_invoice", "=", "Invoice", ".", "create_from_item", "(", "float", "(", "amount", ")", ",", "this_description", ",", "submissionUser", "=", "submissionUser", ",", "calculate_taxes", "=", "(", "taxable", "is", "not", "False", ")", ",", "transactionType", "=", "transactionType", ",", ")", "except", "(", "ValueError", ",", "ObjectDoesNotExist", ")", "as", "e", ":", "logger", ".", "error", "(", "'Invalid registration information passed to createSquarePayment view: (%s, %s, %s)'", "%", "(", "invoice_id", ",", "tr_id", ",", "amount", ")", ")", "messages", ".", "error", "(", "request", ",", "format_html", "(", "'<p>{}</p><ul><li>{}</li></ul>'", ",", "str", "(", "_", "(", "'ERROR: Error with Square checkout transaction attempt.'", ")", ")", ",", "str", "(", "_", "(", "'Invalid registration information passed to createSquarePayment view: (%s, %s, %s)'", "%", "(", "invoice_id", ",", "tr_id", ",", "amount", ")", ")", ")", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "this_currency", "=", "getConstant", "(", "'general__currencyCode'", ")", "this_total", "=", "min", "(", "this_invoice", ".", "outstandingBalance", ",", "amount", ")", "api_instance", "=", "TransactionsApi", "(", ")", "api_instance", ".", "api_client", ".", "configuration", ".", "access_token", "=", "getattr", "(", "settings", ",", "'SQUARE_ACCESS_TOKEN'", ",", "''", ")", "idempotency_key", "=", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "location_id", "=", "getattr", "(", "settings", ",", "'SQUARE_LOCATION_ID'", ",", "''", ")", "amount", "=", "{", "'amount'", ":", "int", "(", "100", "*", "this_total", ")", ",", "'currency'", ":", "this_currency", "}", "body", "=", "{", "'idempotency_key'", ":", "idempotency_key", ",", "'card_nonce'", ":", "nonce_id", ",", "'amount_money'", ":", "amount", "}", "errors_list", "=", "[", "]", "try", ":", "# Charge", "api_response", "=", "api_instance", ".", "charge", "(", "location_id", ",", "body", ")", "if", "api_response", ".", "errors", ":", "logger", ".", "error", "(", "'Error in charging Square transaction: %s'", "%", "api_response", ".", "errors", ")", "errors_list", "=", "api_response", ".", "errors", "except", "ApiException", "as", "e", ":", "logger", ".", "error", "(", "'Exception when calling TransactionApi->charge: %s\\n'", "%", "e", ")", "errors_list", "=", "json", ".", "loads", "(", "e", ".", "body", ")", ".", "get", "(", "'errors'", ",", "[", "]", ")", "if", "errors_list", ":", "this_invoice", ".", "status", "=", "Invoice", ".", "PaymentStatus", ".", "error", "this_invoice", ".", "save", "(", ")", "errors_string", "=", "''", "for", "err", "in", "errors_list", ":", "errors_string", "+=", "'<li><strong>CODE:</strong> %s, %s</li>'", "%", "(", "err", ".", "get", "(", "'code'", ",", "str", "(", "_", "(", "'Unknown'", ")", ")", ")", ",", "err", ".", "get", "(", "'detail'", ",", "str", "(", "_", "(", "'Unknown'", ")", ")", ")", ")", "messages", ".", "error", "(", "request", ",", "format_html", "(", "'<p>{}</p><ul>{}</ul>'", ",", "str", "(", "_", "(", "'ERROR: Error with Square checkout transaction attempt.'", ")", ")", ",", "mark_safe", "(", "errors_list", ")", ",", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "else", ":", "logger", ".", "info", "(", "'Square charge successfully created.'", ")", "transaction", "=", "api_response", ".", "transaction", "paymentRecord", "=", "SquarePaymentRecord", ".", "objects", ".", "create", "(", "invoice", "=", "this_invoice", ",", "transactionId", "=", "transaction", ".", "id", ",", "locationId", "=", "transaction", ".", "location_id", ",", ")", "# We process the payment now, and enqueue the job to retrieve the", "# transaction again once fees have been calculated by Square", "this_invoice", ".", "processPayment", "(", "amount", "=", "this_total", ",", "fees", "=", "0", ",", "paidOnline", "=", "True", ",", "methodName", "=", "'Square Checkout'", ",", "methodTxn", "=", "transaction", ".", "id", ",", "notify", "=", "customerEmail", ",", ")", "updateSquareFees", ".", "schedule", "(", "args", "=", "(", "paymentRecord", ",", ")", ",", "delay", "=", "60", ")", "if", "addSessionInfo", ":", "paymentSession", "=", "request", ".", "session", ".", "get", "(", "INVOICE_VALIDATION_STR", ",", "{", "}", ")", "paymentSession", ".", "update", "(", "{", "'invoiceID'", ":", "str", "(", "this_invoice", ".", "id", ")", ",", "'amount'", ":", "this_total", ",", "'successUrl'", ":", "successUrl", ",", "}", ")", "request", ".", "session", "[", "INVOICE_VALIDATION_STR", "]", "=", "paymentSession", "return", "HttpResponseRedirect", "(", "successUrl", ")" ]
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 requests).
[ "This", "view", "handles", "the", "charging", "of", "approved", "Square", "Checkout", "payments", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/square/views.py#L33-L205
django-danceschool/django-danceschool
danceschool/payments/square/views.py
processPointOfSalePayment
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 response information in the data key: data = json.loads(request.GET.get('data','{}')) if data: status = data.get('status') errorCode = data.get('error_code') errorDescription = errorCode try: stateData = data.get('state','') if stateData: metadata = json.loads(b64decode(unquote(stateData).encode()).decode()) else: metadata = {} except (TypeError, ValueError, binascii.Error): logger.error('Invalid metadata passed from Square app.') messages.error( request, format_html( '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>', str(_('ERROR: Error with Square point of sale transaction attempt.')), str(_('Invalid metadata passed from Square app.')), ) ) return HttpResponseRedirect(reverse('showRegSummary')) # This is the normal transaction identifier, which will be stored in the # database as a SquarePaymentRecord serverTransId = data.get('transaction_id') # This is the only identifier passed for non-card transactions. clientTransId = data.get('client_transaction_id') else: # Android transactions use this GET response syntax errorCode = request.GET.get('com.squareup.pos.ERROR_CODE') errorDescription = request.GET.get('com.squareup.pos.ERROR_DESCRIPTION') status = 'ok' if not errorCode else 'error' # This is the normal transaction identifier, which will be stored in the # database as a SquarePaymentRecord serverTransId = request.GET.get('com.squareup.pos.SERVER_TRANSACTION_ID') # This is the only identifier passed for non-card transactions. clientTransId = request.GET.get('com.squareup.pos.CLIENT_TRANSACTION_ID') # Load the metadata, which includes the registration or invoice ids try: stateData = request.GET.get('com.squareup.pos.REQUEST_METADATA','') if stateData: metadata = json.loads(b64decode(unquote(stateData).encode()).decode()) else: metadata = {} except (TypeError, ValueError, binascii.Error): logger.error('Invalid metadata passed from Square app.') messages.error( request, format_html( '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>', str(_('ERROR: Error with Square point of sale transaction attempt.')), str(_('Invalid metadata passed from Square app.')), ) ) return HttpResponseRedirect(reverse('showRegSummary')) # Other things that can be passed in the metadata sourceUrl = metadata.get('sourceUrl',reverse('showRegSummary')) successUrl = metadata.get('successUrl',reverse('registration')) submissionUserId = metadata.get('userId', getattr(getattr(request,'user',None),'id',None)) transactionType = metadata.get('transaction_type') taxable = metadata.get('taxable', False) addSessionInfo = metadata.get('addSessionInfo',False) customerEmail = metadata.get('customerEmail') if errorCode or status != 'ok': # Return the user to their original page with the error message displayed. logger.error('Error with Square point of sale transaction attempt. CODE: %s; DESCRIPTION: %s' % (errorCode, errorDescription)) messages.error( request, format_html( '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>', str(_('ERROR: Error with Square point of sale transaction attempt.')), errorCode, errorDescription ) ) return HttpResponseRedirect(sourceUrl) api_instance = TransactionsApi() api_instance.api_client.configuration.access_token = getattr(settings,'SQUARE_ACCESS_TOKEN','') location_id = getattr(settings,'SQUARE_LOCATION_ID','') if serverTransId: try: api_response = api_instance.retrieve_transaction(transaction_id=serverTransId,location_id=location_id) except ApiException: logger.error('Unable to find Square transaction by server ID.') messages.error(request,_('ERROR: Unable to find Square transaction by server ID.')) return HttpResponseRedirect(sourceUrl) if api_response.errors: logger.error('Unable to find Square transaction by server ID: %s' % api_response.errors) messages.error(request,str(_('ERROR: Unable to find Square transaction by server ID:')) + api_response.errors) return HttpResponseRedirect(sourceUrl) transaction = api_response.transaction elif clientTransId: # Try to find the transaction in the 50 most recent transactions try: api_response = api_instance.list_transactions(location_id=location_id) except ApiException: logger.error('Unable to find Square transaction by client ID.') messages.error(request,_('ERROR: Unable to find Square transaction by client ID.')) return HttpResponseRedirect(sourceUrl) if api_response.errors: logger.error('Unable to find Square transaction by client ID: %s' % api_response.errors) messages.error(request,str(_('ERROR: Unable to find Square transaction by client ID:')) + api_response.errors) return HttpResponseRedirect(sourceUrl) transactions_list = [x for x in api_response.transactions if x.client_id == clientTransId] if len(transactions_list) == 1: transaction = transactions_list[0] else: logger.error('Returned client transaction ID not found.') messages.error(request,_('ERROR: Returned client transaction ID not found.')) return HttpResponseRedirect(sourceUrl) else: logger.error('An unknown error has occurred with Square point of sale transaction attempt.') messages.error(request,_('ERROR: An unknown error has occurred with Square point of sale transaction attempt.')) return HttpResponseRedirect(sourceUrl) # Get total information from the transaction for handling invoice. this_total = sum([x.amount_money.amount / 100 for x in transaction.tenders or []]) - \ sum([x.amount_money.amount / 100 for x in transaction.refunds or []]) # Parse if a specific submission user is indicated submissionUser = None if submissionUserId: try: submissionUser = User.objects.get(id=int(submissionUserId)) except (ValueError, ObjectDoesNotExist): logger.warning('Invalid user passed, submissionUser will not be recorded.') if 'registration' in metadata.keys(): try: tr_id = int(metadata.get('registration')) tr = TemporaryRegistration.objects.get(id=tr_id) except (ValueError, TypeError, ObjectDoesNotExist): logger.error('Invalid registration ID passed: %s' % metadata.get('registration')) messages.error( request, str(_('ERROR: Invalid registration ID passed')) + ': %s' % metadata.get('registration') ) return HttpResponseRedirect(sourceUrl) tr.expirationDate = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) tr.save() this_invoice = Invoice.get_or_create_from_registration(tr, submissionUser=submissionUser) this_description = _('Registration Payment: #%s' % tr_id) elif 'invoice' in metadata.keys(): try: this_invoice = Invoice.objects.get(id=int(metadata.get('invoice'))) this_description = _('Invoice Payment: %s' % this_invoice.id) except (ValueError, TypeError, ObjectDoesNotExist): logger.error('Invalid invoice ID passed: %s' % metadata.get('invoice')) messages.error( request, str(_('ERROR: Invalid invoice ID passed')) + ': %s' % metadata.get('invoice') ) return HttpResponseRedirect(sourceUrl) else: # Gift certificates automatically get a nicer invoice description if transactionType == 'Gift Certificate': this_description = _('Gift Certificate Purchase') else: this_description = transactionType this_invoice = Invoice.create_from_item( this_total, this_description, submissionUser=submissionUser, calculate_taxes=(taxable is not False), transactionType=transactionType, ) paymentRecord, created = SquarePaymentRecord.objects.get_or_create( transactionId=transaction.id, locationId=transaction.location_id, defaults={'invoice': this_invoice,} ) if created: # We process the payment now, and enqueue the job to retrieve the # transaction again once fees have been calculated by Square this_invoice.processPayment( amount=this_total, fees=0, paidOnline=True, methodName='Square Point of Sale', methodTxn=transaction.id, notify=customerEmail, ) updateSquareFees.schedule(args=(paymentRecord,), delay=60) if addSessionInfo: paymentSession = request.session.get(INVOICE_VALIDATION_STR, {}) paymentSession.update({ 'invoiceID': str(this_invoice.id), 'amount': this_total, 'successUrl': successUrl, }) request.session[INVOICE_VALIDATION_STR] = paymentSession return HttpResponseRedirect(successUrl)
python
def processPointOfSalePayment(request): print('Request data is: %s' % request.GET) data = json.loads(request.GET.get('data','{}')) if data: status = data.get('status') errorCode = data.get('error_code') errorDescription = errorCode try: stateData = data.get('state','') if stateData: metadata = json.loads(b64decode(unquote(stateData).encode()).decode()) else: metadata = {} except (TypeError, ValueError, binascii.Error): logger.error('Invalid metadata passed from Square app.') messages.error( request, format_html( '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>', str(_('ERROR: Error with Square point of sale transaction attempt.')), str(_('Invalid metadata passed from Square app.')), ) ) return HttpResponseRedirect(reverse('showRegSummary')) serverTransId = data.get('transaction_id') clientTransId = data.get('client_transaction_id') else: errorCode = request.GET.get('com.squareup.pos.ERROR_CODE') errorDescription = request.GET.get('com.squareup.pos.ERROR_DESCRIPTION') status = 'ok' if not errorCode else 'error' serverTransId = request.GET.get('com.squareup.pos.SERVER_TRANSACTION_ID') clientTransId = request.GET.get('com.squareup.pos.CLIENT_TRANSACTION_ID') try: stateData = request.GET.get('com.squareup.pos.REQUEST_METADATA','') if stateData: metadata = json.loads(b64decode(unquote(stateData).encode()).decode()) else: metadata = {} except (TypeError, ValueError, binascii.Error): logger.error('Invalid metadata passed from Square app.') messages.error( request, format_html( '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>', str(_('ERROR: Error with Square point of sale transaction attempt.')), str(_('Invalid metadata passed from Square app.')), ) ) return HttpResponseRedirect(reverse('showRegSummary')) sourceUrl = metadata.get('sourceUrl',reverse('showRegSummary')) successUrl = metadata.get('successUrl',reverse('registration')) submissionUserId = metadata.get('userId', getattr(getattr(request,'user',None),'id',None)) transactionType = metadata.get('transaction_type') taxable = metadata.get('taxable', False) addSessionInfo = metadata.get('addSessionInfo',False) customerEmail = metadata.get('customerEmail') if errorCode or status != 'ok': logger.error('Error with Square point of sale transaction attempt. CODE: %s; DESCRIPTION: %s' % (errorCode, errorDescription)) messages.error( request, format_html( '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>', str(_('ERROR: Error with Square point of sale transaction attempt.')), errorCode, errorDescription ) ) return HttpResponseRedirect(sourceUrl) api_instance = TransactionsApi() api_instance.api_client.configuration.access_token = getattr(settings,'SQUARE_ACCESS_TOKEN','') location_id = getattr(settings,'SQUARE_LOCATION_ID','') if serverTransId: try: api_response = api_instance.retrieve_transaction(transaction_id=serverTransId,location_id=location_id) except ApiException: logger.error('Unable to find Square transaction by server ID.') messages.error(request,_('ERROR: Unable to find Square transaction by server ID.')) return HttpResponseRedirect(sourceUrl) if api_response.errors: logger.error('Unable to find Square transaction by server ID: %s' % api_response.errors) messages.error(request,str(_('ERROR: Unable to find Square transaction by server ID:')) + api_response.errors) return HttpResponseRedirect(sourceUrl) transaction = api_response.transaction elif clientTransId: try: api_response = api_instance.list_transactions(location_id=location_id) except ApiException: logger.error('Unable to find Square transaction by client ID.') messages.error(request,_('ERROR: Unable to find Square transaction by client ID.')) return HttpResponseRedirect(sourceUrl) if api_response.errors: logger.error('Unable to find Square transaction by client ID: %s' % api_response.errors) messages.error(request,str(_('ERROR: Unable to find Square transaction by client ID:')) + api_response.errors) return HttpResponseRedirect(sourceUrl) transactions_list = [x for x in api_response.transactions if x.client_id == clientTransId] if len(transactions_list) == 1: transaction = transactions_list[0] else: logger.error('Returned client transaction ID not found.') messages.error(request,_('ERROR: Returned client transaction ID not found.')) return HttpResponseRedirect(sourceUrl) else: logger.error('An unknown error has occurred with Square point of sale transaction attempt.') messages.error(request,_('ERROR: An unknown error has occurred with Square point of sale transaction attempt.')) return HttpResponseRedirect(sourceUrl) this_total = sum([x.amount_money.amount / 100 for x in transaction.tenders or []]) - \ sum([x.amount_money.amount / 100 for x in transaction.refunds or []]) submissionUser = None if submissionUserId: try: submissionUser = User.objects.get(id=int(submissionUserId)) except (ValueError, ObjectDoesNotExist): logger.warning('Invalid user passed, submissionUser will not be recorded.') if 'registration' in metadata.keys(): try: tr_id = int(metadata.get('registration')) tr = TemporaryRegistration.objects.get(id=tr_id) except (ValueError, TypeError, ObjectDoesNotExist): logger.error('Invalid registration ID passed: %s' % metadata.get('registration')) messages.error( request, str(_('ERROR: Invalid registration ID passed')) + ': %s' % metadata.get('registration') ) return HttpResponseRedirect(sourceUrl) tr.expirationDate = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) tr.save() this_invoice = Invoice.get_or_create_from_registration(tr, submissionUser=submissionUser) this_description = _('Registration Payment: elif 'invoice' in metadata.keys(): try: this_invoice = Invoice.objects.get(id=int(metadata.get('invoice'))) this_description = _('Invoice Payment: %s' % this_invoice.id) except (ValueError, TypeError, ObjectDoesNotExist): logger.error('Invalid invoice ID passed: %s' % metadata.get('invoice')) messages.error( request, str(_('ERROR: Invalid invoice ID passed')) + ': %s' % metadata.get('invoice') ) return HttpResponseRedirect(sourceUrl) else: if transactionType == 'Gift Certificate': this_description = _('Gift Certificate Purchase') else: this_description = transactionType this_invoice = Invoice.create_from_item( this_total, this_description, submissionUser=submissionUser, calculate_taxes=(taxable is not False), transactionType=transactionType, ) paymentRecord, created = SquarePaymentRecord.objects.get_or_create( transactionId=transaction.id, locationId=transaction.location_id, defaults={'invoice': this_invoice,} ) if created: this_invoice.processPayment( amount=this_total, fees=0, paidOnline=True, methodName='Square Point of Sale', methodTxn=transaction.id, notify=customerEmail, ) updateSquareFees.schedule(args=(paymentRecord,), delay=60) if addSessionInfo: paymentSession = request.session.get(INVOICE_VALIDATION_STR, {}) paymentSession.update({ 'invoiceID': str(this_invoice.id), 'amount': this_total, 'successUrl': successUrl, }) request.session[INVOICE_VALIDATION_STR] = paymentSession return HttpResponseRedirect(successUrl)
[ "def", "processPointOfSalePayment", "(", "request", ")", ":", "print", "(", "'Request data is: %s'", "%", "request", ".", "GET", ")", "# iOS transactions put all response information in the data key:", "data", "=", "json", ".", "loads", "(", "request", ".", "GET", ".", "get", "(", "'data'", ",", "'{}'", ")", ")", "if", "data", ":", "status", "=", "data", ".", "get", "(", "'status'", ")", "errorCode", "=", "data", ".", "get", "(", "'error_code'", ")", "errorDescription", "=", "errorCode", "try", ":", "stateData", "=", "data", ".", "get", "(", "'state'", ",", "''", ")", "if", "stateData", ":", "metadata", "=", "json", ".", "loads", "(", "b64decode", "(", "unquote", "(", "stateData", ")", ".", "encode", "(", ")", ")", ".", "decode", "(", ")", ")", "else", ":", "metadata", "=", "{", "}", "except", "(", "TypeError", ",", "ValueError", ",", "binascii", ".", "Error", ")", ":", "logger", ".", "error", "(", "'Invalid metadata passed from Square app.'", ")", "messages", ".", "error", "(", "request", ",", "format_html", "(", "'<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>'", ",", "str", "(", "_", "(", "'ERROR: Error with Square point of sale transaction attempt.'", ")", ")", ",", "str", "(", "_", "(", "'Invalid metadata passed from Square app.'", ")", ")", ",", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'showRegSummary'", ")", ")", "# This is the normal transaction identifier, which will be stored in the", "# database as a SquarePaymentRecord", "serverTransId", "=", "data", ".", "get", "(", "'transaction_id'", ")", "# This is the only identifier passed for non-card transactions.", "clientTransId", "=", "data", ".", "get", "(", "'client_transaction_id'", ")", "else", ":", "# Android transactions use this GET response syntax", "errorCode", "=", "request", ".", "GET", ".", "get", "(", "'com.squareup.pos.ERROR_CODE'", ")", "errorDescription", "=", "request", ".", "GET", ".", "get", "(", "'com.squareup.pos.ERROR_DESCRIPTION'", ")", "status", "=", "'ok'", "if", "not", "errorCode", "else", "'error'", "# This is the normal transaction identifier, which will be stored in the", "# database as a SquarePaymentRecord", "serverTransId", "=", "request", ".", "GET", ".", "get", "(", "'com.squareup.pos.SERVER_TRANSACTION_ID'", ")", "# This is the only identifier passed for non-card transactions.", "clientTransId", "=", "request", ".", "GET", ".", "get", "(", "'com.squareup.pos.CLIENT_TRANSACTION_ID'", ")", "# Load the metadata, which includes the registration or invoice ids", "try", ":", "stateData", "=", "request", ".", "GET", ".", "get", "(", "'com.squareup.pos.REQUEST_METADATA'", ",", "''", ")", "if", "stateData", ":", "metadata", "=", "json", ".", "loads", "(", "b64decode", "(", "unquote", "(", "stateData", ")", ".", "encode", "(", ")", ")", ".", "decode", "(", ")", ")", "else", ":", "metadata", "=", "{", "}", "except", "(", "TypeError", ",", "ValueError", ",", "binascii", ".", "Error", ")", ":", "logger", ".", "error", "(", "'Invalid metadata passed from Square app.'", ")", "messages", ".", "error", "(", "request", ",", "format_html", "(", "'<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>'", ",", "str", "(", "_", "(", "'ERROR: Error with Square point of sale transaction attempt.'", ")", ")", ",", "str", "(", "_", "(", "'Invalid metadata passed from Square app.'", ")", ")", ",", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'showRegSummary'", ")", ")", "# Other things that can be passed in the metadata", "sourceUrl", "=", "metadata", ".", "get", "(", "'sourceUrl'", ",", "reverse", "(", "'showRegSummary'", ")", ")", "successUrl", "=", "metadata", ".", "get", "(", "'successUrl'", ",", "reverse", "(", "'registration'", ")", ")", "submissionUserId", "=", "metadata", ".", "get", "(", "'userId'", ",", "getattr", "(", "getattr", "(", "request", ",", "'user'", ",", "None", ")", ",", "'id'", ",", "None", ")", ")", "transactionType", "=", "metadata", ".", "get", "(", "'transaction_type'", ")", "taxable", "=", "metadata", ".", "get", "(", "'taxable'", ",", "False", ")", "addSessionInfo", "=", "metadata", ".", "get", "(", "'addSessionInfo'", ",", "False", ")", "customerEmail", "=", "metadata", ".", "get", "(", "'customerEmail'", ")", "if", "errorCode", "or", "status", "!=", "'ok'", ":", "# Return the user to their original page with the error message displayed.", "logger", ".", "error", "(", "'Error with Square point of sale transaction attempt. CODE: %s; DESCRIPTION: %s'", "%", "(", "errorCode", ",", "errorDescription", ")", ")", "messages", ".", "error", "(", "request", ",", "format_html", "(", "'<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>'", ",", "str", "(", "_", "(", "'ERROR: Error with Square point of sale transaction attempt.'", ")", ")", ",", "errorCode", ",", "errorDescription", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "api_instance", "=", "TransactionsApi", "(", ")", "api_instance", ".", "api_client", ".", "configuration", ".", "access_token", "=", "getattr", "(", "settings", ",", "'SQUARE_ACCESS_TOKEN'", ",", "''", ")", "location_id", "=", "getattr", "(", "settings", ",", "'SQUARE_LOCATION_ID'", ",", "''", ")", "if", "serverTransId", ":", "try", ":", "api_response", "=", "api_instance", ".", "retrieve_transaction", "(", "transaction_id", "=", "serverTransId", ",", "location_id", "=", "location_id", ")", "except", "ApiException", ":", "logger", ".", "error", "(", "'Unable to find Square transaction by server ID.'", ")", "messages", ".", "error", "(", "request", ",", "_", "(", "'ERROR: Unable to find Square transaction by server ID.'", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "if", "api_response", ".", "errors", ":", "logger", ".", "error", "(", "'Unable to find Square transaction by server ID: %s'", "%", "api_response", ".", "errors", ")", "messages", ".", "error", "(", "request", ",", "str", "(", "_", "(", "'ERROR: Unable to find Square transaction by server ID:'", ")", ")", "+", "api_response", ".", "errors", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "transaction", "=", "api_response", ".", "transaction", "elif", "clientTransId", ":", "# Try to find the transaction in the 50 most recent transactions", "try", ":", "api_response", "=", "api_instance", ".", "list_transactions", "(", "location_id", "=", "location_id", ")", "except", "ApiException", ":", "logger", ".", "error", "(", "'Unable to find Square transaction by client ID.'", ")", "messages", ".", "error", "(", "request", ",", "_", "(", "'ERROR: Unable to find Square transaction by client ID.'", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "if", "api_response", ".", "errors", ":", "logger", ".", "error", "(", "'Unable to find Square transaction by client ID: %s'", "%", "api_response", ".", "errors", ")", "messages", ".", "error", "(", "request", ",", "str", "(", "_", "(", "'ERROR: Unable to find Square transaction by client ID:'", ")", ")", "+", "api_response", ".", "errors", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "transactions_list", "=", "[", "x", "for", "x", "in", "api_response", ".", "transactions", "if", "x", ".", "client_id", "==", "clientTransId", "]", "if", "len", "(", "transactions_list", ")", "==", "1", ":", "transaction", "=", "transactions_list", "[", "0", "]", "else", ":", "logger", ".", "error", "(", "'Returned client transaction ID not found.'", ")", "messages", ".", "error", "(", "request", ",", "_", "(", "'ERROR: Returned client transaction ID not found.'", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "else", ":", "logger", ".", "error", "(", "'An unknown error has occurred with Square point of sale transaction attempt.'", ")", "messages", ".", "error", "(", "request", ",", "_", "(", "'ERROR: An unknown error has occurred with Square point of sale transaction attempt.'", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "# Get total information from the transaction for handling invoice.", "this_total", "=", "sum", "(", "[", "x", ".", "amount_money", ".", "amount", "/", "100", "for", "x", "in", "transaction", ".", "tenders", "or", "[", "]", "]", ")", "-", "sum", "(", "[", "x", ".", "amount_money", ".", "amount", "/", "100", "for", "x", "in", "transaction", ".", "refunds", "or", "[", "]", "]", ")", "# Parse if a specific submission user is indicated", "submissionUser", "=", "None", "if", "submissionUserId", ":", "try", ":", "submissionUser", "=", "User", ".", "objects", ".", "get", "(", "id", "=", "int", "(", "submissionUserId", ")", ")", "except", "(", "ValueError", ",", "ObjectDoesNotExist", ")", ":", "logger", ".", "warning", "(", "'Invalid user passed, submissionUser will not be recorded.'", ")", "if", "'registration'", "in", "metadata", ".", "keys", "(", ")", ":", "try", ":", "tr_id", "=", "int", "(", "metadata", ".", "get", "(", "'registration'", ")", ")", "tr", "=", "TemporaryRegistration", ".", "objects", ".", "get", "(", "id", "=", "tr_id", ")", "except", "(", "ValueError", ",", "TypeError", ",", "ObjectDoesNotExist", ")", ":", "logger", ".", "error", "(", "'Invalid registration ID passed: %s'", "%", "metadata", ".", "get", "(", "'registration'", ")", ")", "messages", ".", "error", "(", "request", ",", "str", "(", "_", "(", "'ERROR: Invalid registration ID passed'", ")", ")", "+", "': %s'", "%", "metadata", ".", "get", "(", "'registration'", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "tr", ".", "expirationDate", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "minutes", "=", "getConstant", "(", "'registration__sessionExpiryMinutes'", ")", ")", "tr", ".", "save", "(", ")", "this_invoice", "=", "Invoice", ".", "get_or_create_from_registration", "(", "tr", ",", "submissionUser", "=", "submissionUser", ")", "this_description", "=", "_", "(", "'Registration Payment: #%s'", "%", "tr_id", ")", "elif", "'invoice'", "in", "metadata", ".", "keys", "(", ")", ":", "try", ":", "this_invoice", "=", "Invoice", ".", "objects", ".", "get", "(", "id", "=", "int", "(", "metadata", ".", "get", "(", "'invoice'", ")", ")", ")", "this_description", "=", "_", "(", "'Invoice Payment: %s'", "%", "this_invoice", ".", "id", ")", "except", "(", "ValueError", ",", "TypeError", ",", "ObjectDoesNotExist", ")", ":", "logger", ".", "error", "(", "'Invalid invoice ID passed: %s'", "%", "metadata", ".", "get", "(", "'invoice'", ")", ")", "messages", ".", "error", "(", "request", ",", "str", "(", "_", "(", "'ERROR: Invalid invoice ID passed'", ")", ")", "+", "': %s'", "%", "metadata", ".", "get", "(", "'invoice'", ")", ")", "return", "HttpResponseRedirect", "(", "sourceUrl", ")", "else", ":", "# Gift certificates automatically get a nicer invoice description", "if", "transactionType", "==", "'Gift Certificate'", ":", "this_description", "=", "_", "(", "'Gift Certificate Purchase'", ")", "else", ":", "this_description", "=", "transactionType", "this_invoice", "=", "Invoice", ".", "create_from_item", "(", "this_total", ",", "this_description", ",", "submissionUser", "=", "submissionUser", ",", "calculate_taxes", "=", "(", "taxable", "is", "not", "False", ")", ",", "transactionType", "=", "transactionType", ",", ")", "paymentRecord", ",", "created", "=", "SquarePaymentRecord", ".", "objects", ".", "get_or_create", "(", "transactionId", "=", "transaction", ".", "id", ",", "locationId", "=", "transaction", ".", "location_id", ",", "defaults", "=", "{", "'invoice'", ":", "this_invoice", ",", "}", ")", "if", "created", ":", "# We process the payment now, and enqueue the job to retrieve the", "# transaction again once fees have been calculated by Square", "this_invoice", ".", "processPayment", "(", "amount", "=", "this_total", ",", "fees", "=", "0", ",", "paidOnline", "=", "True", ",", "methodName", "=", "'Square Point of Sale'", ",", "methodTxn", "=", "transaction", ".", "id", ",", "notify", "=", "customerEmail", ",", ")", "updateSquareFees", ".", "schedule", "(", "args", "=", "(", "paymentRecord", ",", ")", ",", "delay", "=", "60", ")", "if", "addSessionInfo", ":", "paymentSession", "=", "request", ".", "session", ".", "get", "(", "INVOICE_VALIDATION_STR", ",", "{", "}", ")", "paymentSession", ".", "update", "(", "{", "'invoiceID'", ":", "str", "(", "this_invoice", ".", "id", ")", ",", "'amount'", ":", "this_total", ",", "'successUrl'", ":", "successUrl", ",", "}", ")", "request", ".", "session", "[", "INVOICE_VALIDATION_STR", "]", "=", "paymentSession", "return", "HttpResponseRedirect", "(", "successUrl", ")" ]
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.
[ "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", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/square/views.py#L208-L424
orcasgit/django-fernet-fields
fernet_fields/fields.py
get_prep_lookup
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))
python
def get_prep_lookup(self): raise FieldError("{} '{}' does not support lookups".format( self.lhs.field.__class__.__name__, self.lookup_name))
[ "def", "get_prep_lookup", "(", "self", ")", ":", "raise", "FieldError", "(", "\"{} '{}' does not support lookups\"", ".", "format", "(", "self", ".", "lhs", ".", "field", ".", "__class__", ".", "__name__", ",", "self", ".", "lookup_name", ")", ")" ]
Raise errors for unsupported lookups
[ "Raise", "errors", "for", "unsupported", "lookups" ]
train
https://github.com/orcasgit/django-fernet-fields/blob/888777e5bdb93c72339663e7464f6ceaf4f5e7dd/fernet_fields/fields.py#L93-L96
orcasgit/django-fernet-fields
fernet_fields/hkdf.py
derive_fernet_key
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)))
python
def derive_fernet_key(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", "derive_fernet_key", "(", "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", ")", ")", ")" ]
Derive a 32-bit b64-encoded Fernet key from arbitrary input key.
[ "Derive", "a", "32", "-", "bit", "b64", "-", "encoded", "Fernet", "key", "from", "arbitrary", "input", "key", "." ]
train
https://github.com/orcasgit/django-fernet-fields/blob/888777e5bdb93c72339663e7464f6ceaf4f5e7dd/fernet_fields/hkdf.py#L14-L23
xnd-project/gumath
python/gumath/__init__.py
reduce_cpu
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=dtype) acc = x.empty(t, device=x.device) if f.identity is not None: _copyto(acc, f.identity) tl = T elif N == 1 and T.type.shape[0] > 0: hd, tl = T[0], T[1:] acc[()] = hd else: raise ValueError( "reduction not possible for function without an identity element") return fold(f, acc, tl)
python
def reduce_cpu(f, x, axes, dtype): 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=dtype) acc = x.empty(t, device=x.device) if f.identity is not None: _copyto(acc, f.identity) tl = T elif N == 1 and T.type.shape[0] > 0: hd, tl = T[0], T[1:] acc[()] = hd else: raise ValueError( "reduction not possible for function without an identity element") return fold(f, acc, tl)
[ "def", "reduce_cpu", "(", "f", ",", "x", ",", "axes", ",", "dtype", ")", ":", "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", "=", "dtype", ")", "acc", "=", "x", ".", "empty", "(", "t", ",", "device", "=", "x", ".", "device", ")", "if", "f", ".", "identity", "is", "not", "None", ":", "_copyto", "(", "acc", ",", "f", ".", "identity", ")", "tl", "=", "T", "elif", "N", "==", "1", "and", "T", ".", "type", ".", "shape", "[", "0", "]", ">", "0", ":", "hd", ",", "tl", "=", "T", "[", "0", "]", ",", "T", "[", "1", ":", "]", "acc", "[", "(", ")", "]", "=", "hd", "else", ":", "raise", "ValueError", "(", "\"reduction not possible for function without an identity element\"", ")", "return", "fold", "(", "f", ",", "acc", ",", "tl", ")" ]
NumPy's reduce in terms of fold.
[ "NumPy", "s", "reduce", "in", "terms", "of", "fold", "." ]
train
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath/__init__.py#L93-L118
xnd-project/gumath
python/gumath/__init__.py
reduce_cuda
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)
python
def reduce_cuda(g, x, axes, dtype): if axes != 0: raise NotImplementedError("'axes' keyword is not implemented for CUDA") return g(x, dtype=dtype)
[ "def", "reduce_cuda", "(", "g", ",", "x", ",", "axes", ",", "dtype", ")", ":", "if", "axes", "!=", "0", ":", "raise", "NotImplementedError", "(", "\"'axes' keyword is not implemented for CUDA\"", ")", "return", "g", "(", "x", ",", "dtype", "=", "dtype", ")" ]
Reductions in CUDA use the thrust library for speed and have limited functionality.
[ "Reductions", "in", "CUDA", "use", "the", "thrust", "library", "for", "speed", "and", "have", "limited", "functionality", "." ]
train
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath/__init__.py#L120-L126
xnd-project/gumath
python/gumath_aux.py
maxlevel
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
python
def maxlevel(lst): 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", "maxlevel", "(", "lst", ")", ":", "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" ]
Return maximum nesting depth
[ "Return", "maximum", "nesting", "depth" ]
train
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath_aux.py#L101-L112
xnd-project/gumath
python/gumath_aux.py
getitem
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) # Empty slice: check if all subsequent indices are in range for the # full slice, raise IndexError otherwise. This is NumPy's behavior. if not item: if lst: _ = getitem(lst, (slice(None),) + indices) elif any(isinstance(k, int) for k in indices): raise IndexError return [] return [getitem(x, indices) for x in item]
python
def getitem(lst, indices): if not indices: return lst i, indices = indices[0], indices[1:] item = list.__getitem__(lst, i) if isinstance(i, int): return getitem(item, indices) if not item: if lst: _ = getitem(lst, (slice(None),) + indices) elif any(isinstance(k, int) for k in indices): raise IndexError return [] return [getitem(x, indices) for x in item]
[ "def", "getitem", "(", "lst", ",", "indices", ")", ":", "if", "not", "indices", ":", "return", "lst", "i", ",", "indices", "=", "indices", "[", "0", "]", ",", "indices", "[", "1", ":", "]", "item", "=", "list", ".", "__getitem__", "(", "lst", ",", "i", ")", "if", "isinstance", "(", "i", ",", "int", ")", ":", "return", "getitem", "(", "item", ",", "indices", ")", "# Empty slice: check if all subsequent indices are in range for the", "# full slice, raise IndexError otherwise. This is NumPy's behavior.", "if", "not", "item", ":", "if", "lst", ":", "_", "=", "getitem", "(", "lst", ",", "(", "slice", "(", "None", ")", ",", ")", "+", "indices", ")", "elif", "any", "(", "isinstance", "(", "k", ",", "int", ")", "for", "k", "in", "indices", ")", ":", "raise", "IndexError", "return", "[", "]", "return", "[", "getitem", "(", "x", ",", "indices", ")", "for", "x", "in", "item", "]" ]
Definition for multidimensional slicing and indexing on arbitrarily shaped nested lists.
[ "Definition", "for", "multidimensional", "slicing", "and", "indexing", "on", "arbitrarily", "shaped", "nested", "lists", "." ]
train
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath_aux.py#L114-L136
xnd-project/gumath
python/gumath_aux.py
genslices
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
python
def genslices(n): 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", "(", "n", ")", ":", "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" ]
Generate all possible slices for a single dimension.
[ "Generate", "all", "possible", "slices", "for", "a", "single", "dimension", "." ]
train
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath_aux.py#L276-L285
xnd-project/gumath
python/gumath_aux.py
genslices_ndim
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)
python
def genslices_ndim(ndim, shape): iterables = [genslices(shape[n]) for n in range(ndim)] yield from product(*iterables)
[ "def", "genslices_ndim", "(", "ndim", ",", "shape", ")", ":", "iterables", "=", "[", "genslices", "(", "shape", "[", "n", "]", ")", "for", "n", "in", "range", "(", "ndim", ")", "]", "yield", "from", "product", "(", "*", "iterables", ")" ]
Generate all possible slice tuples for 'shape'.
[ "Generate", "all", "possible", "slice", "tuples", "for", "shape", "." ]
train
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath_aux.py#L287-L290
aarongarrett/inspyred
inspyred/ec/variators/mutators.py
mutator
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 given function ``mutate`` must have the following signature:: mutant = mutate(random, candidate, args) This function is most commonly used as a function decorator with the following usage:: @mutator def mutate(random, candidate, args): # Implementation of mutation pass The generated function also contains an attribute named ``single_mutation`` which holds the original mutation function. In this way, the original single-candidate function can be retrieved if necessary. """ @functools.wraps(mutate) def inspyred_mutator(random, candidates, args): mutants = [] for i, cs in enumerate(candidates): mutants.append(mutate(random, cs, args)) return mutants inspyred_mutator.single_mutation = mutate return inspyred_mutator
python
def mutator(mutate): @functools.wraps(mutate) def inspyred_mutator(random, candidates, args): mutants = [] for i, cs in enumerate(candidates): mutants.append(mutate(random, cs, args)) return mutants inspyred_mutator.single_mutation = mutate return inspyred_mutator
[ "def", "mutator", "(", "mutate", ")", ":", "@", "functools", ".", "wraps", "(", "mutate", ")", "def", "inspyred_mutator", "(", "random", ",", "candidates", ",", "args", ")", ":", "mutants", "=", "[", "]", "for", "i", ",", "cs", "in", "enumerate", "(", "candidates", ")", ":", "mutants", ".", "append", "(", "mutate", "(", "random", ",", "cs", ",", "args", ")", ")", "return", "mutants", "inspyred_mutator", ".", "single_mutation", "=", "mutate", "return", "inspyred_mutator" ]
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 given function ``mutate`` must have the following signature:: mutant = mutate(random, candidate, args) This function is most commonly used as a function decorator with the following usage:: @mutator def mutate(random, candidate, args): # Implementation of mutation pass The generated function also contains an attribute named ``single_mutation`` which holds the original mutation function. In this way, the original single-candidate function can be retrieved if necessary.
[ "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", "." ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L33-L65
aarongarrett/inspyred
inspyred/ec/variators/mutators.py
bit_flip_mutation
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 generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Optional keyword arguments in args: - *mutation_rate* -- the rate at which mutation is performed (default 0.1) The mutation rate is applied on a bit by bit basis. """ rate = args.setdefault('mutation_rate', 0.1) mutant = copy.copy(candidate) if len(mutant) == len([x for x in mutant if x in [0, 1]]): for i, m in enumerate(mutant): if random.random() < rate: mutant[i] = (m + 1) % 2 return mutant
python
def bit_flip_mutation(random, candidate, args): rate = args.setdefault('mutation_rate', 0.1) mutant = copy.copy(candidate) if len(mutant) == len([x for x in mutant if x in [0, 1]]): for i, m in enumerate(mutant): if random.random() < rate: mutant[i] = (m + 1) % 2 return mutant
[ "def", "bit_flip_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "rate", "=", "args", ".", "setdefault", "(", "'mutation_rate'", ",", "0.1", ")", "mutant", "=", "copy", ".", "copy", "(", "candidate", ")", "if", "len", "(", "mutant", ")", "==", "len", "(", "[", "x", "for", "x", "in", "mutant", "if", "x", "in", "[", "0", ",", "1", "]", "]", ")", ":", "for", "i", ",", "m", "in", "enumerate", "(", "mutant", ")", ":", "if", "random", ".", "random", "(", ")", "<", "rate", ":", "mutant", "[", "i", "]", "=", "(", "m", "+", "1", ")", "%", "2", "return", "mutant" ]
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 generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Optional keyword arguments in args: - *mutation_rate* -- the rate at which mutation is performed (default 0.1) The mutation rate is applied on a bit by bit basis.
[ "Return", "the", "mutants", "produced", "by", "bit", "-", "flip", "mutation", "on", "the", "candidates", "." ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L69-L93
aarongarrett/inspyred
inspyred/ec/variators/mutators.py
random_reset_mutation
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's ``evolve`` method, and it assumes that the bounder contains an attribute called *values* (which is true for instances of ``DiscreteBounder``). The mutation moves through a candidate solution and, with rate equal to the *mutation_rate*, randomly chooses a value from the set of allowed values to be used in that location. Note that this value may be the same as the original value. .. Arguments: random -- the random number generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Optional keyword arguments in args: - *mutation_rate* -- the rate at which mutation is performed (default 0.1) The mutation rate is applied on an element by element basis. """ bounder = args['_ec'].bounder try: values = bounder.values except AttributeError: values = None if values is not None: rate = args.setdefault('mutation_rate', 0.1) mutant = copy.copy(candidate) for i, m in enumerate(mutant): if random.random() < rate: mutant[i] = random.choice(values) return mutant else: return candidate
python
def random_reset_mutation(random, candidate, args): bounder = args['_ec'].bounder try: values = bounder.values except AttributeError: values = None if values is not None: rate = args.setdefault('mutation_rate', 0.1) mutant = copy.copy(candidate) for i, m in enumerate(mutant): if random.random() < rate: mutant[i] = random.choice(values) return mutant else: return candidate
[ "def", "random_reset_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "bounder", "=", "args", "[", "'_ec'", "]", ".", "bounder", "try", ":", "values", "=", "bounder", ".", "values", "except", "AttributeError", ":", "values", "=", "None", "if", "values", "is", "not", "None", ":", "rate", "=", "args", ".", "setdefault", "(", "'mutation_rate'", ",", "0.1", ")", "mutant", "=", "copy", ".", "copy", "(", "candidate", ")", "for", "i", ",", "m", "in", "enumerate", "(", "mutant", ")", ":", "if", "random", ".", "random", "(", ")", "<", "rate", ":", "mutant", "[", "i", "]", "=", "random", ".", "choice", "(", "values", ")", "return", "mutant", "else", ":", "return", "candidate" ]
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's ``evolve`` method, and it assumes that the bounder contains an attribute called *values* (which is true for instances of ``DiscreteBounder``). The mutation moves through a candidate solution and, with rate equal to the *mutation_rate*, randomly chooses a value from the set of allowed values to be used in that location. Note that this value may be the same as the original value. .. Arguments: random -- the random number generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Optional keyword arguments in args: - *mutation_rate* -- the rate at which mutation is performed (default 0.1) The mutation rate is applied on an element by element basis.
[ "Return", "the", "mutants", "produced", "by", "randomly", "choosing", "new", "values", "." ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L97-L137
aarongarrett/inspyred
inspyred/ec/variators/mutators.py
scramble_mutation
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 random number generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Optional keyword arguments in args: - *mutation_rate* -- the rate at which mutation is performed (default 0.1) The mutation rate is applied to the candidate as a whole (i.e., it either mutates or it does not, based on the rate). """ rate = args.setdefault('mutation_rate', 0.1) if random.random() < rate: size = len(candidate) p = random.randint(0, size-1) q = random.randint(0, size-1) p, q = min(p, q), max(p, q) s = candidate[p:q+1] random.shuffle(s) return candidate[:p] + s[::-1] + candidate[q+1:] else: return candidate
python
def scramble_mutation(random, candidate, args): rate = args.setdefault('mutation_rate', 0.1) if random.random() < rate: size = len(candidate) p = random.randint(0, size-1) q = random.randint(0, size-1) p, q = min(p, q), max(p, q) s = candidate[p:q+1] random.shuffle(s) return candidate[:p] + s[::-1] + candidate[q+1:] else: return candidate
[ "def", "scramble_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "rate", "=", "args", ".", "setdefault", "(", "'mutation_rate'", ",", "0.1", ")", "if", "random", ".", "random", "(", ")", "<", "rate", ":", "size", "=", "len", "(", "candidate", ")", "p", "=", "random", ".", "randint", "(", "0", ",", "size", "-", "1", ")", "q", "=", "random", ".", "randint", "(", "0", ",", "size", "-", "1", ")", "p", ",", "q", "=", "min", "(", "p", ",", "q", ")", ",", "max", "(", "p", ",", "q", ")", "s", "=", "candidate", "[", "p", ":", "q", "+", "1", "]", "random", ".", "shuffle", "(", "s", ")", "return", "candidate", "[", ":", "p", "]", "+", "s", "[", ":", ":", "-", "1", "]", "+", "candidate", "[", "q", "+", "1", ":", "]", "else", ":", "return", "candidate" ]
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 random number generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Optional keyword arguments in args: - *mutation_rate* -- the rate at which mutation is performed (default 0.1) The mutation rate is applied to the candidate as a whole (i.e., it either mutates or it does not, based on the rate).
[ "Return", "the", "mutants", "created", "by", "scramble", "mutation", "on", "the", "candidates", "." ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L141-L171
aarongarrett/inspyred
inspyred/ec/variators/mutators.py
gaussian_mutation
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 number generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Optional keyword arguments in args: - *mutation_rate* -- the rate at which mutation is performed (default 0.1) - *gaussian_mean* -- the mean used in the Gaussian function (default 0) - *gaussian_stdev* -- the standard deviation used in the Gaussian function (default 1) The mutation rate is applied on an element by element basis. """ mut_rate = args.setdefault('mutation_rate', 0.1) mean = args.setdefault('gaussian_mean', 0.0) stdev = args.setdefault('gaussian_stdev', 1.0) bounder = args['_ec'].bounder mutant = copy.copy(candidate) for i, m in enumerate(mutant): if random.random() < mut_rate: mutant[i] += random.gauss(mean, stdev) mutant = bounder(mutant, args) return mutant
python
def gaussian_mutation(random, candidate, args): mut_rate = args.setdefault('mutation_rate', 0.1) mean = args.setdefault('gaussian_mean', 0.0) stdev = args.setdefault('gaussian_stdev', 1.0) bounder = args['_ec'].bounder mutant = copy.copy(candidate) for i, m in enumerate(mutant): if random.random() < mut_rate: mutant[i] += random.gauss(mean, stdev) mutant = bounder(mutant, args) return mutant
[ "def", "gaussian_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "mut_rate", "=", "args", ".", "setdefault", "(", "'mutation_rate'", ",", "0.1", ")", "mean", "=", "args", ".", "setdefault", "(", "'gaussian_mean'", ",", "0.0", ")", "stdev", "=", "args", ".", "setdefault", "(", "'gaussian_stdev'", ",", "1.0", ")", "bounder", "=", "args", "[", "'_ec'", "]", ".", "bounder", "mutant", "=", "copy", ".", "copy", "(", "candidate", ")", "for", "i", ",", "m", "in", "enumerate", "(", "mutant", ")", ":", "if", "random", ".", "random", "(", ")", "<", "mut_rate", ":", "mutant", "[", "i", "]", "+=", "random", ".", "gauss", "(", "mean", ",", "stdev", ")", "mutant", "=", "bounder", "(", "mutant", ",", "args", ")", "return", "mutant" ]
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 number generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Optional keyword arguments in args: - *mutation_rate* -- the rate at which mutation is performed (default 0.1) - *gaussian_mean* -- the mean used in the Gaussian function (default 0) - *gaussian_stdev* -- the standard deviation used in the Gaussian function (default 1) The mutation rate is applied on an element by element basis.
[ "Return", "the", "mutants", "created", "by", "Gaussian", "mutation", "on", "the", "candidates", "." ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L208-L239
aarongarrett/inspyred
inspyred/ec/variators/mutators.py
nonuniform_mutation
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 of the bounder function as specified in the EC's ``evolve`` method. .. note:: This function **requires** that *max_generations* be specified in the *args* dictionary. Therefore, it is best to use this operator in conjunction with the ``generation_termination`` terminator. .. Arguments: random -- the random number generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Required keyword arguments in args: - *max_generations* -- the maximum number of generations for which evolution should take place Optional keyword arguments in args: - *mutation_strength* -- the strength of the mutation, where higher values correspond to greater variation (default 1) """ bounder = args['_ec'].bounder num_gens = args['_ec'].num_generations max_gens = args['max_generations'] strength = args.setdefault('mutation_strength', 1) exponent = (1.0 - num_gens / float(max_gens)) ** strength mutant = copy.copy(candidate) for i, (c, lo, hi) in enumerate(zip(candidate, bounder.lower_bound, bounder.upper_bound)): if random.random() <= 0.5: new_value = c + (hi - c) * (1.0 - random.random() ** exponent) else: new_value = c - (c - lo) * (1.0 - random.random() ** exponent) mutant[i] = new_value return mutant
python
def nonuniform_mutation(random, candidate, args): bounder = args['_ec'].bounder num_gens = args['_ec'].num_generations max_gens = args['max_generations'] strength = args.setdefault('mutation_strength', 1) exponent = (1.0 - num_gens / float(max_gens)) ** strength mutant = copy.copy(candidate) for i, (c, lo, hi) in enumerate(zip(candidate, bounder.lower_bound, bounder.upper_bound)): if random.random() <= 0.5: new_value = c + (hi - c) * (1.0 - random.random() ** exponent) else: new_value = c - (c - lo) * (1.0 - random.random() ** exponent) mutant[i] = new_value return mutant
[ "def", "nonuniform_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "bounder", "=", "args", "[", "'_ec'", "]", ".", "bounder", "num_gens", "=", "args", "[", "'_ec'", "]", ".", "num_generations", "max_gens", "=", "args", "[", "'max_generations'", "]", "strength", "=", "args", ".", "setdefault", "(", "'mutation_strength'", ",", "1", ")", "exponent", "=", "(", "1.0", "-", "num_gens", "/", "float", "(", "max_gens", ")", ")", "**", "strength", "mutant", "=", "copy", ".", "copy", "(", "candidate", ")", "for", "i", ",", "(", "c", ",", "lo", ",", "hi", ")", "in", "enumerate", "(", "zip", "(", "candidate", ",", "bounder", ".", "lower_bound", ",", "bounder", ".", "upper_bound", ")", ")", ":", "if", "random", ".", "random", "(", ")", "<=", "0.5", ":", "new_value", "=", "c", "+", "(", "hi", "-", "c", ")", "*", "(", "1.0", "-", "random", ".", "random", "(", ")", "**", "exponent", ")", "else", ":", "new_value", "=", "c", "-", "(", "c", "-", "lo", ")", "*", "(", "1.0", "-", "random", ".", "random", "(", ")", "**", "exponent", ")", "mutant", "[", "i", "]", "=", "new_value", "return", "mutant" ]
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 of the bounder function as specified in the EC's ``evolve`` method. .. note:: This function **requires** that *max_generations* be specified in the *args* dictionary. Therefore, it is best to use this operator in conjunction with the ``generation_termination`` terminator. .. Arguments: random -- the random number generator object candidate -- the candidate solution args -- a dictionary of keyword arguments Required keyword arguments in args: - *max_generations* -- the maximum number of generations for which evolution should take place Optional keyword arguments in args: - *mutation_strength* -- the strength of the mutation, where higher values correspond to greater variation (default 1)
[ "Return", "the", "mutants", "produced", "by", "nonuniform", "mutation", "on", "the", "candidates", "." ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L243-L285
aarongarrett/inspyred
inspyred/ec/archivers.py
population_archiver
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 individuals archive -- the current archive of individuals args -- a dictionary of keyword arguments """ new_archive = [] for ind in population: new_archive.append(ind) return new_archive
python
def population_archiver(random, population, archive, args): new_archive = [] for ind in population: new_archive.append(ind) return new_archive
[ "def", "population_archiver", "(", "random", ",", "population", ",", "archive", ",", "args", ")", ":", "new_archive", "=", "[", "]", "for", "ind", "in", "population", ":", "new_archive", ".", "append", "(", "ind", ")", "return", "new_archive" ]
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 individuals archive -- the current archive of individuals args -- a dictionary of keyword arguments
[ "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", "individuals", "archive", "--", "the", "current", "archive", "of", "individuals", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/archivers.py#L65-L81
aarongarrett/inspyred
inspyred/ec/archivers.py
best_archiver
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 a Pareto archive. .. Arguments: random -- the random number generator object population -- the population of individuals archive -- the current archive of individuals args -- a dictionary of keyword arguments """ new_archive = archive for ind in population: if len(new_archive) == 0: new_archive.append(ind) else: should_remove = [] should_add = True for a in new_archive: if ind.candidate == a.candidate: should_add = False break elif ind < a: should_add = False elif ind > a: should_remove.append(a) for r in should_remove: new_archive.remove(r) if should_add: new_archive.append(ind) return new_archive
python
def best_archiver(random, population, archive, args): new_archive = archive for ind in population: if len(new_archive) == 0: new_archive.append(ind) else: should_remove = [] should_add = True for a in new_archive: if ind.candidate == a.candidate: should_add = False break elif ind < a: should_add = False elif ind > a: should_remove.append(a) for r in should_remove: new_archive.remove(r) if should_add: new_archive.append(ind) return new_archive
[ "def", "best_archiver", "(", "random", ",", "population", ",", "archive", ",", "args", ")", ":", "new_archive", "=", "archive", "for", "ind", "in", "population", ":", "if", "len", "(", "new_archive", ")", "==", "0", ":", "new_archive", ".", "append", "(", "ind", ")", "else", ":", "should_remove", "=", "[", "]", "should_add", "=", "True", "for", "a", "in", "new_archive", ":", "if", "ind", ".", "candidate", "==", "a", ".", "candidate", ":", "should_add", "=", "False", "break", "elif", "ind", "<", "a", ":", "should_add", "=", "False", "elif", "ind", ">", "a", ":", "should_remove", ".", "append", "(", "a", ")", "for", "r", "in", "should_remove", ":", "new_archive", ".", "remove", "(", "r", ")", "if", "should_add", ":", "new_archive", ".", "append", "(", "ind", ")", "return", "new_archive" ]
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 a Pareto archive. .. Arguments: random -- the random number generator object population -- the population of individuals archive -- the current archive of individuals args -- a dictionary of keyword arguments
[ "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", "a", "Pareto", "archive", ".", "..", "Arguments", ":", "random", "--", "the", "random", "number", "generator", "object", "population", "--", "the", "population", "of", "individuals", "archive", "--", "the", "current", "archive", "of", "individuals", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/archivers.py#L84-L118
aarongarrett/inspyred
inspyred/ec/archivers.py
adaptive_grid_archiver
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 archiver is designed specifically for use with the Pareto Archived Evolution Strategy (PAES). .. Arguments: random -- the random number generator object population -- the population of individuals archive -- the current archive of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *max_archive_size* -- the maximum number of individuals in the archive (default len(population)) - *num_grid_divisions* -- the number of grid divisions (default 1) """ def get_grid_location(fitness, num_grid_divisions, global_smallest, global_largest): loc = 0 n = 1 num_objectives = len(fitness) inc = [0 for _ in range(num_objectives)] width = [0 for _ in range(num_objectives)] local_smallest = global_smallest[:] for i, f in enumerate(fitness): if f < local_smallest[i] or f > local_smallest[i] + global_largest[i] - global_smallest[i]: return -1 for i in range(num_objectives): inc[i] = n n *= 2 width[i] = global_largest[i] - global_smallest[i] for d in range(num_grid_divisions): for i, f in enumerate(fitness): if f < width[i] / 2.0 + local_smallest[i]: loc += inc[i] else: local_smallest[i] += width[i] / 2.0 for i in range(num_objectives): inc[i] *= num_objectives * 2 width[i] /= 2.0 return loc def update_grid(individual, archive, num_grid_divisions, global_smallest, global_largest, grid_population): if len(archive) == 0: num_objectives = len(individual.fitness) smallest = [individual.fitness[o] for o in range(num_objectives)] largest = [individual.fitness[o] for o in range(num_objectives)] else: num_objectives = min(min([len(a.fitness) for a in archive]), len(individual.fitness)) smallest = [min(min([a.fitness[o] for a in archive]), individual.fitness[o]) for o in range(num_objectives)] largest = [max(max([a.fitness[o] for a in archive]), individual.fitness[o]) for o in range(num_objectives)] for i in range(num_objectives): global_smallest[i] = smallest[i] - abs(0.2 * smallest[i]) global_largest[i] = largest[i] + abs(0.2 * largest[i]) for i in range(len(grid_population)): grid_population[i] = 0 for a in archive: loc = get_grid_location(a.fitness, num_grid_divisions, global_smallest, global_largest) a.grid_location = loc grid_population[loc] += 1 loc = get_grid_location(individual.fitness, num_grid_divisions, global_smallest, global_largest) individual.grid_location = loc grid_population[loc] += 1 max_archive_size = args.setdefault('max_archive_size', len(population)) num_grid_divisions = args.setdefault('num_grid_divisions', 1) if not 'grid_population' in dir(adaptive_grid_archiver): adaptive_grid_archiver.grid_population = [0 for _ in range(2**(min([len(p.fitness) for p in population]) * num_grid_divisions))] if not 'global_smallest' in dir(adaptive_grid_archiver): adaptive_grid_archiver.global_smallest = [0 for _ in range(min([len(p.fitness) for p in population]))] if not 'global_largest' in dir(adaptive_grid_archiver): adaptive_grid_archiver.global_largest = [0 for _ in range(min([len(p.fitness) for p in population]))] new_archive = archive for ind in population: update_grid(ind, new_archive, num_grid_divisions, adaptive_grid_archiver.global_smallest, adaptive_grid_archiver.global_largest, adaptive_grid_archiver.grid_population) should_be_added = True for a in new_archive: if ind == a or a > ind: should_be_added = False if should_be_added: if len(new_archive) == 0: new_archive.append(ind) else: join = False nondominated = True removal_set = [] for i, a in enumerate(new_archive): if ind > a and not join: new_archive[i] = ind join = True elif ind > a: if not a in removal_set: removal_set.append(a) # Otherwise, the individual is nondominated against this archive member. # We can't use set difference because Individual objects are not hashable. # We'd like to say... # new_archive = list(set(new_archive) - set(removal_set)) # So this code gets that same result without using sets. temp_archive = [] for ind in new_archive: if ind not in removal_set: temp_archive.append(ind) new_archive = temp_archive if not join and nondominated: if len(new_archive) == max_archive_size: replaced_index = 0 found_replacement = False loc = get_grid_location(ind.fitness, num_grid_divisions, adaptive_grid_archiver.global_smallest, adaptive_grid_archiver.global_largest) ind.grid_location = loc if ind.grid_location >= 0: most = adaptive_grid_archiver.grid_population[ind.grid_location] else: most = -1 for i, a in enumerate(new_archive): pop_at_a = adaptive_grid_archiver.grid_population[a.grid_location] if pop_at_a > most: most = pop_at_a replaced_index = i found_replacement = True if found_replacement: new_archive[replaced_index] = ind else: new_archive.append(ind) return new_archive
python
def adaptive_grid_archiver(random, population, archive, args): def get_grid_location(fitness, num_grid_divisions, global_smallest, global_largest): loc = 0 n = 1 num_objectives = len(fitness) inc = [0 for _ in range(num_objectives)] width = [0 for _ in range(num_objectives)] local_smallest = global_smallest[:] for i, f in enumerate(fitness): if f < local_smallest[i] or f > local_smallest[i] + global_largest[i] - global_smallest[i]: return -1 for i in range(num_objectives): inc[i] = n n *= 2 width[i] = global_largest[i] - global_smallest[i] for d in range(num_grid_divisions): for i, f in enumerate(fitness): if f < width[i] / 2.0 + local_smallest[i]: loc += inc[i] else: local_smallest[i] += width[i] / 2.0 for i in range(num_objectives): inc[i] *= num_objectives * 2 width[i] /= 2.0 return loc def update_grid(individual, archive, num_grid_divisions, global_smallest, global_largest, grid_population): if len(archive) == 0: num_objectives = len(individual.fitness) smallest = [individual.fitness[o] for o in range(num_objectives)] largest = [individual.fitness[o] for o in range(num_objectives)] else: num_objectives = min(min([len(a.fitness) for a in archive]), len(individual.fitness)) smallest = [min(min([a.fitness[o] for a in archive]), individual.fitness[o]) for o in range(num_objectives)] largest = [max(max([a.fitness[o] for a in archive]), individual.fitness[o]) for o in range(num_objectives)] for i in range(num_objectives): global_smallest[i] = smallest[i] - abs(0.2 * smallest[i]) global_largest[i] = largest[i] + abs(0.2 * largest[i]) for i in range(len(grid_population)): grid_population[i] = 0 for a in archive: loc = get_grid_location(a.fitness, num_grid_divisions, global_smallest, global_largest) a.grid_location = loc grid_population[loc] += 1 loc = get_grid_location(individual.fitness, num_grid_divisions, global_smallest, global_largest) individual.grid_location = loc grid_population[loc] += 1 max_archive_size = args.setdefault('max_archive_size', len(population)) num_grid_divisions = args.setdefault('num_grid_divisions', 1) if not 'grid_population' in dir(adaptive_grid_archiver): adaptive_grid_archiver.grid_population = [0 for _ in range(2**(min([len(p.fitness) for p in population]) * num_grid_divisions))] if not 'global_smallest' in dir(adaptive_grid_archiver): adaptive_grid_archiver.global_smallest = [0 for _ in range(min([len(p.fitness) for p in population]))] if not 'global_largest' in dir(adaptive_grid_archiver): adaptive_grid_archiver.global_largest = [0 for _ in range(min([len(p.fitness) for p in population]))] new_archive = archive for ind in population: update_grid(ind, new_archive, num_grid_divisions, adaptive_grid_archiver.global_smallest, adaptive_grid_archiver.global_largest, adaptive_grid_archiver.grid_population) should_be_added = True for a in new_archive: if ind == a or a > ind: should_be_added = False if should_be_added: if len(new_archive) == 0: new_archive.append(ind) else: join = False nondominated = True removal_set = [] for i, a in enumerate(new_archive): if ind > a and not join: new_archive[i] = ind join = True elif ind > a: if not a in removal_set: removal_set.append(a) temp_archive = [] for ind in new_archive: if ind not in removal_set: temp_archive.append(ind) new_archive = temp_archive if not join and nondominated: if len(new_archive) == max_archive_size: replaced_index = 0 found_replacement = False loc = get_grid_location(ind.fitness, num_grid_divisions, adaptive_grid_archiver.global_smallest, adaptive_grid_archiver.global_largest) ind.grid_location = loc if ind.grid_location >= 0: most = adaptive_grid_archiver.grid_population[ind.grid_location] else: most = -1 for i, a in enumerate(new_archive): pop_at_a = adaptive_grid_archiver.grid_population[a.grid_location] if pop_at_a > most: most = pop_at_a replaced_index = i found_replacement = True if found_replacement: new_archive[replaced_index] = ind else: new_archive.append(ind) return new_archive
[ "def", "adaptive_grid_archiver", "(", "random", ",", "population", ",", "archive", ",", "args", ")", ":", "def", "get_grid_location", "(", "fitness", ",", "num_grid_divisions", ",", "global_smallest", ",", "global_largest", ")", ":", "loc", "=", "0", "n", "=", "1", "num_objectives", "=", "len", "(", "fitness", ")", "inc", "=", "[", "0", "for", "_", "in", "range", "(", "num_objectives", ")", "]", "width", "=", "[", "0", "for", "_", "in", "range", "(", "num_objectives", ")", "]", "local_smallest", "=", "global_smallest", "[", ":", "]", "for", "i", ",", "f", "in", "enumerate", "(", "fitness", ")", ":", "if", "f", "<", "local_smallest", "[", "i", "]", "or", "f", ">", "local_smallest", "[", "i", "]", "+", "global_largest", "[", "i", "]", "-", "global_smallest", "[", "i", "]", ":", "return", "-", "1", "for", "i", "in", "range", "(", "num_objectives", ")", ":", "inc", "[", "i", "]", "=", "n", "n", "*=", "2", "width", "[", "i", "]", "=", "global_largest", "[", "i", "]", "-", "global_smallest", "[", "i", "]", "for", "d", "in", "range", "(", "num_grid_divisions", ")", ":", "for", "i", ",", "f", "in", "enumerate", "(", "fitness", ")", ":", "if", "f", "<", "width", "[", "i", "]", "/", "2.0", "+", "local_smallest", "[", "i", "]", ":", "loc", "+=", "inc", "[", "i", "]", "else", ":", "local_smallest", "[", "i", "]", "+=", "width", "[", "i", "]", "/", "2.0", "for", "i", "in", "range", "(", "num_objectives", ")", ":", "inc", "[", "i", "]", "*=", "num_objectives", "*", "2", "width", "[", "i", "]", "/=", "2.0", "return", "loc", "def", "update_grid", "(", "individual", ",", "archive", ",", "num_grid_divisions", ",", "global_smallest", ",", "global_largest", ",", "grid_population", ")", ":", "if", "len", "(", "archive", ")", "==", "0", ":", "num_objectives", "=", "len", "(", "individual", ".", "fitness", ")", "smallest", "=", "[", "individual", ".", "fitness", "[", "o", "]", "for", "o", "in", "range", "(", "num_objectives", ")", "]", "largest", "=", "[", "individual", ".", "fitness", "[", "o", "]", "for", "o", "in", "range", "(", "num_objectives", ")", "]", "else", ":", "num_objectives", "=", "min", "(", "min", "(", "[", "len", "(", "a", ".", "fitness", ")", "for", "a", "in", "archive", "]", ")", ",", "len", "(", "individual", ".", "fitness", ")", ")", "smallest", "=", "[", "min", "(", "min", "(", "[", "a", ".", "fitness", "[", "o", "]", "for", "a", "in", "archive", "]", ")", ",", "individual", ".", "fitness", "[", "o", "]", ")", "for", "o", "in", "range", "(", "num_objectives", ")", "]", "largest", "=", "[", "max", "(", "max", "(", "[", "a", ".", "fitness", "[", "o", "]", "for", "a", "in", "archive", "]", ")", ",", "individual", ".", "fitness", "[", "o", "]", ")", "for", "o", "in", "range", "(", "num_objectives", ")", "]", "for", "i", "in", "range", "(", "num_objectives", ")", ":", "global_smallest", "[", "i", "]", "=", "smallest", "[", "i", "]", "-", "abs", "(", "0.2", "*", "smallest", "[", "i", "]", ")", "global_largest", "[", "i", "]", "=", "largest", "[", "i", "]", "+", "abs", "(", "0.2", "*", "largest", "[", "i", "]", ")", "for", "i", "in", "range", "(", "len", "(", "grid_population", ")", ")", ":", "grid_population", "[", "i", "]", "=", "0", "for", "a", "in", "archive", ":", "loc", "=", "get_grid_location", "(", "a", ".", "fitness", ",", "num_grid_divisions", ",", "global_smallest", ",", "global_largest", ")", "a", ".", "grid_location", "=", "loc", "grid_population", "[", "loc", "]", "+=", "1", "loc", "=", "get_grid_location", "(", "individual", ".", "fitness", ",", "num_grid_divisions", ",", "global_smallest", ",", "global_largest", ")", "individual", ".", "grid_location", "=", "loc", "grid_population", "[", "loc", "]", "+=", "1", "max_archive_size", "=", "args", ".", "setdefault", "(", "'max_archive_size'", ",", "len", "(", "population", ")", ")", "num_grid_divisions", "=", "args", ".", "setdefault", "(", "'num_grid_divisions'", ",", "1", ")", "if", "not", "'grid_population'", "in", "dir", "(", "adaptive_grid_archiver", ")", ":", "adaptive_grid_archiver", ".", "grid_population", "=", "[", "0", "for", "_", "in", "range", "(", "2", "**", "(", "min", "(", "[", "len", "(", "p", ".", "fitness", ")", "for", "p", "in", "population", "]", ")", "*", "num_grid_divisions", ")", ")", "]", "if", "not", "'global_smallest'", "in", "dir", "(", "adaptive_grid_archiver", ")", ":", "adaptive_grid_archiver", ".", "global_smallest", "=", "[", "0", "for", "_", "in", "range", "(", "min", "(", "[", "len", "(", "p", ".", "fitness", ")", "for", "p", "in", "population", "]", ")", ")", "]", "if", "not", "'global_largest'", "in", "dir", "(", "adaptive_grid_archiver", ")", ":", "adaptive_grid_archiver", ".", "global_largest", "=", "[", "0", "for", "_", "in", "range", "(", "min", "(", "[", "len", "(", "p", ".", "fitness", ")", "for", "p", "in", "population", "]", ")", ")", "]", "new_archive", "=", "archive", "for", "ind", "in", "population", ":", "update_grid", "(", "ind", ",", "new_archive", ",", "num_grid_divisions", ",", "adaptive_grid_archiver", ".", "global_smallest", ",", "adaptive_grid_archiver", ".", "global_largest", ",", "adaptive_grid_archiver", ".", "grid_population", ")", "should_be_added", "=", "True", "for", "a", "in", "new_archive", ":", "if", "ind", "==", "a", "or", "a", ">", "ind", ":", "should_be_added", "=", "False", "if", "should_be_added", ":", "if", "len", "(", "new_archive", ")", "==", "0", ":", "new_archive", ".", "append", "(", "ind", ")", "else", ":", "join", "=", "False", "nondominated", "=", "True", "removal_set", "=", "[", "]", "for", "i", ",", "a", "in", "enumerate", "(", "new_archive", ")", ":", "if", "ind", ">", "a", "and", "not", "join", ":", "new_archive", "[", "i", "]", "=", "ind", "join", "=", "True", "elif", "ind", ">", "a", ":", "if", "not", "a", "in", "removal_set", ":", "removal_set", ".", "append", "(", "a", ")", "# Otherwise, the individual is nondominated against this archive member.", "# We can't use set difference because Individual objects are not hashable.", "# We'd like to say...", "# new_archive = list(set(new_archive) - set(removal_set))", "# So this code gets that same result without using sets.", "temp_archive", "=", "[", "]", "for", "ind", "in", "new_archive", ":", "if", "ind", "not", "in", "removal_set", ":", "temp_archive", ".", "append", "(", "ind", ")", "new_archive", "=", "temp_archive", "if", "not", "join", "and", "nondominated", ":", "if", "len", "(", "new_archive", ")", "==", "max_archive_size", ":", "replaced_index", "=", "0", "found_replacement", "=", "False", "loc", "=", "get_grid_location", "(", "ind", ".", "fitness", ",", "num_grid_divisions", ",", "adaptive_grid_archiver", ".", "global_smallest", ",", "adaptive_grid_archiver", ".", "global_largest", ")", "ind", ".", "grid_location", "=", "loc", "if", "ind", ".", "grid_location", ">=", "0", ":", "most", "=", "adaptive_grid_archiver", ".", "grid_population", "[", "ind", ".", "grid_location", "]", "else", ":", "most", "=", "-", "1", "for", "i", ",", "a", "in", "enumerate", "(", "new_archive", ")", ":", "pop_at_a", "=", "adaptive_grid_archiver", ".", "grid_population", "[", "a", ".", "grid_location", "]", "if", "pop_at_a", ">", "most", ":", "most", "=", "pop_at_a", "replaced_index", "=", "i", "found_replacement", "=", "True", "if", "found_replacement", ":", "new_archive", "[", "replaced_index", "]", "=", "ind", "else", ":", "new_archive", ".", "append", "(", "ind", ")", "return", "new_archive" ]
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 archiver is designed specifically for use with the Pareto Archived Evolution Strategy (PAES). .. Arguments: random -- the random number generator object population -- the population of individuals archive -- the current archive of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *max_archive_size* -- the maximum number of individuals in the archive (default len(population)) - *num_grid_divisions* -- the number of grid divisions (default 1)
[ "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", "archiver", "is", "designed", "specifically", "for", "use", "with", "the", "Pareto", "Archived", "Evolution", "Strategy", "(", "PAES", ")", "." ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/archivers.py#L121-L256
aarongarrett/inspyred
inspyred/swarm/topologies.py
ring_topology
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. .. Arguments: random -- the random number generator object population -- the population of particles args -- a dictionary of keyword arguments Optional keyword arguments in args: - *neighborhood_size* -- the width of the neighborhood around a particle which determines the size of the neighborhood (default 3) """ neighborhood_size = args.setdefault('neighborhood_size', 3) half_hood = neighborhood_size // 2 neighbor_index_start = [] for index in range(len(population)): if index < half_hood: neighbor_index_start.append(len(population) - half_hood + index) else: neighbor_index_start.append(index - half_hood) neighbors = [] for start in neighbor_index_start: n = [] for i in range(0, neighborhood_size): n.append(population[(start + i) % len(population)]) yield n
python
def ring_topology(random, population, args): neighborhood_size = args.setdefault('neighborhood_size', 3) half_hood = neighborhood_size // 2 neighbor_index_start = [] for index in range(len(population)): if index < half_hood: neighbor_index_start.append(len(population) - half_hood + index) else: neighbor_index_start.append(index - half_hood) neighbors = [] for start in neighbor_index_start: n = [] for i in range(0, neighborhood_size): n.append(population[(start + i) % len(population)]) yield n
[ "def", "ring_topology", "(", "random", ",", "population", ",", "args", ")", ":", "neighborhood_size", "=", "args", ".", "setdefault", "(", "'neighborhood_size'", ",", "3", ")", "half_hood", "=", "neighborhood_size", "//", "2", "neighbor_index_start", "=", "[", "]", "for", "index", "in", "range", "(", "len", "(", "population", ")", ")", ":", "if", "index", "<", "half_hood", ":", "neighbor_index_start", ".", "append", "(", "len", "(", "population", ")", "-", "half_hood", "+", "index", ")", "else", ":", "neighbor_index_start", ".", "append", "(", "index", "-", "half_hood", ")", "neighbors", "=", "[", "]", "for", "start", "in", "neighbor_index_start", ":", "n", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "neighborhood_size", ")", ":", "n", ".", "append", "(", "population", "[", "(", "start", "+", "i", ")", "%", "len", "(", "population", ")", "]", ")", "yield", "n" ]
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. .. Arguments: random -- the random number generator object population -- the population of particles args -- a dictionary of keyword arguments Optional keyword arguments in args: - *neighborhood_size* -- the width of the neighborhood around a particle which determines the size of the neighborhood (default 3)
[ "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", ".", "..", "Arguments", ":", "random", "--", "the", "random", "number", "generator", "object", "population", "--", "the", "population", "of", "particles", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/swarm/topologies.py#L69-L101
aarongarrett/inspyred
inspyred/ec/ec.py
EvolutionaryComputation.evolve
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 an epoch is selection, variation, evaluation, replacement, migration, archival, and observation. The function returns a list of elements of type ``Individual`` representing the individuals contained in the final population. Arguments: - *generator* -- the function to be used to generate candidate solutions - *evaluator* -- the function to be used to evaluate candidate solutions - *pop_size* -- the number of Individuals in the population (default 100) - *seeds* -- an iterable collection of candidate solutions to include in the initial population (default None) - *maximize* -- Boolean value stating use of maximization (default True) - *bounder* -- a function used to bound candidate solutions (default None) - *args* -- a dictionary of keyword arguments The *bounder* parameter, if left as ``None``, will be initialized to a default ``Bounder`` object that performs no bounding on candidates. Note that the *_kwargs* class variable will be initialized to the *args* parameter here. It will also be modified to include the following 'built-in' keyword argument: - *_ec* -- the evolutionary computation (this object) """ self._kwargs = args self._kwargs['_ec'] = self if seeds is None: seeds = [] if bounder is None: bounder = Bounder() self.termination_cause = None self.generator = generator self.evaluator = evaluator self.bounder = bounder self.maximize = maximize self.population = [] self.archive = [] # Create the initial population. if not isinstance(seeds, collections.Sequence): seeds = [seeds] initial_cs = copy.copy(seeds) num_generated = max(pop_size - len(seeds), 0) i = 0 self.logger.debug('generating initial population') while i < num_generated: cs = generator(random=self._random, args=self._kwargs) initial_cs.append(cs) i += 1 self.logger.debug('evaluating initial population') initial_fit = evaluator(candidates=initial_cs, args=self._kwargs) for cs, fit in zip(initial_cs, initial_fit): if fit is not None: ind = Individual(cs, maximize=maximize) ind.fitness = fit self.population.append(ind) else: self.logger.warning('excluding candidate {0} because fitness received as None'.format(cs)) self.logger.debug('population size is now {0}'.format(len(self.population))) self.num_evaluations = len(initial_fit) self.num_generations = 0 self.logger.debug('archiving initial population') self.archive = self.archiver(random=self._random, population=list(self.population), archive=list(self.archive), args=self._kwargs) self.logger.debug('archive size is now {0}'.format(len(self.archive))) self.logger.debug('population size is now {0}'.format(len(self.population))) # Turn observers and variators into lists if not already if isinstance(self.observer, collections.Iterable): observers = self.observer else: observers = [self.observer] if isinstance(self.variator, collections.Iterable): variators = self.variator else: variators = [self.variator] for obs in observers: self.logger.debug('observation using {0} at generation {1} and evaluation {2}'.format(obs.__name__, self.num_generations, self.num_evaluations)) obs(population=list(self.population), num_generations=self.num_generations, num_evaluations=self.num_evaluations, args=self._kwargs) while not self._should_terminate(list(self.population), self.num_generations, self.num_evaluations): # Select individuals. self.logger.debug('selection using {0} at generation {1} and evaluation {2}'.format(self.selector.__name__, self.num_generations, self.num_evaluations)) parents = self.selector(random=self._random, population=list(self.population), args=self._kwargs) self.logger.debug('selected {0} candidates'.format(len(parents))) offspring_cs = [copy.deepcopy(i.candidate) for i in parents] for op in variators: self.logger.debug('variation using {0} at generation {1} and evaluation {2}'.format(op.__name__, self.num_generations, self.num_evaluations)) offspring_cs = op(random=self._random, candidates=offspring_cs, args=self._kwargs) self.logger.debug('created {0} offspring'.format(len(offspring_cs))) # Evaluate offspring. self.logger.debug('evaluation using {0} at generation {1} and evaluation {2}'.format(evaluator.__name__, self.num_generations, self.num_evaluations)) offspring_fit = evaluator(candidates=offspring_cs, args=self._kwargs) offspring = [] for cs, fit in zip(offspring_cs, offspring_fit): if fit is not None: off = Individual(cs, maximize=maximize) off.fitness = fit offspring.append(off) else: self.logger.warning('excluding candidate {0} because fitness received as None'.format(cs)) self.num_evaluations += len(offspring_fit) # Replace individuals. self.logger.debug('replacement using {0} at generation {1} and evaluation {2}'.format(self.replacer.__name__, self.num_generations, self.num_evaluations)) self.population = self.replacer(random=self._random, population=self.population, parents=parents, offspring=offspring, args=self._kwargs) self.logger.debug('population size is now {0}'.format(len(self.population))) # Migrate individuals. self.logger.debug('migration using {0} at generation {1} and evaluation {2}'.format(self.migrator.__name__, self.num_generations, self.num_evaluations)) self.population = self.migrator(random=self._random, population=self.population, args=self._kwargs) self.logger.debug('population size is now {0}'.format(len(self.population))) # Archive individuals. self.logger.debug('archival using {0} at generation {1} and evaluation {2}'.format(self.archiver.__name__, self.num_generations, self.num_evaluations)) self.archive = self.archiver(random=self._random, archive=self.archive, population=list(self.population), args=self._kwargs) self.logger.debug('archive size is now {0}'.format(len(self.archive))) self.logger.debug('population size is now {0}'.format(len(self.population))) self.num_generations += 1 for obs in observers: self.logger.debug('observation using {0} at generation {1} and evaluation {2}'.format(obs.__name__, self.num_generations, self.num_evaluations)) obs(population=list(self.population), num_generations=self.num_generations, num_evaluations=self.num_evaluations, args=self._kwargs) return self.population
python
def evolve(self, generator, evaluator, pop_size=100, seeds=None, maximize=True, bounder=None, **args): self._kwargs = args self._kwargs['_ec'] = self if seeds is None: seeds = [] if bounder is None: bounder = Bounder() self.termination_cause = None self.generator = generator self.evaluator = evaluator self.bounder = bounder self.maximize = maximize self.population = [] self.archive = [] if not isinstance(seeds, collections.Sequence): seeds = [seeds] initial_cs = copy.copy(seeds) num_generated = max(pop_size - len(seeds), 0) i = 0 self.logger.debug('generating initial population') while i < num_generated: cs = generator(random=self._random, args=self._kwargs) initial_cs.append(cs) i += 1 self.logger.debug('evaluating initial population') initial_fit = evaluator(candidates=initial_cs, args=self._kwargs) for cs, fit in zip(initial_cs, initial_fit): if fit is not None: ind = Individual(cs, maximize=maximize) ind.fitness = fit self.population.append(ind) else: self.logger.warning('excluding candidate {0} because fitness received as None'.format(cs)) self.logger.debug('population size is now {0}'.format(len(self.population))) self.num_evaluations = len(initial_fit) self.num_generations = 0 self.logger.debug('archiving initial population') self.archive = self.archiver(random=self._random, population=list(self.population), archive=list(self.archive), args=self._kwargs) self.logger.debug('archive size is now {0}'.format(len(self.archive))) self.logger.debug('population size is now {0}'.format(len(self.population))) if isinstance(self.observer, collections.Iterable): observers = self.observer else: observers = [self.observer] if isinstance(self.variator, collections.Iterable): variators = self.variator else: variators = [self.variator] for obs in observers: self.logger.debug('observation using {0} at generation {1} and evaluation {2}'.format(obs.__name__, self.num_generations, self.num_evaluations)) obs(population=list(self.population), num_generations=self.num_generations, num_evaluations=self.num_evaluations, args=self._kwargs) while not self._should_terminate(list(self.population), self.num_generations, self.num_evaluations): self.logger.debug('selection using {0} at generation {1} and evaluation {2}'.format(self.selector.__name__, self.num_generations, self.num_evaluations)) parents = self.selector(random=self._random, population=list(self.population), args=self._kwargs) self.logger.debug('selected {0} candidates'.format(len(parents))) offspring_cs = [copy.deepcopy(i.candidate) for i in parents] for op in variators: self.logger.debug('variation using {0} at generation {1} and evaluation {2}'.format(op.__name__, self.num_generations, self.num_evaluations)) offspring_cs = op(random=self._random, candidates=offspring_cs, args=self._kwargs) self.logger.debug('created {0} offspring'.format(len(offspring_cs))) self.logger.debug('evaluation using {0} at generation {1} and evaluation {2}'.format(evaluator.__name__, self.num_generations, self.num_evaluations)) offspring_fit = evaluator(candidates=offspring_cs, args=self._kwargs) offspring = [] for cs, fit in zip(offspring_cs, offspring_fit): if fit is not None: off = Individual(cs, maximize=maximize) off.fitness = fit offspring.append(off) else: self.logger.warning('excluding candidate {0} because fitness received as None'.format(cs)) self.num_evaluations += len(offspring_fit) self.logger.debug('replacement using {0} at generation {1} and evaluation {2}'.format(self.replacer.__name__, self.num_generations, self.num_evaluations)) self.population = self.replacer(random=self._random, population=self.population, parents=parents, offspring=offspring, args=self._kwargs) self.logger.debug('population size is now {0}'.format(len(self.population))) self.logger.debug('migration using {0} at generation {1} and evaluation {2}'.format(self.migrator.__name__, self.num_generations, self.num_evaluations)) self.population = self.migrator(random=self._random, population=self.population, args=self._kwargs) self.logger.debug('population size is now {0}'.format(len(self.population))) self.logger.debug('archival using {0} at generation {1} and evaluation {2}'.format(self.archiver.__name__, self.num_generations, self.num_evaluations)) self.archive = self.archiver(random=self._random, archive=self.archive, population=list(self.population), args=self._kwargs) self.logger.debug('archive size is now {0}'.format(len(self.archive))) self.logger.debug('population size is now {0}'.format(len(self.population))) self.num_generations += 1 for obs in observers: self.logger.debug('observation using {0} at generation {1} and evaluation {2}'.format(obs.__name__, self.num_generations, self.num_evaluations)) obs(population=list(self.population), num_generations=self.num_generations, num_evaluations=self.num_evaluations, args=self._kwargs) return self.population
[ "def", "evolve", "(", "self", ",", "generator", ",", "evaluator", ",", "pop_size", "=", "100", ",", "seeds", "=", "None", ",", "maximize", "=", "True", ",", "bounder", "=", "None", ",", "*", "*", "args", ")", ":", "self", ".", "_kwargs", "=", "args", "self", ".", "_kwargs", "[", "'_ec'", "]", "=", "self", "if", "seeds", "is", "None", ":", "seeds", "=", "[", "]", "if", "bounder", "is", "None", ":", "bounder", "=", "Bounder", "(", ")", "self", ".", "termination_cause", "=", "None", "self", ".", "generator", "=", "generator", "self", ".", "evaluator", "=", "evaluator", "self", ".", "bounder", "=", "bounder", "self", ".", "maximize", "=", "maximize", "self", ".", "population", "=", "[", "]", "self", ".", "archive", "=", "[", "]", "# Create the initial population.", "if", "not", "isinstance", "(", "seeds", ",", "collections", ".", "Sequence", ")", ":", "seeds", "=", "[", "seeds", "]", "initial_cs", "=", "copy", ".", "copy", "(", "seeds", ")", "num_generated", "=", "max", "(", "pop_size", "-", "len", "(", "seeds", ")", ",", "0", ")", "i", "=", "0", "self", ".", "logger", ".", "debug", "(", "'generating initial population'", ")", "while", "i", "<", "num_generated", ":", "cs", "=", "generator", "(", "random", "=", "self", ".", "_random", ",", "args", "=", "self", ".", "_kwargs", ")", "initial_cs", ".", "append", "(", "cs", ")", "i", "+=", "1", "self", ".", "logger", ".", "debug", "(", "'evaluating initial population'", ")", "initial_fit", "=", "evaluator", "(", "candidates", "=", "initial_cs", ",", "args", "=", "self", ".", "_kwargs", ")", "for", "cs", ",", "fit", "in", "zip", "(", "initial_cs", ",", "initial_fit", ")", ":", "if", "fit", "is", "not", "None", ":", "ind", "=", "Individual", "(", "cs", ",", "maximize", "=", "maximize", ")", "ind", ".", "fitness", "=", "fit", "self", ".", "population", ".", "append", "(", "ind", ")", "else", ":", "self", ".", "logger", ".", "warning", "(", "'excluding candidate {0} because fitness received as None'", ".", "format", "(", "cs", ")", ")", "self", ".", "logger", ".", "debug", "(", "'population size is now {0}'", ".", "format", "(", "len", "(", "self", ".", "population", ")", ")", ")", "self", ".", "num_evaluations", "=", "len", "(", "initial_fit", ")", "self", ".", "num_generations", "=", "0", "self", ".", "logger", ".", "debug", "(", "'archiving initial population'", ")", "self", ".", "archive", "=", "self", ".", "archiver", "(", "random", "=", "self", ".", "_random", ",", "population", "=", "list", "(", "self", ".", "population", ")", ",", "archive", "=", "list", "(", "self", ".", "archive", ")", ",", "args", "=", "self", ".", "_kwargs", ")", "self", ".", "logger", ".", "debug", "(", "'archive size is now {0}'", ".", "format", "(", "len", "(", "self", ".", "archive", ")", ")", ")", "self", ".", "logger", ".", "debug", "(", "'population size is now {0}'", ".", "format", "(", "len", "(", "self", ".", "population", ")", ")", ")", "# Turn observers and variators into lists if not already", "if", "isinstance", "(", "self", ".", "observer", ",", "collections", ".", "Iterable", ")", ":", "observers", "=", "self", ".", "observer", "else", ":", "observers", "=", "[", "self", ".", "observer", "]", "if", "isinstance", "(", "self", ".", "variator", ",", "collections", ".", "Iterable", ")", ":", "variators", "=", "self", ".", "variator", "else", ":", "variators", "=", "[", "self", ".", "variator", "]", "for", "obs", "in", "observers", ":", "self", ".", "logger", ".", "debug", "(", "'observation using {0} at generation {1} and evaluation {2}'", ".", "format", "(", "obs", ".", "__name__", ",", "self", ".", "num_generations", ",", "self", ".", "num_evaluations", ")", ")", "obs", "(", "population", "=", "list", "(", "self", ".", "population", ")", ",", "num_generations", "=", "self", ".", "num_generations", ",", "num_evaluations", "=", "self", ".", "num_evaluations", ",", "args", "=", "self", ".", "_kwargs", ")", "while", "not", "self", ".", "_should_terminate", "(", "list", "(", "self", ".", "population", ")", ",", "self", ".", "num_generations", ",", "self", ".", "num_evaluations", ")", ":", "# Select individuals.", "self", ".", "logger", ".", "debug", "(", "'selection using {0} at generation {1} and evaluation {2}'", ".", "format", "(", "self", ".", "selector", ".", "__name__", ",", "self", ".", "num_generations", ",", "self", ".", "num_evaluations", ")", ")", "parents", "=", "self", ".", "selector", "(", "random", "=", "self", ".", "_random", ",", "population", "=", "list", "(", "self", ".", "population", ")", ",", "args", "=", "self", ".", "_kwargs", ")", "self", ".", "logger", ".", "debug", "(", "'selected {0} candidates'", ".", "format", "(", "len", "(", "parents", ")", ")", ")", "offspring_cs", "=", "[", "copy", ".", "deepcopy", "(", "i", ".", "candidate", ")", "for", "i", "in", "parents", "]", "for", "op", "in", "variators", ":", "self", ".", "logger", ".", "debug", "(", "'variation using {0} at generation {1} and evaluation {2}'", ".", "format", "(", "op", ".", "__name__", ",", "self", ".", "num_generations", ",", "self", ".", "num_evaluations", ")", ")", "offspring_cs", "=", "op", "(", "random", "=", "self", ".", "_random", ",", "candidates", "=", "offspring_cs", ",", "args", "=", "self", ".", "_kwargs", ")", "self", ".", "logger", ".", "debug", "(", "'created {0} offspring'", ".", "format", "(", "len", "(", "offspring_cs", ")", ")", ")", "# Evaluate offspring.", "self", ".", "logger", ".", "debug", "(", "'evaluation using {0} at generation {1} and evaluation {2}'", ".", "format", "(", "evaluator", ".", "__name__", ",", "self", ".", "num_generations", ",", "self", ".", "num_evaluations", ")", ")", "offspring_fit", "=", "evaluator", "(", "candidates", "=", "offspring_cs", ",", "args", "=", "self", ".", "_kwargs", ")", "offspring", "=", "[", "]", "for", "cs", ",", "fit", "in", "zip", "(", "offspring_cs", ",", "offspring_fit", ")", ":", "if", "fit", "is", "not", "None", ":", "off", "=", "Individual", "(", "cs", ",", "maximize", "=", "maximize", ")", "off", ".", "fitness", "=", "fit", "offspring", ".", "append", "(", "off", ")", "else", ":", "self", ".", "logger", ".", "warning", "(", "'excluding candidate {0} because fitness received as None'", ".", "format", "(", "cs", ")", ")", "self", ".", "num_evaluations", "+=", "len", "(", "offspring_fit", ")", "# Replace individuals.", "self", ".", "logger", ".", "debug", "(", "'replacement using {0} at generation {1} and evaluation {2}'", ".", "format", "(", "self", ".", "replacer", ".", "__name__", ",", "self", ".", "num_generations", ",", "self", ".", "num_evaluations", ")", ")", "self", ".", "population", "=", "self", ".", "replacer", "(", "random", "=", "self", ".", "_random", ",", "population", "=", "self", ".", "population", ",", "parents", "=", "parents", ",", "offspring", "=", "offspring", ",", "args", "=", "self", ".", "_kwargs", ")", "self", ".", "logger", ".", "debug", "(", "'population size is now {0}'", ".", "format", "(", "len", "(", "self", ".", "population", ")", ")", ")", "# Migrate individuals.", "self", ".", "logger", ".", "debug", "(", "'migration using {0} at generation {1} and evaluation {2}'", ".", "format", "(", "self", ".", "migrator", ".", "__name__", ",", "self", ".", "num_generations", ",", "self", ".", "num_evaluations", ")", ")", "self", ".", "population", "=", "self", ".", "migrator", "(", "random", "=", "self", ".", "_random", ",", "population", "=", "self", ".", "population", ",", "args", "=", "self", ".", "_kwargs", ")", "self", ".", "logger", ".", "debug", "(", "'population size is now {0}'", ".", "format", "(", "len", "(", "self", ".", "population", ")", ")", ")", "# Archive individuals.", "self", ".", "logger", ".", "debug", "(", "'archival using {0} at generation {1} and evaluation {2}'", ".", "format", "(", "self", ".", "archiver", ".", "__name__", ",", "self", ".", "num_generations", ",", "self", ".", "num_evaluations", ")", ")", "self", ".", "archive", "=", "self", ".", "archiver", "(", "random", "=", "self", ".", "_random", ",", "archive", "=", "self", ".", "archive", ",", "population", "=", "list", "(", "self", ".", "population", ")", ",", "args", "=", "self", ".", "_kwargs", ")", "self", ".", "logger", ".", "debug", "(", "'archive size is now {0}'", ".", "format", "(", "len", "(", "self", ".", "archive", ")", ")", ")", "self", ".", "logger", ".", "debug", "(", "'population size is now {0}'", ".", "format", "(", "len", "(", "self", ".", "population", ")", ")", ")", "self", ".", "num_generations", "+=", "1", "for", "obs", "in", "observers", ":", "self", ".", "logger", ".", "debug", "(", "'observation using {0} at generation {1} and evaluation {2}'", ".", "format", "(", "obs", ".", "__name__", ",", "self", ".", "num_generations", ",", "self", ".", "num_evaluations", ")", ")", "obs", "(", "population", "=", "list", "(", "self", ".", "population", ")", ",", "num_generations", "=", "self", ".", "num_generations", ",", "num_evaluations", "=", "self", ".", "num_evaluations", ",", "args", "=", "self", ".", "_kwargs", ")", "return", "self", ".", "population" ]
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 an epoch is selection, variation, evaluation, replacement, migration, archival, and observation. The function returns a list of elements of type ``Individual`` representing the individuals contained in the final population. Arguments: - *generator* -- the function to be used to generate candidate solutions - *evaluator* -- the function to be used to evaluate candidate solutions - *pop_size* -- the number of Individuals in the population (default 100) - *seeds* -- an iterable collection of candidate solutions to include in the initial population (default None) - *maximize* -- Boolean value stating use of maximization (default True) - *bounder* -- a function used to bound candidate solutions (default None) - *args* -- a dictionary of keyword arguments The *bounder* parameter, if left as ``None``, will be initialized to a default ``Bounder`` object that performs no bounding on candidates. Note that the *_kwargs* class variable will be initialized to the *args* parameter here. It will also be modified to include the following 'built-in' keyword argument: - *_ec* -- the evolutionary computation (this object)
[ "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", "an", "epoch", "is", "selection", "variation", "evaluation", "replacement", "migration", "archival", "and", "observation", ".", "The", "function", "returns", "a", "list", "of", "elements", "of", "type", "Individual", "representing", "the", "individuals", "contained", "in", "the", "final", "population", ".", "Arguments", ":", "-", "*", "generator", "*", "--", "the", "function", "to", "be", "used", "to", "generate", "candidate", "solutions", "-", "*", "evaluator", "*", "--", "the", "function", "to", "be", "used", "to", "evaluate", "candidate", "solutions", "-", "*", "pop_size", "*", "--", "the", "number", "of", "Individuals", "in", "the", "population", "(", "default", "100", ")", "-", "*", "seeds", "*", "--", "an", "iterable", "collection", "of", "candidate", "solutions", "to", "include", "in", "the", "initial", "population", "(", "default", "None", ")", "-", "*", "maximize", "*", "--", "Boolean", "value", "stating", "use", "of", "maximization", "(", "default", "True", ")", "-", "*", "bounder", "*", "--", "a", "function", "used", "to", "bound", "candidate", "solutions", "(", "default", "None", ")", "-", "*", "args", "*", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/ec.py#L381-L518
aarongarrett/inspyred
inspyred/ec/selectors.py
truncation_selection
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. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default len(population)) """ num_selected = args.setdefault('num_selected', len(population)) population.sort(reverse=True) return population[:num_selected]
python
def truncation_selection(random, population, args): num_selected = args.setdefault('num_selected', len(population)) population.sort(reverse=True) return population[:num_selected]
[ "def", "truncation_selection", "(", "random", ",", "population", ",", "args", ")", ":", "num_selected", "=", "args", ".", "setdefault", "(", "'num_selected'", ",", "len", "(", "population", ")", ")", "population", ".", "sort", "(", "reverse", "=", "True", ")", "return", "population", "[", ":", "num_selected", "]" ]
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. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default len(population))
[ "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", ".", "..", "Arguments", ":", "random", "--", "the", "random", "number", "generator", "object", "population", "--", "the", "population", "of", "individuals", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/selectors.py#L63-L83
aarongarrett/inspyred
inspyred/ec/selectors.py
uniform_selection
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 population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default 1) """ num_selected = args.setdefault('num_selected', 1) selected = [] for _ in range(num_selected): selected.append(population[random.randint(0, len(population)-1)]) return selected
python
def uniform_selection(random, population, args): num_selected = args.setdefault('num_selected', 1) selected = [] for _ in range(num_selected): selected.append(population[random.randint(0, len(population)-1)]) return selected
[ "def", "uniform_selection", "(", "random", ",", "population", ",", "args", ")", ":", "num_selected", "=", "args", ".", "setdefault", "(", "'num_selected'", ",", "1", ")", "selected", "=", "[", "]", "for", "_", "in", "range", "(", "num_selected", ")", ":", "selected", ".", "append", "(", "population", "[", "random", ".", "randint", "(", "0", ",", "len", "(", "population", ")", "-", "1", ")", "]", ")", "return", "selected" ]
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 population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default 1)
[ "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", "population", "--", "the", "population", "of", "individuals", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/selectors.py#L86-L107
aarongarrett/inspyred
inspyred/ec/selectors.py
fitness_proportionate_selection
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 wheel" selection. Note that this selection is not valid for minimization problems. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default 1) """ num_selected = args.setdefault('num_selected', 1) len_pop = len(population) psum = [i for i in range(len_pop)] pop_max_fit = (max(population)).fitness pop_min_fit = (min(population)).fitness # If we're actually doing minimimization, # fitness proportionate selection is not defined. if pop_max_fit < pop_min_fit: raise ValueError('Fitness proportionate selection is not valid for minimization.') # Set up the roulette wheel if pop_max_fit == pop_min_fit: psum = [(index + 1) / float(len_pop) for index in range(len_pop)] elif (pop_max_fit > 0 and pop_min_fit >= 0) or (pop_max_fit <= 0 and pop_min_fit < 0): population.sort(reverse=True) psum[0] = population[0].fitness for i in range(1, len_pop): psum[i] = population[i].fitness + psum[i-1] for i in range(len_pop): psum[i] /= float(psum[len_pop-1]) # Select the individuals selected = [] for _ in range(num_selected): cutoff = random.random() lower = 0 upper = len_pop - 1 while(upper >= lower): mid = (lower + upper) // 2 if psum[mid] > cutoff: upper = mid - 1 else: lower = mid + 1 lower = max(0, min(len_pop-1, lower)) selected.append(population[lower]) return selected
python
def fitness_proportionate_selection(random, population, args): num_selected = args.setdefault('num_selected', 1) len_pop = len(population) psum = [i for i in range(len_pop)] pop_max_fit = (max(population)).fitness pop_min_fit = (min(population)).fitness if pop_max_fit < pop_min_fit: raise ValueError('Fitness proportionate selection is not valid for minimization.') if pop_max_fit == pop_min_fit: psum = [(index + 1) / float(len_pop) for index in range(len_pop)] elif (pop_max_fit > 0 and pop_min_fit >= 0) or (pop_max_fit <= 0 and pop_min_fit < 0): population.sort(reverse=True) psum[0] = population[0].fitness for i in range(1, len_pop): psum[i] = population[i].fitness + psum[i-1] for i in range(len_pop): psum[i] /= float(psum[len_pop-1]) selected = [] for _ in range(num_selected): cutoff = random.random() lower = 0 upper = len_pop - 1 while(upper >= lower): mid = (lower + upper) // 2 if psum[mid] > cutoff: upper = mid - 1 else: lower = mid + 1 lower = max(0, min(len_pop-1, lower)) selected.append(population[lower]) return selected
[ "def", "fitness_proportionate_selection", "(", "random", ",", "population", ",", "args", ")", ":", "num_selected", "=", "args", ".", "setdefault", "(", "'num_selected'", ",", "1", ")", "len_pop", "=", "len", "(", "population", ")", "psum", "=", "[", "i", "for", "i", "in", "range", "(", "len_pop", ")", "]", "pop_max_fit", "=", "(", "max", "(", "population", ")", ")", ".", "fitness", "pop_min_fit", "=", "(", "min", "(", "population", ")", ")", ".", "fitness", "# If we're actually doing minimimization,", "# fitness proportionate selection is not defined.", "if", "pop_max_fit", "<", "pop_min_fit", ":", "raise", "ValueError", "(", "'Fitness proportionate selection is not valid for minimization.'", ")", "# Set up the roulette wheel", "if", "pop_max_fit", "==", "pop_min_fit", ":", "psum", "=", "[", "(", "index", "+", "1", ")", "/", "float", "(", "len_pop", ")", "for", "index", "in", "range", "(", "len_pop", ")", "]", "elif", "(", "pop_max_fit", ">", "0", "and", "pop_min_fit", ">=", "0", ")", "or", "(", "pop_max_fit", "<=", "0", "and", "pop_min_fit", "<", "0", ")", ":", "population", ".", "sort", "(", "reverse", "=", "True", ")", "psum", "[", "0", "]", "=", "population", "[", "0", "]", ".", "fitness", "for", "i", "in", "range", "(", "1", ",", "len_pop", ")", ":", "psum", "[", "i", "]", "=", "population", "[", "i", "]", ".", "fitness", "+", "psum", "[", "i", "-", "1", "]", "for", "i", "in", "range", "(", "len_pop", ")", ":", "psum", "[", "i", "]", "/=", "float", "(", "psum", "[", "len_pop", "-", "1", "]", ")", "# Select the individuals", "selected", "=", "[", "]", "for", "_", "in", "range", "(", "num_selected", ")", ":", "cutoff", "=", "random", ".", "random", "(", ")", "lower", "=", "0", "upper", "=", "len_pop", "-", "1", "while", "(", "upper", ">=", "lower", ")", ":", "mid", "=", "(", "lower", "+", "upper", ")", "//", "2", "if", "psum", "[", "mid", "]", ">", "cutoff", ":", "upper", "=", "mid", "-", "1", "else", ":", "lower", "=", "mid", "+", "1", "lower", "=", "max", "(", "0", ",", "min", "(", "len_pop", "-", "1", ",", "lower", ")", ")", "selected", ".", "append", "(", "population", "[", "lower", "]", ")", "return", "selected" ]
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 wheel" selection. Note that this selection is not valid for minimization problems. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default 1)
[ "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", "wheel", "selection", ".", "Note", "that", "this", "selection", "is", "not", "valid", "for", "minimization", "problems", ".", "..", "Arguments", ":", "random", "--", "the", "random", "number", "generator", "object", "population", "--", "the", "population", "of", "individuals", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/selectors.py#L110-L164
aarongarrett/inspyred
inspyred/ec/selectors.py
rank_selection
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 probability. This means that it can be used for both maximization and minimization problems, since higher rank can be defined correctly for both. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default 1) """ num_selected = args.setdefault('num_selected', 1) # Set up the roulette wheel len_pop = len(population) population.sort() psum = list(range(len_pop)) den = (len_pop * (len_pop + 1)) / 2.0 for i in range(len_pop): psum[i] = (i + 1) / den for i in range(1, len_pop): psum[i] += psum[i-1] # Select the individuals selected = [] for _ in range(num_selected): cutoff = random.random() lower = 0 upper = len_pop - 1 while(upper >= lower): mid = (lower + upper) // 2 if psum[mid] > cutoff: upper = mid - 1 else: lower = mid + 1 lower = max(0, min(len_pop-1, lower)) selected.append(population[lower]) return selected
python
def rank_selection(random, population, args): num_selected = args.setdefault('num_selected', 1) len_pop = len(population) population.sort() psum = list(range(len_pop)) den = (len_pop * (len_pop + 1)) / 2.0 for i in range(len_pop): psum[i] = (i + 1) / den for i in range(1, len_pop): psum[i] += psum[i-1] selected = [] for _ in range(num_selected): cutoff = random.random() lower = 0 upper = len_pop - 1 while(upper >= lower): mid = (lower + upper) // 2 if psum[mid] > cutoff: upper = mid - 1 else: lower = mid + 1 lower = max(0, min(len_pop-1, lower)) selected.append(population[lower]) return selected
[ "def", "rank_selection", "(", "random", ",", "population", ",", "args", ")", ":", "num_selected", "=", "args", ".", "setdefault", "(", "'num_selected'", ",", "1", ")", "# Set up the roulette wheel", "len_pop", "=", "len", "(", "population", ")", "population", ".", "sort", "(", ")", "psum", "=", "list", "(", "range", "(", "len_pop", ")", ")", "den", "=", "(", "len_pop", "*", "(", "len_pop", "+", "1", ")", ")", "/", "2.0", "for", "i", "in", "range", "(", "len_pop", ")", ":", "psum", "[", "i", "]", "=", "(", "i", "+", "1", ")", "/", "den", "for", "i", "in", "range", "(", "1", ",", "len_pop", ")", ":", "psum", "[", "i", "]", "+=", "psum", "[", "i", "-", "1", "]", "# Select the individuals", "selected", "=", "[", "]", "for", "_", "in", "range", "(", "num_selected", ")", ":", "cutoff", "=", "random", ".", "random", "(", ")", "lower", "=", "0", "upper", "=", "len_pop", "-", "1", "while", "(", "upper", ">=", "lower", ")", ":", "mid", "=", "(", "lower", "+", "upper", ")", "//", "2", "if", "psum", "[", "mid", "]", ">", "cutoff", ":", "upper", "=", "mid", "-", "1", "else", ":", "lower", "=", "mid", "+", "1", "lower", "=", "max", "(", "0", ",", "min", "(", "len_pop", "-", "1", ",", "lower", ")", ")", "selected", ".", "append", "(", "population", "[", "lower", "]", ")", "return", "selected" ]
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 probability. This means that it can be used for both maximization and minimization problems, since higher rank can be defined correctly for both. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default 1)
[ "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", "probability", ".", "This", "means", "that", "it", "can", "be", "used", "for", "both", "maximization", "and", "minimization", "problems", "since", "higher", "rank", "can", "be", "defined", "correctly", "for", "both", ".", "..", "Arguments", ":", "random", "--", "the", "random", "number", "generator", "object", "population", "--", "the", "population", "of", "individuals", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/selectors.py#L167-L212
aarongarrett/inspyred
inspyred/ec/selectors.py
tournament_selection
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 and adds the best of the tournament as its selection. If ``tournament_size`` is greater than the population size, the population size is used instead as the size of the tournament. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default 1) - *tournament_size* -- the tournament size (default 2) """ num_selected = args.setdefault('num_selected', 1) tournament_size = args.setdefault('tournament_size', 2) if tournament_size > len(population): tournament_size = len(population) selected = [] for _ in range(num_selected): tourn = random.sample(population, tournament_size) selected.append(max(tourn)) return selected
python
def tournament_selection(random, population, args): num_selected = args.setdefault('num_selected', 1) tournament_size = args.setdefault('tournament_size', 2) if tournament_size > len(population): tournament_size = len(population) selected = [] for _ in range(num_selected): tourn = random.sample(population, tournament_size) selected.append(max(tourn)) return selected
[ "def", "tournament_selection", "(", "random", ",", "population", ",", "args", ")", ":", "num_selected", "=", "args", ".", "setdefault", "(", "'num_selected'", ",", "1", ")", "tournament_size", "=", "args", ".", "setdefault", "(", "'tournament_size'", ",", "2", ")", "if", "tournament_size", ">", "len", "(", "population", ")", ":", "tournament_size", "=", "len", "(", "population", ")", "selected", "=", "[", "]", "for", "_", "in", "range", "(", "num_selected", ")", ":", "tourn", "=", "random", ".", "sample", "(", "population", ",", "tournament_size", ")", "selected", ".", "append", "(", "max", "(", "tourn", ")", ")", "return", "selected" ]
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 and adds the best of the tournament as its selection. If ``tournament_size`` is greater than the population size, the population size is used instead as the size of the tournament. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default 1) - *tournament_size* -- the tournament size (default 2)
[ "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", "and", "adds", "the", "best", "of", "the", "tournament", "as", "its", "selection", ".", "If", "tournament_size", "is", "greater", "than", "the", "population", "size", "the", "population", "size", "is", "used", "instead", "as", "the", "size", "of", "the", "tournament", ".", "..", "Arguments", ":", "random", "--", "the", "random", "number", "generator", "object", "population", "--", "the", "population", "of", "individuals", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/selectors.py#L215-L244
aarongarrett/inspyred
inspyred/ec/observers.py
best_observer
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_generations -- the number of elapsed generations num_evaluations -- the number of candidate solution evaluations args -- a dictionary of keyword arguments """ print("Best Individual: {0}\n".format(str(max(population))))
python
def best_observer(population, num_generations, num_evaluations, args): print("Best Individual: {0}\n".format(str(max(population))))
[ "def", "best_observer", "(", "population", ",", "num_generations", ",", "num_evaluations", ",", "args", ")", ":", "print", "(", "\"Best Individual: {0}\\n\"", ".", "format", "(", "str", "(", "max", "(", "population", ")", ")", ")", ")" ]
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_generations -- the number of elapsed generations num_evaluations -- the number of candidate solution evaluations args -- a dictionary of keyword arguments
[ "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_generations", "--", "the", "number", "of", "elapsed", "generations", "num_evaluations", "--", "the", "number", "of", "candidate", "solution", "evaluations", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/observers.py#L59-L72
aarongarrett/inspyred
inspyred/ec/observers.py
stats_observer
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 evaluations, the maximum fitness, the minimum fitness, the average fitness, and the standard deviation. .. note:: This function makes use of the ``inspyred.ec.analysis.fitness_statistics`` function, so it is subject to the same requirements. .. Arguments: population -- the population of Individuals num_generations -- the number of elapsed generations num_evaluations -- the number of candidate solution evaluations args -- a dictionary of keyword arguments """ stats = inspyred.ec.analysis.fitness_statistics(population) worst_fit = '{0:>10}'.format(stats['worst'])[:10] best_fit = '{0:>10}'.format(stats['best'])[:10] avg_fit = '{0:>10}'.format(stats['mean'])[:10] med_fit = '{0:>10}'.format(stats['median'])[:10] std_fit = '{0:>10}'.format(stats['std'])[:10] print('Generation Evaluation Worst Best Median Average Std Dev') print('---------- ---------- ---------- ---------- ---------- ---------- ----------') print('{0:>10} {1:>10} {2:>10} {3:>10} {4:>10} {5:>10} {6:>10}\n'.format(num_generations, num_evaluations, worst_fit, best_fit, med_fit, avg_fit, std_fit))
python
def stats_observer(population, num_generations, num_evaluations, args): stats = inspyred.ec.analysis.fitness_statistics(population) worst_fit = '{0:>10}'.format(stats['worst'])[:10] best_fit = '{0:>10}'.format(stats['best'])[:10] avg_fit = '{0:>10}'.format(stats['mean'])[:10] med_fit = '{0:>10}'.format(stats['median'])[:10] std_fit = '{0:>10}'.format(stats['std'])[:10] print('Generation Evaluation Worst Best Median Average Std Dev') print('---------- ---------- ---------- ---------- ---------- ---------- ----------') print('{0:>10} {1:>10} {2:>10} {3:>10} {4:>10} {5:>10} {6:>10}\n'.format(num_generations, num_evaluations, worst_fit, best_fit, med_fit, avg_fit, std_fit))
[ "def", "stats_observer", "(", "population", ",", "num_generations", ",", "num_evaluations", ",", "args", ")", ":", "stats", "=", "inspyred", ".", "ec", ".", "analysis", ".", "fitness_statistics", "(", "population", ")", "worst_fit", "=", "'{0:>10}'", ".", "format", "(", "stats", "[", "'worst'", "]", ")", "[", ":", "10", "]", "best_fit", "=", "'{0:>10}'", ".", "format", "(", "stats", "[", "'best'", "]", ")", "[", ":", "10", "]", "avg_fit", "=", "'{0:>10}'", ".", "format", "(", "stats", "[", "'mean'", "]", ")", "[", ":", "10", "]", "med_fit", "=", "'{0:>10}'", ".", "format", "(", "stats", "[", "'median'", "]", ")", "[", ":", "10", "]", "std_fit", "=", "'{0:>10}'", ".", "format", "(", "stats", "[", "'std'", "]", ")", "[", ":", "10", "]", "print", "(", "'Generation Evaluation Worst Best Median Average Std Dev'", ")", "print", "(", "'---------- ---------- ---------- ---------- ---------- ---------- ----------'", ")", "print", "(", "'{0:>10} {1:>10} {2:>10} {3:>10} {4:>10} {5:>10} {6:>10}\\n'", ".", "format", "(", "num_generations", ",", "num_evaluations", ",", "worst_fit", ",", "best_fit", ",", "med_fit", ",", "avg_fit", ",", "std_fit", ")", ")" ]
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 evaluations, the maximum fitness, the minimum fitness, the average fitness, and the standard deviation. .. note:: This function makes use of the ``inspyred.ec.analysis.fitness_statistics`` function, so it is subject to the same requirements. .. Arguments: population -- the population of Individuals num_generations -- the number of elapsed generations num_evaluations -- the number of candidate solution evaluations args -- a dictionary of keyword arguments
[ "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", "evaluations", "the", "maximum", "fitness", "the", "minimum", "fitness", "the", "average", "fitness", "and", "the", "standard", "deviation", ".", "..", "note", "::", "This", "function", "makes", "use", "of", "the", "inspyred", ".", "ec", ".", "analysis", ".", "fitness_statistics", "function", "so", "it", "is", "subject", "to", "the", "same", "requirements", ".", "..", "Arguments", ":", "population", "--", "the", "population", "of", "Individuals", "num_generations", "--", "the", "number", "of", "elapsed", "generations", "num_evaluations", "--", "the", "number", "of", "candidate", "solution", "evaluations", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/observers.py#L75-L110
aarongarrett/inspyred
inspyred/ec/observers.py
population_observer
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: population -- the population of Individuals num_generations -- the number of elapsed generations num_evaluations -- the number of candidate solution evaluations args -- a dictionary of keyword arguments """ population.sort(reverse=True) print('----------------------------------------------------------------------------') print(' Current Population') print('----------------------------------------------------------------------------') for ind in population: print(str(ind)) print('----------------------------------------------------------------------------')
python
def population_observer(population, num_generations, num_evaluations, args): population.sort(reverse=True) print('----------------------------------------------------------------------------') print(' Current Population') print('----------------------------------------------------------------------------') for ind in population: print(str(ind)) print('----------------------------------------------------------------------------')
[ "def", "population_observer", "(", "population", ",", "num_generations", ",", "num_evaluations", ",", "args", ")", ":", "population", ".", "sort", "(", "reverse", "=", "True", ")", "print", "(", "'----------------------------------------------------------------------------'", ")", "print", "(", "' Current Population'", ")", "print", "(", "'----------------------------------------------------------------------------'", ")", "for", "ind", "in", "population", ":", "print", "(", "str", "(", "ind", ")", ")", "print", "(", "'----------------------------------------------------------------------------'", ")" ]
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: population -- the population of Individuals num_generations -- the number of elapsed generations num_evaluations -- the number of candidate solution evaluations args -- a dictionary of keyword arguments
[ "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", ":", "population", "--", "the", "population", "of", "Individuals", "num_generations", "--", "the", "number", "of", "elapsed", "generations", "num_evaluations", "--", "the", "number", "of", "candidate", "solution", "evaluations", "args", "--", "a", "dictionary", "of", "keyword", "arguments" ]
train
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/observers.py#L113-L132