idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
237,700
def to_json ( self ) : roots = [ ] for r in self . roots : roots . append ( r . to_json ( ) ) return { 'roots' : roots }
Returns the JSON representation of this graph .
39
8
237,701
def flatten ( l ) : for el in l : if isinstance ( el , collections . Iterable ) and not isinstance ( el , string_types ) : for sub in flatten ( el ) : yield sub else : yield el
Flatten an iterable .
50
6
237,702
def set_iterable_type ( obj ) : if not isiterable ( obj ) : return obj if config . get_option ( 'use_generators' ) : return obj if isgenerator ( obj ) else ( i for i in obj ) else : return [ set_iterable_type ( i ) for i in obj ]
Returns either a generator or a list depending on config - level settings . Should be used to wrap almost every internal iterable return . Also inspects elements recursively in the case of list returns to ensure that there are no nested generators .
72
48
237,703
def isgenerator ( obj ) : return isinstance ( obj , GeneratorType ) or ( hasattr ( obj , 'iterable' ) and isinstance ( getattr ( obj , 'iterable' ) , GeneratorType ) )
Returns True if object is a generator or a generator wrapped by a tqdm object .
48
18
237,704
def progress_bar_wrapper ( iterable , * * kwargs ) : return tqdm ( iterable , * * kwargs ) if ( config . get_option ( 'progress_bar' ) and not isinstance ( iterable , tqdm ) ) else iterable
Wrapper that applies tqdm progress bar conditional on config settings .
61
14
237,705
def get_frame ( self , index ) : frame_num = self . frame_index [ index ] onset = float ( frame_num ) / self . fps if index < self . n_frames - 1 : next_frame_num = self . frame_index [ index + 1 ] end = float ( next_frame_num ) / self . fps else : end = float ( self . duration ) duration = end - onset if end > onset else 0.0 return VideoFrameStim ( self , frame_num , data = self . clip . get_frame ( onset ) , duration = duration )
Get video frame at the specified index .
127
8
237,706
def save ( self , path ) : # IMPORTANT WARNING: saves entire source video self . clip . write_videofile ( path , audio_fps = self . clip . audio . fps )
Save source video to file .
41
6
237,707
def get_frame ( self , index = None , onset = None ) : if onset : index = int ( onset * self . fps ) return super ( VideoStim , self ) . get_frame ( index )
Overrides the default behavior by giving access to the onset argument .
45
14
237,708
def hash_data ( data , blocksize = 65536 ) : data = pickle . dumps ( data ) hasher = hashlib . sha1 ( ) hasher . update ( data ) return hasher . hexdigest ( )
Hashes list of data strings or data
50
8
237,709
def check_updates ( transformers , datastore = None , stimuli = None ) : # Find datastore file datastore = datastore or expanduser ( '~/.pliers_updates' ) prior_data = pd . read_csv ( datastore ) if exists ( datastore ) else None # Load stimuli stimuli = stimuli or glob . glob ( join ( dirname ( realpath ( __file__ ) ) , '../tests/data/image/CC0/*' ) ) stimuli = load_stims ( stimuli ) # Get transformers loaded_transformers = { get_transformer ( name , * * params ) : ( name , params ) for name , params in transformers } # Transform stimuli results = pd . DataFrame ( { 'time_extracted' : [ datetime . datetime . now ( ) ] } ) for trans in loaded_transformers . keys ( ) : for stim in stimuli : if trans . _stim_matches_input_types ( stim ) : res = trans . transform ( stim ) try : # Add iterable res = [ getattr ( res , '_data' , res . data ) for r in res ] except TypeError : res = getattr ( res , '_data' , res . data ) res = hash_data ( res ) results [ "{}.{}" . format ( trans . __hash__ ( ) , stim . name ) ] = [ res ] # Check for mismatches mismatches = [ ] if prior_data is not None : last = prior_data [ prior_data . time_extracted == prior_data . time_extracted . max ( ) ] . iloc [ 0 ] . drop ( 'time_extracted' ) for label , value in results . iteritems ( ) : old = last . get ( label ) new = value . values [ 0 ] if old is not None : if isinstance ( new , str ) : if new != old : mismatches . append ( label ) elif not np . isclose ( old , new ) : mismatches . append ( label ) results = prior_data . append ( results ) results . to_csv ( datastore , index = False ) # Get corresponding transformer name and parameters def get_trans ( hash_tr ) : for obj , attr in loaded_transformers . items ( ) : if str ( obj . __hash__ ( ) ) == hash_tr : return attr delta_t = set ( [ m . split ( '.' ) [ 0 ] for m in mismatches ] ) delta_t = [ get_trans ( dt ) for dt in delta_t ] return { 'transformers' : delta_t , 'mismatches' : mismatches }
Run transformers through a battery of stimuli and check if output has changed . Store results in csv file for comparison .
585
24
237,710
def scan ( args ) : backend = _get_backend ( args ) print ( 'Scanning for 10 seconds...' ) devices = miflora_scanner . scan ( backend , 10 ) print ( 'Found {} devices:' . format ( len ( devices ) ) ) for device in devices : print ( ' {}' . format ( device ) )
Scan for sensors .
75
4
237,711
def _get_backend ( args ) : if args . backend == 'gatttool' : backend = GatttoolBackend elif args . backend == 'bluepy' : backend = BluepyBackend elif args . backend == 'pygatt' : backend = PygattBackend else : raise Exception ( 'unknown backend: {}' . format ( args . backend ) ) return backend
Extract the backend class from the command line arguments .
85
11
237,712
def list_backends ( _ ) : backends = [ b . __name__ for b in available_backends ( ) ] print ( '\n' . join ( backends ) )
List all available backends .
41
6
237,713
def scan ( backend , timeout = 10 ) : result = [ ] for ( mac , name ) in backend . scan_for_devices ( timeout ) : if ( name is not None and name . lower ( ) in VALID_DEVICE_NAMES ) or mac is not None and mac . upper ( ) . startswith ( DEVICE_PREFIX ) : result . append ( mac . upper ( ) ) return result
Scan for miflora devices .
90
8
237,714
def parameter_value ( self , parameter , read_cached = True ) : # Special handling for battery attribute if parameter == MI_BATTERY : return self . battery_level ( ) # Use the lock to make sure the cache isn't updated multiple times with self . lock : if ( read_cached is False ) or ( self . _last_read is None ) or ( datetime . now ( ) - self . _cache_timeout > self . _last_read ) : self . fill_cache ( ) else : _LOGGER . debug ( "Using cache (%s < %s)" , datetime . now ( ) - self . _last_read , self . _cache_timeout ) if self . cache_available ( ) and ( len ( self . _cache ) == 16 ) : return self . _parse_data ( ) [ parameter ] else : raise BluetoothBackendException ( "Could not read data from Mi Flora sensor %s" % self . _mac )
Return a value of one of the monitored paramaters .
209
11
237,715
def parse_version_string ( version_string ) : string_parts = version_string . split ( "." ) version_parts = [ int ( re . match ( "([0-9]*)" , string_parts [ 0 ] ) . group ( 0 ) ) , int ( re . match ( "([0-9]*)" , string_parts [ 1 ] ) . group ( 0 ) ) , int ( re . match ( "([0-9]*)" , string_parts [ 2 ] ) . group ( 0 ) ) ] return version_parts
Parses a semver version string stripping off rc stuff if present .
121
15
237,716
def bigger_version ( version_string_a , version_string_b ) : major_a , minor_a , patch_a = parse_version_string ( version_string_a ) major_b , minor_b , patch_b = parse_version_string ( version_string_b ) if major_a > major_b : return version_string_a elif major_a == major_b and minor_a > minor_b : return version_string_a elif major_a == major_b and minor_a == minor_b and patch_a > patch_b : return version_string_a return version_string_b
Returns the bigger version of two version strings .
143
9
237,717
def api_version ( created_ver , last_changed_ver , return_value_ver ) : def api_min_version_decorator ( function ) : def wrapper ( function , self , * args , * * kwargs ) : if not self . version_check_mode == "none" : if self . version_check_mode == "created" : version = created_ver else : version = bigger_version ( last_changed_ver , return_value_ver ) major , minor , patch = parse_version_string ( version ) if major > self . mastodon_major : raise MastodonVersionError ( "Version check failed (Need version " + version + ")" ) elif major == self . mastodon_major and minor > self . mastodon_minor : print ( self . mastodon_minor ) raise MastodonVersionError ( "Version check failed (Need version " + version + ")" ) elif major == self . mastodon_major and minor == self . mastodon_minor and patch > self . mastodon_patch : raise MastodonVersionError ( "Version check failed (Need version " + version + ", patch is " + str ( self . mastodon_patch ) + ")" ) return function ( self , * args , * * kwargs ) function . __doc__ = function . __doc__ + "\n\n *Added: Mastodon v" + created_ver + ", last changed: Mastodon v" + last_changed_ver + "*" return decorate ( function , wrapper ) return api_min_version_decorator
Version check decorator . Currently only checks Bigger Than .
343
12
237,718
def verify_minimum_version ( self , version_str ) : self . retrieve_mastodon_version ( ) major , minor , patch = parse_version_string ( version_str ) if major > self . mastodon_major : return False elif major == self . mastodon_major and minor > self . mastodon_minor : return False elif major == self . mastodon_major and minor == self . mastodon_minor and patch > self . mastodon_patch : return False return True
Update version info from server and verify that at least the specified version is present . Returns True if version requirement is satisfied False if not .
109
27
237,719
def log_in ( self , username = None , password = None , code = None , redirect_uri = "urn:ietf:wg:oauth:2.0:oob" , refresh_token = None , scopes = __DEFAULT_SCOPES , to_file = None ) : if username is not None and password is not None : params = self . __generate_params ( locals ( ) , [ 'scopes' , 'to_file' , 'code' , 'refresh_token' ] ) params [ 'grant_type' ] = 'password' elif code is not None : params = self . __generate_params ( locals ( ) , [ 'scopes' , 'to_file' , 'username' , 'password' , 'refresh_token' ] ) params [ 'grant_type' ] = 'authorization_code' elif refresh_token is not None : params = self . __generate_params ( locals ( ) , [ 'scopes' , 'to_file' , 'username' , 'password' , 'code' ] ) params [ 'grant_type' ] = 'refresh_token' else : raise MastodonIllegalArgumentError ( 'Invalid arguments given. username and password or code are required.' ) params [ 'client_id' ] = self . client_id params [ 'client_secret' ] = self . client_secret params [ 'scope' ] = " " . join ( scopes ) try : response = self . __api_request ( 'POST' , '/oauth/token' , params , do_ratelimiting = False ) self . access_token = response [ 'access_token' ] self . __set_refresh_token ( response . get ( 'refresh_token' ) ) self . __set_token_expired ( int ( response . get ( 'expires_in' , 0 ) ) ) except Exception as e : if username is not None or password is not None : raise MastodonIllegalArgumentError ( 'Invalid user name, password, or redirect_uris: %s' % e ) elif code is not None : raise MastodonIllegalArgumentError ( 'Invalid access token or redirect_uris: %s' % e ) else : raise MastodonIllegalArgumentError ( 'Invalid request: %s' % e ) received_scopes = response [ "scope" ] . split ( " " ) for scope_set in self . __SCOPE_SETS . keys ( ) : if scope_set in received_scopes : received_scopes += self . __SCOPE_SETS [ scope_set ] if not set ( scopes ) <= set ( received_scopes ) : raise MastodonAPIError ( 'Granted scopes "' + " " . join ( received_scopes ) + '" do not contain all of the requested scopes "' + " " . join ( scopes ) + '".' ) if to_file is not None : with open ( to_file , 'w' ) as token_file : token_file . write ( response [ 'access_token' ] + '\n' ) self . __logged_in_id = None return response [ 'access_token' ]
Get the access token for a user . The username is the e - mail used to log in into mastodon .
711
23
237,720
def timeline_list ( self , id , max_id = None , min_id = None , since_id = None , limit = None ) : id = self . __unpack_id ( id ) return self . timeline ( 'list/{0}' . format ( id ) , max_id = max_id , min_id = min_id , since_id = since_id , limit = limit )
Fetches a timeline containing all the toots by users in a given list .
90
17
237,721
def conversations ( self , max_id = None , min_id = None , since_id = None , limit = None ) : if max_id != None : max_id = self . __unpack_id ( max_id ) if min_id != None : min_id = self . __unpack_id ( min_id ) if since_id != None : since_id = self . __unpack_id ( since_id ) params = self . __generate_params ( locals ( ) ) return self . __api_request ( 'GET' , "/api/v1/conversations/" , params )
Fetches a users conversations . Returns a list of conversation dicts _ .
136
16
237,722
def status ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch information about a single toot .
57
9
237,723
def status_context ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/context' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch information about ancestors and descendants of a toot .
61
12
237,724
def status_reblogged_by ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/reblogged_by' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch a list of users that have reblogged a status .
69
14
237,725
def status_favourited_by ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/favourited_by' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch a list of users that have favourited a status .
69
13
237,726
def scheduled_status ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/scheduled_statuses/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch information about the scheduled status with the given id .
63
12
237,727
def poll ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/polls/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch information about the poll with the given id
57
10
237,728
def account ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch account information by user id . Does not require authentication . Returns a user dict _ .
57
19
237,729
def account_following ( self , id , max_id = None , min_id = None , since_id = None , limit = None ) : id = self . __unpack_id ( id ) if max_id != None : max_id = self . __unpack_id ( max_id ) if min_id != None : min_id = self . __unpack_id ( min_id ) if since_id != None : since_id = self . __unpack_id ( since_id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) url = '/api/v1/accounts/{0}/following' . format ( str ( id ) ) return self . __api_request ( 'GET' , url , params )
Fetch users the given user is following .
176
9
237,730
def account_lists ( self , id ) : id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) url = '/api/v1/accounts/{0}/lists' . format ( str ( id ) ) return self . __api_request ( 'GET' , url , params )
Get all of the logged - in users lists which the specified user is a member of . Returns a list of list dicts _ .
83
27
237,731
def filter ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/filters/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetches information about the filter with the specified id . Returns a filter dict _ .
57
18
237,732
def search ( self , q , resolve = True , result_type = None , account_id = None , offset = None , min_id = None , max_id = None ) : return self . search_v2 ( q , resolve = resolve , result_type = result_type , account_id = account_id , offset = offset , min_id = min_id , max_id = max_id )
Fetch matching hashtags accounts and statuses . Will perform webfinger lookups if resolve is True . Full - text search is only enabled if the instance supports it and is restricted to statuses the logged - in user wrote or was mentioned in . result_type can be one of accounts hashtags or statuses to only search for that type of object . Specify account_id to only get results from the account with that id . offset min_id and max_id can be used to paginate .
90
103
237,733
def list ( self , id ) : id = self . __unpack_id ( id ) return self . __api_request ( 'GET' , '/api/v1/lists/{0}' . format ( id ) )
Fetch info about a specific list . Returns a list dict _ .
50
14
237,734
def list_accounts ( self , id , max_id = None , min_id = None , since_id = None , limit = None ) : id = self . __unpack_id ( id ) if max_id != None : max_id = self . __unpack_id ( max_id ) if min_id != None : min_id = self . __unpack_id ( min_id ) if since_id != None : since_id = self . __unpack_id ( since_id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) return self . __api_request ( 'GET' , '/api/v1/lists/{0}/accounts' . format ( id ) )
Get the accounts that are on the given list . A limit of 0 can be specified to get all accounts without pagination . Returns a list of user dicts _ .
167
34
237,735
def status_reply ( self , to_status , status , media_ids = None , sensitive = False , visibility = None , spoiler_text = None , language = None , idempotency_key = None , content_type = None , scheduled_at = None , poll = None , untag = False ) : user_id = self . __get_logged_in_id ( ) # Determine users to mention mentioned_accounts = collections . OrderedDict ( ) mentioned_accounts [ to_status . account . id ] = to_status . account . acct if not untag : for account in to_status . mentions : if account . id != user_id and not account . id in mentioned_accounts . keys ( ) : mentioned_accounts [ account . id ] = account . acct # Join into one piece of text. The space is added inside because of self-replies. status = "" . join ( map ( lambda x : "@" + x + " " , mentioned_accounts . values ( ) ) ) + status # Retain visibility / cw if visibility == None and 'visibility' in to_status : visibility = to_status . visibility if spoiler_text == None and 'spoiler_text' in to_status : spoiler_text = to_status . spoiler_text return self . status_post ( status , in_reply_to_id = to_status . id , media_ids = media_ids , sensitive = sensitive , visibility = visibility , spoiler_text = spoiler_text , language = language , idempotency_key = idempotency_key , content_type = content_type , scheduled_at = scheduled_at , poll = poll )
Helper function - acts like status_post but prepends the name of all the users that are being replied to to the status text and retains CW and visibility if not explicitly overridden . Set untag to True if you want the reply to only go to the user you are replying to removing every other mentioned user from the conversation .
370
67
237,736
def status_delete ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}' . format ( str ( id ) ) self . __api_request ( 'DELETE' , url )
Delete a status
60
3
237,737
def status_unreblog ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/unreblog' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Un - reblog a status .
65
7
237,738
def status_favourite ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/favourite' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Favourite a status .
65
6
237,739
def status_unfavourite ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/unfavourite' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Un - favourite a status .
67
6
237,740
def status_mute ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/mute' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Mute notifications for a status .
63
7
237,741
def status_unmute ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/unmute' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Unmute notifications for a status .
65
8
237,742
def status_pin ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/pin' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Pin a status for the logged - in user .
61
10
237,743
def status_unpin ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/unpin' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Unpin a pinned status for the logged - in user .
63
12
237,744
def scheduled_status_update ( self , id , scheduled_at ) : scheduled_at = self . __consistent_isoformat_utc ( scheduled_at ) id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) url = '/api/v1/scheduled_statuses/{0}' . format ( str ( id ) ) return self . __api_request ( 'PUT' , url , params )
Update the scheduled time of a scheduled status . New time must be at least 5 minutes into the future . Returns a scheduled toot dict _
111
28
237,745
def scheduled_status_delete ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/scheduled_statuses/{0}' . format ( str ( id ) ) self . __api_request ( 'DELETE' , url )
Deletes a scheduled status .
66
6
237,746
def poll_vote ( self , id , choices ) : id = self . __unpack_id ( id ) if not isinstance ( choices , list ) : choices = [ choices ] params = self . __generate_params ( locals ( ) , [ 'id' ] ) url = '/api/v1/polls/{0}/votes' . format ( id ) self . __api_request ( 'POST' , url , params )
Vote in the given poll . choices is the index of the choice you wish to register a vote for ( i . e . its index in the corresponding polls options field . In case of a poll that allows selection of more than one option a list of indices can be passed . You can only submit choices for any given poll once in case of single - option polls or only once per option in case of multi - option polls . Returns the updated poll dict _
96
91
237,747
def notifications_dismiss ( self , id ) : id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) ) self . __api_request ( 'POST' , '/api/v1/notifications/dismiss' , params )
Deletes a single notification
65
5
237,748
def account_block ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}/block' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Block a user .
61
4
237,749
def account_unblock ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}/unblock' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Unblock a user .
63
5
237,750
def account_mute ( self , id , notifications = True ) : id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) url = '/api/v1/accounts/{0}/mute' . format ( str ( id ) ) return self . __api_request ( 'POST' , url , params )
Mute a user .
89
5
237,751
def account_unmute ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}/unmute' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Unmute a user .
65
6
237,752
def account_update_credentials ( self , display_name = None , note = None , avatar = None , avatar_mime_type = None , header = None , header_mime_type = None , locked = None , fields = None ) : params_initial = collections . OrderedDict ( locals ( ) ) # Load avatar, if specified if not avatar is None : if avatar_mime_type is None and ( isinstance ( avatar , str ) and os . path . isfile ( avatar ) ) : avatar_mime_type = guess_type ( avatar ) avatar = open ( avatar , 'rb' ) if avatar_mime_type is None : raise MastodonIllegalArgumentError ( 'Could not determine mime type or data passed directly without mime type.' ) # Load header, if specified if not header is None : if header_mime_type is None and ( isinstance ( avatar , str ) and os . path . isfile ( header ) ) : header_mime_type = guess_type ( header ) header = open ( header , 'rb' ) if header_mime_type is None : raise MastodonIllegalArgumentError ( 'Could not determine mime type or data passed directly without mime type.' ) # Convert fields if fields != None : if len ( fields ) > 4 : raise MastodonIllegalArgumentError ( 'A maximum of four fields are allowed.' ) fields_attributes = [ ] for idx , ( field_name , field_value ) in enumerate ( fields ) : params_initial [ 'fields_attributes[' + str ( idx ) + '][name]' ] = field_name params_initial [ 'fields_attributes[' + str ( idx ) + '][value]' ] = field_value # Clean up params for param in [ "avatar" , "avatar_mime_type" , "header" , "header_mime_type" , "fields" ] : if param in params_initial : del params_initial [ param ] # Create file info files = { } if not avatar is None : avatar_file_name = "mastodonpyupload_" + mimetypes . guess_extension ( avatar_mime_type ) files [ "avatar" ] = ( avatar_file_name , avatar , avatar_mime_type ) if not header is None : header_file_name = "mastodonpyupload_" + mimetypes . guess_extension ( header_mime_type ) files [ "header" ] = ( header_file_name , header , header_mime_type ) params = self . __generate_params ( params_initial ) return self . __api_request ( 'PATCH' , '/api/v1/accounts/update_credentials' , params , files = files )
Update the profile for the currently logged - in user .
618
11
237,753
def filter_create ( self , phrase , context , irreversible = False , whole_word = True , expires_in = None ) : params = self . __generate_params ( locals ( ) ) for context_val in context : if not context_val in [ 'home' , 'notifications' , 'public' , 'thread' ] : raise MastodonIllegalArgumentError ( 'Invalid filter context.' ) return self . __api_request ( 'POST' , '/api/v1/filters' , params )
Creates a new keyword filter . phrase is the phrase that should be filtered out context specifies from where to filter the keywords . Valid contexts are home notifications public and thread . Set irreversible to True if you want the filter to just delete statuses server side . This works only for the home and notifications contexts . Set whole_word to False if you want to allow filter matches to start or end within a word not only at word boundaries . Set expires_in to specify for how many seconds the filter should be kept around . Returns the filter dict _ of the newly created filter .
113
115
237,754
def filter_delete ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/filters/{0}' . format ( str ( id ) ) self . __api_request ( 'DELETE' , url )
Deletes the filter with the given id .
60
9
237,755
def suggestion_delete ( self , account_id ) : account_id = self . __unpack_id ( account_id ) url = '/api/v1/suggestions/{0}' . format ( str ( account_id ) ) self . __api_request ( 'DELETE' , url )
Remove the user with the given account_id from the follow suggestions .
68
14
237,756
def list_create ( self , title ) : params = self . __generate_params ( locals ( ) ) return self . __api_request ( 'POST' , '/api/v1/lists' , params )
Create a new list with the given title . Returns the list dict _ of the created list .
47
19
237,757
def list_update ( self , id , title ) : id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) return self . __api_request ( 'PUT' , '/api/v1/lists/{0}' . format ( id ) , params )
Update info about a list where info is really the lists title . Returns the list dict _ of the modified list .
76
23
237,758
def list_delete ( self , id ) : id = self . __unpack_id ( id ) self . __api_request ( 'DELETE' , '/api/v1/lists/{0}' . format ( id ) )
Delete a list .
53
4
237,759
def report ( self , account_id , status_ids = None , comment = None , forward = False ) : account_id = self . __unpack_id ( account_id ) if not status_ids is None : if not isinstance ( status_ids , list ) : status_ids = [ status_ids ] status_ids = list ( map ( lambda x : self . __unpack_id ( x ) , status_ids ) ) params_initial = locals ( ) if forward == False : del params_initial [ 'forward' ] params = self . __generate_params ( params_initial ) return self . __api_request ( 'POST' , '/api/v1/reports/' , params )
Report statuses to the instances administrators .
155
8
237,760
def follow_request_authorize ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/follow_requests/{0}/authorize' . format ( str ( id ) ) self . __api_request ( 'POST' , url )
Accept an incoming follow request .
66
6
237,761
def follow_request_reject ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/follow_requests/{0}/reject' . format ( str ( id ) ) self . __api_request ( 'POST' , url )
Reject an incoming follow request .
66
7
237,762
def domain_block ( self , domain = None ) : params = self . __generate_params ( locals ( ) ) self . __api_request ( 'POST' , '/api/v1/domain_blocks' , params )
Add a block for all statuses originating from the specified domain for the logged - in user .
50
19
237,763
def domain_unblock ( self , domain = None ) : params = self . __generate_params ( locals ( ) ) self . __api_request ( 'DELETE' , '/api/v1/domain_blocks' , params )
Remove a domain block for the logged - in user .
53
11
237,764
def push_subscription_update ( self , follow_events = None , favourite_events = None , reblog_events = None , mention_events = None ) : params = { } if follow_events != None : params [ 'data[alerts][follow]' ] = follow_events if favourite_events != None : params [ 'data[alerts][favourite]' ] = favourite_events if reblog_events != None : params [ 'data[alerts][reblog]' ] = reblog_events if mention_events != None : params [ 'data[alerts][mention]' ] = mention_events return self . __api_request ( 'PUT' , '/api/v1/push/subscription' , params )
Modifies what kind of events the app wishes to subscribe to . Returns the updated push subscription dict _ .
160
21
237,765
def stream_user ( self , listener , run_async = False , timeout = __DEFAULT_STREAM_TIMEOUT , reconnect_async = False , reconnect_async_wait_sec = __DEFAULT_STREAM_RECONNECT_WAIT_SEC ) : return self . __stream ( '/api/v1/streaming/user' , listener , run_async = run_async , timeout = timeout , reconnect_async = reconnect_async , reconnect_async_wait_sec = reconnect_async_wait_sec )
Streams events that are relevant to the authorized user i . e . home timeline and notifications .
123
19
237,766
def stream_hashtag ( self , tag , listener , run_async = False , timeout = __DEFAULT_STREAM_TIMEOUT , reconnect_async = False , reconnect_async_wait_sec = __DEFAULT_STREAM_RECONNECT_WAIT_SEC ) : if tag . startswith ( "#" ) : raise MastodonIllegalArgumentError ( "Tag parameter should omit leading #" ) return self . __stream ( "/api/v1/streaming/hashtag?tag={}" . format ( tag ) , listener , run_async = run_async , timeout = timeout , reconnect_async = reconnect_async , reconnect_async_wait_sec = reconnect_async_wait_sec )
Stream for all public statuses for the hashtag tag seen by the connected instance .
164
16
237,767
def stream_list ( self , id , listener , run_async = False , timeout = __DEFAULT_STREAM_TIMEOUT , reconnect_async = False , reconnect_async_wait_sec = __DEFAULT_STREAM_RECONNECT_WAIT_SEC ) : id = self . __unpack_id ( id ) return self . __stream ( "/api/v1/streaming/list?list={}" . format ( id ) , listener , run_async = run_async , timeout = timeout , reconnect_async = reconnect_async , reconnect_async_wait_sec = reconnect_async_wait_sec )
Stream events for the current user restricted to accounts on the given list .
145
14
237,768
def __datetime_to_epoch ( self , date_time ) : date_time_utc = None if date_time . tzinfo is None : date_time_utc = date_time . replace ( tzinfo = pytz . utc ) else : date_time_utc = date_time . astimezone ( pytz . utc ) epoch_utc = datetime . datetime . utcfromtimestamp ( 0 ) . replace ( tzinfo = pytz . utc ) return ( date_time_utc - epoch_utc ) . total_seconds ( )
Converts a python datetime to unix epoch accounting for time zones and such .
134
17
237,769
def __get_logged_in_id ( self ) : if self . __logged_in_id == None : self . __logged_in_id = self . account_verify_credentials ( ) . id return self . __logged_in_id
Fetch the logged in users ID with caching . ID is reset on calls to log_in .
61
20
237,770
def __json_date_parse ( json_object ) : known_date_fields = [ "created_at" , "week" , "day" , "expires_at" , "scheduled_at" ] for k , v in json_object . items ( ) : if k in known_date_fields : if v != None : try : if isinstance ( v , int ) : json_object [ k ] = datetime . datetime . fromtimestamp ( v , pytz . utc ) else : json_object [ k ] = dateutil . parser . parse ( v ) except : raise MastodonAPIError ( 'Encountered invalid date.' ) return json_object
Parse dates in certain known json fields if possible .
150
11
237,771
def __json_strnum_to_bignum ( json_object ) : for key in ( 'id' , 'week' , 'in_reply_to_id' , 'in_reply_to_account_id' , 'logins' , 'registrations' , 'statuses' ) : if ( key in json_object and isinstance ( json_object [ key ] , six . text_type ) ) : try : json_object [ key ] = int ( json_object [ key ] ) except ValueError : pass return json_object
Converts json string numerals to native python bignums .
122
13
237,772
def __json_hooks ( json_object ) : json_object = Mastodon . __json_strnum_to_bignum ( json_object ) json_object = Mastodon . __json_date_parse ( json_object ) json_object = Mastodon . __json_truefalse_parse ( json_object ) json_object = Mastodon . __json_allow_dict_attrs ( json_object ) return json_object
All the json hooks . Used in request parsing .
97
10
237,773
def __consistent_isoformat_utc ( datetime_val ) : isotime = datetime_val . astimezone ( pytz . utc ) . strftime ( "%Y-%m-%dT%H:%M:%S%z" ) if isotime [ - 2 ] != ":" : isotime = isotime [ : - 2 ] + ":" + isotime [ - 2 : ] return isotime
Function that does what isoformat does but it actually does the same every time instead of randomly doing different things on some systems and also it represents that time as the equivalent UTC time .
95
36
237,774
def __generate_params ( self , params , exclude = [ ] ) : params = collections . OrderedDict ( params ) del params [ 'self' ] param_keys = list ( params . keys ( ) ) for key in param_keys : if isinstance ( params [ key ] , bool ) and params [ key ] == False : params [ key ] = '0' if isinstance ( params [ key ] , bool ) and params [ key ] == True : params [ key ] = '1' for key in param_keys : if params [ key ] is None or key in exclude : del params [ key ] param_keys = list ( params . keys ( ) ) for key in param_keys : if isinstance ( params [ key ] , list ) : params [ key + "[]" ] = params [ key ] del params [ key ] return params
Internal named - parameters - to - dict helper .
182
10
237,775
def __decode_webpush_b64 ( self , data ) : missing_padding = len ( data ) % 4 if missing_padding != 0 : data += '=' * ( 4 - missing_padding ) return base64 . urlsafe_b64decode ( data )
Re - pads and decodes urlsafe base64 .
60
12
237,776
def __set_token_expired ( self , value ) : self . _token_expired = datetime . datetime . now ( ) + datetime . timedelta ( seconds = value ) return
Internal helper for oauth code
43
6
237,777
def __protocolize ( base_url ) : if not base_url . startswith ( "http://" ) and not base_url . startswith ( "https://" ) : base_url = "https://" + base_url # Some API endpoints can't handle extra /'s in path requests base_url = base_url . rstrip ( "/" ) return base_url
Internal add - protocol - to - url helper
87
9
237,778
def status ( self ) : if self . report == None : return SentSms . ENROUTE else : return SentSms . DELIVERED if self . report . deliveryStatus == StatusReport . DELIVERED else SentSms . FAILED
Status of this SMS . Can be ENROUTE DELIVERED or FAILED The actual status report object may be accessed via the report attribute if status is DELIVERED or FAILED
54
40
237,779
def write ( self , data , waitForResponse = True , timeout = 5 , parseError = True , writeTerm = '\r' , expectedResponseTermSeq = None ) : self . log . debug ( 'write: %s' , data ) responseLines = super ( GsmModem , self ) . write ( data + writeTerm , waitForResponse = waitForResponse , timeout = timeout , expectedResponseTermSeq = expectedResponseTermSeq ) if self . _writeWait > 0 : # Sleep a bit if required (some older modems suffer under load) time . sleep ( self . _writeWait ) if waitForResponse : cmdStatusLine = responseLines [ - 1 ] if parseError : if 'ERROR' in cmdStatusLine : cmErrorMatch = self . CM_ERROR_REGEX . match ( cmdStatusLine ) if cmErrorMatch : errorType = cmErrorMatch . group ( 1 ) errorCode = int ( cmErrorMatch . group ( 2 ) ) if errorCode == 515 or errorCode == 14 : # 515 means: "Please wait, init or command processing in progress." # 14 means "SIM busy" self . _writeWait += 0.2 # Increase waiting period temporarily # Retry the command after waiting a bit self . log . debug ( 'Device/SIM busy error detected; self._writeWait adjusted to %fs' , self . _writeWait ) time . sleep ( self . _writeWait ) result = self . write ( data , waitForResponse , timeout , parseError , writeTerm , expectedResponseTermSeq ) self . log . debug ( 'self_writeWait set to 0.1 because of recovering from device busy (515) error' ) if errorCode == 515 : self . _writeWait = 0.1 # Set this to something sane for further commands (slow modem) else : self . _writeWait = 0 # The modem was just waiting for the SIM card return result if errorType == 'CME' : raise CmeError ( data , int ( errorCode ) ) else : # CMS error raise CmsError ( data , int ( errorCode ) ) else : raise CommandError ( data ) elif cmdStatusLine == 'COMMAND NOT SUPPORT' : # Some Huawei modems respond with this for unknown commands raise CommandError ( data + '({0})' . format ( cmdStatusLine ) ) return responseLines
Write data to the modem .
509
6
237,780
def smsTextMode ( self , textMode ) : if textMode != self . _smsTextMode : if self . alive : self . write ( 'AT+CMGF={0}' . format ( 1 if textMode else 0 ) ) self . _smsTextMode = textMode self . _compileSmsRegexes ( )
Set to True for the modem to use text mode for SMS or False for it to use PDU mode
76
21
237,781
def _compileSmsRegexes ( self ) : if self . _smsTextMode : if self . CMGR_SM_DELIVER_REGEX_TEXT == None : self . CMGR_SM_DELIVER_REGEX_TEXT = re . compile ( r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$' ) self . CMGR_SM_REPORT_REGEXT_TEXT = re . compile ( r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$' ) elif self . CMGR_REGEX_PDU == None : self . CMGR_REGEX_PDU = re . compile ( r'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$' )
Compiles regular expression used for parsing SMS messages based on current mode
233
13
237,782
def smsc ( self , smscNumber ) : if smscNumber != self . _smscNumber : if self . alive : self . write ( 'AT+CSCA="{0}"' . format ( smscNumber ) ) self . _smscNumber = smscNumber
Set the default SMSC number to use when sending SMS messages
63
12
237,783
def dial ( self , number , timeout = 5 , callStatusUpdateCallbackFunc = None ) : if self . _waitForCallInitUpdate : # Wait for the "call originated" notification message self . _dialEvent = threading . Event ( ) try : self . write ( 'ATD{0};' . format ( number ) , timeout = timeout , waitForResponse = self . _waitForAtdResponse ) except Exception : self . _dialEvent = None # Cancel the thread sync lock raise else : # Don't wait for a call init update - base the call ID on the number of active calls self . write ( 'ATD{0};' . format ( number ) , timeout = timeout , waitForResponse = self . _waitForAtdResponse ) self . log . debug ( "Not waiting for outgoing call init update message" ) callId = len ( self . activeCalls ) + 1 callType = 0 # Assume voice call = Call ( self , callId , callType , number , callStatusUpdateCallbackFunc ) self . activeCalls [ callId ] = call return call if self . _mustPollCallStatus : # Fake a call notification by polling call status until the status indicates that the call is being dialed threading . Thread ( target = self . _pollCallStatus , kwargs = { 'expectedState' : 0 , 'timeout' : timeout } ) . start ( ) if self . _dialEvent . wait ( timeout ) : self . _dialEvent = None callId , callType = self . _dialResponse call = Call ( self , callId , callType , number , callStatusUpdateCallbackFunc ) self . activeCalls [ callId ] = call return call else : # Call establishing timed out self . _dialEvent = None raise TimeoutException ( )
Calls the specified phone number using a voice phone call
384
11
237,784
def _handleCallInitiated ( self , regexMatch , callId = None , callType = 1 ) : if self . _dialEvent : if regexMatch : groups = regexMatch . groups ( ) # Set self._dialReponse to (callId, callType) if len ( groups ) >= 2 : self . _dialResponse = ( int ( groups [ 0 ] ) , int ( groups [ 1 ] ) ) else : self . _dialResponse = ( int ( groups [ 0 ] ) , 1 ) # assume call type: VOICE else : self . _dialResponse = callId , callType self . _dialEvent . set ( )
Handler for outgoing call initiated event notification line
137
8
237,785
def _handleCallAnswered ( self , regexMatch , callId = None ) : if regexMatch : groups = regexMatch . groups ( ) if len ( groups ) > 1 : callId = int ( groups [ 0 ] ) self . activeCalls [ callId ] . answered = True else : # Call ID not available for this notificition - check for the first outgoing call that has not been answered for call in dictValuesIter ( self . activeCalls ) : if call . answered == False and type ( call ) == Call : call . answered = True return else : # Use supplied values self . activeCalls [ callId ] . answered = True
Handler for outgoing call answered event notification line
139
8
237,786
def _handleSmsReceived ( self , notificationLine ) : self . log . debug ( 'SMS message received' ) cmtiMatch = self . CMTI_REGEX . match ( notificationLine ) if cmtiMatch : msgMemory = cmtiMatch . group ( 1 ) msgIndex = cmtiMatch . group ( 2 ) sms = self . readStoredSms ( msgIndex , msgMemory ) self . deleteStoredSms ( msgIndex ) self . smsReceivedCallback ( sms )
Handler for new SMS unsolicited notification line
111
8
237,787
def _handleSmsStatusReport ( self , notificationLine ) : self . log . debug ( 'SMS status report received' ) cdsiMatch = self . CDSI_REGEX . match ( notificationLine ) if cdsiMatch : msgMemory = cdsiMatch . group ( 1 ) msgIndex = cdsiMatch . group ( 2 ) report = self . readStoredSms ( msgIndex , msgMemory ) self . deleteStoredSms ( msgIndex ) # Update sent SMS status if possible if report . reference in self . sentSms : self . sentSms [ report . reference ] . report = report if self . _smsStatusReportEvent : # A sendSms() call is waiting for this response - notify waiting thread self . _smsStatusReportEvent . set ( ) else : # Nothing is waiting for this report directly - use callback self . smsStatusReportCallback ( report )
Handler for SMS status reports
197
5
237,788
def hangup ( self ) : if self . active : self . _gsmModem . write ( 'ATH' ) self . answered = False self . active = False if self . id in self . _gsmModem . activeCalls : del self . _gsmModem . activeCalls [ self . id ]
End the phone call . Does nothing if the call is already inactive .
70
14
237,789
def _color ( self , color , msg ) : if self . useColor : return '{0}{1}{2}' . format ( color , msg , self . RESET_SEQ ) else : return msg
Converts a message to be printed to the user s terminal in red
46
14
237,790
def _cursorLeft ( self ) : if self . cursorPos > 0 : self . cursorPos -= 1 sys . stdout . write ( console . CURSOR_LEFT ) sys . stdout . flush ( )
Handles cursor left events
48
5
237,791
def _cursorRight ( self ) : if self . cursorPos < len ( self . inputBuffer ) : self . cursorPos += 1 sys . stdout . write ( console . CURSOR_RIGHT ) sys . stdout . flush ( )
Handles cursor right events
54
5
237,792
def _cursorUp ( self ) : if self . historyPos > 0 : self . historyPos -= 1 clearLen = len ( self . inputBuffer ) self . inputBuffer = list ( self . history [ self . historyPos ] ) self . cursorPos = len ( self . inputBuffer ) self . _refreshInputPrompt ( clearLen )
Handles cursor up events
74
5
237,793
def _handleBackspace ( self ) : if self . cursorPos > 0 : #print( 'cp:',self.cursorPos,'was:', self.inputBuffer) self . inputBuffer = self . inputBuffer [ 0 : self . cursorPos - 1 ] + self . inputBuffer [ self . cursorPos : ] self . cursorPos -= 1 #print ('cp:', self.cursorPos,'is:', self.inputBuffer) self . _refreshInputPrompt ( len ( self . inputBuffer ) + 1 )
Handles backspace characters
114
5
237,794
def _handleDelete ( self ) : if self . cursorPos < len ( self . inputBuffer ) : self . inputBuffer = self . inputBuffer [ 0 : self . cursorPos ] + self . inputBuffer [ self . cursorPos + 1 : ] self . _refreshInputPrompt ( len ( self . inputBuffer ) + 1 )
Handles delete characters
72
4
237,795
def _handleEnd ( self ) : self . cursorPos = len ( self . inputBuffer ) self . _refreshInputPrompt ( len ( self . inputBuffer ) )
Handles end character
37
4
237,796
def _doCommandCompletion ( self ) : prefix = '' . join ( self . inputBuffer ) . strip ( ) . upper ( ) matches = self . completion . keys ( prefix ) matchLen = len ( matches ) if matchLen == 0 and prefix [ - 1 ] == '=' : try : command = prefix [ : - 1 ] except KeyError : pass else : self . __printCommandSyntax ( command ) elif matchLen > 0 : if matchLen == 1 : if matches [ 0 ] == prefix : # User has already entered command - show command syntax self . __printCommandSyntax ( prefix ) else : # Complete only possible command self . inputBuffer = list ( matches [ 0 ] ) self . cursorPos = len ( self . inputBuffer ) self . _refreshInputPrompt ( len ( self . inputBuffer ) ) return else : commonPrefix = self . completion . longestCommonPrefix ( '' . join ( self . inputBuffer ) ) self . inputBuffer = list ( commonPrefix ) self . cursorPos = len ( self . inputBuffer ) if matchLen > 20 : matches = matches [ : 20 ] matches . append ( '... ({0} more)' . format ( matchLen - 20 ) ) sys . stdout . write ( '\n' ) for match in matches : sys . stdout . write ( ' {0} ' . format ( match ) ) sys . stdout . write ( '\n' ) sys . stdout . flush ( ) self . _refreshInputPrompt ( len ( self . inputBuffer ) )
Command - completion method
331
4
237,797
def connect ( self ) : self . serial = serial . Serial ( port = self . port , baudrate = self . baudrate , timeout = self . timeout ) # Start read thread self . alive = True self . rxThread = threading . Thread ( target = self . _readLoop ) self . rxThread . daemon = True self . rxThread . start ( )
Connects to the device and starts the read thread
82
10
237,798
def close ( self ) : self . alive = False self . rxThread . join ( ) self . serial . close ( )
Stops the read thread waits for it to exit cleanly then closes the underlying serial port
27
18
237,799
def _readLoop ( self ) : try : readTermSeq = list ( self . RX_EOL_SEQ ) readTermLen = len ( readTermSeq ) rxBuffer = [ ] while self . alive : data = self . serial . read ( 1 ) if data != '' : # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer . append ( data ) if rxBuffer [ - readTermLen : ] == readTermSeq : # A line (or other logical segment) has been read line = '' . join ( rxBuffer [ : - readTermLen ] ) rxBuffer = [ ] if len ( line ) > 0 : #print 'calling handler' self . _handleLineRead ( line ) elif self . _expectResponseTermSeq : if rxBuffer [ - len ( self . _expectResponseTermSeq ) : ] == self . _expectResponseTermSeq : line = '' . join ( rxBuffer ) rxBuffer = [ ] self . _handleLineRead ( line , checkForResponseTerm = False ) #else: #' <RX timeout>' except serial . SerialException as e : self . alive = False try : self . serial . close ( ) except Exception : #pragma: no cover pass # Notify the fatal error handler self . fatalErrorCallback ( e )
Read thread main loop Reads lines from the connected device
310
11