idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
235,400 | def init ( sf2 , driver = None , file = None ) : global midi , initialized if not initialized : if file is not None : midi . start_recording ( file ) else : midi . start_audio_output ( driver ) if not midi . load_sound_font ( sf2 ) : return False midi . fs . program_reset ( ) initialized = True return True | Initialize the audio . | 87 | 5 |
235,401 | def start_recording ( self , file = 'mingus_dump.wav' ) : w = wave . open ( file , 'wb' ) w . setnchannels ( 2 ) w . setsampwidth ( 2 ) w . setframerate ( 44100 ) self . wav = w | Initialize a new wave file for recording . | 64 | 9 |
235,402 | def load_sound_font ( self , sf2 ) : self . sfid = self . fs . sfload ( sf2 ) return not self . sfid == - 1 | Load a sound font . | 42 | 5 |
235,403 | def _create_subscription_definition ( gg_client , group_type , config ) : logging . info ( '[begin] Configuring routing subscriptions' ) sub_info = gg_client . create_subscription_definition ( Name = "{0}_routing" . format ( group_type . type_name ) ) logging . info ( 'Created subscription definition: {0}' . format ( sub_info ) ) subs = group_type . get_subscription_definition ( config = config ) if subs is None : logging . warning ( "[end] No SubscriptionDefinition exists in GroupType:{0}" . format ( group_type . type_name ) ) return subv = gg_client . create_subscription_definition_version ( SubscriptionDefinitionId = sub_info [ 'Id' ] , Subscriptions = subs ) sub_arn = subv [ 'Arn' ] config [ 'subscription_def' ] = { "id" : sub_info [ 'Id' ] , "version_arn" : sub_arn } logging . info ( '[end] Configured routing subscriptions' ) return sub_arn | Configure routing subscriptions for a Greengrass group . | 245 | 10 |
235,404 | def clean_core ( self , config_file , region = None , profile_name = None ) : config = GroupConfigFile ( config_file = config_file ) if region is None : region = self . _region # delete the Core's Certificate core_cert_id = config [ 'core' ] [ 'cert_id' ] core_cert_arn = config [ 'core' ] [ 'cert_arn' ] core_thing_name = config [ 'core' ] [ 'thing_name' ] policy_name = config [ 'misc' ] [ 'policy_name' ] logging . info ( 'Deleting core_thing_name:{0}' . format ( core_thing_name ) ) GroupCommands . _delete_thing ( cert_arn = core_cert_arn , cert_id = core_cert_id , thing_name = core_thing_name , region = region , policy_name = policy_name , profile_name = profile_name ) config . make_core_fresh ( ) | Clean all Core related provisioned artifacts from both the local file and the AWS Greengrass service . | 222 | 19 |
235,405 | def clean_devices ( self , config_file , region = None , profile_name = None ) : config = GroupConfigFile ( config_file = config_file ) if region is None : region = self . _region devices = config [ 'devices' ] if 'device_thing_name' in devices : logging . info ( 'Configured devices already clean' ) return policy_name = config [ 'misc' ] [ 'policy_name' ] for device in devices : cert_arn = devices [ device ] [ 'cert_arn' ] cert_id = devices [ device ] [ 'cert_id' ] thing_name = device logging . info ( 'Deleting device_thing_name:{0}' . format ( thing_name ) ) GroupCommands . _delete_thing ( cert_arn , cert_id , thing_name , region , policy_name , profile_name ) config . make_devices_fresh ( ) | Clean all device related provisioned artifacts from both the local file and the AWS Greengrass service . | 201 | 19 |
235,406 | def clean_file ( config_file ) : logging . info ( '[begin] Cleaning config file' ) config = GroupConfigFile ( config_file = config_file ) if config . is_fresh ( ) is True : raise ValueError ( "Config is already clean." ) config . make_fresh ( ) logging . info ( '[end] Cleaned config file:{0}' . format ( config_file ) ) | Clean all provisioned artifacts from the local config file . | 89 | 11 |
235,407 | def clean_all ( self , config_file , region = None , profile_name = None ) : logging . info ( '[begin] Cleaning all provisioned artifacts' ) config = GroupConfigFile ( config_file = config_file ) if config . is_fresh ( ) is True : raise ValueError ( "Config is already clean." ) if region is None : region = self . _region self . _delete_group ( config_file , region = region , profile_name = profile_name ) self . clean_core ( config_file , region = region ) self . clean_devices ( config_file , region = region ) self . clean_file ( config_file ) logging . info ( '[end] Cleaned all provisioned artifacts' ) | Clean all provisioned artifacts from both the local file and the AWS Greengrass service . | 160 | 17 |
235,408 | def deploy ( self , config_file , region = None , profile_name = None ) : config = GroupConfigFile ( config_file = config_file ) if config . is_fresh ( ) : raise ValueError ( "Config not yet tracking a group. Cannot deploy." ) if region is None : region = self . _region gg_client = _get_gg_session ( region = region , profile_name = profile_name ) dep_req = gg_client . create_deployment ( GroupId = config [ 'group' ] [ 'id' ] , GroupVersionId = config [ 'group' ] [ 'version' ] , DeploymentType = "NewDeployment" ) print ( "Group deploy requested for deployment_id:{0}" . format ( dep_req [ 'DeploymentId' ] , ) ) | Deploy the configuration and Lambda functions of a Greengrass group to the Greengrass core contained in the group . | 179 | 22 |
235,409 | def create_core ( self , thing_name , config_file , region = None , cert_dir = None , account_id = None , policy_name = 'ggc-default-policy' , profile_name = None ) : config = GroupConfigFile ( config_file = config_file ) if config . is_fresh ( ) is False : raise ValueError ( "Config file already tracking previously created core or group" ) if region is None : region = self . _region if account_id is None : account_id = self . _account_id keys_cert , thing = self . create_thing ( thing_name , region , cert_dir ) cert_arn = keys_cert [ 'certificateArn' ] config [ 'core' ] = { 'thing_arn' : thing [ 'thingArn' ] , 'cert_arn' : cert_arn , 'cert_id' : keys_cert [ 'certificateId' ] , 'thing_name' : thing_name } logging . debug ( "create_core cfg:{0}" . format ( config ) ) logging . info ( "Thing:'{0}' associated with cert:'{1}'" . format ( thing_name , cert_arn ) ) core_policy = self . get_core_policy ( core_name = thing_name , account_id = account_id , region = region ) iot_client = _get_iot_session ( region = region , profile_name = profile_name ) self . _create_attach_thing_policy ( cert_arn , core_policy , iot_client = iot_client , policy_name = policy_name ) misc = config [ 'misc' ] misc [ 'policy_name' ] = policy_name config [ 'misc' ] = misc | Using the thing_name value creates a Thing in AWS IoT attaches and downloads new keys & certs to the certificate directory then records the created information in the local config file for inclusion in the Greengrass Group as a Greengrass Core . | 389 | 46 |
235,410 | def create_devices ( self , thing_names , config_file , region = None , cert_dir = None , append = False , account_id = None , policy_name = 'ggd-discovery-policy' , profile_name = None ) : logging . info ( "create_devices thing_names:{0}" . format ( thing_names ) ) config = GroupConfigFile ( config_file = config_file ) if append is False and config . is_device_fresh ( ) is False : raise ValueError ( "Config file tracking previously created devices. Append " "devices instead" ) if region is None : region = self . _region if account_id is None : account_id = self . _account_id devices = dict ( ) if append : devices = config [ 'devices' ] if type ( thing_names ) is str : thing_names = [ thing_names ] iot_client = _get_iot_session ( region = region , profile_name = profile_name ) for thing_name in thing_names : keys_cert , thing = self . create_thing ( thing_name , region , cert_dir ) cert_arn = keys_cert [ 'certificateArn' ] devices [ thing_name ] = { 'thing_arn' : thing [ 'thingArn' ] , 'cert_arn' : cert_arn , 'cert_id' : keys_cert [ 'certificateId' ] , 'thing_name' : thing_name } logging . info ( "Thing:'{0}' associated with cert:'{1}'" . format ( thing_name , cert_arn ) ) device_policy = self . get_device_policy ( device_name = thing_name , account_id = account_id , region = region ) self . _create_attach_thing_policy ( cert_arn , device_policy , iot_client , policy_name ) config [ 'devices' ] = devices logging . info ( "create_devices cfg:{0}" . format ( config ) ) | Using the thing_names values creates Things in AWS IoT attaches and downloads new keys & certs to the certificate directory then records the created information in the local config file for inclusion in the Greengrass Group as Greengrass Devices . | 441 | 44 |
235,411 | def associate_devices ( self , thing_names , config_file , region = None , profile_name = None ) : # TODO remove this function when Group discovery is enriched logging . info ( "associate_devices thing_names:{0}" . format ( thing_names ) ) config = GroupConfigFile ( config_file = config_file ) if region is None : region = self . _region devices = config [ 'devices' ] if type ( thing_names ) is str : thing_names = [ thing_names ] iot_client = _get_iot_session ( region = region , profile_name = profile_name ) for thing_name in thing_names : thing = iot_client . describe_thing ( thingName = thing_name ) logging . info ( "Found existing Thing:{0}" . format ( thing ) ) p = iot_client . list_thing_principals ( thingName = thing_name ) logging . info ( "Existing Thing has principals:{0}" . format ( p ) ) devices [ thing_name ] = { 'thing_arn' : thing [ 'attributes' ] [ 'thingArn' ] , 'cert_arn' : p [ 'principals' ] [ 0 ] , 'cert_id' : thing [ 'attributes' ] [ 'certificateId' ] , 'thing_name' : thing_name } logging . info ( "Thing:'{0}' associated with config:'{1}'" . format ( thing_name , config_file ) ) config [ 'devices' ] = devices | Using the thing_names values associate existing Things in AWS IoT with the config of another Greengrass Group for use as Greengrass Devices . | 341 | 27 |
235,412 | def send_data ( self , message ) : #logger.debug("TX:\n%s", json.dumps(message, indent=2)) data = json . dumps ( message ) . encode ( 'utf-8' ) + b'\n' self . transport . write ( data ) | Given an object encode as JSON and transmit to the server . | 64 | 12 |
235,413 | async def got_who_reply ( self , nick = None , real_name = None , * * kws ) : #logger.debug('who reply: %r' % kws) nick = nick [ 2 : ] if nick [ 0 : 2 ] == 'E_' else nick host , ports = real_name . split ( ' ' , 1 ) self . servers . remove ( nick ) logger . debug ( "Found: '%s' at %s with port list: %s" , nick , host , ports ) self . results [ host . lower ( ) ] = ServerInfo ( nick , host , ports ) if not self . servers : self . all_done . set ( ) | Server replied to one of our WHO requests with details . | 150 | 11 |
235,414 | async def _keepalive ( self ) : while self . protocol : vers = await self . RPC ( 'server.version' ) logger . debug ( "Server version: " + repr ( vers ) ) # Five minutes isn't really enough anymore; looks like # servers are killing 2-minute old idle connections now. # But decreasing interval this seems rude. await asyncio . sleep ( 600 ) | Keep our connect to server alive forever with some pointless traffic . | 83 | 12 |
235,415 | def _send_request ( self , method , params = [ ] , is_subscribe = False ) : # pick a new ID self . next_id += 1 req_id = self . next_id # serialize as JSON msg = { 'id' : req_id , 'method' : method , 'params' : params } # subscriptions are a Q, normal requests are a future if is_subscribe : waitQ = asyncio . Queue ( ) self . subscriptions [ method ] . append ( waitQ ) fut = asyncio . Future ( loop = self . loop ) self . inflight [ req_id ] = ( msg , fut ) # send it via the transport, which serializes it if not self . protocol : logger . debug ( "Need to reconnect to server" ) async def connect_first ( ) : await self . reconnect ( ) self . protocol . send_data ( msg ) self . loop . create_task ( connect_first ( ) ) else : # typical case, send request immediatedly, response is a future self . protocol . send_data ( msg ) return fut if not is_subscribe else ( fut , waitQ ) | Send a new request to the server . Serialized the JSON and tracks id numbers and optional callbacks . | 247 | 21 |
235,416 | def _got_response ( self , msg ) : #logger.debug("MSG: %r" % msg) resp_id = msg . get ( 'id' , None ) if resp_id is None : # subscription traffic comes with method set, but no req id. method = msg . get ( 'method' , None ) if not method : logger . error ( "Incoming server message had no ID nor method in it" , msg ) return # not obvious, but result is on params, not result, for subscriptions result = msg . get ( 'params' , None ) logger . debug ( "Traffic on subscription: %s" % method ) subs = self . subscriptions . get ( method ) for q in subs : self . loop . create_task ( q . put ( result ) ) return assert 'method' not in msg result = msg . get ( 'result' ) # fetch and forget about the request inf = self . inflight . pop ( resp_id ) if not inf : logger . error ( "Incoming server message had unknown ID in it: %s" % resp_id ) return # it's a future which is done now req , rv = inf if 'error' in msg : err = msg [ 'error' ] logger . info ( "Error response: '%s'" % err ) rv . set_exception ( ElectrumErrorResponse ( err , req ) ) else : rv . set_result ( result ) | Decode and dispatch responses from the server . | 310 | 9 |
235,417 | 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 . | 59 | 11 |
235,418 | def from_irc ( self , irc_nickname = None , irc_password = None ) : if have_bottom : from . findall import IrcListener # connect and fetch current set of servers who are # on #electrum channel at freenode bot = IrcListener ( irc_nickname = irc_nickname , irc_password = irc_password ) results = bot . loop . run_until_complete ( bot . collect_data ( ) ) bot . loop . close ( ) # merge by nick name self . update ( results ) else : return ( False ) | Connect to the IRC channel and find all servers presently connected . | 128 | 12 |
235,419 | 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 . | 64 | 7 |
235,420 | 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 . | 45 | 12 |
235,421 | def _post_patched_request ( consumers , lti_key , body , url , method , content_type ) : # pylint: disable=too-many-locals, too-many-arguments 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 ) secret = lti_consumer . secret consumer = oauth2 . Consumer ( key = lti_key , secret = secret ) client = oauth2 . Client ( consumer ) if lti_cert : client . add_certificate ( key = lti_cert , cert = lti_cert , domain = '' ) log . debug ( "cert %s" , lti_cert ) import httplib2 http = httplib2 . Http # pylint: disable=protected-access normalize = http . _normalize_headers def my_normalize ( self , headers ) : """ This function patches Authorization header """ ret = normalize ( self , headers ) if 'authorization' in ret : ret [ 'Authorization' ] = ret . pop ( 'authorization' ) log . debug ( "headers" ) log . debug ( headers ) return ret http . _normalize_headers = my_normalize monkey_patch_function = normalize response , content = client . request ( url , method , body = body . encode ( 'utf-8' ) , headers = { 'Content-Type' : content_type } ) http = httplib2 . Http # pylint: disable=protected-access http . _normalize_headers = monkey_patch_function log . debug ( "key %s" , lti_key ) log . debug ( "secret %s" , secret ) log . debug ( "url %s" , url ) log . debug ( "response %s" , response ) log . debug ( "content %s" , format ( content ) ) return response , content | Authorization header needs to be capitalized for some LTI clients this function ensures that header is capitalized | 470 | 21 |
235,422 | 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 ) return is_success | Posts a signed message to LTI consumer | 105 | 8 |
235,423 | def post_message2 ( consumers , lti_key , url , body , method = 'POST' , content_type = 'application/xml' ) : # pylint: disable=too-many-arguments ( 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 | 107 | 15 |
235,424 | 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 . add_signature_method ( SignatureMethod_PLAINTEXT_Unicode ( ) ) oauth_server . add_signature_method ( SignatureMethod_HMAC_SHA1_Unicode ( ) ) # Check header for SSL before selecting the url if headers . get ( 'X-Forwarded-Proto' , 'http' ) == 'https' : url = url . replace ( 'http:' , 'https:' , 1 ) oauth_request = Request_Fix_Duplicate . from_request ( method , url , headers = dict ( headers ) , parameters = params ) if not oauth_request : log . info ( 'Received non oauth request on oauth protected page' ) raise LTIException ( 'This page requires a valid oauth session ' 'or request' ) try : # pylint: disable=protected-access oauth_consumer_key = oauth_request . get_parameter ( 'oauth_consumer_key' ) consumer = oauth_server . lookup_consumer ( oauth_consumer_key ) if not consumer : raise oauth2 . Error ( 'Invalid consumer.' ) oauth_server . verify_request ( oauth_request , consumer , None ) except oauth2 . Error : # Rethrow our own for nice error handling (don't print # error message as it will contain the key raise LTIException ( "OAuth error: Please check your key and secret" ) return True | Verifies that request is valid | 409 | 6 |
235,425 | def generate_request_xml ( message_identifier_id , operation , lis_result_sourcedid , score ) : # pylint: disable=too-many-locals 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 ( header , 'imsx_POXRequestHeaderInfo' ) version = etree . SubElement ( header_info , 'imsx_version' ) version . text = 'V1.0' message_identifier = etree . SubElement ( header_info , 'imsx_messageIdentifier' ) message_identifier . text = message_identifier_id body = etree . SubElement ( root , 'imsx_POXBody' ) xml_request = etree . SubElement ( body , '%s%s' % ( operation , 'Request' ) ) record = etree . SubElement ( xml_request , 'resultRecord' ) guid = etree . SubElement ( record , 'sourcedGUID' ) sourcedid = etree . SubElement ( guid , 'sourcedId' ) sourcedid . text = lis_result_sourcedid if score is not None : result = etree . SubElement ( record , 'result' ) result_score = etree . SubElement ( result , 'resultScore' ) language = etree . SubElement ( result_score , 'language' ) language . text = 'en' text_string = etree . SubElement ( result_score , 'textString' ) text_string . text = score . __str__ ( ) ret = "<?xml version='1.0' encoding='utf-8'?>\n{}" . format ( etree . tostring ( root , encoding = 'utf-8' ) . decode ( 'utf-8' ) ) log . debug ( "XML Response: \n%s" , ret ) return ret | Generates LTI 1 . 1 XML for posting result to LTI consumer . | 478 | 16 |
235,426 | 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 ] # find the intersection of the roles 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_list , roles , is_user_role_there ) return is_user_role_there else : raise LTIException ( "Unknown role {}." . format ( role ) ) | Verify if user is in role | 163 | 7 |
235,427 | 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 | 105 | 10 |
235,428 | def post_grade ( self , grade ) : message_identifier_id = self . message_identifier_id ( ) operation = 'replaceResult' lis_result_sourcedid = self . lis_result_sourcedid # # edX devbox fix score = float ( grade ) if 0 <= score <= 1.0 : xml = generate_request_xml ( message_identifier_id , operation , lis_result_sourcedid , score ) ret = post_message ( self . _consumers ( ) , self . key , self . response_url , xml ) if not ret : raise LTIPostMessageException ( "Post Message Failed" ) return True return False | Post grade to LTI consumer using XML | 149 | 8 |
235,429 | 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 | 64 | 8 |
235,430 | 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 ( ) ) # url remapping is useful for using devstack # devstack reports httpS://localhost:8000/ and listens on HTTP for prefix , mapping in urls . items ( ) : if url . startswith ( prefix ) : for _from , _to in mapping . items ( ) : url = url . replace ( _from , _to ) return url | Returns remapped lis_outcome_service_url uses PYLTI_URL_FIX map to support edX dev - stack | 143 | 28 |
235,431 | def _consumers ( self ) : consumers = { } for env in os . environ : if env . startswith ( 'CONSUMER_KEY_SECRET_' ) : key = env [ 20 : ] # Strip off the CONSUMER_KEY_SECRET_ prefix # TODO: remove below after live test # consumers[key] = {"secret": os.environ[env], "cert": 'NA'} consumers [ key ] = { "secret" : os . environ [ env ] , "cert" : None } if not consumers : raise LTIException ( "No consumers found. Chalice stores " "consumers in Lambda environment variables. " "Have you created the environment variables?" ) return consumers | 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 . | 157 | 54 |
235,432 | def verify_request ( self ) : request = self . lti_kwargs [ 'app' ] . current_request if request . method == 'POST' : # Chalice expects JSON and does not nativly support forms data in # a post body. The below is copied from the parsing of query # strings as implimented in match_route of Chalice local.py 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_params log . debug ( params ) log . debug ( 'verify_request?' ) try : # Chalice does not have a url property therefore building it. protocol = request . headers . get ( 'x-forwarded-proto' , 'http' ) hostname = request . headers [ 'host' ] path = request . context [ 'path' ] url = urlunparse ( ( protocol , hostname , path , "" , "" , "" ) ) verify_request_common ( self . _consumers ( ) , url , request . method , request . headers , params ) log . debug ( 'verify_request success' ) # All good to go, store all of the LTI params into a # session dict for use in views for prop in LTI_PROPERTY_LIST : if params . get ( prop , None ) : log . debug ( "params %s=%s" , prop , params . get ( prop , None ) ) self . session [ prop ] = params [ prop ] # Set logged in session key self . session [ LTI_SESSION_KEY ] = True return True except LTIException : log . debug ( 'verify_request failed' ) for prop in LTI_PROPERTY_LIST : if self . session . get ( prop , None ) : del self . session [ prop ] self . session [ LTI_SESSION_KEY ] = False raise | Verify LTI request | 442 | 5 |
235,433 | 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 ( count = 0 ) & Q ( status__in = [ Event . RegStatus . hidden , Event . RegStatus . regHidden , Event . RegStatus . disabled ] ) ) | Recent events are listed in link form . | 137 | 8 |
235,434 | def get_context_data ( self , * * kwargs ) : # Update the site session data so that registration processes know to send return links to # the view class registrations page. set_return_page() is in SiteHistoryMixin. 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__customer__user__first_name' , 'registration__customer__user__last_name' ) , } context . update ( kwargs ) return super ( EventRegistrationSummaryView , self ) . get_context_data ( * * context ) | Add the list of registrations for the given series | 184 | 9 |
235,435 | 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 : redirect_url = Page . objects . get ( pk = getConstant ( 'general__defaultAdminSuccessPage' ) ) . get_absolute_url ( settings . LANGUAGE_CODE ) except ObjectDoesNotExist : redirect_url = '/' context . update ( { 'redirect_url' : redirect_url , 'seconds' : self . request . GET . get ( 'seconds' , 5 ) , } ) return context | 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 . | 197 | 34 |
235,436 | 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 ( ViewInvoiceView , self ) . get ( request , * args , * * kwargs ) return self . handle_no_permission ( ) | Invoices can be viewed only if the validation string is provided unless the user is logged in and has view_all_invoice permissions | 128 | 28 |
235,437 | 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 : self . invoices = Invoice . objects . filter ( id__in = [ x for x in ids . split ( ',' ) ] ) [ : ] except ValueError : return HttpResponseBadRequest ( _ ( 'Invalid invoice identifiers specified.' ) ) if not self . invoices : return HttpResponseBadRequest ( _ ( 'No invoice identifiers specified.' ) ) toNotify = [ ] cannotNotify = [ ] for invoice in self . invoices : if invoice . get_default_recipients ( ) : toNotify . append ( invoice ) else : cannotNotify . append ( invoice ) self . toNotify = toNotify self . cannotNotify = cannotNotify return super ( InvoiceNotificationView , self ) . dispatch ( request , * args , * * kwargs ) | Get the set of invoices for which to permit notifications | 285 | 12 |
235,438 | 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 | 54 | 12 |
235,439 | def dispatch ( self , request , * args , * * kwargs ) : ids = request . GET . get ( 'customers' ) groups = request . GET . get ( 'customergroup' ) self . customers = None if ids or groups : # Initial filter applies to no one but allows appending by logical or filters = Q ( id__isnull = True ) if ids : filters = filters | Q ( id__in = [ int ( x ) for x in ids . split ( ',' ) ] ) if groups : filters = filters | Q ( groups__id__in = [ int ( x ) for x in groups . split ( ',' ) ] ) try : self . customers = Customer . objects . filter ( filters ) except ValueError : return HttpResponseBadRequest ( _ ( 'Invalid customer ids passed' ) ) return super ( SendEmailView , self ) . dispatch ( request , * args , * * kwargs ) | If a list of customers or groups was passed then parse it | 204 | 12 |
235,440 | 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 = lastStart . year else : month = timezone . now ( ) . month year = timezone . now ( ) . year months = [ ( '' , _ ( 'None' ) ) ] for i in range ( 0 , numMonths ) : newmonth = ( month - i - 1 ) % 12 + 1 newyear = year if month - i - 1 < 0 : newyear = year - 1 newdate = datetime ( year = newyear , month = newmonth , day = 1 ) newdateStr = newdate . strftime ( "%m-%Y" ) monthStr = newdate . strftime ( "%B, %Y" ) months . append ( ( newdateStr , monthStr ) ) cutoff = timezone . now ( ) - timedelta ( days = 120 ) allEvents = Event . objects . filter ( startTime__gte = cutoff ) . order_by ( '-startTime' ) recentSeries = [ ( '' , 'None' ) ] + [ ( x . id , '%s %s: %s' % ( month_name [ x . month ] , x . year , x . name ) ) for x in allEvents ] kwargs = super ( SendEmailView , self ) . get_form_kwargs ( * * kwargs ) kwargs . update ( { "months" : months , "recentseries" : recentSeries , "customers" : self . customers , } ) return kwargs | Get the list of recent months and recent series to pass to the form | 411 | 14 |
235,441 | 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 | 76 | 21 |
235,442 | 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 | 70 | 7 |
235,443 | 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' ) # Create a list of start dates, based on the passed values of repeatEvery, # periodicity, quantity and endDate. This list will be iterated through to # create the new instances for each event. if periodicity == 'D' : delta = { 'days' : repeatEvery } elif periodicity == 'W' : delta = { 'weeks' : repeatEvery } elif periodicity == 'M' : delta = { 'months' : repeatEvery } repeat_list = [ ] this_date = startDate if quantity : for k in range ( 0 , quantity ) : repeat_list . append ( this_date ) this_date = this_date + relativedelta ( * * delta ) elif endDate : while ( this_date <= endDate ) : repeat_list . append ( this_date ) this_date = this_date + relativedelta ( * * delta ) # Now, loop through the events in the queryset to create duplicates of them for event in self . queryset : # For each new occurrence, we determine the new startime by the distance from # midnight of the first occurrence date, where the first occurrence date is # replaced by the date given in repeat list old_min_time = event . localStartTime . replace ( hour = 0 , minute = 0 , second = 0 , microsecond = 0 ) old_occurrence_data = [ ( x . startTime - old_min_time , x . endTime - old_min_time , x . cancelled ) for x in event . eventoccurrence_set . all ( ) ] old_role_data = [ ( x . role , x . capacity ) for x in event . eventrole_set . all ( ) ] for instance_date in repeat_list : # Ensure that time zones are treated properly combined_datetime = datetime . combine ( instance_date , datetime . min . time ( ) ) new_datetime = ensure_timezone ( combined_datetime , old_min_time . tzinfo ) # Removing the pk and ID allow new instances of the event to # be created upon saving with automatically generated ids. event . id = None event . pk = None event . save ( ) # Create new occurrences for occurrence in old_occurrence_data : EventOccurrence . objects . create ( event = event , startTime = new_datetime + occurrence [ 0 ] , endTime = new_datetime + occurrence [ 1 ] , cancelled = occurrence [ 2 ] , ) # Create new event-specific role data for role in old_role_data : EventRole . objects . create ( event = event , role = role [ 0 ] , capacity = role [ 1 ] , ) # Need to save twice to ensure that startTime etc. get # updated properly. event . save ( ) return super ( RepeatEventsView , self ) . form_valid ( form ) | For each object in the queryset create the duplicated objects | 706 | 13 |
235,444 | 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 ( ) ) ) . filter ( Q ( startTime__lte = timezone . now ( ) + timedelta ( days = 60 ) ) & Q ( endTime__gte = timezone . now ( ) - timedelta ( days = 60 ) ) ) | Get the set of recent and upcoming events to which this list applies . | 150 | 14 |
235,445 | 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 . | 90 | 22 |
235,446 | 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 . | 65 | 11 |
235,447 | 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 | 40 | 11 |
235,448 | 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' ) ) # Component-by-component, OR append filters to an initial filter that always # evaluates to False. components = self . guestlistcomponent_set . all ( ) filters = Q ( pk__isnull = True ) # Add prior staff based on the component rule. for component in components : if event and self . appliesToEvent ( event ) : filters = filters | self . getComponentFilters ( component , event = event ) else : filters = filters | self . getComponentFilters ( component , dateTime = timezone . now ( ) ) # Add all event staff if that box is checked (no need for separate components) if self . includeStaff and event and self . appliesToEvent ( event ) : filters = filters | Q ( eventstaffmember__event = event ) # Execute the constructed query and add the names of staff names += list ( StaffMember . objects . filter ( filters ) . annotate ( guestType = Case ( When ( eventstaffmember__event = event , then = Concat ( Value ( 'Event Staff: ' ) , 'eventstaffmember__category__name' ) ) , default = Value ( ugettext ( 'Other Staff' ) ) , output_field = models . CharField ( ) ) ) . distinct ( ) . values ( 'firstName' , 'lastName' , 'guestType' ) ) if self . includeRegistrants and event and self . appliesToEvent ( event ) : names += list ( Registration . objects . filter ( eventregistration__event = event ) . annotate ( guestType = Value ( _ ( 'Registered' ) , output_field = models . CharField ( ) ) ) . values ( 'firstName' , 'lastName' , 'guestType' ) ) return names | Get the list of names associated with a particular event . | 471 | 11 |
235,449 | 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 . | 74 | 14 |
235,450 | 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_option ) else : # Only return attributes for valid requests return JsonResponse ( { } ) outClasses = { } for option in seriesClasses : outClasses [ str ( option . id ) ] = option . __str__ ( ) outTeachers = { } for option in seriesTeachers : outTeachers [ str ( option . id ) ] = option . __str__ ( ) return JsonResponse ( { 'id_occurrences' : outClasses , 'id_replacedStaffMember' : outTeachers , } ) | This function handles the filtering of available series classes and seriesteachers when a series is chosen on the Substitute Teacher reporting form . | 198 | 27 |
235,451 | 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." ) ) # Get all possible registrations, so that we can set those that are not included to False (and set those that are included to True) all_eventreg = list ( EventRegistration . objects . filter ( event__id = event_id ) ) for this_reg in all_eventreg : if str ( this_reg . registration . id ) in reg_ids and not this_reg . checkedIn : this_reg . checkedIn = True this_reg . save ( ) elif str ( this_reg . registration . id ) not in reg_ids and this_reg . checkedIn : this_reg . checkedIn = False this_reg . save ( ) return HttpResponse ( "OK." ) | This function handles the Ajax call made when a user is marked as checked in | 219 | 15 |
235,452 | 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, no template ID provided." ) ) try : this_template = EmailTemplate . objects . get ( id = template_id ) except ObjectDoesNotExist : return HttpResponse ( _ ( "Error getting template." ) ) if this_template . groupRequired and this_template . groupRequired not in request . user . groups . all ( ) : return HttpResponse ( _ ( "Error, no permission to access this template." ) ) if this_template . hideFromForm : return HttpResponse ( _ ( "Error, no permission to access this template." ) ) return JsonResponse ( { 'subject' : this_template . subject , 'content' : this_template . content , 'html_content' : this_template . html_content , 'richTextChoice' : this_template . richTextChoice , } ) | This function handles the Ajax call made when a user wants a specific email template | 266 | 15 |
235,453 | 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 ( 'registration' ) ) # Check that Invoice matching passed ID exists try : i = Invoice . objects . get ( id = self . invoiceID ) except ObjectDoesNotExist : return HttpResponseBadRequest ( _ ( 'Invalid invoice information passed.' ) ) if i . unpaid or i . amountPaid != self . amount : return HttpResponseBadRequest ( _ ( 'Passed invoice is not paid.' ) ) return super ( GiftCertificateCustomizeView , self ) . dispatch ( request , * args , * * kwargs ) | Check that a valid Invoice ID has been passed in session data and that said invoice is marked as paid . | 206 | 22 |
235,454 | 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 ( 'Processing gift certificate.' ) try : voucher = Voucher . create_new_code ( prefix = 'GC_' , name = _ ( 'Gift certificate: %s%s for %s' % ( getConstant ( 'general__currencySymbol' ) , self . amount , emailTo ) ) , category = getConstant ( 'vouchers__giftCertCategory' ) , originalAmount = self . amount , singleUse = False , forFirstTimeCustomersOnly = False , expirationDate = None , ) except IntegrityError : logger . error ( 'Error creating gift certificate voucher for Invoice #%s' % self . invoiceId ) emailErrorMessage ( _ ( 'Gift certificate transaction not completed' ) , self . invoiceId ) template = getConstant ( 'vouchers__giftCertTemplate' ) # Attempt to attach a PDF of the gift certificate rf = RequestFactory ( ) pdf_request = rf . get ( '/' ) pdf_kwargs = { 'currencySymbol' : getConstant ( 'general__currencySymbol' ) , 'businessName' : getConstant ( 'contact__businessName' ) , 'certificateAmount' : voucher . originalAmount , 'certificateCode' : voucher . voucherId , 'certificateMessage' : message , 'recipientName' : recipientName , 'fromName' : fromName , } if recipientName : pdf_kwargs . update ( { } ) attachment = GiftCertificatePDFView ( request = pdf_request ) . get ( request = pdf_request , * * pdf_kwargs ) . content or None if attachment : attachment_name = 'gift_certificate.pdf' else : attachment_name = None # Send a confirmation email email_class = EmailRecipientMixin ( ) email_class . email_recipient ( subject = template . subject , content = template . content , send_html = template . send_html , html_content = template . html_content , from_address = template . defaultFromAddress , from_name = template . defaultFromName , cc = template . defaultCC , to = emailTo , currencySymbol = getConstant ( 'general__currencySymbol' ) , businessName = getConstant ( 'contact__businessName' ) , certificateAmount = voucher . originalAmount , certificateCode = voucher . voucherId , certificateMessage = message , recipientName = recipientName , fromName = fromName , emailType = emailType , recipient_name = recipientName , attachment_name = attachment_name , attachment = attachment ) # Remove the invoice session data self . request . session . pop ( INVOICE_VALIDATION_STR , None ) return HttpResponseRedirect ( self . get_success_url ( ) ) | Create the gift certificate voucher with the indicated information and send the email as directed . | 684 | 16 |
235,455 | 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_series : series . updateRegistrationStatus ( ) | Every hour check if the series that are currently open for registration should be closed . | 88 | 16 |
235,456 | def clearExpiredTemporaryRegistrations ( ) : from . models import TemporaryRegistration if not getConstant ( 'general__enableCronTasks' ) : return if getConstant ( 'registration__deleteExpiredTemporaryRegistrations' ) : TemporaryRegistration . objects . filter ( expirationDate__lte = timezone . now ( ) - timedelta ( minutes = 1 ) ) . delete ( ) call_command ( 'clearsessions' ) | 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 . | 98 | 47 |
235,457 | def updateFinancialItems ( ) : if not getConstant ( 'general__enableCronTasks' ) : return logger . info ( 'Creating automatically-generated financial items.' ) if getConstant ( 'financial__autoGenerateExpensesEventStaff' ) : createExpenseItemsForEvents ( ) if getConstant ( 'financial__autoGenerateExpensesVenueRental' ) : createExpenseItemsForVenueRental ( ) if getConstant ( 'financial__autoGenerateRevenueRegistrations' ) : createRevenueItemsForRegistrations ( ) | Every hour create any necessary revenue items and expense items for activities that need them . | 124 | 16 |
235,458 | 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 . error ( 'Cannot send error emails because addresses have not been specified.' ) return try : send_mail ( subject , message , send_from , [ send_to ] , fail_silently = False ) logger . debug ( 'Error email sent.' ) except Exception as e : logger . error ( 'Error email was not sent: %s' % e ) | Useful for sending error messages via email . | 165 | 9 |
235,459 | 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 ( ) : kwargs [ 'basis' ] = 'accrualDate' return super ( ) . get ( request , * args , * * kwargs ) | Allow passing of basis and time limitations | 149 | 7 |
235,460 | 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 = list ( month_name ) . index ( self . kwargs . get ( 'month' ) . title ( ) ) except ( ValueError , TypeError ) : month = None else : month = getIntFromGet ( request , 'month' ) try : event_id = int ( self . kwargs . get ( 'event' ) ) except ( ValueError , TypeError ) : event_id = getIntFromGet ( request , 'event' ) event = None if event_id : try : event = Event . objects . get ( id = event_id ) except ObjectDoesNotExist : pass kwargs . update ( { 'year' : year , 'month' : month , 'startDate' : getDateTimeFromGet ( request , 'startDate' ) , 'endDate' : getDateTimeFromGet ( request , 'endDate' ) , 'basis' : request . GET . get ( 'basis' ) , 'event' : event , } ) if kwargs . get ( 'basis' ) not in EXPENSE_BASES . keys ( ) : kwargs [ 'basis' ] = 'accrualDate' context = self . get_context_data ( * * kwargs ) return self . render_to_response ( context ) | Pass any permissable GET data . URL parameters override GET parameters | 384 | 13 |
235,461 | 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 | 62 | 10 |
235,462 | 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' ] # Set the new reminder's time new_reminder_time = occurrence . startTime - timedelta ( minutes = int ( float ( sendReminderWhen ) ) ) new_reminder = EventReminder ( eventOccurrence = occurrence , time = new_reminder_time ) new_reminder . save ( ) # Set reminders based on the choice the user made if sendReminderTo == 'all' : user_set = User . objects . filter ( Q ( staffmember__isnull = False ) | Q ( is_staff = True ) ) elif sendReminderTo == 'me' : user_set = User . objects . filter ( id = occurrence . event . submissionUser . id ) elif sendReminderTo == 'users' : user_set = User . objects . filter ( * * { 'id__in' : sendReminderUsers } ) elif sendReminderTo == 'group' : user_set = User . objects . filter ( * * { 'groups' : sendReminderGroup } ) else : user_set = [ ] for user in user_set : new_reminder . notifyList . add ( user ) | This function is called to create the actual reminders for each occurrence that is created . | 340 | 16 |
235,463 | 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 . | 36 | 33 |
235,464 | 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 . | 78 | 34 |
235,465 | 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 . | 77 | 47 |
235,466 | 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 . | 100 | 25 |
235,467 | def get_fieldsets ( self , request , obj = None ) : # If subclass declares fieldsets, this is respected 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 : return ( ( self . extra_fieldset_title , { 'fields' : other_fields } ) , ) + self . base_fieldsets else : return self . base_fieldsets | Override polymorphic default to put the subclass - specific fields first | 141 | 12 |
235,468 | 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 . write ( self . style . ERROR ( message ) ) result = '' elif not result and default : # Return default for fields with default return default elif not result and required : # Ask again for required fields self . stdout . write ( self . style . ERROR ( 'Answer is required.' ) ) elif not required : # No need to re-ask for non-required fields requiredFlag = False return result | Method for input disallowing special characters with optionally specifiable regex pattern and error message . | 179 | 18 |
235,469 | 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 default : float_result = default if float_result is None and requiredFlag : try : float_result = float ( result ) except ValueError : self . stdout . write ( self . style . ERROR ( message ) ) float_result = None return float_result | Method for floating point inputs with optionally specifiable error message . | 134 | 12 |
235,470 | 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 ) # If neither condition is met, then we can return what was passed 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 . | 111 | 38 |
235,471 | 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' , 'GenericRepeatedExpense' ) # First, update expense items and Generic repeated expense rules for item in chain ( ExpenseItem . objects . filter ( Q ( payToUser__isnull = False ) | Q ( payToLocation__isnull = False ) | Q ( payToName__isnull = False ) ) , GenericRepeatedExpense . objects . filter ( Q ( payToUser__isnull = False ) | Q ( payToLocation__isnull = False ) | Q ( payToName__isnull = False ) ) , ) : if getattr ( item , 'payToUser' , None ) : party = TransactionParty . objects . get_or_create ( user = item . payToUser , defaults = { 'name' : getFullName ( item . payToUser ) , 'staffMember' : getattr ( item . payToUser , 'staffmember' , None ) , } ) [ 0 ] elif getattr ( item , 'payToLocation' , None ) : party = TransactionParty . objects . get_or_create ( location = item . payToLocation , defaults = { 'name' : item . payToLocation . name , } ) [ 0 ] elif getattr ( item , 'payToName' , None ) : party = createPartyFromName ( apps , item . payToName ) item . payTo = party item . save ( ) # Finally, update revenue items for item in RevenueItem . objects . filter ( Q ( receivedFromName__isnull = False ) ) : party = createPartyFromName ( apps , item . receivedFromName ) item . receivedFrom = party item . save ( ) | 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 . | 439 | 50 |
235,472 | 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 | 82 | 7 |
235,473 | 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' : 'success' , 'redirect' : returnUrl } ) return HttpResponseRedirect ( returnUrl ) return super ( ) . dispatch ( request , * args , * * kwargs ) | Check that registration is online before proceeding . If this is a POST request determine whether the response should be provided in JSON form . | 133 | 25 |
235,474 | def get_context_data ( self , * * kwargs ) : context = self . get_listing ( ) context [ 'showDescriptionRule' ] = getConstant ( 'registration__showDescriptionRule' ) or 'all' context . update ( kwargs ) # Update the site session data so that registration processes know to send return links to # the registration page. set_return_page() is in SiteHistoryMixin. self . set_return_page ( 'registration' , _ ( 'Registration' ) ) return super ( ClassRegistrationView , self ) . get_context_data ( * * context ) | Add the event and series listing data | 134 | 7 |
235,475 | 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' ] , 'closedEvents' : listing [ 'closedEvents' ] , } ) return kwargs | Tell the form which fields to render | 120 | 7 |
235,476 | 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' ) ) # Get the Event listing here to avoid duplicate queries self . allEvents = Event . objects . filter ( * * timeFilters ) . filter ( Q ( instance_of = PublicEvent ) | Q ( instance_of = Series ) ) . annotate ( * * self . get_annotations ( ) ) . exclude ( Q ( status = Event . RegStatus . hidden ) | Q ( status = Event . RegStatus . regHidden ) | Q ( status = Event . RegStatus . linkOnly ) ) . order_by ( * self . get_ordering ( ) ) return self . allEvents | 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 | 224 | 27 |
235,477 | 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 ( Series ) self . listing = { 'allEvents' : allEvents , 'openEvents' : openEvents , 'closedEvents' : closedEvents , 'publicEvents' : publicEvents , 'allSeries' : allSeries , 'regOpenEvents' : publicEvents . filter ( registrationOpen = True ) . filter ( Q ( publicevent__category__isnull = True ) | Q ( publicevent__category__separateOnRegistrationPage = False ) ) , 'regClosedEvents' : publicEvents . filter ( registrationOpen = False ) . filter ( Q ( publicevent__category__isnull = True ) | Q ( publicevent__category__separateOnRegistrationPage = False ) ) , 'categorySeparateEvents' : publicEvents . filter ( publicevent__category__separateOnRegistrationPage = True ) . order_by ( 'publicevent__category' ) , 'regOpenSeries' : allSeries . filter ( registrationOpen = True ) . filter ( Q ( series__category__isnull = True ) | Q ( series__category__separateOnRegistrationPage = False ) ) , 'regClosedSeries' : allSeries . filter ( registrationOpen = False ) . filter ( Q ( series__category__isnull = True ) | Q ( series__category__separateOnRegistrationPage = False ) ) , 'categorySeparateSeries' : allSeries . filter ( series__category__separateOnRegistrationPage = True ) . order_by ( 'series__category' ) , } return self . listing | 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 | 414 | 26 |
235,478 | 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 ( 'temporaryRegistrationId' ) ) except ObjectDoesNotExist : messages . error ( request , _ ( 'Invalid registration identifier passed to summary view.' ) ) return HttpResponseRedirect ( reverse ( 'registration' ) ) expiry = parse_datetime ( self . request . session [ REG_VALIDATION_STR ] . get ( 'temporaryRegistrationExpiry' , '' ) , ) if not expiry or expiry < timezone . now ( ) : messages . info ( request , _ ( 'Your registration session has expired. Please try again.' ) ) return HttpResponseRedirect ( reverse ( 'registration' ) ) # If OK, pass the registration and proceed kwargs . update ( { 'reg' : reg , } ) return super ( RegistrationSummaryView , self ) . dispatch ( request , * args , * * kwargs ) | Always check that the temporary registration has not expired | 274 | 9 |
235,479 | 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 . get ( 'discount_codes' , None ) discount_amount = regSession . get ( 'total_discount_amount' , 0 ) voucher_names = regSession . get ( 'voucher_names' , [ ] ) total_voucher_amount = regSession . get ( 'total_voucher_amount' , 0 ) addons = regSession . get ( 'addons' , [ ] ) if reg . priceWithDiscount == 0 : # Create a new Invoice if one does not already exist. new_invoice = Invoice . get_or_create_from_registration ( reg , status = Invoice . PaymentStatus . paid ) new_invoice . processPayment ( 0 , 0 , forceFinalize = True ) isFree = True else : isFree = False context_data . update ( { 'registration' : reg , "totalPrice" : reg . totalPrice , 'subtotal' : reg . priceWithDiscount , 'taxes' : reg . addTaxes , "netPrice" : reg . priceWithDiscountAndTaxes , "addonItems" : addons , "discount_codes" : discount_codes , "discount_code_amount" : discount_amount , "voucher_names" : voucher_names , "total_voucher_amount" : total_voucher_amount , "total_discount_amount" : discount_amount + total_voucher_amount , "currencyCode" : getConstant ( 'general__currencyCode' ) , 'payAtDoor' : reg . payAtDoor , 'is_free' : isFree , } ) if self . request . user : door_permission = self . request . user . has_perm ( 'core.accept_door_payments' ) invoice_permission = self . request . user . has_perm ( 'core.send_invoices' ) if door_permission or invoice_permission : context_data [ 'form' ] = DoorAmountForm ( user = self . request . user , doorPortion = door_permission , invoicePortion = invoice_permission , payerEmail = reg . email , discountAmount = max ( reg . totalPrice - reg . priceWithDiscount , 0 ) , ) return context_data | Pass the initial kwargs then update with the needed registration info . | 597 | 14 |
235,480 | 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 ( 'temporaryRegistrationId' ) ) except ObjectDoesNotExist : messages . error ( request , _ ( 'Invalid registration identifier passed to sign-up form.' ) ) return HttpResponseRedirect ( reverse ( 'registration' ) ) expiry = parse_datetime ( self . request . session [ REG_VALIDATION_STR ] . get ( 'temporaryRegistrationExpiry' , '' ) , ) if not expiry or expiry < timezone . now ( ) : messages . info ( request , _ ( 'Your registration session has expired. Please try again.' ) ) return HttpResponseRedirect ( reverse ( 'registration' ) ) return super ( StudentInfoView , self ) . dispatch ( request , * args , * * kwargs ) | 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 . | 242 | 36 |
235,481 | def form_valid ( self , form ) : reg = self . temporaryRegistration # The session expires after a period of inactivity that is specified in preferences. 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 . session . modified = True # Update the expiration date for this registration, and pass in the data from # this form. reg . expirationDate = expiry reg . firstName = form . cleaned_data . pop ( 'firstName' ) reg . lastName = form . cleaned_data . pop ( 'lastName' ) reg . email = form . cleaned_data . pop ( 'email' ) reg . phone = form . cleaned_data . pop ( 'phone' , None ) reg . student = form . cleaned_data . pop ( 'student' , False ) reg . comments = form . cleaned_data . pop ( 'comments' , None ) reg . howHeardAboutUs = form . cleaned_data . pop ( 'howHeardAboutUs' , None ) # Anything else in the form goes to the TemporaryRegistration data. reg . data . update ( form . cleaned_data ) reg . save ( ) # This signal (formerly the post_temporary_registration signal) allows # vouchers to be applied temporarily, and it can be used for other tasks post_student_info . send ( sender = StudentInfoView , registration = reg ) return HttpResponseRedirect ( self . get_success_url ( ) ) | 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 | 380 | 51 |
235,482 | 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 ( customer__email = email_address . email , customer__user__isnull = True , dateTime__isnull = False ) . order_by ( '-dateTime' ) . first ( ) if last_reg : customer = last_reg . customer customer . user = user customer . save ( ) if not user . first_name and not user . last_name : user . first_name = customer . first_name user . last_name = customer . last_name user . save ( ) | 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 with with Customer and if missing fill in the user s name information with the Customer s name . This way when a new or existing customer creates a user account they are seamlessly linked to their most recent existing registration at the time they verify their email address . | 192 | 106 |
235,483 | 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 = registration . customer try : verified_email = EmailAddress . objects . get ( email = customer . email , verified = True , primary = True , user__customer__isnull = True ) logger . info ( "Found user %s to associate with customer %s." , verified_email . user . id , customer . id ) customer . user = verified_email . user customer . save ( ) if not customer . user . first_name and not customer . user . last_name : customer . user . first_name = customer . first_name customer . user . last_name = customer . last_name customer . user . save ( ) except ObjectDoesNotExist : logger . info ( "No user found to associate with customer %s." , customer . id ) except MultipleObjectsReturned : # This should never happen, as email should be unique in the db table account_emailaddress. # If it does, something's broken in the database or Django. errmsg = "Something's not right with the database: more than one entry found on the database for the email %s. \ This duplicate key value violates unique constraint \"account_emailaddress_email_key\". \ The email field should be unique for each account.\n" logger . exception ( errmsg , customer . email ) | 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 new User verifies their email account before they have submitted any Registrations their Customer account is seamlessly linked when they do complete their first Registration . | 349 | 90 |
235,484 | 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 ) . create_object ( text ) | Allow creation of staff members using a full name string . | 107 | 11 |
235,485 | 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 = formData . get ( 'email' ) request = kwargs . get ( 'request' , { } ) session = getattr ( request , 'session' , { } ) . get ( REG_VALIDATION_STR , { } ) registrationId = getattr ( kwargs . get ( 'registration' , None ) , 'id' , None ) records = BannedPerson . objects . exclude ( disabled = True ) . exclude ( expirationDate__lte = timezone . now ( ) ) . filter ( ( Q ( firstName__iexact = first ) & Q ( lastName__iexact = last ) ) | Q ( bannedemail__email__iexact = email ) ) if not records . exists ( ) : return # Generate an "error code" to reference so that it is easier to lookup # the record on why they were flagged. flagCode = '' . join ( random . choice ( string . ascii_uppercase ) for x in range ( 8 ) ) ip = get_client_ip ( request ) respondTo = getConstant ( 'registration__banListContactEmail' ) or getConstant ( 'contact__businessEmail' ) for record in records : flagRecord = BanFlaggedRecord . objects . create ( flagCode = flagCode , person = record , ipAddress = ip , data = { 'session' : session , 'formData' : formData , 'registrationId' : registrationId } ) notify = getConstant ( 'registration__banListNotificationEmail' ) if notify : send_from = getConstant ( 'contact__businessEmail' ) subject = _ ( 'Notice of attempted registration by banned individual' ) message = _ ( 'This is an automated notification that the following individual has attempted ' + 'to register for a class series or event:\n\n' + 'Name: %s\n' % record . fullName + 'Email: %s\n' % email + 'Date/Time: %s\n' % flagRecord . dateTime + 'IP Address: %s\n\n' % ip + 'This individual has been prevented from finalizing their registration, and they ' + 'have been asked to notify the school at %s with code %s to proceed.' % ( respondTo , flagCode ) ) sendEmail ( subject , message , send_from , to = [ notify ] ) message = ugettext ( 'There appears to be an issue with this registration. ' 'Please contact %s to proceed with the registration process. ' 'You may reference the error code %s.' % ( respondTo , flagCode ) ) if request . user . has_perm ( 'banlist.ignore_ban' ) : messages . warning ( request , message ) else : raise ValidationError ( message ) | Check that this individual is not on the ban list . | 690 | 11 |
235,486 | 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 ValidationError ( _ ( 'Transaction party may not be both a Location and a User or StaffMember.' ) ) | Verify that the user and staffMember are not mismatched . Location can only be specified if user and staffMember are not . | 98 | 26 |
235,487 | 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 , 'staffmember' , None ) and not self . staffMember ) or ( isinstance ( updateBy , User ) and getattr ( self . user , 'staffmember' , None ) ) : self . staffMember = self . user . staffmember # Don't replace the name if it has been given, but do fill it out if it is blank. if not self . name : if self . user and self . user . get_full_name ( ) : self . name = self . user . get_full_name ( ) elif self . staffMember : self . name = self . staffMember . fullName or self . staffMember . privateEmail elif self . location : self . name = self . location . name super ( TransactionParty , self ) . save ( * args , * * kwargs ) | Verify that the user and staffMember are populated with linked information and ensure that the name is properly specified . | 258 | 22 |
235,488 | def ruleName ( self ) : return '%s %s' % ( self . rentalRate , self . RateRuleChoices . values . get ( self . applyRateRule , self . applyRateRule ) ) | This should be overridden for child classes | 45 | 8 |
235,489 | def ruleName ( self ) : return _ ( '%s at %s' % ( self . room . name , self . room . location . name ) ) | overrides from parent class | 34 | 6 |
235,490 | 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 | 80 | 15 |
235,491 | def save ( self , * args , * * kwargs ) : # Set the approval and payment dates if they have just been approved/paid. 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 not self . approvalDate and not self . __approvalDate : self . approvalDate = timezone . now ( ) if self . paid and not self . paymentDate and not self . __paymentDate : self . paymentDate = timezone . now ( ) # Fill out the series and event properties to permit easy calculation of # revenues and expenses by series or by event. if self . expenseRule and not self . payTo : this_loc = getattr ( self . expenseRule , 'location' , None ) this_member = getattr ( self . expenseRule , 'location' , None ) if this_loc : self . payTo = TransactionParty . objects . get_or_create ( location = this_loc , defaults = { 'name' : this_loc . name } ) [ 0 ] elif this_member : self . payTo = TransactionParty . objects . get_or_create ( staffMember = this_member , defaults = { 'name' : this_member . fullName , 'user' : getattr ( this_member , 'userAccount' , None ) } ) [ 0 ] # Set the accrual date. The method for events ensures that the accrualDate month # is the same as the reported month of the series/event by accruing to the end date of the last # class or occurrence in that month. if not self . accrualDate : if self . event and self . event . month : self . accrualDate = self . event . eventoccurrence_set . order_by ( 'endTime' ) . filter ( * * { 'endTime__month' : self . event . month } ) . last ( ) . endTime elif self . submissionDate : self . accrualDate = self . submissionDate else : self . submissionDate = timezone . now ( ) self . accrualDate = self . submissionDate # Set the total for hourly work if self . hours and not self . wageRate and not self . total and not getattr ( getattr ( self , 'payTo' , None ) , 'location' , None ) and self . category : self . wageRate = self . category . defaultRate elif self . hours and not self . wageRate and not self . total and getattr ( getattr ( self , 'payTo' , None ) , 'location' , None ) : self . wageRate = self . payTo . location . rentalRate if self . hours and self . wageRate and not self . total : self . total = self . hours * self . wageRate super ( ExpenseItem , self ) . save ( * args , * * kwargs ) self . __approved = self . approved self . __paid = self . paid self . __approvalDate = self . approvalDate self . __paymentDate = self . paymentDate # If a file is attached, ensure that it is not public, and that it is saved in the 'Expense Receipts' folder if self . attachment : try : self . attachment . folder = Folder . objects . get ( name = _ ( 'Expense Receipts' ) ) except ObjectDoesNotExist : pass self . attachment . is_public = False self . attachment . save ( ) | 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 . | 794 | 38 |
235,492 | 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 . | 32 | 19 |
235,493 | def save ( self , * args , * * kwargs ) : # Set the received date if the payment was just marked received 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 ( ) # Set the accrual date. The method for series/events ensures that the accrualDate month # is the same as the reported month of the event/series by accruing to the start date of the first # occurrence in that month. if not self . accrualDate : if self . invoiceItem and self . invoiceItem . finalEventRegistration : min_event_time = self . invoiceItem . finalEventRegistration . event . eventoccurrence_set . filter ( * * { 'startTime__month' : self . invoiceItem . finalEventRegistration . event . month } ) . first ( ) . startTime self . accrualDate = min_event_time elif self . event : self . accrualDate = self . event . eventoccurrence_set . order_by ( 'startTime' ) . filter ( * * { 'startTime__month' : self . event . month } ) . last ( ) . startTime elif self . invoiceItem : self . accrualDate = self . invoiceItem . invoice . creationDate elif self . receivedDate : self . accrualDate = self . receivedDate elif self . submissionDate : self . accrualDate = self . submissionDate else : self . submissionDate = timezone . now ( ) self . accrualDate = self . submissionDate # Now, set the registration property and check that this item is not attributed # to multiple categories. if self . invoiceItem and self . invoiceItem . finalEventRegistration : self . event = self . invoiceItem . finalEventRegistration . event elif self . invoiceItem and self . invoiceItem . temporaryEventRegistration : self . event = self . invoiceItem . temporaryEventRegistration . event # If no grossTotal is reported, use the net total. If no net total is reported, use the grossTotal if self . grossTotal is None and self . total : self . grossTotal = self . total if self . total is None and self . grossTotal : self . total = self . grossTotal super ( RevenueItem , self ) . save ( * args , * * kwargs ) self . __received = self . received self . __receivedDate = self . receivedDate # If a file is attached, ensure that it is not public, and that it is saved in the 'Expense Receipts' folder if self . attachment : try : self . attachment . folder = Folder . objects . get ( name = _ ( 'Revenue Receipts' ) ) except ObjectDoesNotExist : pass self . attachment . is_public = False self . attachment . save ( ) | 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 . | 644 | 39 |
235,494 | 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 ( 'instructorId' ) existingSlots = InstructorAvailabilitySlot . objects . filter ( instructor = instructor , startTime__gt = ( ensure_localtime ( datetime . combine ( startDate , startTime ) ) - timedelta ( minutes = getConstant ( 'privateLessons__lessonLengthInterval' ) ) ) , startTime__lt = ensure_localtime ( datetime . combine ( endDate , endTime ) ) , ) if existingSlots . exists ( ) : raise ValidationError ( _ ( 'Newly created slots cannot overlap existing slots for this instructor.' ) , code = 'invalid' ) | Only allow submission if there are not already slots in the submitted window and only allow rooms associated with the chosen location . | 226 | 23 |
235,495 | 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 ( 'paymentMethod' , flat = True ) . distinct ( ) methods_list = list ( set ( methods ) ) if None in methods_list : methods_list . remove ( None ) return methods_list | Include manual methods by default | 147 | 6 |
235,496 | 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 . request ) : ''' Generate querysets of Locations, StaffMembers, and Users that match the query string. ''' for s in Location . objects . filter ( Q ( Q ( name__istartswith = q ) & Q ( transactionparty__isnull = True ) ) ) : create_option += [ { 'id' : 'Location_%s' % s . id , 'text' : _ ( 'Generate from location "%(location)s"' ) % { 'location' : s . name } , 'create_id' : True , } ] for s in StaffMember . objects . filter ( Q ( ( Q ( firstName__istartswith = q ) | Q ( lastName__istartswith = q ) ) & Q ( transactionparty__isnull = True ) ) ) : create_option += [ { 'id' : 'StaffMember_%s' % s . id , 'text' : _ ( 'Generate from staff member "%(staff_member)s"' ) % { 'staff_member' : s . fullName } , 'create_id' : True , } ] for s in User . objects . filter ( Q ( ( Q ( first_name__istartswith = q ) | Q ( last_name__istartswith = q ) ) & Q ( staffmember__isnull = True ) & Q ( transactionparty__isnull = True ) ) ) : create_option += [ { 'id' : 'User_%s' % s . id , 'text' : _ ( 'Generate from user "%(user)s"' ) % { 'user' : s . get_full_name ( ) } , 'create_id' : True , } ] # Finally, allow creation from a name only. create_option += [ { 'id' : q , 'text' : _ ( 'Create "%(new_value)s"' ) % { 'new_value' : q } , 'create_id' : True , } ] return create_option | Form the correct create_option to append to results . | 529 | 11 |
235,497 | 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 . startswith ( 'StaffMember_' ) : this_id = text [ len ( 'StaffMember_' ) : ] this_member = StaffMember . objects . get ( id = this_id ) return self . get_queryset ( ) . get_or_create ( name = this_member . fullName , staffMember = this_member , defaults = { 'user' : getattr ( this_member , 'userAccount' , None ) } ) [ 0 ] elif text . startswith ( 'User_' ) : this_id = text [ len ( 'User_' ) : ] this_user = User . objects . get ( id = this_id ) return self . get_queryset ( ) . get_or_create ( name = this_user . get_full_name ( ) , user = this_user , defaults = { 'staffMember' : getattr ( this_user , 'staffmember' , None ) } ) [ 0 ] else : return self . get_queryset ( ) . get_or_create ( name = text , staffMember = None , user = None , location = None ) [ 0 ] else : return super ( TransactionPartyAutoComplete , self ) . create_object ( text ) | Allow creation of transaction parties using a full name string . | 373 | 11 |
235,498 | 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 . | 34 | 28 |
235,499 | 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_list [ 0 ] return sub_list | 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 . | 110 | 47 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.