idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
227,800 | def setup_es ( hosts , port , use_ssl = False , auth = None ) : kwargs = dict ( hosts = hosts or [ 'localhost' ] , port = port or 9200 , use_ssl = use_ssl , ) if auth : kwargs . update ( http_auth = auth ) CLIENT = Elasticsearch ( * * kwargs ) S = Search ( using = CLIENT , index = "geonames" ) return S | Setup an Elasticsearch connection | 95 | 5 |
227,801 | def _feature_country_mentions ( self , doc ) : c_list = [ ] for i in doc . ents : try : country = self . _both_codes [ i . text ] c_list . append ( country ) except KeyError : pass count = Counter ( c_list ) . most_common ( ) try : top , top_count = count [ 0 ] except : top = "" top_count = 0 try : two , two_count = count [ 1 ] except : two = "" two_count = 0 countries = ( top , top_count , two , two_count ) return countries | Given a document count how many times different country names and adjectives are mentioned . These are features used in the country picking phase . | 131 | 26 |
227,802 | def clean_entity ( self , ent ) : dump_list = [ 'province' , 'the' , 'area' , 'airport' , 'district' , 'square' , 'town' , 'village' , 'prison' , "river" , "valley" , "provincial" , "prison" , "region" , "municipality" , "state" , "territory" , "of" , "in" , "county" , "central" ] # maybe have 'city'? Works differently in different countries # also, "District of Columbia". Might need to use cap/no cap keep_positions = [ ] for word in ent : if word . text . lower ( ) not in dump_list : keep_positions . append ( word . i ) keep_positions = np . asarray ( keep_positions ) try : new_ent = ent . doc [ keep_positions . min ( ) : keep_positions . max ( ) + 1 ] # can't set directly #new_ent.label_.__set__(ent.label_) except ValueError : new_ent = ent return new_ent | Strip out extra words that often get picked up by spaCy s NER . | 253 | 17 |
227,803 | def _feature_most_alternative ( self , results , full_results = False ) : try : alt_names = [ len ( i [ 'alternativenames' ] ) for i in results [ 'hits' ] [ 'hits' ] ] most_alt = results [ 'hits' ] [ 'hits' ] [ np . array ( alt_names ) . argmax ( ) ] if full_results : return most_alt else : return most_alt [ 'country_code3' ] except ( IndexError , ValueError , TypeError ) : return "" | Find the placename with the most alternative names and return its country . More alternative names are a rough measure of importance . | 125 | 24 |
227,804 | def _feature_most_population ( self , results ) : try : populations = [ i [ 'population' ] for i in results [ 'hits' ] [ 'hits' ] ] most_pop = results [ 'hits' ] [ 'hits' ] [ np . array ( populations ) . astype ( "int" ) . argmax ( ) ] return most_pop [ 'country_code3' ] except Exception as e : return "" | Find the placename with the largest population and return its country . More population is a rough measure of importance . | 98 | 22 |
227,805 | def _feature_word_embedding ( self , text ) : try : simils = np . dot ( self . _prebuilt_vec , text . vector ) except Exception as e : #print("Vector problem, ", Exception, e) return { "country_1" : "" , "confid_a" : 0 , "confid_b" : 0 , "country_2" : "" } ranks = simils . argsort ( ) [ : : - 1 ] confid = simils . max ( ) confid2 = simils [ ranks [ 0 ] ] - simils [ ranks [ 1 ] ] if confid == 0 or confid2 == 0 : return "" country_code = self . _cts [ str ( self . _ct_nlp [ ranks [ 0 ] ] ) ] country_picking = { "country_1" : country_code , "confid_a" : confid , "confid_b" : confid2 , "country_2" : self . _cts [ str ( self . _ct_nlp [ ranks [ 1 ] ] ) ] } return country_picking | Given a word guess the appropriate country by word vector . | 237 | 11 |
227,806 | def _feature_first_back ( self , results ) : try : first_back = results [ 'hits' ] [ 'hits' ] [ 0 ] [ 'country_code3' ] except ( TypeError , IndexError ) : # usually occurs if no Geonames result first_back = "" try : second_back = results [ 'hits' ] [ 'hits' ] [ 1 ] [ 'country_code3' ] except ( TypeError , IndexError ) : second_back = "" top = ( first_back , second_back ) return top | Get the country of the first two results back from geonames . | 123 | 14 |
227,807 | def is_country ( self , text ) : ct_list = self . _just_cts . keys ( ) if text in ct_list : return True else : return False | Check if a piece of text is in the list of countries | 40 | 12 |
227,808 | def query_geonames ( self , placename ) : # first first, try for country name if self . is_country ( placename ) : q = { "multi_match" : { "query" : placename , "fields" : [ 'name' , 'asciiname' , 'alternativenames' ] , "type" : "phrase" } } res = self . conn . filter ( "term" , feature_code = 'PCLI' ) . query ( q ) [ 0 : 5 ] . execute ( ) # always 5 else : # second, try for an exact phrase match q = { "multi_match" : { "query" : placename , "fields" : [ 'name^5' , 'asciiname^5' , 'alternativenames' ] , "type" : "phrase" } } res = self . conn . query ( q ) [ 0 : 50 ] . execute ( ) # if no results, use some fuzziness, but still require all terms to be present. # Fuzzy is not allowed in "phrase" searches. if res . hits . total == 0 : # tried wrapping this in a {"constant_score" : {"query": ... but made it worse q = { "multi_match" : { "query" : placename , "fields" : [ 'name' , 'asciiname' , 'alternativenames' ] , "fuzziness" : 1 , "operator" : "and" } } res = self . conn . query ( q ) [ 0 : 50 ] . execute ( ) es_result = utilities . structure_results ( res ) return es_result | Wrap search parameters into an elasticsearch query to the geonames index and return results . | 359 | 19 |
227,809 | def query_geonames_country ( self , placename , country ) : # first, try for an exact phrase match q = { "multi_match" : { "query" : placename , "fields" : [ 'name^5' , 'asciiname^5' , 'alternativenames' ] , "type" : "phrase" } } res = self . conn . filter ( "term" , country_code3 = country ) . query ( q ) [ 0 : 50 ] . execute ( ) # if no results, use some fuzziness, but still require all terms to be present. # Fuzzy is not allowed in "phrase" searches. if res . hits . total == 0 : # tried wrapping this in a {"constant_score" : {"query": ... but made it worse q = { "multi_match" : { "query" : placename , "fields" : [ 'name' , 'asciiname' , 'alternativenames' ] , "fuzziness" : 1 , "operator" : "and" } } res = self . conn . filter ( "term" , country_code3 = country ) . query ( q ) [ 0 : 50 ] . execute ( ) out = utilities . structure_results ( res ) return out | Like query_geonames but this time limited to a specified country . | 277 | 14 |
227,810 | def make_country_matrix ( self , loc ) : top = loc [ 'features' ] [ 'ct_mention' ] top_count = loc [ 'features' ] [ 'ctm_count1' ] two = loc [ 'features' ] [ 'ct_mention2' ] two_count = loc [ 'features' ] [ 'ctm_count2' ] word_vec = loc [ 'features' ] [ 'word_vec' ] first_back = loc [ 'features' ] [ 'first_back' ] most_alt = loc [ 'features' ] [ 'most_alt' ] most_pop = loc [ 'features' ] [ 'most_pop' ] possible_labels = set ( [ top , two , word_vec , first_back , most_alt , most_pop ] ) possible_labels = [ i for i in possible_labels if i ] X_mat = [ ] for label in possible_labels : inputs = np . array ( [ word_vec , first_back , most_alt , most_pop ] ) x = inputs == label x = np . asarray ( ( x * 2 ) - 1 ) # convert to -1, 1 # get missing values exists = inputs != "" exists = np . asarray ( ( exists * 2 ) - 1 ) counts = np . asarray ( [ top_count , two_count ] ) # cludgy, should be up with "inputs" right = np . asarray ( [ top , two ] ) == label right = right * 2 - 1 right [ counts == 0 ] = 0 # get correct values features = np . concatenate ( [ x , exists , counts , right ] ) X_mat . append ( np . asarray ( features ) ) keras_inputs = { "labels" : possible_labels , "matrix" : np . asmatrix ( X_mat ) } return keras_inputs | Create features for all possible country labels return as matrix for keras . | 422 | 14 |
227,811 | def infer_country ( self , doc ) : if not hasattr ( doc , "ents" ) : doc = nlp ( doc ) proced = self . make_country_features ( doc , require_maj = False ) if not proced : pass # logging! #print("Nothing came back from make_country_features") feat_list = [ ] #proced = self.ent_list_to_matrix(proced) for loc in proced : feat = self . make_country_matrix ( loc ) #labels = loc['labels'] feat_list . append ( feat ) #try: # for each potential country... for n , i in enumerate ( feat_list ) : labels = i [ 'labels' ] try : prediction = self . country_model . predict ( i [ 'matrix' ] ) . transpose ( ) [ 0 ] ranks = prediction . argsort ( ) [ : : - 1 ] labels = np . asarray ( labels ) [ ranks ] prediction = prediction [ ranks ] except ValueError : prediction = np . array ( [ 0 ] ) labels = np . array ( [ "" ] ) loc [ 'country_predicted' ] = labels [ 0 ] loc [ 'country_conf' ] = prediction [ 0 ] loc [ 'all_countries' ] = labels loc [ 'all_confidence' ] = prediction return proced | NLP a doc find its entities get their features and return the model s country guess for each . Maybe use a better name . | 293 | 26 |
227,812 | def get_admin1 ( self , country_code2 , admin1_code ) : lookup_key = "." . join ( [ country_code2 , admin1_code ] ) try : admin1_name = self . _admin1_dict [ lookup_key ] return admin1_name except KeyError : #print("No admin code found for country {} and code {}".format(country_code2, admin1_code)) return "NA" | Convert a geonames admin1 code to the associated place name . | 98 | 15 |
227,813 | def ranker ( self , X , meta ) : # total score is just a sum of each row total_score = X . sum ( axis = 1 ) . transpose ( ) total_score = np . squeeze ( np . asarray ( total_score ) ) # matrix to array ranks = total_score . argsort ( ) ranks = ranks [ : : - 1 ] # sort the list of dicts according to ranks sorted_meta = [ meta [ r ] for r in ranks ] sorted_X = X [ ranks ] return ( sorted_X , sorted_meta ) | Sort the place features list by the score of its relevance . | 121 | 12 |
227,814 | def format_for_prodigy ( self , X , meta , placename , return_feature_subset = False ) : all_tasks = [ ] sorted_X , sorted_meta = self . ranker ( X , meta ) sorted_meta = sorted_meta [ : 4 ] sorted_X = sorted_X [ : 4 ] for n , i in enumerate ( sorted_meta ) : feature_code = i [ 'feature_code' ] try : fc = self . _code_to_text [ feature_code ] except KeyError : fc = '' text = '' . join ( [ '"' , i [ 'place_name' ] , '"' , ", a " , fc , " in " , i [ 'country_code3' ] , ", id: " , i [ 'geonameid' ] ] ) d = { "id" : n + 1 , "text" : text } all_tasks . append ( d ) if return_feature_subset : return ( all_tasks , sorted_meta , sorted_X ) else : return all_tasks | Given a feature matrix geonames data and the original query construct a prodigy task . | 238 | 18 |
227,815 | def format_geonames ( self , entry , searchterm = None ) : try : lat , lon = entry [ 'coordinates' ] . split ( "," ) new_res = { "admin1" : self . get_admin1 ( entry [ 'country_code2' ] , entry [ 'admin1_code' ] ) , "lat" : lat , "lon" : lon , "country_code3" : entry [ "country_code3" ] , "geonameid" : entry [ "geonameid" ] , "place_name" : entry [ "name" ] , "feature_class" : entry [ "feature_class" ] , "feature_code" : entry [ "feature_code" ] } return new_res except ( IndexError , TypeError ) : # two conditions for these errors: # 1. there are no results for some reason (Index) # 2. res is set to "" because the country model was below the thresh new_res = { "admin1" : "" , "lat" : "" , "lon" : "" , "country_code3" : "" , "geonameid" : "" , "place_name" : "" , "feature_class" : "" , "feature_code" : "" } return new_res | Pull out just the fields we want from a geonames entry | 281 | 13 |
227,816 | def clean_proced ( self , proced ) : for loc in proced : try : del loc [ 'all_countries' ] except KeyError : pass try : del loc [ 'matrix' ] except KeyError : pass try : del loc [ 'all_confidence' ] except KeyError : pass try : del loc [ 'place_confidence' ] except KeyError : pass try : del loc [ 'text' ] except KeyError : pass try : del loc [ 'label' ] except KeyError : pass try : del loc [ 'features' ] except KeyError : pass return proced | Small helper function to delete the features from the final dictionary . These features are mostly interesting for debugging but won t be relevant for most users . | 124 | 28 |
227,817 | def geoparse ( self , doc , verbose = False ) : if not hasattr ( doc , "ents" ) : doc = nlp ( doc ) proced = self . infer_country ( doc ) if not proced : return [ ] # logging! #print("Nothing came back from infer_country...") if self . threads : pool = ThreadPool ( len ( proced ) ) results = pool . map ( self . proc_lookup_country , proced ) pool . close ( ) pool . join ( ) else : results = [ ] for loc in proced : # if the confidence is too low, don't use the country info if loc [ 'country_conf' ] > self . country_threshold : res = self . query_geonames_country ( loc [ 'word' ] , loc [ 'country_predicted' ] ) results . append ( res ) else : results . append ( "" ) for n , loc in enumerate ( proced ) : res = results [ n ] try : _ = res [ 'hits' ] [ 'hits' ] # If there's no geonames result, what to do? # For now, just continue. # In the future, delete? Or add an empty "loc" field? except ( TypeError , KeyError ) : continue # Pick the best place X , meta = self . features_for_rank ( loc , res ) if X . shape [ 1 ] == 0 : # This happens if there are no results... continue all_tasks , sorted_meta , sorted_X = self . format_for_prodigy ( X , meta , loc [ 'word' ] , return_feature_subset = True ) fl_pad = np . pad ( sorted_X , ( ( 0 , 4 - sorted_X . shape [ 0 ] ) , ( 0 , 0 ) ) , 'constant' ) fl_unwrap = fl_pad . flatten ( ) prediction = self . rank_model . predict ( np . asmatrix ( fl_unwrap ) ) place_confidence = prediction . max ( ) loc [ 'geo' ] = sorted_meta [ prediction . argmax ( ) ] loc [ 'place_confidence' ] = place_confidence if not verbose : proced = self . clean_proced ( proced ) return proced | Main geoparsing function . Text to extracted resolved entities . | 488 | 12 |
227,818 | def batch_geoparse ( self , text_list ) : if not self . threads : print ( "batch_geoparsed should be used with threaded searches. Please set `threads=True` when initializing the geoparser." ) nlped_docs = list ( nlp . pipe ( text_list , as_tuples = False , n_threads = multiprocessing . cpu_count ( ) ) ) processed = [ ] for i in tqdm ( nlped_docs , disable = not self . progress ) : p = self . geoparse ( i ) processed . append ( p ) return processed | Batch geoparsing function . Take in a list of text documents and return a list of lists of the geoparsed documents . The speed improvements come exclusively from using spaCy s nlp . pipe . | 135 | 42 |
227,819 | def entry_to_matrix ( prodigy_entry ) : doc = prodigy_entry [ 'text' ] doc = nlp ( doc ) geo_proced = geo . process_text ( doc , require_maj = False ) # find the geoproced entity that matches the Prodigy entry ent_text = np . asarray ( [ gp [ 'word' ] for gp in geo_proced ] ) # get mask for correct ent #print(ent_text) match = ent_text == entry [ 'meta' ] [ 'word' ] #print("match: ", match) anti_match = np . abs ( match - 1 ) #print("Anti-match ", anti_match) match_position = match . argmax ( ) geo_proc = geo_proced [ match_position ] iso = geo . cts [ prodigy_entry [ 'label' ] ] # convert country text label to ISO feat = geo . features_to_matrix ( geo_proc ) answer_x = feat [ 'matrix' ] label = np . asarray ( feat [ 'labels' ] ) if prodigy_entry [ 'answer' ] == "accept" : answer_binary = label == iso answer_binary = answer_binary . astype ( 'int' ) #print(answer_x.shape) #print(answer_binary.shape) elif prodigy_entry [ 'answer' ] == "reject" : # all we know is that the label that was presented is wrong. # just return the corresponding row in the feature matrix, # and force the label to be 0 answer_binary = label == iso answer_x = answer_x [ answer_binary , : ] # just take the row corresponding to the answer answer_binary = np . asarray ( [ 0 ] ) # set the outcome to 0 because reject # NEED TO SHARE LABELS ACROSS! THE CORRECT ONE MIGHT NOT EVEN APPEAR FOR ALL ENTITIES x = feat [ 'matrix' ] other_x = x [ anti_match , : ] #print(other_x) #print(label[anti_match]) # here, need to get the rows corresponding to the correct label # print(geo_proc['meta']) # here's where we get the other place name features. # Need to: # 1. do features_to_matrix but use the label of the current entity # to determine 0/1 in the feature matrix # 2. put them all into one big feature matrix, # 3. ...ordering by distance? And need to decide max entity length # 4. also include these distances as one of the features #print(answer_x.shape[0]) #print(answer_binary.shape[0]) try : if answer_x . shape [ 0 ] == answer_binary . shape [ 0 ] : return ( answer_x , answer_binary ) except : pass | Take in a line from the labeled json and return a vector of labels and a matrix of features for training . | 622 | 22 |
227,820 | def refresh_client ( self ) : req = self . session . post ( self . _fmip_refresh_url , params = self . params , data = json . dumps ( { 'clientContext' : { 'fmly' : True , 'shouldLocate' : True , 'selectedDevice' : 'all' , } } ) ) self . response = req . json ( ) for device_info in self . response [ 'content' ] : device_id = device_info [ 'id' ] if device_id not in self . _devices : self . _devices [ device_id ] = AppleDevice ( device_info , self . session , self . params , manager = self , sound_url = self . _fmip_sound_url , lost_url = self . _fmip_lost_url , message_url = self . _fmip_message_url , ) else : self . _devices [ device_id ] . update ( device_info ) if not self . _devices : raise PyiCloudNoDevicesException ( ) | Refreshes the FindMyiPhoneService endpoint | 227 | 9 |
227,821 | def status ( self , additional = [ ] ) : self . manager . refresh_client ( ) fields = [ 'batteryLevel' , 'deviceDisplayName' , 'deviceStatus' , 'name' ] fields += additional properties = { } for field in fields : properties [ field ] = self . content . get ( field ) return properties | Returns status information for device . | 71 | 6 |
227,822 | def lost_device ( self , number , text = 'This iPhone has been lost. Please call me.' , newpasscode = "" ) : data = json . dumps ( { 'text' : text , 'userText' : True , 'ownerNbr' : number , 'lostModeEnabled' : True , 'trackingEnabled' : True , 'device' : self . content [ 'id' ] , 'passcode' : newpasscode } ) self . session . post ( self . lost_url , params = self . params , data = data ) | Send a request to the device to trigger lost mode . | 118 | 11 |
227,823 | def events ( self , from_dt = None , to_dt = None ) : self . refresh_client ( from_dt , to_dt ) return self . response [ 'Event' ] | Retrieves events for a given date range by default this month . | 41 | 14 |
227,824 | def calendars ( self ) : today = datetime . today ( ) first_day , last_day = monthrange ( today . year , today . month ) from_dt = datetime ( today . year , today . month , first_day ) to_dt = datetime ( today . year , today . month , last_day ) params = dict ( self . params ) params . update ( { 'lang' : 'en-us' , 'usertz' : get_localzone ( ) . zone , 'startDate' : from_dt . strftime ( '%Y-%m-%d' ) , 'endDate' : to_dt . strftime ( '%Y-%m-%d' ) } ) req = self . session . get ( self . _calendars , params = params ) self . response = req . json ( ) return self . response [ 'Collection' ] | Retrieves calendars for this month | 194 | 7 |
227,825 | def create_pickled_data ( idevice , filename ) : data = { } for x in idevice . content : data [ x ] = idevice . content [ x ] location = filename pickle_file = open ( location , 'wb' ) pickle . dump ( data , pickle_file , protocol = pickle . HIGHEST_PROTOCOL ) pickle_file . close ( ) | This helper will output the idevice to a pickled file named after the passed filename . | 87 | 18 |
227,826 | def refresh_client ( self , from_dt = None , to_dt = None ) : params_contacts = dict ( self . params ) params_contacts . update ( { 'clientVersion' : '2.1' , 'locale' : 'en_US' , 'order' : 'last,first' , } ) req = self . session . get ( self . _contacts_refresh_url , params = params_contacts ) self . response = req . json ( ) params_refresh = dict ( self . params ) params_refresh . update ( { 'prefToken' : req . json ( ) [ "prefToken" ] , 'syncToken' : req . json ( ) [ "syncToken" ] , } ) self . session . post ( self . _contacts_changeset_url , params = params_refresh ) req = self . session . get ( self . _contacts_refresh_url , params = params_contacts ) self . response = req . json ( ) | Refreshes the ContactsService endpoint ensuring that the contacts data is up - to - date . | 224 | 20 |
227,827 | def authenticate ( self ) : logger . info ( "Authenticating as %s" , self . user [ 'apple_id' ] ) data = dict ( self . user ) # We authenticate every time, so "remember me" is not needed data . update ( { 'extended_login' : False } ) try : req = self . session . post ( self . _base_login_url , params = self . params , data = json . dumps ( data ) ) except PyiCloudAPIResponseError as error : msg = 'Invalid email/password combination.' raise PyiCloudFailedLoginException ( msg , error ) resp = req . json ( ) self . params . update ( { 'dsid' : resp [ 'dsInfo' ] [ 'dsid' ] } ) if not os . path . exists ( self . _cookie_directory ) : os . mkdir ( self . _cookie_directory ) self . session . cookies . save ( ) logger . debug ( "Cookies saved to %s" , self . _get_cookiejar_path ( ) ) self . data = resp self . webservices = self . data [ 'webservices' ] logger . info ( "Authentication completed successfully" ) logger . debug ( self . params ) | Handles authentication and persists the X - APPLE - WEB - KB cookie so that subsequent logins will not cause additional e - mails from Apple . | 273 | 32 |
227,828 | def trusted_devices ( self ) : request = self . session . get ( '%s/listDevices' % self . _setup_endpoint , params = self . params ) return request . json ( ) . get ( 'devices' ) | Returns devices trusted for two - step authentication . | 52 | 9 |
227,829 | def send_verification_code ( self , device ) : data = json . dumps ( device ) request = self . session . post ( '%s/sendVerificationCode' % self . _setup_endpoint , params = self . params , data = data ) return request . json ( ) . get ( 'success' , False ) | Requests that a verification code is sent to the given device | 72 | 12 |
227,830 | def validate_verification_code ( self , device , code ) : device . update ( { 'verificationCode' : code , 'trustBrowser' : True } ) data = json . dumps ( device ) try : request = self . session . post ( '%s/validateVerificationCode' % self . _setup_endpoint , params = self . params , data = data ) except PyiCloudAPIResponseError as error : if error . code == - 21669 : # Wrong verification code return False raise # Re-authenticate, which will both update the HSA data, and # ensure that we save the X-APPLE-WEBAUTH-HSA-TRUST cookie. self . authenticate ( ) return not self . requires_2sa | Verifies a verification code received on a trusted device | 163 | 10 |
227,831 | def devices ( self ) : service_root = self . webservices [ 'findme' ] [ 'url' ] return FindMyiPhoneServiceManager ( service_root , self . session , self . params ) | Return all devices . | 45 | 4 |
227,832 | def send ( r , pool = None , stream = False ) : if pool is not None : return pool . spawn ( r . send , stream = stream ) return gevent . spawn ( r . send , stream = stream ) | Sends the request object using the specified pool . If a pool isn t specified this method blocks . Pools are useful because you can specify size and can hence limit concurrency . | 47 | 36 |
227,833 | def imap ( requests , stream = False , size = 2 , exception_handler = None ) : pool = Pool ( size ) def send ( r ) : return r . send ( stream = stream ) for request in pool . imap_unordered ( send , requests ) : if request . response is not None : yield request . response elif exception_handler : ex_result = exception_handler ( request , request . exception ) if ex_result is not None : yield ex_result pool . join ( ) | Concurrently converts a generator object of Requests to a generator of Responses . | 107 | 16 |
227,834 | def set_user_profile ( self , displayname = None , avatar_url = None , reason = "Changing room profile information" ) : member = self . client . api . get_membership ( self . room_id , self . client . user_id ) if member [ "membership" ] != "join" : raise Exception ( "Can't set profile if you have not joined the room." ) if displayname is None : displayname = member [ "displayname" ] if avatar_url is None : avatar_url = member [ "avatar_url" ] self . client . api . set_membership ( self . room_id , self . client . user_id , 'join' , reason , { "displayname" : displayname , "avatar_url" : avatar_url } ) | Set user profile within a room . | 175 | 7 |
227,835 | def display_name ( self ) : if self . name : return self . name elif self . canonical_alias : return self . canonical_alias # Member display names without me members = [ u . get_display_name ( self ) for u in self . get_joined_members ( ) if self . client . user_id != u . user_id ] members . sort ( ) if len ( members ) == 1 : return members [ 0 ] elif len ( members ) == 2 : return "{0} and {1}" . format ( members [ 0 ] , members [ 1 ] ) elif len ( members ) > 2 : return "{0} and {1} others" . format ( members [ 0 ] , len ( members ) - 1 ) else : # len(members) <= 0 or not an integer # TODO i18n return "Empty room" | Calculates the display name for a room . | 183 | 10 |
227,836 | def send_text ( self , text ) : return self . client . api . send_message ( self . room_id , text ) | Send a plain text message to the room . | 29 | 9 |
227,837 | def send_html ( self , html , body = None , msgtype = "m.text" ) : return self . client . api . send_message_event ( self . room_id , "m.room.message" , self . get_html_content ( html , body , msgtype ) ) | Send an html formatted message . | 66 | 6 |
227,838 | def send_file ( self , url , name , * * fileinfo ) : return self . client . api . send_content ( self . room_id , url , name , "m.file" , extra_information = fileinfo ) | Send a pre - uploaded file to the room . | 51 | 10 |
227,839 | def send_image ( self , url , name , * * imageinfo ) : return self . client . api . send_content ( self . room_id , url , name , "m.image" , extra_information = imageinfo ) | Send a pre - uploaded image to the room . | 51 | 10 |
227,840 | def send_location ( self , geo_uri , name , thumb_url = None , * * thumb_info ) : return self . client . api . send_location ( self . room_id , geo_uri , name , thumb_url , thumb_info ) | Send a location to the room . | 57 | 7 |
227,841 | def send_video ( self , url , name , * * videoinfo ) : return self . client . api . send_content ( self . room_id , url , name , "m.video" , extra_information = videoinfo ) | Send a pre - uploaded video to the room . | 51 | 10 |
227,842 | def send_audio ( self , url , name , * * audioinfo ) : return self . client . api . send_content ( self . room_id , url , name , "m.audio" , extra_information = audioinfo ) | Send a pre - uploaded audio to the room . | 51 | 10 |
227,843 | def redact_message ( self , event_id , reason = None ) : return self . client . api . redact_event ( self . room_id , event_id , reason ) | Redacts the message with specified event_id for the given reason . | 41 | 14 |
227,844 | def add_listener ( self , callback , event_type = None ) : listener_id = uuid4 ( ) self . listeners . append ( { 'uid' : listener_id , 'callback' : callback , 'event_type' : event_type } ) return listener_id | Add a callback handler for events going to this room . | 62 | 11 |
227,845 | def remove_listener ( self , uid ) : self . listeners [ : ] = ( listener for listener in self . listeners if listener [ 'uid' ] != uid ) | Remove listener with given uid . | 38 | 7 |
227,846 | def add_ephemeral_listener ( self , callback , event_type = None ) : listener_id = uuid4 ( ) self . ephemeral_listeners . append ( { 'uid' : listener_id , 'callback' : callback , 'event_type' : event_type } ) return listener_id | Add a callback handler for ephemeral events going to this room . | 71 | 14 |
227,847 | def remove_ephemeral_listener ( self , uid ) : self . ephemeral_listeners [ : ] = ( listener for listener in self . ephemeral_listeners if listener [ 'uid' ] != uid ) | Remove ephemeral listener with given uid . | 52 | 10 |
227,848 | def invite_user ( self , user_id ) : try : self . client . api . invite_user ( self . room_id , user_id ) return True except MatrixRequestError : return False | Invite a user to this room . | 43 | 8 |
227,849 | def kick_user ( self , user_id , reason = "" ) : try : self . client . api . kick_user ( self . room_id , user_id ) return True except MatrixRequestError : return False | Kick a user from this room . | 47 | 7 |
227,850 | def leave ( self ) : try : self . client . api . leave_room ( self . room_id ) del self . client . rooms [ self . room_id ] return True except MatrixRequestError : return False | Leave the room . | 46 | 4 |
227,851 | def update_room_name ( self ) : try : response = self . client . api . get_room_name ( self . room_id ) if "name" in response and response [ "name" ] != self . name : self . name = response [ "name" ] return True else : return False except MatrixRequestError : return False | Updates self . name and returns True if room name has changed . | 73 | 14 |
227,852 | def set_room_name ( self , name ) : try : self . client . api . set_room_name ( self . room_id , name ) self . name = name return True except MatrixRequestError : return False | Return True if room name successfully changed . | 48 | 8 |
227,853 | def send_state_event ( self , event_type , content , state_key = "" ) : return self . client . api . send_state_event ( self . room_id , event_type , content , state_key ) | Send a state event to the room . | 51 | 8 |
227,854 | def update_room_topic ( self ) : try : response = self . client . api . get_room_topic ( self . room_id ) if "topic" in response and response [ "topic" ] != self . topic : self . topic = response [ "topic" ] return True else : return False except MatrixRequestError : return False | Updates self . topic and returns True if room topic has changed . | 73 | 14 |
227,855 | def set_room_topic ( self , topic ) : try : self . client . api . set_room_topic ( self . room_id , topic ) self . topic = topic return True except MatrixRequestError : return False | Set room topic . | 48 | 4 |
227,856 | def update_aliases ( self ) : try : response = self . client . api . get_room_state ( self . room_id ) for chunk in response : if "content" in chunk and "aliases" in chunk [ "content" ] : if chunk [ "content" ] [ "aliases" ] != self . aliases : self . aliases = chunk [ "content" ] [ "aliases" ] return True else : return False except MatrixRequestError : return False | Get aliases information from room state . | 102 | 7 |
227,857 | def add_room_alias ( self , room_alias ) : try : self . client . api . set_room_alias ( self . room_id , room_alias ) return True except MatrixRequestError : return False | Add an alias to the room and return True if successful . | 47 | 12 |
227,858 | def backfill_previous_messages ( self , reverse = False , limit = 10 ) : res = self . client . api . get_room_messages ( self . room_id , self . prev_batch , direction = "b" , limit = limit ) events = res [ "chunk" ] if not reverse : events = reversed ( events ) for event in events : self . _put_event ( event ) | Backfill handling of previous messages . | 91 | 7 |
227,859 | def modify_user_power_levels ( self , users = None , users_default = None ) : try : content = self . client . api . get_power_levels ( self . room_id ) if users_default : content [ "users_default" ] = users_default if users : if "users" in content : content [ "users" ] . update ( users ) else : content [ "users" ] = users # Remove any keys with value None for user , power_level in list ( content [ "users" ] . items ( ) ) : if power_level is None : del content [ "users" ] [ user ] self . client . api . set_power_levels ( self . room_id , content ) return True except MatrixRequestError : return False | Modify the power level for a subset of users | 166 | 10 |
227,860 | def modify_required_power_levels ( self , events = None , * * kwargs ) : try : content = self . client . api . get_power_levels ( self . room_id ) content . update ( kwargs ) for key , value in list ( content . items ( ) ) : if value is None : del content [ key ] if events : if "events" in content : content [ "events" ] . update ( events ) else : content [ "events" ] = events # Remove any keys with value None for event , power_level in list ( content [ "events" ] . items ( ) ) : if power_level is None : del content [ "events" ] [ event ] self . client . api . set_power_levels ( self . room_id , content ) return True except MatrixRequestError : return False | Modifies room power level requirements . | 181 | 7 |
227,861 | def set_invite_only ( self , invite_only ) : join_rule = "invite" if invite_only else "public" try : self . client . api . set_join_rule ( self . room_id , join_rule ) self . invite_only = invite_only return True except MatrixRequestError : return False | Set how the room can be joined . | 73 | 8 |
227,862 | def set_guest_access ( self , allow_guests ) : guest_access = "can_join" if allow_guests else "forbidden" try : self . client . api . set_guest_access ( self . room_id , guest_access ) self . guest_access = allow_guests return True except MatrixRequestError : return False | Set whether guests can join the room and return True if successful . | 79 | 13 |
227,863 | def enable_encryption ( self ) : try : self . send_state_event ( "m.room.encryption" , { "algorithm" : "m.megolm.v1.aes-sha2" } ) self . encrypted = True return True except MatrixRequestError : return False | Enables encryption in the room . | 66 | 7 |
227,864 | def example ( host , user , password , token ) : client = None try : if token : print ( 'token login' ) client = MatrixClient ( host , token = token , user_id = user ) else : print ( 'password login' ) client = MatrixClient ( host ) token = client . login_with_password ( user , password ) print ( 'got token: %s' % token ) except MatrixRequestError as e : print ( e ) if e . code == 403 : print ( "Bad username or password" ) exit ( 2 ) elif e . code == 401 : print ( "Bad username or token" ) exit ( 3 ) else : print ( "Verify server details." ) exit ( 4 ) except MissingSchema as e : print ( e ) print ( "Bad formatting of URL." ) exit ( 5 ) except InvalidSchema as e : print ( e ) print ( "Invalid URL schema" ) exit ( 6 ) print ( "is in rooms" ) for room_id , room in client . get_rooms ( ) . items ( ) : print ( room_id ) | run the example . | 233 | 4 |
227,865 | def main ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( "--host" , type = str , required = True ) parser . add_argument ( "--user" , type = str , required = True ) parser . add_argument ( "--password" , type = str ) parser . add_argument ( "--token" , type = str ) args = parser . parse_args ( ) if not args . password and not args . token : print ( 'password or token is required' ) exit ( 1 ) example ( args . host , args . user , args . password , args . token ) | Main entry . | 134 | 3 |
227,866 | def sync ( self , since = None , timeout_ms = 30000 , filter = None , full_state = None , set_presence = None ) : request = { # non-integer timeouts appear to cause issues "timeout" : int ( timeout_ms ) } if since : request [ "since" ] = since if filter : request [ "filter" ] = filter if full_state : request [ "full_state" ] = json . dumps ( full_state ) if set_presence : request [ "set_presence" ] = set_presence return self . _send ( "GET" , "/sync" , query_params = request , api_path = MATRIX_V2_API_PATH ) | Perform a sync request . | 157 | 6 |
227,867 | def send_location ( self , room_id , geo_uri , name , thumb_url = None , thumb_info = None , timestamp = None ) : content_pack = { "geo_uri" : geo_uri , "msgtype" : "m.location" , "body" : name , } if thumb_url : content_pack [ "thumbnail_url" ] = thumb_url if thumb_info : content_pack [ "thumbnail_info" ] = thumb_info return self . send_message_event ( room_id , "m.room.message" , content_pack , timestamp = timestamp ) | Send m . location message event | 137 | 6 |
227,868 | def kick_user ( self , room_id , user_id , reason = "" ) : self . set_membership ( room_id , user_id , "leave" , reason ) | Calls set_membership with membership = leave for the user_id provided | 41 | 16 |
227,869 | def media_download ( self , mxcurl , allow_remote = True ) : query_params = { } if not allow_remote : query_params [ "allow_remote" ] = False if mxcurl . startswith ( 'mxc://' ) : return self . _send ( "GET" , mxcurl [ 6 : ] , api_path = "/_matrix/media/r0/download/" , query_params = query_params , return_json = False ) else : raise ValueError ( "MXC URL '%s' did not begin with 'mxc://'" % mxcurl ) | Download raw media from provided mxc URL . | 135 | 9 |
227,870 | def get_thumbnail ( self , mxcurl , width , height , method = 'scale' , allow_remote = True ) : if method not in [ 'scale' , 'crop' ] : raise ValueError ( "Unsupported thumb method '%s'" % method ) query_params = { "width" : width , "height" : height , "method" : method } if not allow_remote : query_params [ "allow_remote" ] = False if mxcurl . startswith ( 'mxc://' ) : return self . _send ( "GET" , mxcurl [ 6 : ] , query_params = query_params , api_path = "/_matrix/media/r0/thumbnail/" , return_json = False ) else : raise ValueError ( "MXC URL '%s' did not begin with 'mxc://'" % mxcurl ) | Download raw media thumbnail from provided mxc URL . | 194 | 10 |
227,871 | def get_url_preview ( self , url , ts = None ) : params = { 'url' : url } if ts : params [ 'ts' ] = ts return self . _send ( "GET" , "" , query_params = params , api_path = "/_matrix/media/r0/preview_url" ) | Get preview for URL . | 75 | 5 |
227,872 | def get_room_id ( self , room_alias ) : content = self . _send ( "GET" , "/directory/room/{}" . format ( quote ( room_alias ) ) ) return content . get ( "room_id" , None ) | Get room id from its alias . | 56 | 7 |
227,873 | def set_room_alias ( self , room_id , room_alias ) : data = { "room_id" : room_id } return self . _send ( "PUT" , "/directory/room/{}" . format ( quote ( room_alias ) ) , content = data ) | Set alias to room id | 63 | 5 |
227,874 | def set_join_rule ( self , room_id , join_rule ) : content = { "join_rule" : join_rule } return self . send_state_event ( room_id , "m.room.join_rules" , content ) | Set the rule for users wishing to join the room . | 56 | 11 |
227,875 | def set_guest_access ( self , room_id , guest_access ) : content = { "guest_access" : guest_access } return self . send_state_event ( room_id , "m.room.guest_access" , content ) | Set the guest access policy of the room . | 59 | 9 |
227,876 | def update_device_info ( self , device_id , display_name ) : content = { "display_name" : display_name } return self . _send ( "PUT" , "/devices/%s" % device_id , content = content ) | Update the display name of a device . | 56 | 8 |
227,877 | def delete_device ( self , auth_body , device_id ) : content = { "auth" : auth_body } return self . _send ( "DELETE" , "/devices/%s" % device_id , content = content ) | Deletes the given device and invalidates any access token associated with it . | 54 | 15 |
227,878 | def delete_devices ( self , auth_body , devices ) : content = { "auth" : auth_body , "devices" : devices } return self . _send ( "POST" , "/delete_devices" , content = content ) | Bulk deletion of devices . | 51 | 6 |
227,879 | def upload_keys ( self , device_keys = None , one_time_keys = None ) : content = { } if device_keys : content [ "device_keys" ] = device_keys if one_time_keys : content [ "one_time_keys" ] = one_time_keys return self . _send ( "POST" , "/keys/upload" , content = content ) | Publishes end - to - end encryption keys for the device . | 86 | 13 |
227,880 | def query_keys ( self , user_devices , timeout = None , token = None ) : content = { "device_keys" : user_devices } if timeout : content [ "timeout" ] = timeout if token : content [ "token" ] = token return self . _send ( "POST" , "/keys/query" , content = content ) | Query HS for public keys by user and optionally device . | 75 | 11 |
227,881 | def claim_keys ( self , key_request , timeout = None ) : content = { "one_time_keys" : key_request } if timeout : content [ "timeout" ] = timeout return self . _send ( "POST" , "/keys/claim" , content = content ) | Claims one - time keys for use in pre - key messages . | 62 | 14 |
227,882 | def key_changes ( self , from_token , to_token ) : params = { "from" : from_token , "to" : to_token } return self . _send ( "GET" , "/keys/changes" , query_params = params ) | Gets a list of users who have updated their device identity keys . | 57 | 14 |
227,883 | def send_to_device ( self , event_type , messages , txn_id = None ) : txn_id = txn_id if txn_id else self . _make_txn_id ( ) return self . _send ( "PUT" , "/sendToDevice/{}/{}" . format ( event_type , txn_id ) , content = { "messages" : messages } ) | Sends send - to - device events to a set of client devices . | 93 | 15 |
227,884 | def register_with_password ( self , username , password ) : response = self . api . register ( auth_body = { "type" : "m.login.dummy" } , kind = 'user' , username = username , password = password , ) return self . _post_registration ( response ) | Register for a new account on this HS . | 67 | 9 |
227,885 | def login_with_password_no_sync ( self , username , password ) : warn ( "login_with_password_no_sync is deprecated. Use login with sync=False." , DeprecationWarning ) return self . login ( username , password , sync = False ) | Deprecated . Use login with sync = False . | 59 | 10 |
227,886 | def login_with_password ( self , username , password , limit = 10 ) : warn ( "login_with_password is deprecated. Use login with sync=True." , DeprecationWarning ) return self . login ( username , password , limit , sync = True ) | Deprecated . Use login with sync = True . | 57 | 10 |
227,887 | def login ( self , username , password , limit = 10 , sync = True , device_id = None ) : response = self . api . login ( "m.login.password" , user = username , password = password , device_id = device_id ) self . user_id = response [ "user_id" ] self . token = response [ "access_token" ] self . hs = response [ "home_server" ] self . api . token = self . token self . device_id = response [ "device_id" ] if self . _encryption : self . olm_device = OlmDevice ( self . api , self . user_id , self . device_id , * * self . encryption_conf ) self . olm_device . upload_identity_keys ( ) self . olm_device . upload_one_time_keys ( ) if sync : """ Limit Filter """ self . sync_filter = '{ "room": { "timeline" : { "limit" : %i } } }' % limit self . _sync ( ) return self . token | Login to the homeserver . | 238 | 6 |
227,888 | def create_room ( self , alias = None , is_public = False , invitees = None ) : response = self . api . create_room ( alias = alias , is_public = is_public , invitees = invitees ) return self . _mkroom ( response [ "room_id" ] ) | Create a new room on the homeserver . | 67 | 9 |
227,889 | def add_listener ( self , callback , event_type = None ) : listener_uid = uuid4 ( ) # TODO: listeners should be stored in dict and accessed/deleted directly. Add # convenience method such that MatrixClient.listeners.new(Listener(...)) performs # MatrixClient.listeners[uuid4()] = Listener(...) self . listeners . append ( { 'uid' : listener_uid , 'callback' : callback , 'event_type' : event_type } ) return listener_uid | Add a listener that will send a callback when the client recieves an event . | 115 | 16 |
227,890 | def add_presence_listener ( self , callback ) : listener_uid = uuid4 ( ) self . presence_listeners [ listener_uid ] = callback return listener_uid | Add a presence listener that will send a callback when the client receives a presence update . | 40 | 17 |
227,891 | def listen_forever ( self , timeout_ms = 30000 , exception_handler = None , bad_sync_timeout = 5 ) : _bad_sync_timeout = bad_sync_timeout self . should_listen = True while ( self . should_listen ) : try : self . _sync ( timeout_ms ) _bad_sync_timeout = bad_sync_timeout # TODO: we should also handle MatrixHttpLibError for retry in case no response except MatrixRequestError as e : logger . warning ( "A MatrixRequestError occured during sync." ) if e . code >= 500 : logger . warning ( "Problem occured serverside. Waiting %i seconds" , bad_sync_timeout ) sleep ( bad_sync_timeout ) _bad_sync_timeout = min ( _bad_sync_timeout * 2 , self . bad_sync_timeout_limit ) elif exception_handler is not None : exception_handler ( e ) else : raise except Exception as e : logger . exception ( "Exception thrown during sync" ) if exception_handler is not None : exception_handler ( e ) else : raise | Keep listening for events forever . | 241 | 6 |
227,892 | def start_listener_thread ( self , timeout_ms = 30000 , exception_handler = None ) : try : thread = Thread ( target = self . listen_forever , args = ( timeout_ms , exception_handler ) ) thread . daemon = True self . sync_thread = thread self . should_listen = True thread . start ( ) except RuntimeError : e = sys . exc_info ( ) [ 0 ] logger . error ( "Error: unable to start thread. %s" , str ( e ) ) | Start a listener thread to listen for events in the background . | 113 | 12 |
227,893 | def stop_listener_thread ( self ) : if self . sync_thread : self . should_listen = False self . sync_thread . join ( ) self . sync_thread = None | Stop listener thread running in the background | 42 | 7 |
227,894 | def upload ( self , content , content_type , filename = None ) : try : response = self . api . media_upload ( content , content_type , filename ) if "content_uri" in response : return response [ "content_uri" ] else : raise MatrixUnexpectedResponse ( "The upload was successful, but content_uri wasn't found." ) except MatrixRequestError as e : raise MatrixRequestError ( code = e . code , content = "Upload failed: %s" % e ) | Upload content to the home server and recieve a MXC url . | 107 | 14 |
227,895 | def remove_room_alias ( self , room_alias ) : try : self . api . remove_room_alias ( room_alias ) return True except MatrixRequestError : return False | Remove mapping of an alias | 39 | 5 |
227,896 | def upload_identity_keys ( self ) : device_keys = { 'user_id' : self . user_id , 'device_id' : self . device_id , 'algorithms' : self . _algorithms , 'keys' : { '{}:{}' . format ( alg , self . device_id ) : key for alg , key in self . identity_keys . items ( ) } } self . sign_json ( device_keys ) ret = self . api . upload_keys ( device_keys = device_keys ) self . one_time_keys_manager . server_counts = ret [ 'one_time_key_counts' ] logger . info ( 'Uploaded identity keys.' ) | Uploads this device s identity keys to HS . | 162 | 10 |
227,897 | def upload_one_time_keys ( self , force_update = False ) : if force_update or not self . one_time_keys_manager . server_counts : counts = self . api . upload_keys ( ) [ 'one_time_key_counts' ] self . one_time_keys_manager . server_counts = counts signed_keys_to_upload = self . one_time_keys_manager . signed_curve25519_to_upload unsigned_keys_to_upload = self . one_time_keys_manager . curve25519_to_upload self . olm_account . generate_one_time_keys ( signed_keys_to_upload + unsigned_keys_to_upload ) one_time_keys = { } keys = self . olm_account . one_time_keys [ 'curve25519' ] for i , key_id in enumerate ( keys ) : if i < signed_keys_to_upload : key = self . sign_json ( { 'key' : keys [ key_id ] } ) key_type = 'signed_curve25519' else : key = keys [ key_id ] key_type = 'curve25519' one_time_keys [ '{}:{}' . format ( key_type , key_id ) ] = key ret = self . api . upload_keys ( one_time_keys = one_time_keys ) self . one_time_keys_manager . server_counts = ret [ 'one_time_key_counts' ] self . olm_account . mark_keys_as_published ( ) keys_uploaded = { } if unsigned_keys_to_upload : keys_uploaded [ 'curve25519' ] = unsigned_keys_to_upload if signed_keys_to_upload : keys_uploaded [ 'signed_curve25519' ] = signed_keys_to_upload logger . info ( 'Uploaded new one-time keys: %s.' , keys_uploaded ) return keys_uploaded | Uploads new one - time keys to the HS if needed . | 455 | 13 |
227,898 | def update_one_time_key_counts ( self , counts ) : self . one_time_keys_manager . server_counts = counts if self . one_time_keys_manager . should_upload ( ) : logger . info ( 'Uploading new one-time keys.' ) self . upload_one_time_keys ( ) | Update data on one - time keys count and upload new ones if necessary . | 75 | 15 |
227,899 | def sign_json ( self , json ) : signatures = json . pop ( 'signatures' , { } ) unsigned = json . pop ( 'unsigned' , None ) signature_base64 = self . olm_account . sign ( encode_canonical_json ( json ) ) key_id = 'ed25519:{}' . format ( self . device_id ) signatures . setdefault ( self . user_id , { } ) [ key_id ] = signature_base64 json [ 'signatures' ] = signatures if unsigned : json [ 'unsigned' ] = unsigned return json | Signs a JSON object . | 126 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.