idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
47,500
def from_json ( self , fname ) : with open ( fname , 'rt' ) as fp : for row in json . load ( fp ) : nn = ServerInfo . from_dict ( row ) self [ str ( nn ) ] = nn
Read contents of a CSV containing a list of servers .
47,501
def from_irc ( self , irc_nickname = None , irc_password = None ) : if have_bottom : from . findall import IrcListener bot = IrcListener ( irc_nickname = irc_nickname , irc_password = irc_password ) results = bot . loop . run_until_complete ( bot . collect_data ( ) ) bot . loop . close ( ) self . update ( results ) els...
Connect to the IRC channel and find all servers presently connected .
47,502
def save_json ( self , fname = 'servers.json' ) : rows = sorted ( self . keys ( ) ) with open ( fname , 'wt' ) as fp : json . dump ( [ self [ k ] for k in rows ] , fp , indent = 1 )
Write out to a CSV file .
47,503
def select ( self , ** kws ) : lst = [ i for i in self . values ( ) if i . select ( ** kws ) ] random . shuffle ( lst ) return lst
Find all servers with indicated protocol support . Shuffled .
47,504
def _post_patched_request ( consumers , lti_key , body , url , method , content_type ) : oauth_server = LTIOAuthServer ( consumers ) oauth_server . add_signature_method ( SignatureMethod_HMAC_SHA1_Unicode ( ) ) lti_consumer = oauth_server . lookup_consumer ( lti_key ) lti_cert = oauth_server . lookup_cert ( lti_key ) s...
Authorization header needs to be capitalized for some LTI clients this function ensures that header is capitalized
47,505
def post_message ( consumers , lti_key , url , body ) : content_type = 'application/xml' method = 'POST' ( _ , content ) = _post_patched_request ( consumers , lti_key , body , url , method , content_type , ) is_success = b"<imsx_codeMajor>success</imsx_codeMajor>" in content log . debug ( "is success %s" , is_success )...
Posts a signed message to LTI consumer
47,506
def post_message2 ( consumers , lti_key , url , body , method = 'POST' , content_type = 'application/xml' ) : ( response , _ ) = _post_patched_request ( consumers , lti_key , body , url , method , content_type , ) is_success = response . status == 200 log . debug ( "is success %s" , is_success ) return is_success
Posts a signed message to LTI consumer using LTI 2 . 0 format
47,507
def verify_request_common ( consumers , url , method , headers , params ) : log . debug ( "consumers %s" , consumers ) log . debug ( "url %s" , url ) log . debug ( "method %s" , method ) log . debug ( "headers %s" , headers ) log . debug ( "params %s" , params ) oauth_server = LTIOAuthServer ( consumers ) oauth_server ...
Verifies that request is valid
47,508
def generate_request_xml ( message_identifier_id , operation , lis_result_sourcedid , score ) : root = etree . Element ( u'imsx_POXEnvelopeRequest' , xmlns = u'http://www.imsglobal.org/services/' u'ltiv1p1/xsd/imsoms_v1p0' ) header = etree . SubElement ( root , 'imsx_POXHeader' ) header_info = etree . SubElement ( head...
Generates LTI 1 . 1 XML for posting result to LTI consumer .
47,509
def is_role ( self , role ) : log . debug ( "is_role %s" , role ) roles = self . session [ 'roles' ] . split ( ',' ) if role in LTI_ROLES : role_list = LTI_ROLES [ role ] roles = set ( role_list ) & set ( roles ) is_user_role_there = len ( roles ) >= 1 log . debug ( "is_role roles_list=%s role=%s in list=%s" , role_lis...
Verify if user is in role
47,510
def _check_role ( self ) : role = u'any' if 'role' in self . lti_kwargs : role = self . lti_kwargs [ 'role' ] log . debug ( "check_role lti_role=%s decorator_role=%s" , self . role , role ) if not ( role == u'any' or self . is_role ( self , role ) ) : raise LTIRoleException ( 'Not authorized.' )
Check that user is in role specified as wrapper attribute
47,511
def post_grade ( self , grade ) : message_identifier_id = self . message_identifier_id ( ) operation = 'replaceResult' lis_result_sourcedid = self . lis_result_sourcedid score = float ( grade ) if 0 <= score <= 1.0 : xml = generate_request_xml ( message_identifier_id , operation , lis_result_sourcedid , score ) ret = p...
Post grade to LTI consumer using XML
47,512
def _consumers ( self ) : app_config = self . lti_kwargs [ 'app' ] . config config = app_config . get ( 'PYLTI_CONFIG' , dict ( ) ) consumers = config . get ( 'consumers' , dict ( ) ) return consumers
Gets consumer s map from app config
47,513
def response_url ( self ) : url = "" url = self . session [ 'lis_outcome_service_url' ] app_config = self . lti_kwargs [ 'app' ] . config urls = app_config . get ( 'PYLTI_URL_FIX' , dict ( ) ) for prefix , mapping in urls . items ( ) : if url . startswith ( prefix ) : for _from , _to in mapping . items ( ) : url = url ...
Returns remapped lis_outcome_service_url uses PYLTI_URL_FIX map to support edX dev - stack
47,514
def _consumers ( self ) : consumers = { } for env in os . environ : if env . startswith ( 'CONSUMER_KEY_SECRET_' ) : key = env [ 20 : ] consumers [ key ] = { "secret" : os . environ [ env ] , "cert" : None } if not consumers : raise LTIException ( "No consumers found. Chalice stores " "consumers in Lambda environment v...
Gets consumers from Lambda environment variables prefixed with CONSUMER_KEY_SECRET_ . For example given a consumer key of foo and a shared secret of bar you should have an environment variable CONSUMER_KEY_SECRET_foo = bar .
47,515
def verify_request ( self ) : request = self . lti_kwargs [ 'app' ] . current_request if request . method == 'POST' : parsed_url = request . raw_body . decode ( ) parsed_qs = parse_qs ( parsed_url , keep_blank_values = True ) params = { k : v [ 0 ] for k , v in parsed_qs . items ( ) } else : params = request . query_pa...
Verify LTI request
47,516
def get_queryset ( self ) : return Event . objects . filter ( Q ( startTime__gte = timezone . now ( ) - timedelta ( days = 90 ) ) & ( Q ( series__isnull = False ) | Q ( publicevent__isnull = False ) ) ) . annotate ( count = Count ( 'eventregistration' ) ) . annotate ( ** self . get_annotations ( ) ) . exclude ( Q ( cou...
Recent events are listed in link form .
47,517
def get_context_data ( self , ** kwargs ) : self . set_return_page ( 'viewregistrations' , _ ( 'View Registrations' ) , event_id = self . object . id ) context = { 'event' : self . object , 'registrations' : EventRegistration . objects . filter ( event = self . object , cancelled = False ) . order_by ( 'registration__c...
Add the list of registrations for the given series
47,518
def get_context_data ( self , ** kwargs ) : context = super ( SubmissionRedirectView , self ) . get_context_data ( ** kwargs ) redirect_url = unquote ( self . request . GET . get ( 'redirect_url' , '' ) ) if not redirect_url : redirect_url = self . get_return_page ( ) . get ( 'url' , '' ) if not redirect_url : try : re...
The URL to redirect to can be explicitly specified or it can come from the site session history or it can be the default admin success page as specified in the site settings .
47,519
def get ( self , request , * args , ** kwargs ) : user_has_validation_string = self . get_object ( ) . validationString user_has_permissions = request . user . has_perm ( 'core.view_all_invoices' ) if request . GET . get ( 'v' , None ) == user_has_validation_string or user_has_permissions : return super ( ViewInvoiceVi...
Invoices can be viewed only if the validation string is provided unless the user is logged in and has view_all_invoice permissions
47,520
def dispatch ( self , request , * args , ** kwargs ) : if 'pk' in self . kwargs : try : self . invoices = Invoice . objects . filter ( pk = self . kwargs . get ( 'pk' ) ) [ : ] except ValueError : raise Http404 ( ) if not self . invoices : raise Http404 ( ) else : ids = request . GET . get ( 'invoices' , '' ) try : sel...
Get the set of invoices for which to permit notifications
47,521
def get_form_kwargs ( self ) : kwargs = super ( InvoiceNotificationView , self ) . get_form_kwargs ( ) kwargs [ 'invoices' ] = self . toNotify return kwargs
Pass the set of invoices to the form for creation
47,522
def dispatch ( self , request , * args , ** kwargs ) : ids = request . GET . get ( 'customers' ) groups = request . GET . get ( 'customergroup' ) self . customers = None if ids or groups : filters = Q ( id__isnull = True ) if ids : filters = filters | Q ( id__in = [ int ( x ) for x in ids . split ( ',' ) ] ) if groups ...
If a list of customers or groups was passed then parse it
47,523
def get_form_kwargs ( self , ** kwargs ) : numMonths = 12 lastStart = ( Event . objects . annotate ( Min ( 'eventoccurrence__startTime' ) ) . order_by ( '-eventoccurrence__startTime__min' ) . values_list ( 'eventoccurrence__startTime__min' , flat = True ) . first ( ) ) if lastStart : month = lastStart . month year = la...
Get the list of recent months and recent series to pass to the form
47,524
def get_initial ( self ) : initial = super ( SendEmailView , self ) . get_initial ( ) form_data = self . request . session . get ( EMAIL_VALIDATION_STR , { } ) . get ( 'form_data' , { } ) if form_data : initial . update ( form_data ) return initial
If the user already submitted the form and decided to return from the confirmation page then re - populate the form
47,525
def form_valid ( self , form ) : form . cleaned_data . pop ( 'template' , None ) self . request . session [ EMAIL_VALIDATION_STR ] = { 'form_data' : form . cleaned_data } return HttpResponseRedirect ( reverse ( 'emailConfirmation' ) )
Pass form data to the confirmation view
47,526
def form_valid ( self , form ) : startDate = form . cleaned_data . get ( 'startDate' ) repeatEvery = form . cleaned_data . get ( 'repeatEvery' ) periodicity = form . cleaned_data . get ( 'periodicity' ) quantity = form . cleaned_data . get ( 'quantity' ) endDate = form . cleaned_data . get ( 'endDate' ) if periodicity ...
For each object in the queryset create the duplicated objects
47,527
def recentEvents ( self ) : return Event . objects . filter ( Q ( pk__in = self . individualEvents . values_list ( 'pk' , flat = True ) ) | Q ( session__in = self . eventSessions . all ( ) ) | Q ( publicevent__category__in = self . eventCategories . all ( ) ) | Q ( series__category__in = self . seriesCategories . all (...
Get the set of recent and upcoming events to which this list applies .
47,528
def currentEvent ( self ) : currentEvent = self . recentEvents . filter ( endTime__gte = timezone . now ( ) ) . order_by ( 'startTime' ) . first ( ) if not currentEvent : currentEvent = self . recentEvents . filter ( endTime__lte = timezone . now ( ) ) . order_by ( '-endTime' ) . first ( ) return currentEvent
Return the first event that hasn t ended yet or if there are no future events the last one to end .
47,529
def appliesToEvent ( self , event ) : return ( event in self . individualEvents . all ( ) or event . session in self . eventSessions . all ( ) or event . category in self . seriesCategories . all ( ) or event . category in self . eventCategories . all ( ) )
Check whether this guest list is applicable to an event .
47,530
def getDayStart ( self , dateTime ) : return ensure_localtime ( dateTime ) . replace ( hour = 0 , minute = 0 , second = 0 , microsecond = 0 )
Ensure local time and get the beginning of the day
47,531
def getListForEvent ( self , event = None ) : names = list ( self . guestlistname_set . annotate ( guestType = Case ( When ( notes__isnull = False , then = F ( 'notes' ) ) , default = Value ( ugettext ( 'Manually Added' ) ) , output_field = models . CharField ( ) ) ) . values ( 'firstName' , 'lastName' , 'guestType' ) ...
Get the list of names associated with a particular event .
47,532
def clean ( self ) : if not self . staffCategory and not self . staffMember : raise ValidationError ( _ ( 'Either staff category or staff member must be specified.' ) ) if self . staffCategory and self . staffMember : raise ValidationError ( _ ( 'Specify either a staff category or a staff member, not both.' ) )
Either staffCategory or staffMember must be filled in but not both .
47,533
def updateSeriesAttributes ( request ) : if request . method == 'POST' and request . POST . get ( 'event' ) : series_option = request . POST . get ( 'event' ) or None seriesClasses = EventOccurrence . objects . filter ( event__id = series_option ) seriesTeachers = SeriesTeacher . objects . filter ( event__id = series_o...
This function handles the filtering of available series classes and seriesteachers when a series is chosen on the Substitute Teacher reporting form .
47,534
def processCheckIn ( request ) : if request . method == 'POST' : event_id = request . POST . get ( 'event_id' ) reg_ids = request . POST . getlist ( 'reg_id' ) if not event_id : return HttpResponse ( _ ( "Error at start." ) ) all_eventreg = list ( EventRegistration . objects . filter ( event__id = event_id ) ) for this...
This function handles the Ajax call made when a user is marked as checked in
47,535
def getEmailTemplate ( request ) : if request . method != 'POST' : return HttpResponse ( _ ( 'Error, no POST data.' ) ) if not hasattr ( request , 'user' ) : return HttpResponse ( _ ( 'Error, not authenticated.' ) ) template_id = request . POST . get ( 'template' ) if not template_id : return HttpResponse ( _ ( "Error,...
This function handles the Ajax call made when a user wants a specific email template
47,536
def dispatch ( self , request , * args , ** kwargs ) : paymentSession = request . session . get ( INVOICE_VALIDATION_STR , { } ) self . invoiceID = paymentSession . get ( 'invoiceID' ) self . amount = paymentSession . get ( 'amount' , 0 ) self . success_url = paymentSession . get ( 'success_url' , reverse ( 'registrati...
Check that a valid Invoice ID has been passed in session data and that said invoice is marked as paid .
47,537
def form_valid ( self , form ) : emailTo = form . cleaned_data . get ( 'emailTo' ) emailType = form . cleaned_data . get ( 'emailType' ) recipientName = form . cleaned_data . get ( 'recipientName' ) fromName = form . cleaned_data . get ( 'fromName' ) message = form . cleaned_data . get ( 'message' ) logger . info ( 'Pr...
Create the gift certificate voucher with the indicated information and send the email as directed .
47,538
def updateSeriesRegistrationStatus ( ) : from . models import Series if not getConstant ( 'general__enableCronTasks' ) : return logger . info ( 'Checking status of Series that are open for registration.' ) open_series = Series . objects . filter ( ) . filter ( ** { 'registrationOpen' : True } ) for series in open_serie...
Every hour check if the series that are currently open for registration should be closed .
47,539
def clearExpiredTemporaryRegistrations ( ) : from . models import TemporaryRegistration if not getConstant ( 'general__enableCronTasks' ) : return if getConstant ( 'registration__deleteExpiredTemporaryRegistrations' ) : TemporaryRegistration . objects . filter ( expirationDate__lte = timezone . now ( ) - timedelta ( mi...
Every hour look for TemporaryRegistrations that have expired and delete them . To ensure that there are no issues that arise from slight differences between session expiration dates and TemporaryRegistration expiration dates only delete instances that have been expired for one minute .
47,540
def updateFinancialItems ( ) : if not getConstant ( 'general__enableCronTasks' ) : return logger . info ( 'Creating automatically-generated financial items.' ) if getConstant ( 'financial__autoGenerateExpensesEventStaff' ) : createExpenseItemsForEvents ( ) if getConstant ( 'financial__autoGenerateExpensesVenueRental' )...
Every hour create any necessary revenue items and expense items for activities that need them .
47,541
def emailErrorMessage ( subject , message ) : if not getConstant ( 'email__enableErrorEmails' ) : logger . info ( 'Not sending error email: error emails are not enabled.' ) return send_from = getConstant ( 'email__errorEmailFrom' ) send_to = getConstant ( 'email__errorEmailTo' ) if not send_from or not send_to : logger...
Useful for sending error messages via email .
47,542
def get ( self , request , * args , ** kwargs ) : try : year = int ( self . kwargs . get ( 'year' ) ) except ( ValueError , TypeError ) : year = getIntFromGet ( request , 'year' ) kwargs . update ( { 'year' : year , 'basis' : request . GET . get ( 'basis' ) , } ) if kwargs . get ( 'basis' ) not in EXPENSE_BASES . keys ...
Allow passing of basis and time limitations
47,543
def get ( self , request , * args , ** kwargs ) : try : year = int ( self . kwargs . get ( 'year' ) ) except ( ValueError , TypeError ) : year = getIntFromGet ( request , 'year' ) if self . kwargs . get ( 'month' ) : try : month = int ( self . kwargs . get ( 'month' ) ) except ( ValueError , TypeError ) : try : month =...
Pass any permissable GET data . URL parameters override GET parameters
47,544
def get_form_kwargs ( self , ** kwargs ) : kwargs = super ( CompensationActionView , self ) . get_form_kwargs ( ** kwargs ) kwargs [ 'staffmembers' ] = self . queryset return kwargs
pass the list of staff members along to the form
47,545
def setReminder ( self , occurrence ) : sendReminderTo = self [ 0 ] . cleaned_data [ 'sendReminderTo' ] sendReminderWhen = self [ 0 ] . cleaned_data [ 'sendReminderWhen' ] sendReminderGroup = self [ 0 ] . cleaned_data [ 'sendReminderGroup' ] sendReminderUsers = self [ 0 ] . cleaned_data [ 'sendReminderUsers' ] new_remi...
This function is called to create the actual reminders for each occurrence that is created .
47,546
def getIntFromGet ( request , key ) : try : return int ( request . GET . get ( key ) ) except ( ValueError , TypeError ) : return None
This function just parses the request GET data for the requested key and returns it as an integer returning none if the key is not available or is in incorrect format .
47,547
def getDateTimeFromGet ( request , key ) : if request . GET . get ( key , '' ) : try : return ensure_timezone ( datetime . strptime ( unquote ( request . GET . get ( key , '' ) ) , '%Y-%m-%d' ) ) except ( ValueError , TypeError ) : pass return None
This function just parses the request GET data for the requested key and returns it in datetime format returning none if the key is not available or is in incorrect format .
47,548
def finalizePrivateLessonRegistration ( sender , ** kwargs ) : finalReg = kwargs . pop ( 'registration' ) for er in finalReg . eventregistration_set . filter ( event__privatelessonevent__isnull = False ) : er . event . finalizeBooking ( eventRegistration = er , notifyStudent = False )
Once a private lesson registration is finalized mark the slots that were used to book the private lesson as booked and associate them with the final registration . No need to notify students in this instance because they are already receiving a notification of their registration .
47,549
def resetStaffCompensationInfo ( self , request , queryset ) : selected = request . POST . getlist ( admin . ACTION_CHECKBOX_NAME ) ct = ContentType . objects . get_for_model ( queryset . model ) return HttpResponseRedirect ( reverse ( 'resetCompensationRules' ) + "?ct=%s&ids=%s" % ( ct . pk , "," . join ( selected ) )...
This action is added to the list for staff member to permit bulk reseting to category defaults of compensation information for staff members .
47,550
def get_fieldsets ( self , request , obj = None ) : if ( hasattr ( self , 'declared_fieldset' ) and self . declared_fieldsets ) or not self . base_fieldsets : return super ( PolymorphicChildModelAdmin , self ) . get_fieldsets ( request , obj ) other_fields = self . get_subclass_fields ( request , obj ) if other_fields ...
Override polymorphic default to put the subclass - specific fields first
47,551
def pattern_input ( self , question , message = 'Invalid entry' , pattern = '^[a-zA-Z0-9_ ]+$' , default = '' , required = True ) : result = '' requiredFlag = True while ( not result and requiredFlag ) : result = input ( '%s: ' % question ) if result and pattern and not re . match ( pattern , result ) : self . stdout ....
Method for input disallowing special characters with optionally specifiable regex pattern and error message .
47,552
def float_input ( self , question , message = 'Invalid entry' , default = None , required = True ) : float_result = None requiredFlag = True while ( float_result is None and requiredFlag ) : result = input ( '%s: ' % question ) if not result and not required : float_result = None requiredFlag = False if not result and ...
Method for floating point inputs with optionally specifiable error message .
47,553
def ensure_timezone ( dateTime , timeZone = None ) : if is_aware ( dateTime ) and not getattr ( settings , 'USE_TZ' , False ) : return make_naive ( dateTime , timezone = timeZone ) if is_naive ( dateTime ) and getattr ( settings , 'USE_TZ' , False ) : return make_aware ( dateTime , timezone = timeZone ) return dateTime
Since this project is designed to be used in both time - zone aware and naive environments this utility just returns a datetime as either aware or naive depending on whether time zone support is enabled .
47,554
def update_payTo ( apps , schema_editor ) : TransactionParty = apps . get_model ( 'financial' , 'TransactionParty' ) ExpenseItem = apps . get_model ( 'financial' , 'ExpenseItem' ) RevenueItem = apps . get_model ( 'financial' , 'RevenueItem' ) GenericRepeatedExpense = apps . get_model ( 'financial' , 'GenericRepeatedExp...
With the new TransactionParty model the senders and recipients of financial transactions are held in one place . So we need to loop through old ExpenseItems RevenueItems and GenericRepeatedExpense and move their old party references to the new party model .
47,555
def create_initial_category ( apps , schema_editor ) : DiscountCategory = apps . get_model ( 'discounts' , 'DiscountCategory' ) db_alias = schema_editor . connection . alias DiscountCategory . objects . using ( db_alias ) . create ( id = 1 , name = 'General Discounts' , order = 1 , cannotCombine = False )
Create a default category for existing discounts
47,556
def dispatch ( self , request , * args , ** kwargs ) : self . returnJson = ( request . POST . get ( 'json' ) in [ 'true' , True ] ) regonline = getConstant ( 'registration__registrationEnabled' ) if not regonline : returnUrl = reverse ( 'registrationOffline' ) if self . returnJson : return JsonResponse ( { 'status' : '...
Check that registration is online before proceeding . If this is a POST request determine whether the response should be provided in JSON form .
47,557
def get_context_data ( self , ** kwargs ) : context = self . get_listing ( ) context [ 'showDescriptionRule' ] = getConstant ( 'registration__showDescriptionRule' ) or 'all' context . update ( kwargs ) self . set_return_page ( 'registration' , _ ( 'Registration' ) ) return super ( ClassRegistrationView , self ) . get_c...
Add the event and series listing data
47,558
def get_form_kwargs ( self , ** kwargs ) : kwargs = super ( ClassRegistrationView , self ) . get_form_kwargs ( ** kwargs ) kwargs [ 'user' ] = self . request . user if hasattr ( self . request , 'user' ) else None listing = self . get_listing ( ) kwargs . update ( { 'openEvents' : listing [ 'openEvents' ] , 'closedEven...
Tell the form which fields to render
47,559
def get_allEvents ( self ) : if not hasattr ( self , 'allEvents' ) : timeFilters = { 'endTime__gte' : timezone . now ( ) } if getConstant ( 'registration__displayLimitDays' ) or 0 > 0 : timeFilters [ 'startTime__lte' ] = timezone . now ( ) + timedelta ( days = getConstant ( 'registration__displayLimitDays' ) ) self . a...
Splitting this method out to get the set of events to filter allows one to subclass for different subsets of events without copying other logic
47,560
def get_listing ( self ) : if not hasattr ( self , 'listing' ) : allEvents = self . get_allEvents ( ) openEvents = allEvents . filter ( registrationOpen = True ) closedEvents = allEvents . filter ( registrationOpen = False ) publicEvents = allEvents . instance_of ( PublicEvent ) allSeries = allEvents . instance_of ( Se...
This function gets all of the information that we need to either render or validate the form . It is structured to avoid duplicate DB queries
47,561
def dispatch ( self , request , * args , ** kwargs ) : regSession = self . request . session . get ( REG_VALIDATION_STR , { } ) if not regSession : return HttpResponseRedirect ( reverse ( 'registration' ) ) try : reg = TemporaryRegistration . objects . get ( id = self . request . session [ REG_VALIDATION_STR ] . get ( ...
Always check that the temporary registration has not expired
47,562
def get_context_data ( self , ** kwargs ) : context_data = super ( RegistrationSummaryView , self ) . get_context_data ( ** kwargs ) regSession = self . request . session [ REG_VALIDATION_STR ] reg_id = regSession [ "temp_reg_id" ] reg = TemporaryRegistration . objects . get ( id = reg_id ) discount_codes = regSession ...
Pass the initial kwargs then update with the needed registration info .
47,563
def dispatch ( self , request , * args , ** kwargs ) : if REG_VALIDATION_STR not in request . session : return HttpResponseRedirect ( reverse ( 'registration' ) ) try : self . temporaryRegistration = TemporaryRegistration . objects . get ( id = self . request . session [ REG_VALIDATION_STR ] . get ( 'temporaryRegistrat...
Require session data to be set to proceed otherwise go back to step 1 . Because they have the same expiration date this also implies that the TemporaryRegistration object is not yet expired .
47,564
def form_valid ( self , form ) : reg = self . temporaryRegistration expiry = timezone . now ( ) + timedelta ( minutes = getConstant ( 'registration__sessionExpiryMinutes' ) ) self . request . session [ REG_VALIDATION_STR ] [ "temporaryRegistrationExpiry" ] = expiry . strftime ( '%Y-%m-%dT%H:%M:%S%z' ) self . request . ...
Even if this form is valid the handlers for this form may have added messages to the request . In that case then the page should be handled as if the form were invalid . Otherwise update the session data with the form data and then move to the next view
47,565
def linkUserToMostRecentCustomer ( sender , ** kwargs ) : email_address = kwargs . get ( 'email_address' , None ) if not email_address or not email_address . primary or not email_address . verified : return user = email_address . user if not hasattr ( user , 'customer' ) : last_reg = Registration . objects . filter ( c...
If a new primary email address has just been confirmed check if the user associated with that email has an associated customer object yet . If not then look for the customer with that email address who most recently registered for something and that is not associated with another user . Automatically associate the User...
47,566
def linkCustomerToVerifiedUser ( sender , ** kwargs ) : registration = kwargs . get ( 'registration' , None ) if not registration or ( hasattr ( registration . customer , 'user' ) and registration . customer . user ) : return logger . debug ( 'Checking for User for Customer with no associated registration.' ) customer ...
If a Registration is processed in which the associated Customer does not yet have a User then check to see if the Customer s email address has been verified as belonging to a specific User and if that User has an associated Customer . If such a User is found then associated this Customer with that User . This way if a ...
47,567
def create_object ( self , text ) : if self . create_field == 'fullName' : firstName = text . split ( ' ' ) [ 0 ] lastName = ' ' . join ( text . split ( ' ' ) [ 1 : ] ) return self . get_queryset ( ) . create ( ** { 'firstName' : firstName , 'lastName' : lastName } ) else : return super ( StaffMemberAutoComplete , self...
Allow creation of staff members using a full name string .
47,568
def checkBanlist ( sender , ** kwargs ) : if not getConstant ( 'registration__enableBanList' ) : return logger . debug ( 'Signal to check RegistrationContactForm handled by banlist app.' ) formData = kwargs . get ( 'formData' , { } ) first = formData . get ( 'firstName' ) last = formData . get ( 'lastName' ) email = fo...
Check that this individual is not on the ban list .
47,569
def clean ( self ) : if self . staffMember and self . staffMember . userAccount and self . user and not self . staffMember . userAccount == self . user : raise ValidationError ( _ ( 'Transaction party user does not match staff member user.' ) ) if self . location and ( self . user or self . staffMember ) : raise Valida...
Verify that the user and staffMember are not mismatched . Location can only be specified if user and staffMember are not .
47,570
def save ( self , updateBy = None , * args , ** kwargs ) : if ( self . staffMember and self . staffMember . userAccount and not self . user ) or ( isinstance ( updateBy , StaffMember ) and self . staffMember . userAccount ) : self . user = self . staffMember . userAccount elif ( self . user and getattr ( self . user , ...
Verify that the user and staffMember are populated with linked information and ensure that the name is properly specified .
47,571
def ruleName ( self ) : return '%s %s' % ( self . rentalRate , self . RateRuleChoices . values . get ( self . applyRateRule , self . applyRateRule ) )
This should be overridden for child classes
47,572
def ruleName ( self ) : return _ ( '%s at %s' % ( self . room . name , self . room . location . name ) )
overrides from parent class
47,573
def clean ( self ) : if not self . priorDays and not self . startDate : raise ValidationError ( _ ( 'Either a start date or an "up to __ days in the past" limit is required ' + 'for repeated expense rules that are not associated with a venue or a staff member.' ) ) super ( GenericRepeatedExpense , self ) . clean ( )
priorDays is required for Generic Repeated Expenses to avoid infinite loops
47,574
def save ( self , * args , ** kwargs ) : if not hasattr ( self , '__paid' ) or not hasattr ( self , '__approved' ) : if self . approved and not self . approvalDate : self . approvalDate = timezone . now ( ) if self . paid and not self . paymentDate : self . paymentDate = timezone . now ( ) else : if self . approved and...
This custom save method ensures that an expense is not attributed to multiple categories . It also ensures that the series and event properties are always associated with any type of expense of that series or event .
47,575
def relatedItems ( self ) : if self . registration : return self . registration . revenueitem_set . exclude ( pk = self . pk )
If this item is associated with a registration then return all other items associated with the same registration .
47,576
def save ( self , * args , ** kwargs ) : if not hasattr ( self , '__received' ) : if self . received and not self . receivedDate : self . receivedDate = timezone . now ( ) else : if self . received and not self . receivedDate and not self . __receivedDate : self . receivedDate = timezone . now ( ) if not self . accrual...
This custom save method ensures that a revenue item is not attributed to multiple categories . It also ensures that the series and event properties are always associated with any type of revenue of that series or event .
47,577
def clean ( self ) : super ( SlotCreationForm , self ) . clean ( ) startDate = self . cleaned_data . get ( 'startDate' ) endDate = self . cleaned_data . get ( 'endDate' ) startTime = self . cleaned_data . get ( 'startTime' ) endTime = self . cleaned_data . get ( 'endTime' ) instructor = self . cleaned_data . get ( 'ins...
Only allow submission if there are not already slots in the submitted window and only allow rooms associated with the chosen location .
47,578
def get_method_list ( ) : methods = [ str ( _ ( 'Cash' ) ) , str ( _ ( 'Check' ) ) , str ( _ ( 'Bank/Debit Card' ) ) , str ( _ ( 'Other' ) ) ] methods += ExpenseItem . objects . order_by ( ) . values_list ( 'paymentMethod' , flat = True ) . distinct ( ) methods += RevenueItem . objects . order_by ( ) . values_list ( 'p...
Include manual methods by default
47,579
def get_create_option ( self , context , q ) : create_option = [ ] display_create_option = False if self . create_field and q : page_obj = context . get ( 'page_obj' , None ) if page_obj is None or page_obj . number == 1 : display_create_option = True if display_create_option and self . has_add_permission ( self . requ...
Form the correct create_option to append to results .
47,580
def create_object ( self , text ) : if self . create_field == 'name' : if text . startswith ( 'Location_' ) : this_id = text [ len ( 'Location_' ) : ] this_loc = Location . objects . get ( id = this_id ) return self . get_queryset ( ) . get_or_create ( name = this_loc . name , location = this_loc ) [ 0 ] elif text . st...
Allow creation of transaction parties using a full name string .
47,581
def has_group ( user , group_name ) : if user . groups . filter ( name = group_name ) . exists ( ) : return True return False
This allows specification group - based permissions in templates . In most instances creating model - based permissions and giving them to the desired group is preferable .
47,582
def get_item_by_key ( passed_list , key , value ) : if value in [ None , '' ] : return if type ( passed_list ) in [ QuerySet , PolymorphicQuerySet ] : sub_list = passed_list . filter ( ** { key : value } ) else : sub_list = [ x for x in passed_list if x . get ( key ) == value ] if len ( sub_list ) == 1 : return sub_lis...
This one allows us to get one or more items from a list of dictionaries based on the value of a specified key where both the key and the value can be variable names . Does not work with None or null string passed values .
47,583
def get_field_for_object ( field_type , field_id , form ) : field_name = field_type + '_' + str ( field_id ) return form . __getitem__ ( field_name )
This tag allows one to get a specific series or event form field in registration views .
47,584
def template_exists ( template_name ) : try : template . loader . get_template ( template_name ) return True except template . TemplateDoesNotExist : return False
Determine if a given template exists so that it can be loaded if so or a default alternative can be used if not .
47,585
def numRegisteredForRole ( event , role ) : if not isinstance ( event , Event ) or not isinstance ( role , DanceRole ) : return None return event . numRegisteredForRole ( role )
This tag allows one to access the number of registrations for any dance role .
47,586
def soldOutForRole ( event , role ) : if not isinstance ( event , Event ) or not isinstance ( role , DanceRole ) : return None return event . soldOutForRole ( role )
This tag allows one to determine whether any event is sold out for any particular role .
47,587
def numRegisteredForRoleName ( event , roleName ) : if not isinstance ( event , Event ) : return None try : role = DanceRole . objects . get ( name = roleName ) except ObjectDoesNotExist : return None return event . numRegisteredForRole ( role )
This tag allows one to access the number of registrations for any dance role using only the role s name .
47,588
def create_new_code ( cls , ** kwargs ) : prefix = kwargs . pop ( 'prefix' , '' ) new = False while not new : random_string = '' . join ( random . choice ( string . ascii_uppercase ) for z in range ( 10 ) ) if not Voucher . objects . filter ( voucherId = '%s%s' % ( prefix , random_string ) ) . exists ( ) : new = True r...
Creates a new Voucher with a unique voucherId
47,589
def customerMeetsRequirement ( self , customer , danceRole = None , registration = None ) : cust_reqs = self . customerrequirement_set . filter ( customer = customer , met = True ) if customer : cust_priors = customer . eventregistration_set . filter ( event__series__isnull = False ) else : cust_priors = EventRegistrat...
This method checks whether a given customer meets a given set of requirements .
47,590
def updateTransactionParty ( sender , instance , ** kwargs ) : if 'loaddata' in sys . argv or ( 'raw' in kwargs and kwargs [ 'raw' ] ) : return logger . debug ( 'TransactionParty signal fired for %s %s.' % ( instance . __class__ . __name__ , instance . id ) ) party = getattr ( instance , 'transactionparty' , None ) if ...
If a User StaffMember or Location is updated and there exists an associated TransactionParty then the name and other attributes of that party should be updated to reflect the new information .
47,591
def updateSquareFees ( paymentRecord ) : fees = paymentRecord . netFees invoice = paymentRecord . invoice invoice . fees = fees invoice . save ( ) invoice . allocateFees ( ) return fees
The Square Checkout API does not calculate fees immediately so this task is called to be asynchronously run 1 minute after the initial transaction so that any Invoice or ExpenseItem associated with this transaction also remains accurate .
47,592
def getClassTypeMonthlyData ( year = None , series = None , typeLimit = None ) : if not year : year = timezone . now ( ) . year role_list = DanceRole . objects . distinct ( ) if series not in [ 'registrations' , 'studenthours' ] and series not in [ x . pluralName for x in role_list ] : series = 'registrations' when_all...
To break out by class type and month simultaneously get data for each series and aggregate by class type .
47,593
def form_valid ( self , form ) : startDate = form . cleaned_data [ 'startDate' ] endDate = form . cleaned_data [ 'endDate' ] startTime = form . cleaned_data [ 'startTime' ] endTime = form . cleaned_data [ 'endTime' ] instructor = form . cleaned_data [ 'instructorId' ] interval_minutes = getConstant ( 'privateLessons__l...
Create slots and return success message .
47,594
def form_valid ( self , form ) : slotIds = form . cleaned_data [ 'slotIds' ] deleteSlot = form . cleaned_data . get ( 'deleteSlot' , False ) these_slots = InstructorAvailabilitySlot . objects . filter ( id__in = slotIds ) if deleteSlot : these_slots . delete ( ) else : for this_slot in these_slots : this_slot . locatio...
Modify or delete the availability slot as requested and return success message .
47,595
def get_form_kwargs ( self , ** kwargs ) : kwargs = super ( BookPrivateLessonView , self ) . get_form_kwargs ( ** kwargs ) kwargs [ 'user' ] = self . request . user if hasattr ( self . request , 'user' ) else None return kwargs
Pass the current user to the form to render the payAtDoor field if applicable .
47,596
def dispatch ( self , request , * args , ** kwargs ) : lessonSession = request . session . get ( PRIVATELESSON_VALIDATION_STR , { } ) try : self . lesson = PrivateLessonEvent . objects . get ( id = lessonSession . get ( 'lesson' ) ) except ( ValueError , ObjectDoesNotExist ) : messages . error ( request , _ ( 'Invalid ...
Handle the session data passed by the prior view .
47,597
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
47,598
def get_context_data ( self , ** kwargs ) : 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.' ) ) if not event : event = self . object . currentEvent conte...
Add the list of names for the given guest list
47,599
def getBasePrice ( self , ** kwargs ) : if not self . pricingTier : return None return self . pricingTier . getBasePrice ( ** kwargs ) * max ( self . numSlots , 1 )
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 .