idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
60,500
def addNodeLabelPrefix ( self , prefix = None , copy = False ) : nxgraph = Topology . __relabel_graph ( self . __nxgraph , prefix ) if copy : newtopo = copy . deepcopy ( self ) newtopo . nxgraph = nxgraph return newtopo else : self . __nxgraph = nxgraph
Rename all nodes in the network from x to prefix_x . If no prefix is given use the name of the graph as the prefix . The purpose of this method is to make node names unique so that composing two graphs is well - defined .
60,501
def from_bytes ( self , raw ) : if len ( raw ) < 4 : raise NotEnoughDataError ( "Not enough bytes ({}) to reconstruct a Null object" . format ( len ( raw ) ) ) fields = struct . unpack ( '=I' , raw [ : 4 ] ) self . _af = fields [ 0 ] return raw [ 4 : ]
Return a Null header object reconstructed from raw bytes or an Exception if we can t resurrect the packet .
60,502
def add_header ( self , ph ) : if isinstance ( ph , bytes ) : ph = RawPacketContents ( ph ) if isinstance ( ph , PacketHeaderBase ) : self . _headers . append ( ph ) return self raise Exception ( "Payload for a packet header must be an object that is a subclass of PacketHeaderBase, or a bytes object." )
Add a PacketHeaderBase derived class object or a raw bytes object as the next header item in this packet . Note that header may be a slight misnomer since the last portion of a packet is considered application payload and not a header per se .
60,503
def has_header ( self , hdrclass ) : if isinstance ( hdrclass , str ) : return self . get_header_by_name ( hdrclass ) is not None return self . get_header ( hdrclass ) is not None
Return True if the packet has a header of the given hdrclass False otherwise .
60,504
def get_header ( self , hdrclass , returnval = None ) : if isinstance ( hdrclass , str ) : return self . get_header_by_name ( hdrclass ) for hdr in self . _headers : if isinstance ( hdr , hdrclass ) : return hdr return returnval
Return the first header object that is of class hdrclass or None if the header class isn t found .
60,505
def next_header_class ( self ) : if self . _next_header_class_key == '' : return None key = getattr ( self , self . _next_header_class_key ) rv = self . _next_header_map . get ( key , None ) if rv is None : log_warn ( "No class exists to handle next header value {}" . format ( key ) ) return rv
Return class of next header if known .
60,506
def get ( self , request , hook_id ) : try : bot = caching . get_or_set ( MessengerBot , hook_id ) except MessengerBot . DoesNotExist : logger . warning ( "Hook id %s not associated to a bot" % hook_id ) return Response ( status = status . HTTP_404_NOT_FOUND ) if request . query_params . get ( 'hub.verify_token' ) == str ( bot . id ) : return Response ( int ( request . query_params . get ( 'hub.challenge' ) ) ) return Response ( 'Error, wrong validation token' )
Verify token when configuring webhook from facebook dev . MessengerBot . id is used for verification
60,507
def _format_value ( self , value ) : if hasattr ( self , 'format_value' ) : return super ( DateTimePicker , self ) . format_value ( value ) else : return super ( DateTimePicker , self ) . _format_value ( value )
This function name was changed in Django 1 . 10 and removed in 2 . 0 .
60,508
def authorize_url ( self , client_id , redirect_uri , scope , state = None ) : params = [ ( 'client_id' , client_id ) , ( 'redirect_uri' , redirect_uri ) , ( 'scope' , scope ) ] if state : params . append ( ( 'state' , state ) ) return "%s?%s" % ( CreateSend . oauth_uri , urlencode ( params ) )
Get the authorization URL for your application given the application s client_id redirect_uri scope and optional state data .
60,509
def exchange_token ( self , client_id , client_secret , redirect_uri , code ) : params = [ ( 'grant_type' , 'authorization_code' ) , ( 'client_id' , client_id ) , ( 'client_secret' , client_secret ) , ( 'redirect_uri' , redirect_uri ) , ( 'code' , code ) , ] response = self . _post ( '' , urlencode ( params ) , CreateSend . oauth_token_uri , "application/x-www-form-urlencoded" ) access_token , expires_in , refresh_token = None , None , None r = json_to_py ( response ) if hasattr ( r , 'error' ) and hasattr ( r , 'error_description' ) : err = "Error exchanging code for access token: " err += "%s - %s" % ( r . error , r . error_description ) raise Exception ( err ) access_token , expires_in , refresh_token = r . access_token , r . expires_in , r . refresh_token return [ access_token , expires_in , refresh_token ]
Exchange a provided OAuth code for an OAuth access token expires in value and refresh token .
60,510
def refresh_token ( self ) : if ( not self . auth_details or not 'refresh_token' in self . auth_details or not self . auth_details [ 'refresh_token' ] ) : raise Exception ( "auth_details['refresh_token'] does not contain a refresh token." ) refresh_token = self . auth_details [ 'refresh_token' ] params = [ ( 'grant_type' , 'refresh_token' ) , ( 'refresh_token' , refresh_token ) ] response = self . _post ( '' , urlencode ( params ) , CreateSend . oauth_token_uri , "application/x-www-form-urlencoded" ) new_access_token , new_expires_in , new_refresh_token = None , None , None r = json_to_py ( response ) new_access_token , new_expires_in , new_refresh_token = r . access_token , r . expires_in , r . refresh_token self . auth ( { 'access_token' : new_access_token , 'refresh_token' : new_refresh_token } ) return [ new_access_token , new_expires_in , new_refresh_token ]
Refresh an OAuth token given a refresh token .
60,511
def stub_request ( self , expected_url , filename , status = None , body = None ) : self . fake_web = True self . faker = get_faker ( expected_url , filename , status , body )
Stub a web request for testing .
60,512
def get ( self , client_id = None , email_address = None ) : params = { "email" : email_address or self . email_address } response = self . _get ( "/clients/%s/people.json" % ( client_id or self . client_id ) , params = params ) return json_to_py ( response )
Gets a person by client ID and email address .
60,513
def add ( self , client_id , email_address , name , access_level , password ) : body = { "EmailAddress" : email_address , "Name" : name , "AccessLevel" : access_level , "Password" : password } response = self . _post ( "/clients/%s/people.json" % client_id , json . dumps ( body ) ) return json_to_py ( response )
Adds a person to a client . Password is optional and if not supplied an invitation will be emailed to the person
60,514
def update ( self , new_email_address , name , access_level , password = None ) : params = { "email" : self . email_address } body = { "EmailAddress" : new_email_address , "Name" : name , "AccessLevel" : access_level , "Password" : password } response = self . _put ( "/clients/%s/people.json" % self . client_id , body = json . dumps ( body ) , params = params ) self . email_address = new_email_address
Updates the details for a person . Password is optional and is only updated if supplied .
60,515
def create ( self , client_id , subject , name , from_name , from_email , reply_to , html_url , text_url , list_ids , segment_ids ) : body = { "Subject" : subject , "Name" : name , "FromName" : from_name , "FromEmail" : from_email , "ReplyTo" : reply_to , "HtmlUrl" : html_url , "TextUrl" : text_url , "ListIDs" : list_ids , "SegmentIDs" : segment_ids } response = self . _post ( "/campaigns/%s.json" % client_id , json . dumps ( body ) ) self . campaign_id = json_to_py ( response ) return self . campaign_id
Creates a new campaign for a client .
60,516
def create_from_template ( self , client_id , subject , name , from_name , from_email , reply_to , list_ids , segment_ids , template_id , template_content ) : body = { "Subject" : subject , "Name" : name , "FromName" : from_name , "FromEmail" : from_email , "ReplyTo" : reply_to , "ListIDs" : list_ids , "SegmentIDs" : segment_ids , "TemplateID" : template_id , "TemplateContent" : template_content } response = self . _post ( "/campaigns/%s/fromtemplate.json" % client_id , json . dumps ( body ) ) self . campaign_id = json_to_py ( response ) return self . campaign_id
Creates a new campaign for a client from a template .
60,517
def send_preview ( self , recipients , personalize = "fallback" ) : body = { "PreviewRecipients" : [ recipients ] if isinstance ( recipients , str ) else recipients , "Personalize" : personalize } response = self . _post ( self . uri_for ( "sendpreview" ) , json . dumps ( body ) )
Sends a preview of this campaign .
60,518
def send ( self , confirmation_email , send_date = "immediately" ) : body = { "ConfirmationEmail" : confirmation_email , "SendDate" : send_date } response = self . _post ( self . uri_for ( "send" ) , json . dumps ( body ) )
Sends this campaign .
60,519
def opens ( self , date = "" , page = 1 , page_size = 1000 , order_field = "date" , order_direction = "asc" ) : params = { "date" : date , "page" : page , "pagesize" : page_size , "orderfield" : order_field , "orderdirection" : order_direction } response = self . _get ( self . uri_for ( "opens" ) , params = params ) return json_to_py ( response )
Retrieves the opens for this campaign .
60,520
def create ( self , company , timezone , country ) : body = { "CompanyName" : company , "TimeZone" : timezone , "Country" : country } response = self . _post ( "/clients.json" , json . dumps ( body ) ) self . client_id = json_to_py ( response ) return self . client_id
Creates a client .
60,521
def lists_for_email ( self , email_address ) : params = { "email" : email_address } response = self . _get ( self . uri_for ( "listsforemail" ) , params = params ) return json_to_py ( response )
Gets the lists across a client to which a subscriber with a particular email address belongs .
60,522
def suppressionlist ( self , page = 1 , page_size = 1000 , order_field = "email" , order_direction = "asc" ) : params = { "page" : page , "pagesize" : page_size , "orderfield" : order_field , "orderdirection" : order_direction } response = self . _get ( self . uri_for ( "suppressionlist" ) , params = params ) return json_to_py ( response )
Gets this client s suppression list .
60,523
def suppress ( self , email ) : body = { "EmailAddresses" : [ email ] if isinstance ( email , str ) else email } response = self . _post ( self . uri_for ( "suppress" ) , json . dumps ( body ) )
Adds email addresses to a client s suppression list
60,524
def unsuppress ( self , email ) : params = { "email" : email } response = self . _put ( self . uri_for ( "unsuppress" ) , body = " " , params = params )
Unsuppresses an email address by removing it from the the client s suppression list
60,525
def set_payg_billing ( self , currency , can_purchase_credits , client_pays , markup_percentage , markup_on_delivery = 0 , markup_per_recipient = 0 , markup_on_design_spam_test = 0 ) : body = { "Currency" : currency , "CanPurchaseCredits" : can_purchase_credits , "ClientPays" : client_pays , "MarkupPercentage" : markup_percentage , "MarkupOnDelivery" : markup_on_delivery , "MarkupPerRecipient" : markup_per_recipient , "MarkupOnDesignSpamTest" : markup_on_design_spam_test } response = self . _put ( self . uri_for ( 'setpaygbilling' ) , json . dumps ( body ) )
Sets the PAYG billing settings for this client .
60,526
def set_monthly_billing ( self , currency , client_pays , markup_percentage , monthly_scheme = None ) : body = { "Currency" : currency , "ClientPays" : client_pays , "MarkupPercentage" : markup_percentage } if monthly_scheme is not None : body [ "MonthlyScheme" ] = monthly_scheme response = self . _put ( self . uri_for ( 'setmonthlybilling' ) , json . dumps ( body ) )
Sets the monthly billing settings for this client .
60,527
def transfer_credits ( self , credits , can_use_my_credits_when_they_run_out ) : body = { "Credits" : credits , "CanUseMyCreditsWhenTheyRunOut" : can_use_my_credits_when_they_run_out } response = self . _post ( self . uri_for ( 'credits' ) , json . dumps ( body ) ) return json_to_py ( response )
Transfer credits to or from this client .
60,528
def set_primary_contact ( self , email ) : params = { "email" : email } response = self . _put ( self . uri_for ( 'primarycontact' ) , params = params ) return json_to_py ( response )
assigns the primary contact for this client
60,529
def smart_email_list ( self , status = "all" , client_id = None ) : if client_id is None : response = self . _get ( "/transactional/smartEmail?status=%s" % status ) else : response = self . _get ( "/transactional/smartEmail?status=%s&clientID=%s" % ( status , client_id ) ) return json_to_py ( response )
Gets the smart email list .
60,530
def smart_email_send ( self , smart_email_id , to , consent_to_track , cc = None , bcc = None , attachments = None , data = None , add_recipients_to_list = None ) : validate_consent_to_track ( consent_to_track ) body = { "To" : to , "CC" : cc , "BCC" : bcc , "Attachments" : attachments , "Data" : data , "AddRecipientsToList" : add_recipients_to_list , "ConsentToTrack" : consent_to_track , } response = self . _post ( "/transactional/smartEmail/%s/send" % smart_email_id , json . dumps ( body ) ) return json_to_py ( response )
Sends the smart email .
60,531
def classic_email_send ( self , subject , from_address , to , consent_to_track , client_id = None , cc = None , bcc = None , html = None , text = None , attachments = None , track_opens = True , track_clicks = True , inline_css = True , group = None , add_recipients_to_list = None ) : validate_consent_to_track ( consent_to_track ) body = { "Subject" : subject , "From" : from_address , "To" : to , "CC" : cc , "BCC" : bcc , "HTML" : html , "Text" : text , "Attachments" : attachments , "TrackOpens" : track_opens , "TrackClicks" : track_clicks , "InlineCSS" : inline_css , "Group" : group , "AddRecipientsToList" : add_recipients_to_list , "ConsentToTrack" : consent_to_track , } if client_id is None : response = self . _post ( "/transactional/classicEmail/send" , json . dumps ( body ) ) else : response = self . _post ( "/transactional/classicEmail/send?clientID=%s" % client_id , json . dumps ( body ) ) return json_to_py ( response )
Sends a classic email .
60,532
def classic_email_groups ( self , client_id = None ) : if client_id is None : response = self . _get ( "/transactional/classicEmail/groups" ) else : response = self . _get ( "/transactional/classicEmail/groups?clientID=%s" % client_id ) return json_to_py ( response )
Gets the list of classic email groups .
60,533
def message_details ( self , message_id , statistics = False ) : response = self . _get ( "/transactional/messages/%s?statistics=%s" % ( message_id , statistics ) ) return json_to_py ( response )
Gets the details of this message .
60,534
def create ( self , list_id , title , rulegroups ) : body = { "Title" : title , "RuleGroups" : rulegroups } response = self . _post ( "/segments/%s.json" % list_id , json . dumps ( body ) ) self . segment_id = json_to_py ( response ) return self . segment_id
Creates a new segment .
60,535
def update ( self , title , rulegroups ) : body = { "Title" : title , "RuleGroups" : rulegroups } response = self . _put ( "/segments/%s.json" % self . segment_id , json . dumps ( body ) )
Updates this segment .
60,536
def add_rulegroup ( self , rulegroup ) : body = rulegroup response = self . _post ( "/segments/%s/rules.json" % self . segment_id , json . dumps ( body ) )
Adds a rulegroup to this segment .
60,537
def subscribers ( self , date = "" , page = 1 , page_size = 1000 , order_field = "email" , order_direction = "asc" , include_tracking_information = False ) : params = { "date" : date , "page" : page , "pagesize" : page_size , "orderfield" : order_field , "orderdirection" : order_direction , "includetrackinginformation" : include_tracking_information } response = self . _get ( self . uri_for ( "active" ) , params = params ) return json_to_py ( response )
Gets the active subscribers in this segment .
60,538
def create ( self , client_id , name , html_url , zip_url ) : body = { "Name" : name , "HtmlPageURL" : html_url , "ZipFileURL" : zip_url } response = self . _post ( "/templates/%s.json" % client_id , json . dumps ( body ) ) self . template_id = json_to_py ( response ) return self . template_id
Creates a new email template .
60,539
def update ( self , name , html_url , zip_url ) : body = { "Name" : name , "HtmlPageURL" : html_url , "ZipFileURL" : zip_url } response = self . _put ( "/templates/%s.json" % self . template_id , json . dumps ( body ) )
Updates this email template .
60,540
def add ( self , email_address , name ) : body = { "EmailAddress" : email_address , "Name" : name } response = self . _post ( "/admins.json" , json . dumps ( body ) ) return json_to_py ( response )
Adds an administrator to an account .
60,541
def update ( self , new_email_address , name ) : params = { "email" : self . email_address } body = { "EmailAddress" : new_email_address , "Name" : name } response = self . _put ( "/admins.json" , body = json . dumps ( body ) , params = params ) self . email_address = new_email_address
Updates the details for an administrator .
60,542
def delete ( self ) : params = { "email" : self . email_address } response = self . _delete ( "/admins.json" , params = params )
Deletes the administrator from the account .
60,543
def create ( self , client_id , title , unsubscribe_page , confirmed_opt_in , confirmation_success_page , unsubscribe_setting = "AllClientLists" ) : body = { "Title" : title , "UnsubscribePage" : unsubscribe_page , "ConfirmedOptIn" : confirmed_opt_in , "ConfirmationSuccessPage" : confirmation_success_page , "UnsubscribeSetting" : unsubscribe_setting } response = self . _post ( "/lists/%s.json" % client_id , json . dumps ( body ) ) self . list_id = json_to_py ( response ) return self . list_id
Creates a new list for a client .
60,544
def create_custom_field ( self , field_name , data_type , options = [ ] , visible_in_preference_center = True ) : body = { "FieldName" : field_name , "DataType" : data_type , "Options" : options , "VisibleInPreferenceCenter" : visible_in_preference_center } response = self . _post ( self . uri_for ( "customfields" ) , json . dumps ( body ) ) return json_to_py ( response )
Creates a new custom field for this list .
60,545
def update_custom_field ( self , custom_field_key , field_name , visible_in_preference_center ) : custom_field_key = quote ( custom_field_key , '' ) body = { "FieldName" : field_name , "VisibleInPreferenceCenter" : visible_in_preference_center } response = self . _put ( self . uri_for ( "customfields/%s" % custom_field_key ) , json . dumps ( body ) ) return json_to_py ( response )
Updates a custom field belonging to this list .
60,546
def delete_custom_field ( self , custom_field_key ) : custom_field_key = quote ( custom_field_key , '' ) response = self . _delete ( "/lists/%s/customfields/%s.json" % ( self . list_id , custom_field_key ) )
Deletes a custom field associated with this list .
60,547
def update_custom_field_options ( self , custom_field_key , new_options , keep_existing_options ) : custom_field_key = quote ( custom_field_key , '' ) body = { "Options" : new_options , "KeepExistingOptions" : keep_existing_options } response = self . _put ( self . uri_for ( "customfields/%s/options" % custom_field_key ) , json . dumps ( body ) )
Updates the options of a multi - optioned custom field on this list .
60,548
def active ( self , date = "" , page = 1 , page_size = 1000 , order_field = "email" , order_direction = "asc" , include_tracking_preference = False ) : params = { "date" : date , "page" : page , "pagesize" : page_size , "orderfield" : order_field , "orderdirection" : order_direction , "includetrackingpreference" : include_tracking_preference , } response = self . _get ( self . uri_for ( "active" ) , params = params ) return json_to_py ( response )
Gets the active subscribers for this list .
60,549
def update ( self , title , unsubscribe_page , confirmed_opt_in , confirmation_success_page , unsubscribe_setting = "AllClientLists" , add_unsubscribes_to_supp_list = False , scrub_active_with_supp_list = False ) : body = { "Title" : title , "UnsubscribePage" : unsubscribe_page , "ConfirmedOptIn" : confirmed_opt_in , "ConfirmationSuccessPage" : confirmation_success_page , "UnsubscribeSetting" : unsubscribe_setting , "AddUnsubscribesToSuppList" : add_unsubscribes_to_supp_list , "ScrubActiveWithSuppList" : scrub_active_with_supp_list } response = self . _put ( "/lists/%s.json" % self . list_id , json . dumps ( body ) )
Updates this list .
60,550
def get ( self , list_id = None , email_address = None , include_tracking_preference = False ) : params = { "email" : email_address or self . email_address , "includetrackingpreference" : include_tracking_preference , } response = self . _get ( "/subscribers/%s.json" % ( list_id or self . list_id ) , params = params ) return json_to_py ( response )
Gets a subscriber by list ID and email address .
60,551
def add ( self , list_id , email_address , name , custom_fields , resubscribe , consent_to_track , restart_subscription_based_autoresponders = False ) : validate_consent_to_track ( consent_to_track ) body = { "EmailAddress" : email_address , "Name" : name , "CustomFields" : custom_fields , "Resubscribe" : resubscribe , "ConsentToTrack" : consent_to_track , "RestartSubscriptionBasedAutoresponders" : restart_subscription_based_autoresponders } response = self . _post ( "/subscribers/%s.json" % list_id , json . dumps ( body ) ) return json_to_py ( response )
Adds a subscriber to a subscriber list .
60,552
def update ( self , new_email_address , name , custom_fields , resubscribe , consent_to_track , restart_subscription_based_autoresponders = False ) : validate_consent_to_track ( consent_to_track ) params = { "email" : self . email_address } body = { "EmailAddress" : new_email_address , "Name" : name , "CustomFields" : custom_fields , "Resubscribe" : resubscribe , "ConsentToTrack" : consent_to_track , "RestartSubscriptionBasedAutoresponders" : restart_subscription_based_autoresponders } response = self . _put ( "/subscribers/%s.json" % self . list_id , body = json . dumps ( body ) , params = params ) self . email_address = new_email_address
Updates any aspect of a subscriber including email address name and custom field data if supplied .
60,553
def import_subscribers ( self , list_id , subscribers , resubscribe , queue_subscription_based_autoresponders = False , restart_subscription_based_autoresponders = False ) : body = { "Subscribers" : subscribers , "Resubscribe" : resubscribe , "QueueSubscriptionBasedAutoresponders" : queue_subscription_based_autoresponders , "RestartSubscriptionBasedAutoresponders" : restart_subscription_based_autoresponders } try : response = self . _post ( "/subscribers/%s/import.json" % list_id , json . dumps ( body ) ) except BadRequest as br : if hasattr ( br . data , 'ResultData' ) : return br . data . ResultData else : raise br return json_to_py ( response )
Imports subscribers into a subscriber list .
60,554
def unsubscribe ( self ) : body = { "EmailAddress" : self . email_address } response = self . _post ( "/subscribers/%s/unsubscribe.json" % self . list_id , json . dumps ( body ) )
Unsubscribes this subscriber from the associated list .
60,555
def history ( self ) : params = { "email" : self . email_address } response = self . _get ( "/subscribers/%s/history.json" % self . list_id , params = params ) return json_to_py ( response )
Gets the historical record of this subscriber s trackable actions .
60,556
def set_input ( self ) : name = self . attrs . get ( "_override" , self . widget . __class__ . __name__ ) self . values [ "field" ] = str ( FIELDS . get ( name , FIELDS . get ( None ) ) ( self . field , self . attrs ) )
Returns form input field of Field .
60,557
def set_label ( self ) : if not self . field . label or self . attrs . get ( "_no_label" ) : return self . values [ "label" ] = format_html ( LABEL_TEMPLATE , self . field . html_name , mark_safe ( self . field . label ) )
Set label markup .
60,558
def set_help ( self ) : if not ( self . field . help_text and self . attrs . get ( "_help" ) ) : return self . values [ "help" ] = HELP_TEMPLATE . format ( self . field . help_text )
Set help text markup .
60,559
def set_errors ( self ) : if not self . field . errors or self . attrs . get ( "_no_errors" ) : return self . values [ "class" ] . append ( "error" ) for error in self . field . errors : self . values [ "errors" ] += ERROR_WRAPPER % { "message" : error }
Set errors markup .
60,560
def set_icon ( self ) : if not self . attrs . get ( "_icon" ) : return if "Date" in self . field . field . __class__ . __name__ : return self . values [ "field" ] = INPUT_WRAPPER % { "field" : self . values [ "field" ] , "help" : self . values [ "help" ] , "style" : "%sicon " % escape ( pad ( self . attrs . get ( "_align" , "" ) ) ) , "icon" : format_html ( ICON_TEMPLATE , self . attrs . get ( "_icon" ) ) , }
Wrap current field with icon wrapper . This setter must be the last setter called .
60,561
def set_classes ( self ) : if self . attrs . get ( "_field_class" ) : self . values [ "class" ] . append ( escape ( self . attrs . get ( "_field_class" ) ) ) if self . attrs . get ( "_inline" ) : self . values [ "class" ] . append ( "inline" ) if self . field . field . disabled : self . values [ "class" ] . append ( "disabled" ) if self . field . field . required and not self . attrs . get ( "_no_required" ) : self . values [ "class" ] . append ( "required" ) elif self . attrs . get ( "_required" ) and not self . field . field . required : self . values [ "class" ] . append ( "required" )
Set field properties and custom classes .
60,562
def render ( self ) : self . widget . attrs = { k : v for k , v in self . attrs . items ( ) if k [ 0 ] != "_" } self . set_input ( ) if not self . attrs . get ( "_no_wrapper" ) : self . set_label ( ) self . set_help ( ) self . set_errors ( ) self . set_classes ( ) self . set_icon ( ) self . values [ "class" ] = pad ( " " . join ( self . values [ "class" ] ) ) . lstrip ( ) result = mark_safe ( FIELD_WRAPPER % self . values ) self . widget . attrs = self . attrs return result
Render field as HTML .
60,563
def ready ( self ) : from . models import Friend try : Friend . objects . get_or_create ( first_name = "Michael" , last_name = "1" , age = 22 ) Friend . objects . get_or_create ( first_name = "Joe" , last_name = "2" , age = 21 ) Friend . objects . get_or_create ( first_name = "Bill" , last_name = "3" , age = 20 ) except : pass
Create test friends for displaying .
60,564
def render_booleanfield ( field , attrs ) : attrs . setdefault ( "_no_label" , True ) attrs . setdefault ( "_inline" , True ) field . field . widget . attrs [ "style" ] = "display:hidden" return wrappers . CHECKBOX_WRAPPER % { "style" : pad ( attrs . get ( "_style" , "" ) ) , "field" : field , "label" : format_html ( wrappers . LABEL_TEMPLATE , field . html_name , mark_safe ( field . label ) ) }
Render BooleanField with label next to instead of above .
60,565
def render_choicefield ( field , attrs , choices = None ) : if not choices : choices = format_html_join ( "" , wrappers . CHOICE_TEMPLATE , get_choices ( field ) ) field . field . widget . attrs [ "value" ] = field . value ( ) or attrs . get ( "value" , "" ) return wrappers . DROPDOWN_WRAPPER % { "name" : field . html_name , "attrs" : pad ( flatatt ( field . field . widget . attrs ) ) , "placeholder" : attrs . get ( "placeholder" ) or get_placeholder_text ( ) , "style" : pad ( attrs . get ( "_style" , "" ) ) , "icon" : format_html ( wrappers . ICON_TEMPLATE , attrs . get ( "_dropdown_icon" ) or "dropdown" ) , "choices" : choices }
Render ChoiceField as div dropdown rather than select for more customization .
60,566
def render_countryfield ( field , attrs ) : choices = ( ( k , k . lower ( ) , v ) for k , v in field . field . _choices [ 1 : ] ) return render_choicefield ( field , attrs , format_html_join ( "" , wrappers . COUNTRY_TEMPLATE , choices ) )
Render a custom ChoiceField specific for CountryFields .
60,567
def render_multiplechoicefield ( field , attrs , choices = None ) : choices = format_html_join ( "" , wrappers . CHOICE_TEMPLATE , get_choices ( field ) ) return wrappers . MULTIPLE_DROPDOWN_WRAPPER % { "name" : field . html_name , "field" : field , "choices" : choices , "placeholder" : attrs . get ( "placeholder" ) or get_placeholder_text ( ) , "style" : pad ( attrs . get ( "_style" , "" ) ) , "icon" : format_html ( wrappers . ICON_TEMPLATE , attrs . get ( "_dropdown_icon" ) or "dropdown" ) , }
MultipleChoiceField uses its own field but also uses a queryset .
60,568
def render_datefield ( field , attrs , style = "date" ) : return wrappers . CALENDAR_WRAPPER % { "field" : field , "style" : pad ( style ) , "align" : pad ( attrs . get ( "_align" , "" ) ) , "icon" : format_html ( wrappers . ICON_TEMPLATE , attrs . get ( "_icon" ) ) , }
DateField that uses wrappers . CALENDAR_WRAPPER .
60,569
def render_filefield ( field , attrs ) : field . field . widget . attrs [ "style" ] = "display:none" if not "_no_label" in attrs : attrs [ "_no_label" ] = True return wrappers . FILE_WRAPPER % { "field" : field , "id" : "id_" + field . name , "style" : pad ( attrs . get ( "_style" , "" ) ) , "text" : escape ( attrs . get ( "_text" , "Select File" ) ) , "icon" : format_html ( wrappers . ICON_TEMPLATE , attrs . get ( "_icon" , "file outline" ) ) }
Render a typical File Field .
60,570
def _repeat_iter ( input_iter ) : last_value = None for value in input_iter : last_value = value yield value if last_value is not None : while True : yield last_value
Iterate over the input iter values . Then repeat the last value indefinitely . This is useful to repeat seed values when an insufficient number of seeds are provided .
60,571
def seed ( self , x = None , * args ) : if x is None : try : x = long ( _hexlify ( _urandom ( 16 ) ) , 16 ) except NotImplementedError : import time x = long ( time . time ( ) * 256 ) elif not isinstance ( x , _Integral ) : x = hash ( x ) self . rng_iterator . seed ( x , * args , mix_extras = True )
For consistent cross - platform seeding provide an integer seed .
60,572
def setbpf ( self , bpf ) : self . _bpf = min ( bpf , self . BPF ) self . _rng_n = int ( ( self . _bpf + self . RNG_RANGE_BITS - 1 ) / self . RNG_RANGE_BITS )
Set number of bits per float output
60,573
def get_info ( cls ) : mod = try_import ( cls . mod_name ) if not mod : return None version = getattr ( mod , '__version__' , None ) or getattr ( mod , 'version' , None ) return BackendInfo ( version or 'deprecated' , '' )
Return information about backend and its availability .
60,574
def get_choices ( field ) : empty_label = getattr ( field . field , "empty_label" , False ) needs_empty_value = False choices = [ ] if hasattr ( field . field , "_choices" ) : choices = field . field . _choices elif hasattr ( field . field , "_queryset" ) : queryset = field . field . _queryset field_name = getattr ( field . field , "to_field_name" ) or "pk" choices += ( ( getattr ( obj , field_name ) , str ( obj ) ) for obj in queryset ) if choices and ( choices [ 0 ] [ 1 ] == BLANK_CHOICE_DASH [ 0 ] [ 1 ] or choices [ 0 ] [ 0 ] ) : needs_empty_value = True if not choices [ 0 ] [ 0 ] : del choices [ 0 ] if empty_label == BLANK_CHOICE_DASH [ 0 ] [ 1 ] : empty_label = None if empty_label or not field . field . required : if needs_empty_value : choices . insert ( 0 , ( "" , empty_label or BLANK_CHOICE_DASH [ 0 ] [ 1 ] ) ) return choices
Find choices of a field whether it has choices or has a queryset .
60,575
def get_class_list ( cls ) -> DOMTokenList : cl = [ ] cl . append ( DOMTokenList ( cls , cls . class_ ) ) if cls . inherit_class : for base_cls in cls . __bases__ : if issubclass ( base_cls , WdomElement ) : cl . append ( base_cls . get_class_list ( ) ) cl . reverse ( ) return DOMTokenList ( cls , * cl )
Get class - level class list including all super class s .
60,576
def appendChild ( self , child : 'WdomElement' ) -> Node : if self . connected : self . _append_child_web ( child ) return self . _append_child ( child )
Append child node at the last of child nodes .
60,577
def insertBefore ( self , child : Node , ref_node : Node ) -> Node : if self . connected : self . _insert_before_web ( child , ref_node ) return self . _insert_before ( child , ref_node )
Insert new child node before the reference child node .
60,578
def removeChild ( self , child : Node ) -> Node : if self . connected : self . _remove_child_web ( child ) return self . _remove_child ( child )
Remove the child node from this node .
60,579
def replaceChild ( self , new_child : 'WdomElement' , old_child : 'WdomElement' ) -> Node : if self . connected : self . _replace_child_web ( new_child , old_child ) return self . _replace_child ( new_child , old_child )
Replace child nodes .
60,580
def textContent ( self , text : str ) -> None : self . _set_text_content ( text ) if self . connected : self . _set_text_content_web ( text )
Set textContent both on this node and related browser node .
60,581
def innerHTML ( self , html : str ) -> None : df = self . _parse_html ( html ) if self . connected : self . _set_inner_html_web ( df . html ) self . _empty ( ) self . _append_child ( df )
Set innerHTML both on this node and related browser node .
60,582
def click ( self ) -> None : if self . connected : self . js_exec ( 'click' ) else : msg = { 'proto' : '' , 'type' : 'click' , 'currentTarget' : { 'id' : self . wdom_id } , 'target' : { 'id' : self . wdom_id } } e = create_event ( msg ) self . _dispatch_event ( e )
Send click event .
60,583
def getElementById ( id : str ) -> Optional [ Node ] : elm = Element . _elements_with_id . get ( id ) return elm
Get element with id .
60,584
def getElementByWdomId ( id : str ) -> Optional [ WebEventTarget ] : if not id : return None elif id == 'document' : return get_document ( ) elif id == 'window' : return get_document ( ) . defaultView elm = WdomElement . _elements_with_wdom_id . get ( id ) return elm
Get element with wdom_id .
60,585
def _cleanup ( path : str ) -> None : if os . path . isdir ( path ) : shutil . rmtree ( path )
Cleanup temporary directory .
60,586
def create_element ( tag : str , name : str = None , base : type = None , attr : dict = None ) -> Node : from wdom . web_node import WdomElement from wdom . tag import Tag from wdom . window import customElements if attr is None : attr = { } if name : base_class = customElements . get ( ( name , tag ) ) else : base_class = customElements . get ( ( tag , None ) ) if base_class is None : attr [ '_registered' ] = False base_class = base or WdomElement if issubclass ( base_class , Tag ) : return base_class ( ** attr ) return base_class ( tag , ** attr )
Create element with a tag of name .
60,587
def characterSet ( self , charset : str ) -> None : charset_node = self . _find_charset_node ( ) or Meta ( parent = self . head ) charset_node . setAttribute ( 'charset' , charset )
Set character set of this document .
60,588
def getElementsBy ( self , cond : Callable [ [ Element ] , bool ] ) -> NodeList : return getElementsBy ( self , cond )
Get elements in this document which matches condition .
60,589
def getElementById ( self , id : str ) -> Optional [ Node ] : elm = getElementById ( id ) if elm and elm . ownerDocument is self : return elm return None
Get element by id .
60,590
def createElement ( self , tag : str ) -> Node : return create_element ( tag , base = self . _default_class )
Create new element whose tag name is tag .
60,591
def getElementByWdomId ( self , id : Union [ str ] ) -> Optional [ WebEventTarget ] : elm = getElementByWdomId ( id ) if elm and elm . ownerDocument is self : return elm return None
Get an element node with wdom_id .
60,592
def add_jsfile ( self , src : str ) -> None : self . body . appendChild ( Script ( src = src ) )
Add JS file to load at this document s bottom of the body .
60,593
def add_jsfile_head ( self , src : str ) -> None : self . head . appendChild ( Script ( src = src ) )
Add JS file to load at this document s header .
60,594
def add_cssfile ( self , src : str ) -> None : self . head . appendChild ( Link ( rel = 'stylesheet' , href = src ) )
Add CSS file to load at this document s header .
60,595
def register_theme ( self , theme : ModuleType ) -> None : if not hasattr ( theme , 'css_files' ) : raise ValueError ( 'theme module must include `css_files`.' ) for css in getattr ( theme , 'css_files' , [ ] ) : self . add_cssfile ( css ) for js in getattr ( theme , 'js_files' , [ ] ) : self . add_jsfile ( js ) for header in getattr ( theme , 'headers' , [ ] ) : self . add_header ( header ) for cls in getattr ( theme , 'extended_classes' , [ ] ) : self . defaultView . customElements . define ( cls )
Set theme for this docuemnt .
60,596
def build ( self ) -> str : self . _set_autoreload ( ) return '' . join ( child . html for child in self . childNodes )
Return HTML representation of this document .
60,597
def send_message ( ) -> None : if not _msg_queue : return msg = json . dumps ( _msg_queue ) _msg_queue . clear ( ) for conn in module . connections : conn . write_message ( msg )
Send message via WS to all client connections .
60,598
def add_static_path ( prefix : str , path : str , no_watch : bool = False ) -> None : app = get_app ( ) app . add_static_path ( prefix , path ) if not no_watch : watch_dir ( path )
Add directory to serve static files .
60,599
def start ( ** kwargs : Any ) -> None : start_server ( ** kwargs ) try : asyncio . get_event_loop ( ) . run_forever ( ) except KeyboardInterrupt : stop_server ( )
Start web server .