id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
3,600
django-danceschool/django-danceschool
danceschool/private_lessons/views.py
AddAvailabilitySlotView.form_valid
def form_valid(self, form): ''' Create slots and return success message. ''' startDate = form.cleaned_data['startDate'] endDate = form.cleaned_data['endDate'] startTime = form.cleaned_data['startTime'] endTime = form.cleaned_data['endTime'] instructor = fo...
python
def form_valid(self, form): ''' Create slots and return success message. ''' startDate = form.cleaned_data['startDate'] endDate = form.cleaned_data['endDate'] startTime = form.cleaned_data['startTime'] endTime = form.cleaned_data['endTime'] instructor = fo...
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "startDate", "=", "form", ".", "cleaned_data", "[", "'startDate'", "]", "endDate", "=", "form", ".", "cleaned_data", "[", "'endDate'", "]", "startTime", "=", "form", ".", "cleaned_data", "[", "'start...
Create slots and return success message.
[ "Create", "slots", "and", "return", "success", "message", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/views.py#L61-L88
3,601
django-danceschool/django-danceschool
danceschool/private_lessons/views.py
UpdateAvailabilitySlotView.form_valid
def form_valid(self, form): ''' Modify or delete the availability slot as requested and return success message. ''' slotIds = form.cleaned_data['slotIds'] deleteSlot = form.cleaned_data.get('deleteSlot', False) these_slots = InstructorAvailabilitySlot.objects.filter(id__...
python
def form_valid(self, form): ''' Modify or delete the availability slot as requested and return success message. ''' slotIds = form.cleaned_data['slotIds'] deleteSlot = form.cleaned_data.get('deleteSlot', False) these_slots = InstructorAvailabilitySlot.objects.filter(id__...
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "slotIds", "=", "form", ".", "cleaned_data", "[", "'slotIds'", "]", "deleteSlot", "=", "form", ".", "cleaned_data", ".", "get", "(", "'deleteSlot'", ",", "False", ")", "these_slots", "=", "Instructor...
Modify or delete the availability slot as requested and return success message.
[ "Modify", "or", "delete", "the", "availability", "slot", "as", "requested", "and", "return", "success", "message", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/views.py#L101-L120
3,602
django-danceschool/django-danceschool
danceschool/private_lessons/views.py
BookPrivateLessonView.get_form_kwargs
def get_form_kwargs(self, **kwargs): ''' Pass the current user to the form to render the payAtDoor field if applicable. ''' kwargs = super(BookPrivateLessonView, self).get_form_kwargs(**kwargs) kwargs['user'] = self.request.user if hasattr(self.request,'user') else None r...
python
def get_form_kwargs(self, **kwargs): ''' Pass the current user to the form to render the payAtDoor field if applicable. ''' kwargs = super(BookPrivateLessonView, self).get_form_kwargs(**kwargs) kwargs['user'] = self.request.user if hasattr(self.request,'user') else None r...
[ "def", "get_form_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "super", "(", "BookPrivateLessonView", ",", "self", ")", ".", "get_form_kwargs", "(", "*", "*", "kwargs", ")", "kwargs", "[", "'user'", "]", "=", "self", ".", "req...
Pass the current user to the form to render the payAtDoor field if applicable.
[ "Pass", "the", "current", "user", "to", "the", "form", "to", "render", "the", "payAtDoor", "field", "if", "applicable", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/views.py#L137-L143
3,603
django-danceschool/django-danceschool
danceschool/private_lessons/views.py
PrivateLessonStudentInfoView.dispatch
def dispatch(self,request,*args,**kwargs): ''' Handle the session data passed by the prior view. ''' lessonSession = request.session.get(PRIVATELESSON_VALIDATION_STR,{}) try: self.lesson = PrivateLessonEvent.objects.get(id=lessonSession.get('lesson')) except...
python
def dispatch(self,request,*args,**kwargs): ''' Handle the session data passed by the prior view. ''' lessonSession = request.session.get(PRIVATELESSON_VALIDATION_STR,{}) try: self.lesson = PrivateLessonEvent.objects.get(id=lessonSession.get('lesson')) except...
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lessonSession", "=", "request", ".", "session", ".", "get", "(", "PRIVATELESSON_VALIDATION_STR", ",", "{", "}", ")", "try", ":", "self", ".", "lesson"...
Handle the session data passed by the prior view.
[ "Handle", "the", "session", "data", "passed", "by", "the", "prior", "view", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/views.py#L308-L327
3,604
django-danceschool/django-danceschool
danceschool/guestlist/views.py
GuestListView.get_object
def get_object(self, queryset=None): ''' Get the guest list from the URL ''' return get_object_or_404( GuestList.objects.filter(id=self.kwargs.get('guestlist_id')))
python
def get_object(self, queryset=None): ''' Get the guest list from the URL ''' return get_object_or_404( GuestList.objects.filter(id=self.kwargs.get('guestlist_id')))
[ "def", "get_object", "(", "self", ",", "queryset", "=", "None", ")", ":", "return", "get_object_or_404", "(", "GuestList", ".", "objects", ".", "filter", "(", "id", "=", "self", ".", "kwargs", ".", "get", "(", "'guestlist_id'", ")", ")", ")" ]
Get the guest list from the URL
[ "Get", "the", "guest", "list", "from", "the", "URL" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/guestlist/views.py#L18-L21
3,605
django-danceschool/django-danceschool
danceschool/guestlist/views.py
GuestListView.get_context_data
def get_context_data(self,**kwargs): ''' Add the list of names for the given guest list ''' event = Event.objects.filter(id=self.kwargs.get('event_id')).first() if self.kwargs.get('event_id') and not self.object.appliesToEvent(event): raise Http404(_('Invalid event.')) ...
python
def get_context_data(self,**kwargs): ''' Add the list of names for the given guest list ''' event = Event.objects.filter(id=self.kwargs.get('event_id')).first() if self.kwargs.get('event_id') and not self.object.appliesToEvent(event): raise Http404(_('Invalid event.')) ...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "event", "=", "Event", ".", "objects", ".", "filter", "(", "id", "=", "self", ".", "kwargs", ".", "get", "(", "'event_id'", ")", ")", ".", "first", "(", ")", "if", "self", ...
Add the list of names for the given guest list
[ "Add", "the", "list", "of", "names", "for", "the", "given", "guest", "list" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/guestlist/views.py#L23-L39
3,606
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
PrivateLessonEvent.getBasePrice
def getBasePrice(self,**kwargs): ''' This method overrides the method of the base Event class by checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate price for it. ''' if not self.pricingTier: return None return ...
python
def getBasePrice(self,**kwargs): ''' This method overrides the method of the base Event class by checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate price for it. ''' if not self.pricingTier: return None return ...
[ "def", "getBasePrice", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pricingTier", ":", "return", "None", "return", "self", ".", "pricingTier", ".", "getBasePrice", "(", "*", "*", "kwargs", ")", "*", "max", "(", "self", "...
This method overrides the method of the base Event class by checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate price for it.
[ "This", "method", "overrides", "the", "method", "of", "the", "base", "Event", "class", "by", "checking", "the", "pricingTier", "associated", "with", "this", "PrivateLessonEvent", "and", "getting", "the", "appropriate", "price", "for", "it", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L48-L56
3,607
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
PrivateLessonEvent.customers
def customers(self): ''' List both any individuals signed up via the registration and payment system, and any individuals signed up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistrati...
python
def customers(self): ''' List both any individuals signed up via the registration and payment system, and any individuals signed up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistrati...
[ "def", "customers", "(", "self", ")", ":", "return", "Customer", ".", "objects", ".", "filter", "(", "Q", "(", "privatelessoncustomer__lesson", "=", "self", ")", "|", "Q", "(", "registration__eventregistration__event", "=", "self", ")", ")", ".", "distinct", ...
List both any individuals signed up via the registration and payment system, and any individuals signed up without payment.
[ "List", "both", "any", "individuals", "signed", "up", "via", "the", "registration", "and", "payment", "system", "and", "any", "individuals", "signed", "up", "without", "payment", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L122-L130
3,608
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
PrivateLessonEvent.save
def save(self, *args, **kwargs): ''' Set registration status to hidden if it is not specified otherwise ''' if not self.status: self.status == Event.RegStatus.hidden super(PrivateLessonEvent,self).save(*args,**kwargs)
python
def save(self, *args, **kwargs): ''' Set registration status to hidden if it is not specified otherwise ''' if not self.status: self.status == Event.RegStatus.hidden super(PrivateLessonEvent,self).save(*args,**kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "status", ":", "self", ".", "status", "==", "Event", ".", "RegStatus", ".", "hidden", "super", "(", "PrivateLessonEvent", ",", "self", ")", "...
Set registration status to hidden if it is not specified otherwise
[ "Set", "registration", "status", "to", "hidden", "if", "it", "is", "not", "specified", "otherwise" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L172-L176
3,609
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
InstructorAvailabilitySlot.availableDurations
def availableDurations(self): ''' A lesson can always be booked for the length of a single slot, but this method checks if multiple slots are available. This method requires that slots are non-overlapping, which needs to be enforced on slot save. ''' potential_slots = In...
python
def availableDurations(self): ''' A lesson can always be booked for the length of a single slot, but this method checks if multiple slots are available. This method requires that slots are non-overlapping, which needs to be enforced on slot save. ''' potential_slots = In...
[ "def", "availableDurations", "(", "self", ")", ":", "potential_slots", "=", "InstructorAvailabilitySlot", ".", "objects", ".", "filter", "(", "instructor", "=", "self", ".", "instructor", ",", "location", "=", "self", ".", "location", ",", "room", "=", "self",...
A lesson can always be booked for the length of a single slot, but this method checks if multiple slots are available. This method requires that slots are non-overlapping, which needs to be enforced on slot save.
[ "A", "lesson", "can", "always", "be", "booked", "for", "the", "length", "of", "a", "single", "slot", "but", "this", "method", "checks", "if", "multiple", "slots", "are", "available", ".", "This", "method", "requires", "that", "slots", "are", "non", "-", ...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L252-L284
3,610
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
InstructorAvailabilitySlot.availableRoles
def availableRoles(self): ''' Some instructors only offer private lessons for certain roles, so we should only allow booking for the roles that have been selected for the instructor. ''' if not hasattr(self.instructor,'instructorprivatelessondetails'): return [] ...
python
def availableRoles(self): ''' Some instructors only offer private lessons for certain roles, so we should only allow booking for the roles that have been selected for the instructor. ''' if not hasattr(self.instructor,'instructorprivatelessondetails'): return [] ...
[ "def", "availableRoles", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ".", "instructor", ",", "'instructorprivatelessondetails'", ")", ":", "return", "[", "]", "return", "[", "[", "x", ".", "id", ",", "x", ".", "name", "]", "for", "x", ...
Some instructors only offer private lessons for certain roles, so we should only allow booking for the roles that have been selected for the instructor.
[ "Some", "instructors", "only", "offer", "private", "lessons", "for", "certain", "roles", "so", "we", "should", "only", "allow", "booking", "for", "the", "roles", "that", "have", "been", "selected", "for", "the", "instructor", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L287-L297
3,611
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
InstructorAvailabilitySlot.checkIfAvailable
def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available, but also tentative slots that have been held as tentative past their expiration date ''' return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBook...
python
def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available, but also tentative slots that have been held as tentative past their expiration date ''' return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBook...
[ "def", "checkIfAvailable", "(", "self", ",", "dateTime", "=", "timezone", ".", "now", "(", ")", ")", ":", "return", "(", "self", ".", "startTime", ">=", "dateTime", "+", "timedelta", "(", "days", "=", "getConstant", "(", "'privateLessons__closeBookingDays'", ...
Available slots are available, but also tentative slots that have been held as tentative past their expiration date
[ "Available", "slots", "are", "available", "but", "also", "tentative", "slots", "that", "have", "been", "held", "as", "tentative", "past", "their", "expiration", "date" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L299-L313
3,612
django-danceschool/django-danceschool
danceschool/private_events/feeds.py
json_event_feed
def json_event_feed(request,location_id=None,room_id=None): ''' The Jquery fullcalendar app requires a JSON news feed, so this function creates the feed from upcoming PrivateEvent objects ''' if not getConstant('calendar__privateCalendarFeedEnabled') or not request.user.is_staff: ret...
python
def json_event_feed(request,location_id=None,room_id=None): ''' The Jquery fullcalendar app requires a JSON news feed, so this function creates the feed from upcoming PrivateEvent objects ''' if not getConstant('calendar__privateCalendarFeedEnabled') or not request.user.is_staff: ret...
[ "def", "json_event_feed", "(", "request", ",", "location_id", "=", "None", ",", "room_id", "=", "None", ")", ":", "if", "not", "getConstant", "(", "'calendar__privateCalendarFeedEnabled'", ")", "or", "not", "request", ".", "user", ".", "is_staff", ":", "return...
The Jquery fullcalendar app requires a JSON news feed, so this function creates the feed from upcoming PrivateEvent objects
[ "The", "Jquery", "fullcalendar", "app", "requires", "a", "JSON", "news", "feed", "so", "this", "function", "creates", "the", "feed", "from", "upcoming", "PrivateEvent", "objects" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_events/feeds.py#L122-L159
3,613
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.') ...
python
def checkRequirements(sender,**kwargs): ''' Check that the customer meets all prerequisites for the items in the registration. ''' if not getConstant('requirements__enableRequirements'): return logger.debug('Signal to check RegistrationContactForm handled by prerequisites app.') ...
[ "def", "checkRequirements", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "getConstant", "(", "'requirements__enableRequirements'", ")", ":", "return", "logger", ".", "debug", "(", "'Signal to check RegistrationContactForm handled by prerequisites app.'",...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/prerequisites/handlers.py#L22-L74
3,614
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 variabl...
python
def get_email_context(self,**kwargs): ''' This method can be overridden in classes that inherit from this mixin so that additional object-specific context is provided to the email template. This should return a dictionary. By default, only general financial context variabl...
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "kwargs", "context", ".", "update", "(", "{", "'currencyCode'", ":", "getConstant", "(", "'general__currencyCode'", ")", ",", "'currencySymbol'", ":", "getConstant", "(...
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...
[ "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", "...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L107-L128
3,615
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,se...
python
def get_group_required(self): ''' Get the group_required value from the object ''' this_object = self.model_object if hasattr(this_object,self.group_required_field): if hasattr(getattr(this_object,self.group_required_field),'name'): return [getattr(this_object,se...
[ "def", "get_group_required", "(", "self", ")", ":", "this_object", "=", "self", ".", "model_object", "if", "hasattr", "(", "this_object", ",", "self", ".", "group_required_field", ")", ":", "if", "hasattr", "(", "getattr", "(", "this_object", ",", "self", "....
Get the group_required value from the object
[ "Get", "the", "group_required", "value", "from", "the", "object" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L179-L185
3,616
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) ...
python
def check_membership(self, groups): ''' Allows for objects with no required groups ''' if not groups or groups == ['']: return True if self.request.user.is_superuser: return True user_groups = self.request.user.groups.values_list("name", flat=True) ...
[ "def", "check_membership", "(", "self", ",", "groups", ")", ":", "if", "not", "groups", "or", "groups", "==", "[", "''", "]", ":", "return", "True", "if", "self", ".", "request", ".", "user", ".", "is_superuser", ":", "return", "True", "user_groups", "...
Allows for objects with no required groups
[ "Allows", "for", "objects", "with", "no", "required", "groups" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L187-L194
3,617
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_requir...
python
def dispatch(self, request, *args, **kwargs): ''' This override of dispatch ensures that if no group is required, then the request still goes through without being logged in. ''' self.request = request in_group = False required_group = self.get_group_requir...
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "request", "=", "request", "in_group", "=", "False", "required_group", "=", "self", ".", "get_group_required", "(", ")", "if", "not", "req...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L196-L218
3,618
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 TemplateDoesNotEx...
python
def validate(self,value): ''' Check for empty values, and for an existing template, but do not check if this is one of the initial choices provided. ''' super(ChoiceField,self).validate(value) try: get_template(value) except TemplateDoesNotEx...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "super", "(", "ChoiceField", ",", "self", ")", ".", "validate", "(", "value", ")", "try", ":", "get_template", "(", "value", ")", "except", "TemplateDoesNotExist", ":", "raise", "ValidationError", "("...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L242-L252
3,619
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): ''' Permits setting of the template in the plugin instance configuration ''' if instance and instance.template: self.render_template = instance.template return super(PluginTemplateMixin,self).render(context,instance,placeholder)
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "if", "instance", "and", "instance", ".", "template", ":", "self", ".", "render_template", "=", "instance", ".", "template", "return", "super", "(", "PluginTemplateM...
Permits setting of the template in the plugin instance configuration
[ "Permits", "setting", "of", "the", "template", "in", "the", "plugin", "instance", "configuration" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L261-L265
3,620
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): ''' This is just a wrapper for the getReturnPage helper function. ''' 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", "...
This is just a wrapper for the getReturnPage helper function.
[ "This", "is", "just", "a", "wrapper", "for", "the", "getReturnPage", "helper", "function", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L487-L490
3,621
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...
python
def is_valid(self): ''' For this form to be considered valid, there must be not only no errors, but also no messages on the request that need to be shown. ''' valid = super(RegistrationContactForm,self).is_valid() msgs = messages.get_messages(self._request) # We...
[ "def", "is_valid", "(", "self", ")", ":", "valid", "=", "super", "(", "RegistrationContactForm", ",", "self", ")", ".", "is_valid", "(", ")", "msgs", "=", "messages", ".", "get_messages", "(", "self", ".", "_request", ")", "# We only want validation messages t...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L378-L401
3,622
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...
python
def clean_total_refund_amount(self): ''' The Javascript should ensure that the hidden input is updated, but double check it here. ''' initial = self.cleaned_data.get('initial_refund_amount', 0) total = self.cleaned_data['total_refund_amount'] summed_refunds = sum([v for k...
[ "def", "clean_total_refund_amount", "(", "self", ")", ":", "initial", "=", "self", ".", "cleaned_data", ".", "get", "(", "'initial_refund_amount'", ",", "0", ")", "total", "=", "self", ".", "cleaned_data", "[", "'total_refund_amount'", "]", "summed_refunds", "="...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L662-L679
3,623
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() occurre...
python
def clean(self): ''' This code prevents multiple individuals from substituting for the same class and class teacher. It also prevents an individual from substituting for a class in which they are a teacher. ''' super(SubstituteReportingForm,self).clean() occurre...
[ "def", "clean", "(", "self", ")", ":", "super", "(", "SubstituteReportingForm", ",", "self", ")", ".", "clean", "(", ")", "occurrences", "=", "self", ".", "cleaned_data", ".", "get", "(", "'occurrences'", ",", "[", "]", ")", "staffMember", "=", "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.
[ "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...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L868-L888
3,624
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. ...
python
def save(self, commit=True): ''' If a staff member is reporting substitute teaching for a second time, then we should update the list of occurrences for which they are a substitute on their existing EventStaffMember record, rather than creating a new record and creating database issues. ...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "existing_record", "=", "EventStaffMember", ".", "objects", ".", "filter", "(", "staffMember", "=", "self", ".", "cleaned_data", ".", "get", "(", "'staffMember'", ")", ",", "event", "=", "...
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", "Event...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L898-L917
3,625
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.insta...
python
def save(self, commit=True): ''' If the staff member is an instructor, also update the availableForPrivates field on the Instructor record. ''' if getattr(self.instance,'instructor',None): self.instance.instructor.availableForPrivates = self.cleaned_data.pop('availableForPrivates',self.insta...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "if", "getattr", "(", "self", ".", "instance", ",", "'instructor'", ",", "None", ")", ":", "self", ".", "instance", ".", "instructor", ".", "availableForPrivates", "=", "self", ".", "cle...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/forms.py#L942-L947
3,626
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): ''' Just add "s" if no plural name given. ''' if not self.pluralName: self.pluralName = self.name + 's' super(self.__class__, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pluralName", ":", "self", ".", "pluralName", "=", "self", ".", "name", "+", "'s'", "super", "(", "self", ".", "__class__", ",", "self", ")...
Just add "s" if no plural name given.
[ "Just", "add", "s", "if", "no", "plural", "name", "given", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L83-L89
3,627
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('payA...
python
def getBasePrice(self,**kwargs): ''' This handles the logic of finding the correct price. If more sophisticated discounting systems are needed, then this PricingTier model can be subclassed, or the discounts and vouchers apps can be used. ''' payAtDoor = kwargs.get('payA...
[ "def", "getBasePrice", "(", "self", ",", "*", "*", "kwargs", ")", ":", "payAtDoor", "=", "kwargs", ".", "get", "(", "'payAtDoor'", ",", "False", ")", "dropIns", "=", "kwargs", ".", "get", "(", "'dropIns'", ",", "0", ")", "if", "dropIns", ":", "return...
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", "v...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L432-L445
3,628
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...
python
def availableRoles(self): ''' Returns the set of roles for this event. Since roles are not always custom specified for event, this looks for the set of available roles in multiple places. If no roles are found, then the method returns an empty list, in which case it can be assumed that...
[ "def", "availableRoles", "(", "self", ")", ":", "eventRoles", "=", "self", ".", "eventrole_set", ".", "filter", "(", "capacity__gt", "=", "0", ")", "if", "eventRoles", ".", "count", "(", ")", ">", "0", ":", "return", "[", "x", ".", "role", "for", "x"...
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-...
[ "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", ...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L952-L964
3,629
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: ...
python
def numRegisteredForRole(self, role, includeTemporaryRegs=False): ''' Accepts a DanceRole object and returns the number of registrations of that role. ''' count = self.eventregistration_set.filter(cancelled=False,dropIn=False,role=role).count() if includeTemporaryRegs: ...
[ "def", "numRegisteredForRole", "(", "self", ",", "role", ",", "includeTemporaryRegs", "=", "False", ")", ":", "count", "=", "self", ".", "eventregistration_set", ".", "filter", "(", "cancelled", "=", "False", ",", "dropIn", "=", "False", ",", "role", "=", ...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L967-L975
3,630
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 e...
python
def capacityForRole(self,role): ''' Accepts a DanceRole object and determines the capacity for that role at this event.this Since roles are not always custom specified for events, this looks for the set of available roles in multiple places, and only returns the overall capacity of the e...
[ "def", "capacityForRole", "(", "self", ",", "role", ")", ":", "if", "isinstance", "(", "role", ",", "DanceRole", ")", ":", "role_id", "=", "role", ".", "id", "else", ":", "role_id", "=", "role", "eventRoles", "=", "self", ".", "eventrole_set", ".", "fi...
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", ...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L986-L1022
3,631
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=include...
python
def soldOutForRole(self,role,includeTemporaryRegs=False): ''' Accepts a DanceRole object and responds if the number of registrations for that role exceeds the capacity for that role at this event. ''' return self.numRegisteredForRole( role,includeTemporaryRegs=include...
[ "def", "soldOutForRole", "(", "self", ",", "role", ",", "includeTemporaryRegs", "=", "False", ")", ":", "return", "self", ".", "numRegisteredForRole", "(", "role", ",", "includeTemporaryRegs", "=", "includeTemporaryRegs", ")", ">=", "(", "self", ".", "capacityFo...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1024-L1030
3,632
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 ...
python
def allDayForDate(self,this_date,timeZone=None): ''' This method determines whether the occurrence lasts the entirety of a specified day in the specified time zone. If no time zone is specified, then it uses the default time zone). Also, give a grace period of a few minutes to ...
[ "def", "allDayForDate", "(", "self", ",", "this_date", ",", "timeZone", "=", "None", ")", ":", "if", "isinstance", "(", "this_date", ",", "datetime", ")", ":", "d", "=", "this_date", ".", "date", "(", ")", "else", ":", "d", "=", "this_date", "date_star...
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", ...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1191-L1211
3,633
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 [getC...
python
def netHours(self): ''' For regular event staff, this is the net hours worked for financial purposes. For Instructors, netHours is caclulated net of any substitutes. ''' if self.specifiedHours is not None: return self.specifiedHours elif self.category in [getC...
[ "def", "netHours", "(", "self", ")", ":", "if", "self", ".", "specifiedHours", "is", "not", "None", ":", "return", "self", ".", "specifiedHours", "elif", "self", ".", "category", "in", "[", "getConstant", "(", "'general__eventStaffCategoryAssistant'", ")", ","...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1284-L1294
3,634
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): ''' Overrides property from Event base class. ''' cd = getattr(self,'classDescription',None) if cd: sd = getattr(cd,'shortDescription','') d = getattr(cd,'description','') return sd if sd else d return ''
[ "def", "shortDescription", "(", "self", ")", ":", "cd", "=", "getattr", "(", "self", ",", "'classDescription'", ",", "None", ")", "if", "cd", ":", "sd", "=", "getattr", "(", "cd", ",", "'shortDescription'", ",", "''", ")", "d", "=", "getattr", "(", "...
Overrides property from Event base class.
[ "Overrides", "property", "from", "Event", "base", "class", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1360-L1369
3,635
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 ...
python
def netHours(self): ''' For regular event staff, this is the net hours worked for financial purposes. For Instructors, netHours is calculated net of any substitutes. ''' if self.specifiedHours is not None: return self.specifiedHours return self.event.duration ...
[ "def", "netHours", "(", "self", ")", ":", "if", "self", ".", "specifiedHours", "is", "not", "None", ":", "return", "self", ".", "specifiedHours", "return", "self", ".", "event", ".", "duration", "-", "sum", "(", "[", "sub", ".", "netHours", "for", "sub...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1466-L1473
3,636
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.temporaryeventre...
python
def getTimeOfClassesRemaining(self,numClasses=0): ''' For checking things like prerequisites, it's useful to check if a requirement is 'almost' met ''' occurrences = EventOccurrence.objects.filter( cancelled=False, event__in=[x.event for x in self.temporaryeventre...
[ "def", "getTimeOfClassesRemaining", "(", "self", ",", "numClasses", "=", "0", ")", ":", "occurrences", "=", "EventOccurrence", ".", "objects", ".", "filter", "(", "cancelled", "=", "False", ",", "event__in", "=", "[", "x", ".", "event", "for", "x", "in", ...
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" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1952-L1963
3,637
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 F...
python
def finalize(self,**kwargs): ''' This method is called when the payment process has been completed and a registration is ready to be finalized. It also fires the post-registration signal ''' dateTime = kwargs.pop('dateTime', timezone.now()) # If sendEmail is passed as F...
[ "def", "finalize", "(", "self", ",", "*", "*", "kwargs", ")", ":", "dateTime", "=", "kwargs", ".", "pop", "(", "'dateTime'", ",", "timezone", ".", "now", "(", ")", ")", "# If sendEmail is passed as False, then we won't send an email", "sendEmail", "=", "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
[ "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" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1987-L2061
3,638
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...
python
def save(self, *args, **kwargs): ''' If this is an HTML template, then set the non-HTML content to be the stripped version of the HTML. If this is a plain text template, then set the HTML content to be null. ''' if self.send_html: self.content = get_text_for_html(self...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "send_html", ":", "self", ".", "content", "=", "get_text_for_html", "(", "self", ".", "html_content", ")", "else", ":", "self", ".", "html_content", "...
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", ...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2469-L2479
3,639
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) ...
python
def create_from_registration(cls, reg, **kwargs): ''' Handles the creation of an Invoice as well as one InvoiceItem per assodciated TemporaryEventRegistration or registration. Also handles taxes appropriately. ''' submissionUser = kwargs.pop('submissionUser', None) ...
[ "def", "create_from_registration", "(", "cls", ",", "reg", ",", "*", "*", "kwargs", ")", ":", "submissionUser", "=", "kwargs", ".", "pop", "(", "'submissionUser'", ",", "None", ")", "collectedByUser", "=", "kwargs", ".", "pop", "(", "'collectedByUser'", ",",...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2591-L2656
3,640
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.ge...
python
def url(self): ''' Because invoice URLs are generally emailed, this includes the default site URL and the protocol specified in settings. ''' if self.id: return '%s://%s%s' % ( getConstant('email__linkProtocol'), Site.objects.ge...
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "id", ":", "return", "'%s://%s%s'", "%", "(", "getConstant", "(", "'email__linkProtocol'", ")", ",", "Site", ".", "objects", ".", "get_current", "(", ")", ".", "domain", ",", "reverse", "(", "'vie...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2710-L2721
3,641
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 se...
python
def calculateTaxes(self): ''' Updates the tax field to reflect the amount of taxes depending on the local rate as well as whether the buyer or seller pays sales tax. ''' tax_rate = (getConstant('registration__salesTaxRate') or 0) / 100 if tax_rate > 0: if se...
[ "def", "calculateTaxes", "(", "self", ")", ":", "tax_rate", "=", "(", "getConstant", "(", "'registration__salesTaxRate'", ")", "or", "0", ")", "/", "100", "if", "tax_rate", ">", "0", ":", "if", "self", ".", "buyerPaysSalesTax", ":", "# If the buyer pays taxes,...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2777-L2793
3,642
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...
python
def allocateFees(self): ''' Fees are allocated across invoice items based on their discounted total price net of adjustments as a proportion of the overall invoice's total price ''' items = list(self.invoiceitem_set.all()) # Check that totals and adjusments match...
[ "def", "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", "(", "[", "...
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" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L2865-L2903
3,643
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 ...
python
def applyAndAllocate(self,allocatedPrices,tieredTuples,payAtDoor=False): ''' This method takes an initial allocation of prices across events, and an identical length list of allocation tuples. It applies the rule specified by this discount, allocates the discount across the listed ...
[ "def", "applyAndAllocate", "(", "self", ",", "allocatedPrices", ",", "tieredTuples", ",", "payAtDoor", "=", "False", ")", ":", "initial_net_price", "=", "sum", "(", "[", "x", "for", "x", "in", "allocatedPrices", "]", ")", "if", "self", ".", "discountType", ...
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", "th...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/discounts/models.py#L146-L201
3,644
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...
python
def getComponentList(self): ''' This function just returns a list with items that are supposed to be present in the the list multiple times as multiple elements of the list. It simplifies checking whether a discount's conditions are satisfied. ''' component_list...
[ "def", "getComponentList", "(", "self", ")", ":", "component_list", "=", "[", "]", "for", "x", "in", "self", ".", "discountcombocomponent_set", ".", "all", "(", ")", ":", "for", "y", "in", "range", "(", "0", ",", "x", ".", "quantity", ")", ":", "comp...
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", ...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/discounts/models.py#L215-L230
3,645
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.discount...
python
def save(self, *args, **kwargs): ''' Don't save any passed values related to a type of discount that is not the specified type ''' if self.discountType != self.DiscountType.flatPrice: self.onlinePrice = None self.doorPrice = None if self.discount...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "discountType", "!=", "self", ".", "DiscountType", ".", "flatPrice", ":", "self", ".", "onlinePrice", "=", "None", "self", ".", "doorPrice", "=", "Non...
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" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/discounts/models.py#L232-L249
3,646
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'...
python
def checkVoucherCode(sender,**kwargs): ''' Check that the given voucher code is valid ''' logger.debug('Signal to check RegistrationContactForm handled by vouchers app.') formData = kwargs.get('formData',{}) request = kwargs.get('request',{}) registration = kwargs.get('registration'...
[ "def", "checkVoucherCode", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Signal to check RegistrationContactForm handled by vouchers app.'", ")", "formData", "=", "kwargs", ".", "get", "(", "'formData'", ",", "{", "}", ")", "re...
Check that the given voucher code is valid
[ "Check", "that", "the", "given", "voucher", "code", "is", "valid" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L20-L71
3,647
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. '...
python
def applyVoucherCodeTemporarily(sender,**kwargs): ''' When the core registration system creates a temporary registration with a voucher code, the voucher app looks for vouchers that match that code and creates TemporaryVoucherUse objects to keep track of the fact that the voucher may be used. '...
[ "def", "applyVoucherCodeTemporarily", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Signal fired to apply temporary vouchers.'", ")", "reg", "=", "kwargs", ".", "pop", "(", "'registration'", ")", "voucherId", "=", "reg", ".", ...
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", ...
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L75-L94
3,648
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(...
python
def applyReferrerVouchersTemporarily(sender,**kwargs): ''' Unlike voucher codes which have to be manually supplied, referrer discounts are automatically applied here, assuming that the referral program is enabled. ''' # Only continue if the referral program is enabled if not getConstant(...
[ "def", "applyReferrerVouchersTemporarily", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "# Only continue if the referral program is enabled\r", "if", "not", "getConstant", "(", "'referrals__enableReferralProgram'", ")", ":", "return", "logger", ".", "debug", "(", "...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L98-L124
3,649
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 = ...
python
def applyVoucherCodesFinal(sender,**kwargs): ''' Once a registration has been completed, vouchers are used and referrers are awarded ''' logger.debug('Signal fired to mark voucher codes as applied.') finalReg = kwargs.pop('registration') tr = finalReg.temporaryRegistration tvus = ...
[ "def", "applyVoucherCodesFinal", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Signal fired to mark voucher codes as applied.'", ")", "finalReg", "=", "kwargs", ".", "pop", "(", "'registration'", ")", "tr", "=", "finalReg", "."...
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" ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L170-L185
3,650
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__e...
python
def provideCustomerReferralCode(sender,**kwargs): ''' If the vouchers app is installed and referrals are enabled, then the customer's profile page can show their voucher referral code. ''' customer = kwargs.pop('customer') if getConstant('vouchers__enableVouchers') and getConstant('referrals__e...
[ "def", "provideCustomerReferralCode", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "customer", "=", "kwargs", ".", "pop", "(", "'customer'", ")", "if", "getConstant", "(", "'vouchers__enableVouchers'", ")", "and", "getConstant", "(", "'referrals__enableReferr...
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", "." ]
bb08cbf39017a812a5a94bdb4ea34170bf1a30ba
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/handlers.py#L189-L199
3,651
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 errors for unsupported lookups""" 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" ]
888777e5bdb93c72339663e7464f6ceaf4f5e7dd
https://github.com/orcasgit/django-fernet-fields/blob/888777e5bdb93c72339663e7464f6ceaf4f5e7dd/fernet_fields/fields.py#L93-L96
3,652
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): """Derive a 32-bit b64-encoded Fernet key from arbitrary input key.""" hkdf = HKDF( algorithm=hashes.SHA256(), length=32, salt=salt, info=info, backend=backend, ) return base64.urlsafe_b64encode(hkdf.derive(force_bytes(input_key))...
[ "def", "derive_fernet_key", "(", "input_key", ")", ":", "hkdf", "=", "HKDF", "(", "algorithm", "=", "hashes", ".", "SHA256", "(", ")", ",", "length", "=", "32", ",", "salt", "=", "salt", ",", "info", "=", "info", ",", "backend", "=", "backend", ",", ...
Derive a 32-bit b64-encoded Fernet key from arbitrary input key.
[ "Derive", "a", "32", "-", "bit", "b64", "-", "encoded", "Fernet", "key", "from", "arbitrary", "input", "key", "." ]
888777e5bdb93c72339663e7464f6ceaf4f5e7dd
https://github.com/orcasgit/django-fernet-fields/blob/888777e5bdb93c72339663e7464f6ceaf4f5e7dd/fernet_fields/hkdf.py#L14-L23
3,653
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=d...
python
def reduce_cpu(f, x, axes, dtype): """NumPy's reduce in terms of fold.""" axes = _get_axes(axes, x.ndim) if not axes: return x permute = [n for n in range(x.ndim) if n not in axes] permute = axes + permute T = x.transpose(permute=permute) N = len(axes) t = T.type.at(N, dtype=d...
[ "def", "reduce_cpu", "(", "f", ",", "x", ",", "axes", ",", "dtype", ")", ":", "axes", "=", "_get_axes", "(", "axes", ",", "x", ".", "ndim", ")", "if", "not", "axes", ":", "return", "x", "permute", "=", "[", "n", "for", "n", "in", "range", "(", ...
NumPy's reduce in terms of fold.
[ "NumPy", "s", "reduce", "in", "terms", "of", "fold", "." ]
a20ed5621db566ef805b8fb27ba4d8487f48c6b5
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath/__init__.py#L93-L118
3,654
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): """Reductions in CUDA use the thrust library for speed and have limited functionality.""" if axes != 0: raise NotImplementedError("'axes' keyword is not implemented for CUDA") return g(x, dtype=dtype)
[ "def", "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", "." ]
a20ed5621db566ef805b8fb27ba4d8487f48c6b5
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath/__init__.py#L120-L126
3,655
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): """Return maximum nesting depth""" maxlev = 0 def f(lst, level): nonlocal maxlev if isinstance(lst, list): level += 1 maxlev = max(level, maxlev) for item in lst: f(item, level) f(lst, 0) return maxlev
[ "def", "maxlevel", "(", "lst", ")", ":", "maxlev", "=", "0", "def", "f", "(", "lst", ",", "level", ")", ":", "nonlocal", "maxlev", "if", "isinstance", "(", "lst", ",", "list", ")", ":", "level", "+=", "1", "maxlev", "=", "max", "(", "level", ",",...
Return maximum nesting depth
[ "Return", "maximum", "nesting", "depth" ]
a20ed5621db566ef805b8fb27ba4d8487f48c6b5
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath_aux.py#L101-L112
3,656
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)...
python
def getitem(lst, indices): """Definition for multidimensional slicing and indexing on arbitrarily shaped nested lists. """ if not indices: return lst i, indices = indices[0], indices[1:] item = list.__getitem__(lst, i) if isinstance(i, int): return getitem(item, indices)...
[ "def", "getitem", "(", "lst", ",", "indices", ")", ":", "if", "not", "indices", ":", "return", "lst", "i", ",", "indices", "=", "indices", "[", "0", "]", ",", "indices", "[", "1", ":", "]", "item", "=", "list", ".", "__getitem__", "(", "lst", ","...
Definition for multidimensional slicing and indexing on arbitrarily shaped nested lists.
[ "Definition", "for", "multidimensional", "slicing", "and", "indexing", "on", "arbitrarily", "shaped", "nested", "lists", "." ]
a20ed5621db566ef805b8fb27ba4d8487f48c6b5
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath_aux.py#L114-L136
3,657
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): """Generate all possible slices for a single dimension.""" def range_with_none(): yield None yield from range(-n, n+1) for t in product(range_with_none(), range_with_none(), range_with_none()): s = slice(*t) if s.step != 0: yield s
[ "def", "genslices", "(", "n", ")", ":", "def", "range_with_none", "(", ")", ":", "yield", "None", "yield", "from", "range", "(", "-", "n", ",", "n", "+", "1", ")", "for", "t", "in", "product", "(", "range_with_none", "(", ")", ",", "range_with_none",...
Generate all possible slices for a single dimension.
[ "Generate", "all", "possible", "slices", "for", "a", "single", "dimension", "." ]
a20ed5621db566ef805b8fb27ba4d8487f48c6b5
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath_aux.py#L276-L285
3,658
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): """Generate all possible slice tuples for '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", "." ]
a20ed5621db566ef805b8fb27ba4d8487f48c6b5
https://github.com/xnd-project/gumath/blob/a20ed5621db566ef805b8fb27ba4d8487f48c6b5/python/gumath_aux.py#L287-L290
3,659
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 gi...
python
def mutator(mutate): """Return an inspyred mutator function based on the given function. This function generator takes a function that operates on only one candidate to produce a single mutated candidate. The generator handles the iteration over each candidate in the set to be mutated. The gi...
[ "def", "mutator", "(", "mutate", ")", ":", "@", "functools", ".", "wraps", "(", "mutate", ")", "def", "inspyred_mutator", "(", "random", ",", "candidates", ",", "args", ")", ":", "mutants", "=", "[", "]", "for", "i", ",", "cs", "in", "enumerate", "("...
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...
[ "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", "cand...
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L33-L65
3,660
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 gener...
python
def bit_flip_mutation(random, candidate, args): """Return the mutants produced by bit-flip mutation on the candidates. This function performs bit-flip mutation. If a candidate solution contains non-binary values, this function leaves it unchanged. .. Arguments: random -- the random number gener...
[ "def", "bit_flip_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "rate", "=", "args", ".", "setdefault", "(", "'mutation_rate'", ",", "0.1", ")", "mutant", "=", "copy", ".", "copy", "(", "candidate", ")", "if", "len", "(", "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 ...
[ "Return", "the", "mutants", "produced", "by", "bit", "-", "flip", "mutation", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L69-L93
3,661
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'...
python
def random_reset_mutation(random, candidate, args): """Return the mutants produced by randomly choosing new values. This function performs random-reset mutation. It assumes that candidate solutions are composed of discrete values. This function makes use of the bounder function as specified in the EC'...
[ "def", "random_reset_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "bounder", "=", "args", "[", "'_ec'", "]", ".", "bounder", "try", ":", "values", "=", "bounder", ".", "values", "except", "AttributeError", ":", "values", "=", "None", ...
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 c...
[ "Return", "the", "mutants", "produced", "by", "randomly", "choosing", "new", "values", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L97-L137
3,662
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 rand...
python
def scramble_mutation(random, candidate, args): """Return the mutants created by scramble mutation on the candidates. This function performs scramble mutation. It randomly chooses two locations along the candidate and scrambles the values within that slice. .. Arguments: random -- the rand...
[ "def", "scramble_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "rate", "=", "args", ".", "setdefault", "(", "'mutation_rate'", ",", "0.1", ")", "if", "random", ".", "random", "(", ")", "<", "rate", ":", "size", "=", "len", "(", "...
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 cand...
[ "Return", "the", "mutants", "created", "by", "scramble", "mutation", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L141-L171
3,663
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 n...
python
def gaussian_mutation(random, candidate, args): """Return the mutants created by Gaussian mutation on the candidates. This function performs Gaussian mutation. This function makes use of the bounder function as specified in the EC's ``evolve`` method. .. Arguments: random -- the random n...
[ "def", "gaussian_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "mut_rate", "=", "args", ".", "setdefault", "(", "'mutation_rate'", ",", "0.1", ")", "mean", "=", "args", ".", "setdefault", "(", "'gaussian_mean'", ",", "0.0", ")", "stdev...
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 candidat...
[ "Return", "the", "mutants", "created", "by", "Gaussian", "mutation", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L208-L239
3,664
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 o...
python
def nonuniform_mutation(random, candidate, args): """Return the mutants produced by nonuniform mutation on the candidates. The function performs nonuniform mutation as specified in (Michalewicz, "Genetic Algorithms + Data Structures = Evolution Programs," Springer, 1996). This function also makes use o...
[ "def", "nonuniform_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "bounder", "=", "args", "[", "'_ec'", "]", ".", "bounder", "num_gens", "=", "args", "[", "'_ec'", "]", ".", "num_generations", "max_gens", "=", "args", "[", "'max_generat...
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 ``ev...
[ "Return", "the", "mutants", "produced", "by", "nonuniform", "mutation", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/mutators.py#L243-L285
3,665
aarongarrett/inspyred
inspyred/ec/variators/crossovers.py
crossover
def crossover(cross): """Return an inspyred crossover function based on the given function. This function generator takes a function that operates on only two parent candidates to produce an iterable sequence of offspring (typically two). The generator handles the pairing of selected parents and co...
python
def crossover(cross): """Return an inspyred crossover function based on the given function. This function generator takes a function that operates on only two parent candidates to produce an iterable sequence of offspring (typically two). The generator handles the pairing of selected parents and co...
[ "def", "crossover", "(", "cross", ")", ":", "@", "functools", ".", "wraps", "(", "cross", ")", "def", "inspyred_crossover", "(", "random", ",", "candidates", ",", "args", ")", ":", "if", "len", "(", "candidates", ")", "%", "2", "==", "1", ":", "candi...
Return an inspyred crossover function based on the given function. This function generator takes a function that operates on only two parent candidates to produce an iterable sequence of offspring (typically two). The generator handles the pairing of selected parents and collecting of all offspring. ...
[ "Return", "an", "inspyred", "crossover", "function", "based", "on", "the", "given", "function", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/crossovers.py#L38-L83
3,666
aarongarrett/inspyred
inspyred/ec/variators/crossovers.py
n_point_crossover
def n_point_crossover(random, mom, dad, args): """Return the offspring of n-point crossover on the candidates. This function performs n-point crossover (NPX). It selects *n* random points without replacement at which to 'cut' the candidate solutions and recombine them. .. Arguments: rando...
python
def n_point_crossover(random, mom, dad, args): """Return the offspring of n-point crossover on the candidates. This function performs n-point crossover (NPX). It selects *n* random points without replacement at which to 'cut' the candidate solutions and recombine them. .. Arguments: rando...
[ "def", "n_point_crossover", "(", "random", ",", "mom", ",", "dad", ",", "args", ")", ":", "crossover_rate", "=", "args", ".", "setdefault", "(", "'crossover_rate'", ",", "1.0", ")", "num_crossover_points", "=", "args", ".", "setdefault", "(", "'num_crossover_p...
Return the offspring of n-point crossover on the candidates. This function performs n-point crossover (NPX). It selects *n* random points without replacement at which to 'cut' the candidate solutions and recombine them. .. Arguments: random -- the random number generator object mom -- ...
[ "Return", "the", "offspring", "of", "n", "-", "point", "crossover", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/crossovers.py#L87-L129
3,667
aarongarrett/inspyred
inspyred/ec/variators/crossovers.py
uniform_crossover
def uniform_crossover(random, mom, dad, args): """Return the offspring of uniform crossover on the candidates. This function performs uniform crossover (UX). For each element of the parents, a biased coin is flipped to determine whether the first offspring gets the 'mom' or the 'dad' element. An ...
python
def uniform_crossover(random, mom, dad, args): """Return the offspring of uniform crossover on the candidates. This function performs uniform crossover (UX). For each element of the parents, a biased coin is flipped to determine whether the first offspring gets the 'mom' or the 'dad' element. An ...
[ "def", "uniform_crossover", "(", "random", ",", "mom", ",", "dad", ",", "args", ")", ":", "ux_bias", "=", "args", ".", "setdefault", "(", "'ux_bias'", ",", "0.5", ")", "crossover_rate", "=", "args", ".", "setdefault", "(", "'crossover_rate'", ",", "1.0", ...
Return the offspring of uniform crossover on the candidates. This function performs uniform crossover (UX). For each element of the parents, a biased coin is flipped to determine whether the first offspring gets the 'mom' or the 'dad' element. An optional keyword argument in args, ``ux_bias``, deter...
[ "Return", "the", "offspring", "of", "uniform", "crossover", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/crossovers.py#L133-L170
3,668
aarongarrett/inspyred
inspyred/ec/variators/crossovers.py
partially_matched_crossover
def partially_matched_crossover(random, mom, dad, args): """Return the offspring of partially matched crossover on the candidates. This function performs partially matched crossover (PMX). This type of crossover assumes that candidates are composed of discrete values that are permutations of a given se...
python
def partially_matched_crossover(random, mom, dad, args): """Return the offspring of partially matched crossover on the candidates. This function performs partially matched crossover (PMX). This type of crossover assumes that candidates are composed of discrete values that are permutations of a given se...
[ "def", "partially_matched_crossover", "(", "random", ",", "mom", ",", "dad", ",", "args", ")", ":", "crossover_rate", "=", "args", ".", "setdefault", "(", "'crossover_rate'", ",", "1.0", ")", "if", "random", ".", "random", "(", ")", "<", "crossover_rate", ...
Return the offspring of partially matched crossover on the candidates. This function performs partially matched crossover (PMX). This type of crossover assumes that candidates are composed of discrete values that are permutations of a given set (typically integers). It produces offspring that are thems...
[ "Return", "the", "offspring", "of", "partially", "matched", "crossover", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/crossovers.py#L174-L212
3,669
aarongarrett/inspyred
inspyred/ec/variators/crossovers.py
arithmetic_crossover
def arithmetic_crossover(random, mom, dad, args): """Return the offspring of arithmetic crossover on the candidates. This function performs arithmetic crossover (AX), which is similar to a generalized weighted averaging of the candidate elements. The allele of each parent is weighted by the *ax_alpha*...
python
def arithmetic_crossover(random, mom, dad, args): """Return the offspring of arithmetic crossover on the candidates. This function performs arithmetic crossover (AX), which is similar to a generalized weighted averaging of the candidate elements. The allele of each parent is weighted by the *ax_alpha*...
[ "def", "arithmetic_crossover", "(", "random", ",", "mom", ",", "dad", ",", "args", ")", ":", "ax_alpha", "=", "args", ".", "setdefault", "(", "'ax_alpha'", ",", "0.5", ")", "ax_points", "=", "args", ".", "setdefault", "(", "'ax_points'", ",", "None", ")"...
Return the offspring of arithmetic crossover on the candidates. This function performs arithmetic crossover (AX), which is similar to a generalized weighted averaging of the candidate elements. The allele of each parent is weighted by the *ax_alpha* keyword argument, and the allele of the complement p...
[ "Return", "the", "offspring", "of", "arithmetic", "crossover", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/crossovers.py#L216-L265
3,670
aarongarrett/inspyred
inspyred/ec/variators/crossovers.py
blend_crossover
def blend_crossover(random, mom, dad, args): """Return the offspring of blend crossover on the candidates. This function performs blend crossover (BLX), which is similar to arithmetic crossover with a bit of mutation. It creates offspring whose values are chosen randomly from a range bounded by the ...
python
def blend_crossover(random, mom, dad, args): """Return the offspring of blend crossover on the candidates. This function performs blend crossover (BLX), which is similar to arithmetic crossover with a bit of mutation. It creates offspring whose values are chosen randomly from a range bounded by the ...
[ "def", "blend_crossover", "(", "random", ",", "mom", ",", "dad", ",", "args", ")", ":", "blx_alpha", "=", "args", ".", "setdefault", "(", "'blx_alpha'", ",", "0.1", ")", "blx_points", "=", "args", ".", "setdefault", "(", "'blx_points'", ",", "None", ")",...
Return the offspring of blend crossover on the candidates. This function performs blend crossover (BLX), which is similar to arithmetic crossover with a bit of mutation. It creates offspring whose values are chosen randomly from a range bounded by the parent alleles but that is also extended by some a...
[ "Return", "the", "offspring", "of", "blend", "crossover", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/crossovers.py#L269-L320
3,671
aarongarrett/inspyred
inspyred/ec/variators/crossovers.py
heuristic_crossover
def heuristic_crossover(random, candidates, args): """Return the offspring of heuristic crossover on the candidates. It performs heuristic crossover (HX), which is similar to the update rule used in particle swarm optimization. This function also makes use of the bounder function as specified in the ...
python
def heuristic_crossover(random, candidates, args): """Return the offspring of heuristic crossover on the candidates. It performs heuristic crossover (HX), which is similar to the update rule used in particle swarm optimization. This function also makes use of the bounder function as specified in the ...
[ "def", "heuristic_crossover", "(", "random", ",", "candidates", ",", "args", ")", ":", "crossover_rate", "=", "args", ".", "setdefault", "(", "'crossover_rate'", ",", "1.0", ")", "bounder", "=", "args", "[", "'_ec'", "]", ".", "bounder", "if", "len", "(", ...
Return the offspring of heuristic crossover on the candidates. It performs heuristic crossover (HX), which is similar to the update rule used in particle swarm optimization. This function also makes use of the bounder function as specified in the EC's ``evolve`` method. .. note:: Th...
[ "Return", "the", "offspring", "of", "heuristic", "crossover", "on", "the", "candidates", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/variators/crossovers.py#L323-L379
3,672
aarongarrett/inspyred
docs/moonshot.py
gravitational_force
def gravitational_force(position_a, mass_a, position_b, mass_b): """Returns the gravitational force between the two bodies a and b.""" distance = distance_between(position_a, position_b) # Calculate the direction and magnitude of the force. angle = math.atan2(position_a[1] - position_b[1], position_a[0...
python
def gravitational_force(position_a, mass_a, position_b, mass_b): """Returns the gravitational force between the two bodies a and b.""" distance = distance_between(position_a, position_b) # Calculate the direction and magnitude of the force. angle = math.atan2(position_a[1] - position_b[1], position_a[0...
[ "def", "gravitational_force", "(", "position_a", ",", "mass_a", ",", "position_b", ",", "mass_b", ")", ":", "distance", "=", "distance_between", "(", "position_a", ",", "position_b", ")", "# Calculate the direction and magnitude of the force.", "angle", "=", "math", "...
Returns the gravitational force between the two bodies a and b.
[ "Returns", "the", "gravitational", "force", "between", "the", "two", "bodies", "a", "and", "b", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/docs/moonshot.py#L37-L50
3,673
aarongarrett/inspyred
docs/moonshot.py
force_on_satellite
def force_on_satellite(position, mass): """Returns the total gravitational force acting on the body from the Earth and Moon.""" earth_grav_force = gravitational_force(position, mass, earth_position, earth_mass) moon_grav_force = gravitational_force(position, mass, moon_position, moon_mass) F_x = earth_g...
python
def force_on_satellite(position, mass): """Returns the total gravitational force acting on the body from the Earth and Moon.""" earth_grav_force = gravitational_force(position, mass, earth_position, earth_mass) moon_grav_force = gravitational_force(position, mass, moon_position, moon_mass) F_x = earth_g...
[ "def", "force_on_satellite", "(", "position", ",", "mass", ")", ":", "earth_grav_force", "=", "gravitational_force", "(", "position", ",", "mass", ",", "earth_position", ",", "earth_mass", ")", "moon_grav_force", "=", "gravitational_force", "(", "position", ",", "...
Returns the total gravitational force acting on the body from the Earth and Moon.
[ "Returns", "the", "total", "gravitational", "force", "acting", "on", "the", "body", "from", "the", "Earth", "and", "Moon", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/docs/moonshot.py#L52-L58
3,674
aarongarrett/inspyred
docs/moonshot.py
acceleration_of_satellite
def acceleration_of_satellite(position, mass): """Returns the acceleration based on all forces acting upon the body.""" F_x, F_y = force_on_satellite(position, mass) return F_x / mass, F_y / mass
python
def acceleration_of_satellite(position, mass): """Returns the acceleration based on all forces acting upon the body.""" F_x, F_y = force_on_satellite(position, mass) return F_x / mass, F_y / mass
[ "def", "acceleration_of_satellite", "(", "position", ",", "mass", ")", ":", "F_x", ",", "F_y", "=", "force_on_satellite", "(", "position", ",", "mass", ")", "return", "F_x", "/", "mass", ",", "F_y", "/", "mass" ]
Returns the acceleration based on all forces acting upon the body.
[ "Returns", "the", "acceleration", "based", "on", "all", "forces", "acting", "upon", "the", "body", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/docs/moonshot.py#L60-L63
3,675
aarongarrett/inspyred
inspyred/ec/evaluators.py
evaluator
def evaluator(evaluate): """Return an inspyred evaluator function based on the given function. This function generator takes a function that evaluates only one candidate. The generator handles the iteration over each candidate to be evaluated. The given function ``evaluate`` must have the fol...
python
def evaluator(evaluate): """Return an inspyred evaluator function based on the given function. This function generator takes a function that evaluates only one candidate. The generator handles the iteration over each candidate to be evaluated. The given function ``evaluate`` must have the fol...
[ "def", "evaluator", "(", "evaluate", ")", ":", "@", "functools", ".", "wraps", "(", "evaluate", ")", "def", "inspyred_evaluator", "(", "candidates", ",", "args", ")", ":", "fitness", "=", "[", "]", "for", "candidate", "in", "candidates", ":", "fitness", ...
Return an inspyred evaluator function based on the given function. This function generator takes a function that evaluates only one candidate. The generator handles the iteration over each candidate to be evaluated. The given function ``evaluate`` must have the following signature:: ...
[ "Return", "an", "inspyred", "evaluator", "function", "based", "on", "the", "given", "function", ".", "This", "function", "generator", "takes", "a", "function", "that", "evaluates", "only", "one", "candidate", ".", "The", "generator", "handles", "the", "iteration...
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/evaluators.py#L45-L77
3,676
aarongarrett/inspyred
inspyred/ec/evaluators.py
parallel_evaluation_pp
def parallel_evaluation_pp(candidates, args): """Evaluate the candidates in parallel using Parallel Python. This function allows parallel evaluation of candidate solutions. It uses the `Parallel Python <http://www.parallelpython.com>`_ (pp) library to accomplish the parallelization. This library must ...
python
def parallel_evaluation_pp(candidates, args): """Evaluate the candidates in parallel using Parallel Python. This function allows parallel evaluation of candidate solutions. It uses the `Parallel Python <http://www.parallelpython.com>`_ (pp) library to accomplish the parallelization. This library must ...
[ "def", "parallel_evaluation_pp", "(", "candidates", ",", "args", ")", ":", "import", "pp", "logger", "=", "args", "[", "'_ec'", "]", ".", "logger", "try", ":", "evaluator", "=", "args", "[", "'pp_evaluator'", "]", "except", "KeyError", ":", "logger", ".", ...
Evaluate the candidates in parallel using Parallel Python. This function allows parallel evaluation of candidate solutions. It uses the `Parallel Python <http://www.parallelpython.com>`_ (pp) library to accomplish the parallelization. This library must already be installed in order to use this functi...
[ "Evaluate", "the", "candidates", "in", "parallel", "using", "Parallel", "Python", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/evaluators.py#L80-L162
3,677
aarongarrett/inspyred
inspyred/ec/evaluators.py
parallel_evaluation_mp
def parallel_evaluation_mp(candidates, args): """Evaluate the candidates in parallel using ``multiprocessing``. This function allows parallel evaluation of candidate solutions. It uses the standard multiprocessing library to accomplish the parallelization. The function assigns the evaluation of each ...
python
def parallel_evaluation_mp(candidates, args): """Evaluate the candidates in parallel using ``multiprocessing``. This function allows parallel evaluation of candidate solutions. It uses the standard multiprocessing library to accomplish the parallelization. The function assigns the evaluation of each ...
[ "def", "parallel_evaluation_mp", "(", "candidates", ",", "args", ")", ":", "import", "time", "import", "multiprocessing", "logger", "=", "args", "[", "'_ec'", "]", ".", "logger", "try", ":", "evaluator", "=", "args", "[", "'mp_evaluator'", "]", "except", "Ke...
Evaluate the candidates in parallel using ``multiprocessing``. This function allows parallel evaluation of candidate solutions. It uses the standard multiprocessing library to accomplish the parallelization. The function assigns the evaluation of each candidate to its own job, all of which are then di...
[ "Evaluate", "the", "candidates", "in", "parallel", "using", "multiprocessing", "." ]
d5976ab503cc9d51c6f586cbb7bb601a38c01128
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/evaluators.py#L165-L230
3,678
djsutho/django-debug-toolbar-request-history
ddt_request_history/panels/request_history.py
allow_ajax
def allow_ajax(request): """ Default function to determine whether to show the toolbar on a given page. """ if request.META.get('REMOTE_ADDR', None) not in settings.INTERNAL_IPS: return False if toolbar_version < LooseVersion('1.8') \ and request.get_full_path().startswith(DEBUG_...
python
def allow_ajax(request): """ Default function to determine whether to show the toolbar on a given page. """ if request.META.get('REMOTE_ADDR', None) not in settings.INTERNAL_IPS: return False if toolbar_version < LooseVersion('1.8') \ and request.get_full_path().startswith(DEBUG_...
[ "def", "allow_ajax", "(", "request", ")", ":", "if", "request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ",", "None", ")", "not", "in", "settings", ".", "INTERNAL_IPS", ":", "return", "False", "if", "toolbar_version", "<", "LooseVersion", "(", "'1.8'...
Default function to determine whether to show the toolbar on a given page.
[ "Default", "function", "to", "determine", "whether", "to", "show", "the", "toolbar", "on", "a", "given", "page", "." ]
b3da3e12762d68c23a307ffb279e6047f80ba695
https://github.com/djsutho/django-debug-toolbar-request-history/blob/b3da3e12762d68c23a307ffb279e6047f80ba695/ddt_request_history/panels/request_history.py#L104-L114
3,679
djsutho/django-debug-toolbar-request-history
ddt_request_history/panels/request_history.py
RequestHistoryPanel.content
def content(self): """ Content of the panel when it's displayed in full screen. """ toolbars = OrderedDict() for id, toolbar in DebugToolbar._store.items(): content = {} for panel in toolbar.panels: panel_id = None nav_title = '' ...
python
def content(self): """ Content of the panel when it's displayed in full screen. """ toolbars = OrderedDict() for id, toolbar in DebugToolbar._store.items(): content = {} for panel in toolbar.panels: panel_id = None nav_title = '' ...
[ "def", "content", "(", "self", ")", ":", "toolbars", "=", "OrderedDict", "(", ")", "for", "id", ",", "toolbar", "in", "DebugToolbar", ".", "_store", ".", "items", "(", ")", ":", "content", "=", "{", "}", "for", "panel", "in", "toolbar", ".", "panels"...
Content of the panel when it's displayed in full screen.
[ "Content", "of", "the", "panel", "when", "it", "s", "displayed", "in", "full", "screen", "." ]
b3da3e12762d68c23a307ffb279e6047f80ba695
https://github.com/djsutho/django-debug-toolbar-request-history/blob/b3da3e12762d68c23a307ffb279e6047f80ba695/ddt_request_history/panels/request_history.py#L184-L215
3,680
AlexMathew/scrapple
scrapple/selectors/selector.py
Selector.extract_content
def extract_content(self, selector='', attr='', default='', connector='', *args, **kwargs): """ Method for performing the content extraction for the particular selector type. \ If the selector is "url", the URL of the current web page is returned. Otherwise, the selector expression is used to extract content. ...
python
def extract_content(self, selector='', attr='', default='', connector='', *args, **kwargs): """ Method for performing the content extraction for the particular selector type. \ If the selector is "url", the URL of the current web page is returned. Otherwise, the selector expression is used to extract content. ...
[ "def", "extract_content", "(", "self", ",", "selector", "=", "''", ",", "attr", "=", "''", ",", "default", "=", "''", ",", "connector", "=", "''", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "selector", ".", "lower", "(...
Method for performing the content extraction for the particular selector type. \ If the selector is "url", the URL of the current web page is returned. Otherwise, the selector expression is used to extract content. The particular \ attribute to be extracted ("text", "href", etc.) is specified in the method \ a...
[ "Method", "for", "performing", "the", "content", "extraction", "for", "the", "particular", "selector", "type", ".", "\\" ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L81-L119
3,681
AlexMathew/scrapple
scrapple/selectors/selector.py
Selector.extract_links
def extract_links(self, selector='', *args, **kwargs): """ Method for performing the link extraction for the crawler. \ The selector passed as the argument is a selector to point to the anchor tags \ that the crawler should pass through. A list of links is obtained, and the links \ are iterated through. The ...
python
def extract_links(self, selector='', *args, **kwargs): """ Method for performing the link extraction for the crawler. \ The selector passed as the argument is a selector to point to the anchor tags \ that the crawler should pass through. A list of links is obtained, and the links \ are iterated through. The ...
[ "def", "extract_links", "(", "self", ",", "selector", "=", "''", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "links", "=", "self", ".", "get_tree_tag", "(", "selector", "=", "selector", ")", "for", "link", "in", "links", ":", "...
Method for performing the link extraction for the crawler. \ The selector passed as the argument is a selector to point to the anchor tags \ that the crawler should pass through. A list of links is obtained, and the links \ are iterated through. The relative paths are converted into absolute paths and \ a ``Xp...
[ "Method", "for", "performing", "the", "link", "extraction", "for", "the", "crawler", ".", "\\" ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L122-L147
3,682
AlexMathew/scrapple
scrapple/selectors/selector.py
Selector.extract_tabular
def extract_tabular(self, header='', prefix='', suffix='', table_type='', *args, **kwargs): """ Method for performing the tabular data extraction. \ :param result: A dictionary containing the extracted data so far :param table_type: Can be "rows" or "columns". This determines the type of table to be extracted....
python
def extract_tabular(self, header='', prefix='', suffix='', table_type='', *args, **kwargs): """ Method for performing the tabular data extraction. \ :param result: A dictionary containing the extracted data so far :param table_type: Can be "rows" or "columns". This determines the type of table to be extracted....
[ "def", "extract_tabular", "(", "self", ",", "header", "=", "''", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ",", "table_type", "=", "''", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "type", "(", "header", ")", "in", "[", ...
Method for performing the tabular data extraction. \ :param result: A dictionary containing the extracted data so far :param table_type: Can be "rows" or "columns". This determines the type of table to be extracted. \ A row extraction is when there is a single row to be extracted and mapped to a set of headers. ...
[ "Method", "for", "performing", "the", "tabular", "data", "extraction", ".", "\\" ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L150-L187
3,683
AlexMathew/scrapple
scrapple/selectors/selector.py
Selector.extract_rows
def extract_rows(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs): """ Row data extraction for extract_tabular """ result_list = [] try: values = self.get_tree_tag(selector) if len(table_headers) >= len(values): from itertools import i...
python
def extract_rows(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs): """ Row data extraction for extract_tabular """ result_list = [] try: values = self.get_tree_tag(selector) if len(table_headers) >= len(values): from itertools import i...
[ "def", "extract_rows", "(", "self", ",", "result", "=", "{", "}", ",", "selector", "=", "''", ",", "table_headers", "=", "[", "]", ",", "attr", "=", "''", ",", "connector", "=", "''", ",", "default", "=", "''", ",", "verbosity", "=", "0", ",", "*...
Row data extraction for extract_tabular
[ "Row", "data", "extraction", "for", "extract_tabular" ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L190-L224
3,684
AlexMathew/scrapple
scrapple/selectors/selector.py
Selector.extract_columns
def extract_columns(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs): """ Column data extraction for extract_tabular """ result_list = [] try: if type(selector) in [str, unicode]: selectors = [selector] elif type(selector) == list: ...
python
def extract_columns(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs): """ Column data extraction for extract_tabular """ result_list = [] try: if type(selector) in [str, unicode]: selectors = [selector] elif type(selector) == list: ...
[ "def", "extract_columns", "(", "self", ",", "result", "=", "{", "}", ",", "selector", "=", "''", ",", "table_headers", "=", "[", "]", ",", "attr", "=", "''", ",", "connector", "=", "''", ",", "default", "=", "''", ",", "verbosity", "=", "0", ",", ...
Column data extraction for extract_tabular
[ "Column", "data", "extraction", "for", "extract_tabular" ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L227-L271
3,685
AlexMathew/scrapple
scrapple/cmd.py
runCLI
def runCLI(): """ The starting point for the execution of the Scrapple command line tool. runCLI uses the docstring as the usage description for the scrapple command. \ The class for the required command is selected by a dynamic dispatch, and the \ command is executed through the execute_command() ...
python
def runCLI(): """ The starting point for the execution of the Scrapple command line tool. runCLI uses the docstring as the usage description for the scrapple command. \ The class for the required command is selected by a dynamic dispatch, and the \ command is executed through the execute_command() ...
[ "def", "runCLI", "(", ")", ":", "args", "=", "docopt", "(", "__doc__", ",", "version", "=", "'0.3.0'", ")", "try", ":", "check_arguments", "(", "args", ")", "command_list", "=", "[", "'genconfig'", ",", "'run'", ",", "'generate'", "]", "select", "=", "...
The starting point for the execution of the Scrapple command line tool. runCLI uses the docstring as the usage description for the scrapple command. \ The class for the required command is selected by a dynamic dispatch, and the \ command is executed through the execute_command() method of the command clas...
[ "The", "starting", "point", "for", "the", "execution", "of", "the", "Scrapple", "command", "line", "tool", "." ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/cmd.py#L49-L67
3,686
AlexMathew/scrapple
scrapple/utils/exceptions.py
check_arguments
def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise Inv...
python
def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise Inv...
[ "def", "check_arguments", "(", "args", ")", ":", "projectname_re", "=", "re", ".", "compile", "(", "r'[^a-zA-Z0-9_]'", ")", "if", "args", "[", "'genconfig'", "]", ":", "if", "args", "[", "'--type'", "]", "not", "in", "[", "'scraper'", ",", "'crawler'", "...
Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None
[ "Validates", "the", "arguments", "passed", "through", "the", "CLI", "commands", "." ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/exceptions.py#L36-L66
3,687
AlexMathew/scrapple
scrapple/utils/form.py
form_to_json
def form_to_json(form): """ Takes the form from the POST request in the web interface, and generates the JSON config\ file :param form: The form from the POST request :return: None """ config = dict() if form['project_name'] == "": raise Exception('Project name cannot be empty.') if form['selector_type'] ...
python
def form_to_json(form): """ Takes the form from the POST request in the web interface, and generates the JSON config\ file :param form: The form from the POST request :return: None """ config = dict() if form['project_name'] == "": raise Exception('Project name cannot be empty.') if form['selector_type'] ...
[ "def", "form_to_json", "(", "form", ")", ":", "config", "=", "dict", "(", ")", "if", "form", "[", "'project_name'", "]", "==", "\"\"", ":", "raise", "Exception", "(", "'Project name cannot be empty.'", ")", "if", "form", "[", "'selector_type'", "]", "not", ...
Takes the form from the POST request in the web interface, and generates the JSON config\ file :param form: The form from the POST request :return: None
[ "Takes", "the", "form", "from", "the", "POST", "request", "in", "the", "web", "interface", "and", "generates", "the", "JSON", "config", "\\", "file" ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/form.py#L13-L48
3,688
AlexMathew/scrapple
scrapple/commands/run.py
RunCommand.execute_command
def execute_command(self): """ The run command implements the web content extractor corresponding to the given \ configuration file. The execute_command() validates the input project name and opens the JSON \ configuration file. The run() method handles the execution of the ext...
python
def execute_command(self): """ The run command implements the web content extractor corresponding to the given \ configuration file. The execute_command() validates the input project name and opens the JSON \ configuration file. The run() method handles the execution of the ext...
[ "def", "execute_command", "(", "self", ")", ":", "try", ":", "self", ".", "args", "[", "'--verbosity'", "]", "=", "int", "(", "self", ".", "args", "[", "'--verbosity'", "]", ")", "if", "self", ".", "args", "[", "'--verbosity'", "]", "not", "in", "[",...
The run command implements the web content extractor corresponding to the given \ configuration file. The execute_command() validates the input project name and opens the JSON \ configuration file. The run() method handles the execution of the extractor run. The extractor implementati...
[ "The", "run", "command", "implements", "the", "web", "content", "extractor", "corresponding", "to", "the", "given", "\\", "configuration", "file", "." ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/commands/run.py#L29-L74
3,689
AlexMathew/scrapple
scrapple/utils/config.py
traverse_next
def traverse_next(page, nextx, results, tabular_data_headers=[], verbosity=0): """ Recursive generator to traverse through the next attribute and \ crawl through the links to be followed. :param page: The current page being parsed :param next: The next attribute of the current scraping dict :pa...
python
def traverse_next(page, nextx, results, tabular_data_headers=[], verbosity=0): """ Recursive generator to traverse through the next attribute and \ crawl through the links to be followed. :param page: The current page being parsed :param next: The next attribute of the current scraping dict :pa...
[ "def", "traverse_next", "(", "page", ",", "nextx", ",", "results", ",", "tabular_data_headers", "=", "[", "]", ",", "verbosity", "=", "0", ")", ":", "for", "link", "in", "page", ".", "extract_links", "(", "selector", "=", "nextx", "[", "'follow_link'", "...
Recursive generator to traverse through the next attribute and \ crawl through the links to be followed. :param page: The current page being parsed :param next: The next attribute of the current scraping dict :param results: The current extracted content, stored in a dict :return: The extracted con...
[ "Recursive", "generator", "to", "traverse", "through", "the", "next", "attribute", "and", "\\", "crawl", "through", "the", "links", "to", "be", "followed", "." ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/config.py#L20-L58
3,690
AlexMathew/scrapple
scrapple/utils/config.py
validate_config
def validate_config(config): """ Validates the extractor configuration file. Ensures that there are no duplicate field names, etc. :param config: The configuration file that contains the specification of the extractor :return: True if config is valid, else raises a exception that specifies the correcti...
python
def validate_config(config): """ Validates the extractor configuration file. Ensures that there are no duplicate field names, etc. :param config: The configuration file that contains the specification of the extractor :return: True if config is valid, else raises a exception that specifies the correcti...
[ "def", "validate_config", "(", "config", ")", ":", "fields", "=", "[", "f", "for", "f", "in", "get_fields", "(", "config", ")", "]", "if", "len", "(", "fields", ")", "!=", "len", "(", "set", "(", "fields", ")", ")", ":", "raise", "InvalidConfigExcept...
Validates the extractor configuration file. Ensures that there are no duplicate field names, etc. :param config: The configuration file that contains the specification of the extractor :return: True if config is valid, else raises a exception that specifies the correction to be made
[ "Validates", "the", "extractor", "configuration", "file", ".", "Ensures", "that", "there", "are", "no", "duplicate", "field", "names", "etc", "." ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/config.py#L61-L74
3,691
AlexMathew/scrapple
scrapple/utils/config.py
get_fields
def get_fields(config): """ Recursive generator that yields the field names in the config file :param config: The configuration file that contains the specification of the extractor :return: The field names in the config file, through a generator """ for data in config['scraping']['data']: ...
python
def get_fields(config): """ Recursive generator that yields the field names in the config file :param config: The configuration file that contains the specification of the extractor :return: The field names in the config file, through a generator """ for data in config['scraping']['data']: ...
[ "def", "get_fields", "(", "config", ")", ":", "for", "data", "in", "config", "[", "'scraping'", "]", "[", "'data'", "]", ":", "if", "data", "[", "'field'", "]", "!=", "''", ":", "yield", "data", "[", "'field'", "]", "if", "'next'", "in", "config", ...
Recursive generator that yields the field names in the config file :param config: The configuration file that contains the specification of the extractor :return: The field names in the config file, through a generator
[ "Recursive", "generator", "that", "yields", "the", "field", "names", "in", "the", "config", "file" ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/config.py#L77-L91
3,692
AlexMathew/scrapple
scrapple/utils/config.py
extract_fieldnames
def extract_fieldnames(config): """ Function to return a list of unique field names from the config file :param config: The configuration file that contains the specification of the extractor :return: A list of field names from the config file """ fields = [] for x in get_fields(config): ...
python
def extract_fieldnames(config): """ Function to return a list of unique field names from the config file :param config: The configuration file that contains the specification of the extractor :return: A list of field names from the config file """ fields = [] for x in get_fields(config): ...
[ "def", "extract_fieldnames", "(", "config", ")", ":", "fields", "=", "[", "]", "for", "x", "in", "get_fields", "(", "config", ")", ":", "if", "x", "in", "fields", ":", "fields", ".", "append", "(", "x", "+", "'_'", "+", "str", "(", "fields", ".", ...
Function to return a list of unique field names from the config file :param config: The configuration file that contains the specification of the extractor :return: A list of field names from the config file
[ "Function", "to", "return", "a", "list", "of", "unique", "field", "names", "from", "the", "config", "file" ]
eeb604601b155d6cc7e035855ff4d3f48f8bed74
https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/config.py#L94-L108
3,693
CQCL/pytket
pytket/qiskit/tket_pass.py
TketPass.run
def run(self, dag:DAGCircuit) -> DAGCircuit: """ Run one pass of optimisation on the circuit and route for the given backend. :param dag: The circuit to optimise and route :return: The modified circuit """ circ = dagcircuit_to_tk(dag, _DROP_CONDS=self.DROP_CONDS,_BO...
python
def run(self, dag:DAGCircuit) -> DAGCircuit: """ Run one pass of optimisation on the circuit and route for the given backend. :param dag: The circuit to optimise and route :return: The modified circuit """ circ = dagcircuit_to_tk(dag, _DROP_CONDS=self.DROP_CONDS,_BO...
[ "def", "run", "(", "self", ",", "dag", ":", "DAGCircuit", ")", "->", "DAGCircuit", ":", "circ", "=", "dagcircuit_to_tk", "(", "dag", ",", "_DROP_CONDS", "=", "self", ".", "DROP_CONDS", ",", "_BOX_UNKNOWN", "=", "self", ".", "BOX_UNKNOWN", ")", "circ", ",...
Run one pass of optimisation on the circuit and route for the given backend. :param dag: The circuit to optimise and route :return: The modified circuit
[ "Run", "one", "pass", "of", "optimisation", "on", "the", "circuit", "and", "route", "for", "the", "given", "backend", "." ]
ae68f7402dcb5fb45221832cc6185d267bdd7a71
https://github.com/CQCL/pytket/blob/ae68f7402dcb5fb45221832cc6185d267bdd7a71/pytket/qiskit/tket_pass.py#L51-L68
3,694
CQCL/pytket
pytket/cirq/qubits.py
_sort_row_col
def _sort_row_col(qubits: Iterator[GridQubit]) -> List[GridQubit]: """Sort grid qubits first by row then by column""" return sorted(qubits, key=lambda x: (x.row, x.col))
python
def _sort_row_col(qubits: Iterator[GridQubit]) -> List[GridQubit]: """Sort grid qubits first by row then by column""" return sorted(qubits, key=lambda x: (x.row, x.col))
[ "def", "_sort_row_col", "(", "qubits", ":", "Iterator", "[", "GridQubit", "]", ")", "->", "List", "[", "GridQubit", "]", ":", "return", "sorted", "(", "qubits", ",", "key", "=", "lambda", "x", ":", "(", "x", ".", "row", ",", "x", ".", "col", ")", ...
Sort grid qubits first by row then by column
[ "Sort", "grid", "qubits", "first", "by", "row", "then", "by", "column" ]
ae68f7402dcb5fb45221832cc6185d267bdd7a71
https://github.com/CQCL/pytket/blob/ae68f7402dcb5fb45221832cc6185d267bdd7a71/pytket/cirq/qubits.py#L51-L54
3,695
CQCL/pytket
pytket/chemistry/aqua/qse.py
QSE.print_setting
def print_setting(self) -> str: """ Presents the QSE settings as a string. :return: The formatted settings of the QSE instance """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}"...
python
def print_setting(self) -> str: """ Presents the QSE settings as a string. :return: The formatted settings of the QSE instance """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}"...
[ "def", "print_setting", "(", "self", ")", "->", "str", ":", "ret", "=", "\"\\n\"", "ret", "+=", "\"==================== Setting of {} ============================\\n\"", ".", "format", "(", "self", ".", "configuration", "[", "'name'", "]", ")", "ret", "+=", "\"{}\...
Presents the QSE settings as a string. :return: The formatted settings of the QSE instance
[ "Presents", "the", "QSE", "settings", "as", "a", "string", "." ]
ae68f7402dcb5fb45221832cc6185d267bdd7a71
https://github.com/CQCL/pytket/blob/ae68f7402dcb5fb45221832cc6185d267bdd7a71/pytket/chemistry/aqua/qse.py#L117-L129
3,696
CQCL/pytket
pytket/chemistry/aqua/qse.py
QSE._energy_evaluation
def _energy_evaluation(self, operator): """ Evaluate the energy of the current input circuit with respect to the given operator. :param operator: Hamiltonian of the system :return: Energy of the Hamiltonian """ if self._quantum_state is not None: input_circu...
python
def _energy_evaluation(self, operator): """ Evaluate the energy of the current input circuit with respect to the given operator. :param operator: Hamiltonian of the system :return: Energy of the Hamiltonian """ if self._quantum_state is not None: input_circu...
[ "def", "_energy_evaluation", "(", "self", ",", "operator", ")", ":", "if", "self", ".", "_quantum_state", "is", "not", "None", ":", "input_circuit", "=", "self", ".", "_quantum_state", "else", ":", "input_circuit", "=", "[", "self", ".", "opt_circuit", "]", ...
Evaluate the energy of the current input circuit with respect to the given operator. :param operator: Hamiltonian of the system :return: Energy of the Hamiltonian
[ "Evaluate", "the", "energy", "of", "the", "current", "input", "circuit", "with", "respect", "to", "the", "given", "operator", "." ]
ae68f7402dcb5fb45221832cc6185d267bdd7a71
https://github.com/CQCL/pytket/blob/ae68f7402dcb5fb45221832cc6185d267bdd7a71/pytket/chemistry/aqua/qse.py#L131-L151
3,697
CQCL/pytket
pytket/chemistry/aqua/qse.py
QSE._run
def _run(self) -> dict: """ Runs the QSE algorithm to compute the eigenvalues of the Hamiltonian. :return: Dictionary of results """ if not self._quantum_instance.is_statevector: raise AquaError("Can only calculate state for QSE with statevector backends") re...
python
def _run(self) -> dict: """ Runs the QSE algorithm to compute the eigenvalues of the Hamiltonian. :return: Dictionary of results """ if not self._quantum_instance.is_statevector: raise AquaError("Can only calculate state for QSE with statevector backends") re...
[ "def", "_run", "(", "self", ")", "->", "dict", ":", "if", "not", "self", ".", "_quantum_instance", ".", "is_statevector", ":", "raise", "AquaError", "(", "\"Can only calculate state for QSE with statevector backends\"", ")", "ret", "=", "self", ".", "_quantum_instan...
Runs the QSE algorithm to compute the eigenvalues of the Hamiltonian. :return: Dictionary of results
[ "Runs", "the", "QSE", "algorithm", "to", "compute", "the", "eigenvalues", "of", "the", "Hamiltonian", "." ]
ae68f7402dcb5fb45221832cc6185d267bdd7a71
https://github.com/CQCL/pytket/blob/ae68f7402dcb5fb45221832cc6185d267bdd7a71/pytket/chemistry/aqua/qse.py#L260-L274
3,698
bkabrda/flask-whooshee
flask_whooshee.py
WhoosheeQuery.whooshee_search
def whooshee_search(self, search_string, group=whoosh.qparser.OrGroup, whoosheer=None, match_substrings=True, limit=None, order_by_relevance=10): """Do a fulltext search on the query. Returns a query filtered with results of the fulltext search. :param search_string: The...
python
def whooshee_search(self, search_string, group=whoosh.qparser.OrGroup, whoosheer=None, match_substrings=True, limit=None, order_by_relevance=10): """Do a fulltext search on the query. Returns a query filtered with results of the fulltext search. :param search_string: The...
[ "def", "whooshee_search", "(", "self", ",", "search_string", ",", "group", "=", "whoosh", ".", "qparser", ".", "OrGroup", ",", "whoosheer", "=", "None", ",", "match_substrings", "=", "True", ",", "limit", "=", "None", ",", "order_by_relevance", "=", "10", ...
Do a fulltext search on the query. Returns a query filtered with results of the fulltext search. :param search_string: The string to search for. :param group: The whoosh group to use for searching. Defaults to :class:`whoosh.qparser.OrGroup` which sea...
[ "Do", "a", "fulltext", "search", "on", "the", "query", ".", "Returns", "a", "query", "filtered", "with", "results", "of", "the", "fulltext", "search", "." ]
773fc51ed53043bd5e92c65eadef5663845ae8c4
https://github.com/bkabrda/flask-whooshee/blob/773fc51ed53043bd5e92c65eadef5663845ae8c4/flask_whooshee.py#L44-L123
3,699
bkabrda/flask-whooshee
flask_whooshee.py
AbstractWhoosheer.search
def search(cls, search_string, values_of='', group=whoosh.qparser.OrGroup, match_substrings=True, limit=None): """Searches the fields for given search_string. Returns the found records if 'values_of' is left empty, else the values of the given columns. :param search_string: The string t...
python
def search(cls, search_string, values_of='', group=whoosh.qparser.OrGroup, match_substrings=True, limit=None): """Searches the fields for given search_string. Returns the found records if 'values_of' is left empty, else the values of the given columns. :param search_string: The string t...
[ "def", "search", "(", "cls", ",", "search_string", ",", "values_of", "=", "''", ",", "group", "=", "whoosh", ".", "qparser", ".", "OrGroup", ",", "match_substrings", "=", "True", ",", "limit", "=", "None", ")", ":", "index", "=", "Whooshee", ".", "get_...
Searches the fields for given search_string. Returns the found records if 'values_of' is left empty, else the values of the given columns. :param search_string: The string to search for. :param values_of: If given, the method will not return the whole records, ...
[ "Searches", "the", "fields", "for", "given", "search_string", ".", "Returns", "the", "found", "records", "if", "values_of", "is", "left", "empty", "else", "the", "values", "of", "the", "given", "columns", "." ]
773fc51ed53043bd5e92c65eadef5663845ae8c4
https://github.com/bkabrda/flask-whooshee/blob/773fc51ed53043bd5e92c65eadef5663845ae8c4/flask_whooshee.py#L138-L163