idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
49,800
def run ( self , stim , merge = True , ** merge_kwargs ) : results = list ( chain ( * [ self . run_node ( n , stim ) for n in self . roots ] ) ) results = list ( flatten ( results ) ) self . _results = results return merge_results ( results , ** merge_kwargs ) if merge else results
Executes the graph by calling all Transformers in sequence .
49,801
def run_node ( self , node , stim ) : if isinstance ( node , string_types ) : node = self . nodes [ node ] result = node . transformer . transform ( stim ) if node . is_leaf ( ) : return listify ( result ) stim = result if len ( node . children ) > 1 and isgenerator ( stim ) : stim = list ( stim ) return list ( chain ( * [ self . run_node ( c , stim ) for c in node . children ] ) )
Executes the Transformer at a specific node .
49,802
def draw ( self , filename , color = True ) : verify_dependencies ( [ 'pgv' ] ) if not hasattr ( self , '_results' ) : raise RuntimeError ( "Graph cannot be drawn before it is executed. " "Try calling run() first." ) g = pgv . AGraph ( directed = True ) g . node_attr [ 'colorscheme' ] = 'set312' for elem in self . _results : if not hasattr ( elem , 'history' ) : continue log = elem . history while log : source_from = log . parent [ 6 ] if log . parent else '' s_node = hash ( ( source_from , log [ 2 ] ) ) s_color = stim_list . index ( log [ 2 ] ) s_color = s_color % 12 + 1 t_node = hash ( ( log [ 6 ] , log [ 7 ] ) ) t_style = 'filled,' if color else '' t_style += 'dotted' if log . implicit else '' if log [ 6 ] . endswith ( 'Extractor' ) : t_color = '#0082c8' elif log [ 6 ] . endswith ( 'Filter' ) : t_color = '#e6194b' else : t_color = '#3cb44b' r_node = hash ( ( log [ 6 ] , log [ 5 ] ) ) r_color = stim_list . index ( log [ 5 ] ) r_color = r_color % 12 + 1 if color : g . add_node ( s_node , label = log [ 2 ] , shape = 'ellipse' , style = 'filled' , fillcolor = s_color ) g . add_node ( t_node , label = log [ 6 ] , shape = 'box' , style = t_style , fillcolor = t_color ) g . add_node ( r_node , label = log [ 5 ] , shape = 'ellipse' , style = 'filled' , fillcolor = r_color ) else : g . add_node ( s_node , label = log [ 2 ] , shape = 'ellipse' ) g . add_node ( t_node , label = log [ 6 ] , shape = 'box' , style = t_style ) g . add_node ( r_node , label = log [ 5 ] , shape = 'ellipse' ) g . add_edge ( s_node , t_node , style = t_style ) g . add_edge ( t_node , r_node , style = t_style ) log = log . parent g . draw ( filename , prog = 'dot' )
Render a plot of the graph via pygraphviz .
49,803
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 .
49,804
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 .
49,805
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 .
49,806
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 .
49,807
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 .
49,808
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 .
49,809
def save ( self , path ) : self . clip . write_videofile ( path , audio_fps = self . clip . audio . fps )
Save source video to file .
49,810
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 .
49,811
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
49,812
def check_updates ( transformers , datastore = None , stimuli = None ) : datastore = datastore or expanduser ( '~/.pliers_updates' ) prior_data = pd . read_csv ( datastore ) if exists ( datastore ) else None stimuli = stimuli or glob . glob ( join ( dirname ( realpath ( __file__ ) ) , '../tests/data/image/CC0/*' ) ) stimuli = load_stims ( stimuli ) loaded_transformers = { get_transformer ( name , ** params ) : ( name , params ) for name , params in transformers } 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 : 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 ] 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 ) 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 .
49,813
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 .
49,814
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 .
49,815
def list_backends ( _ ) : backends = [ b . __name__ for b in available_backends ( ) ] print ( '\n' . join ( backends ) )
List all available backends .
49,816
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 .
49,817
def parameter_value ( self , parameter , read_cached = True ) : if parameter == MI_BATTERY : return self . battery_level ( ) 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 .
49,818
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 .
49,819
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 .
49,820
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 .
49,821
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 .
49,822
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 .
49,823
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 .
49,824
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 _ .
49,825
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 .
49,826
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 .
49,827
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 .
49,828
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 .
49,829
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 .
49,830
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
49,831
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 _ .
49,832
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 .
49,833
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 _ .
49,834
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 _ .
49,835
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 .
49,836
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 _ .
49,837
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 _ .
49,838
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 ( ) 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 status = "" . join ( map ( lambda x : "@" + x + " " , mentioned_accounts . values ( ) ) ) + status 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 .
49,839
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
49,840
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 .
49,841
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 .
49,842
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 .
49,843
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 .
49,844
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 .
49,845
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 .
49,846
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 .
49,847
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 _
49,848
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 .
49,849
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 _
49,850
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
49,851
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 .
49,852
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 .
49,853
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 .
49,854
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 .
49,855
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 ( ) ) 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.' ) 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.' ) 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 for param in [ "avatar" , "avatar_mime_type" , "header" , "header_mime_type" , "fields" ] : if param in params_initial : del params_initial [ param ] 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 .
49,856
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 .
49,857
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 .
49,858
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 .
49,859
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 .
49,860
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 .
49,861
def list_delete ( self , id ) : id = self . __unpack_id ( id ) self . __api_request ( 'DELETE' , '/api/v1/lists/{0}' . format ( id ) )
Delete a list .
49,862
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 .
49,863
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 .
49,864
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 .
49,865
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 .
49,866
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 .
49,867
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 _ .
49,868
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 .
49,869
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 .
49,870
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 .
49,871
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 .
49,872
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 .
49,873
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 .
49,874
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 .
49,875
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 .
49,876
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 .
49,877
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 .
49,878
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 .
49,879
def __set_token_expired ( self , value ) : self . _token_expired = datetime . datetime . now ( ) + datetime . timedelta ( seconds = value ) return
Internal helper for oauth code
49,880
def __protocolize ( base_url ) : if not base_url . startswith ( "http://" ) and not base_url . startswith ( "https://" ) : base_url = "https://" + base_url base_url = base_url . rstrip ( "/" ) return base_url
Internal add - protocol - to - url helper
49,881
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
49,882
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 : 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 : self . _writeWait += 0.2 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 else : self . _writeWait = 0 return result if errorType == 'CME' : raise CmeError ( data , int ( errorCode ) ) else : raise CmsError ( data , int ( errorCode ) ) else : raise CommandError ( data ) elif cmdStatusLine == 'COMMAND NOT SUPPORT' : raise CommandError ( data + '({0})' . format ( cmdStatusLine ) ) return responseLines
Write data to the modem .
49,883
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
49,884
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
49,885
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
49,886
def dial ( self , number , timeout = 5 , callStatusUpdateCallbackFunc = None ) : if self . _waitForCallInitUpdate : self . _dialEvent = threading . Event ( ) try : self . write ( 'ATD{0};' . format ( number ) , timeout = timeout , waitForResponse = self . _waitForAtdResponse ) except Exception : self . _dialEvent = None raise else : 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 call = Call ( self , callId , callType , number , callStatusUpdateCallbackFunc ) self . activeCalls [ callId ] = call return call if self . _mustPollCallStatus : 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 : self . _dialEvent = None raise TimeoutException ( )
Calls the specified phone number using a voice phone call
49,887
def _handleCallInitiated ( self , regexMatch , callId = None , callType = 1 ) : if self . _dialEvent : if regexMatch : groups = regexMatch . groups ( ) if len ( groups ) >= 2 : self . _dialResponse = ( int ( groups [ 0 ] ) , int ( groups [ 1 ] ) ) else : self . _dialResponse = ( int ( groups [ 0 ] ) , 1 ) else : self . _dialResponse = callId , callType self . _dialEvent . set ( )
Handler for outgoing call initiated event notification line
49,888
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 : for call in dictValuesIter ( self . activeCalls ) : if call . answered == False and type ( call ) == Call : call . answered = True return else : self . activeCalls [ callId ] . answered = True
Handler for outgoing call answered event notification line
49,889
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
49,890
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 ) if report . reference in self . sentSms : self . sentSms [ report . reference ] . report = report if self . _smsStatusReportEvent : self . _smsStatusReportEvent . set ( ) else : self . smsStatusReportCallback ( report )
Handler for SMS status reports
49,891
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 .
49,892
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
49,893
def _cursorLeft ( self ) : if self . cursorPos > 0 : self . cursorPos -= 1 sys . stdout . write ( console . CURSOR_LEFT ) sys . stdout . flush ( )
Handles cursor left events
49,894
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
49,895
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
49,896
def _handleBackspace ( self ) : if self . cursorPos > 0 : self . inputBuffer = self . inputBuffer [ 0 : self . cursorPos - 1 ] + self . inputBuffer [ self . cursorPos : ] self . cursorPos -= 1 self . _refreshInputPrompt ( len ( self . inputBuffer ) + 1 )
Handles backspace characters
49,897
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
49,898
def _handleEnd ( self ) : self . cursorPos = len ( self . inputBuffer ) self . _refreshInputPrompt ( len ( self . inputBuffer ) )
Handles end character
49,899
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 : self . __printCommandSyntax ( prefix ) else : 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