idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
57,600 | def get_collection_documents_generator ( client , database_name , collection_name , spec , latest_n , sort_key ) : mongo_database = client [ database_name ] collection = mongo_database [ collection_name ] collection . create_index ( sort_key ) if latest_n is not None : skip_n = collection . count ( ) - latest_n if coll... | This is a python generator that yields tweets stored in a mongodb collection . |
57,601 | def extract_connected_components ( graph , connectivity_type , node_to_id ) : nx_graph = nx . from_scipy_sparse_matrix ( graph , create_using = nx . DiGraph ( ) ) if connectivity_type == "weak" : largest_connected_component_list = nxalgcom . weakly_connected_component_subgraphs ( nx_graph ) elif connectivity_type == "s... | Extract the largest connected component from a graph . |
57,602 | def sendEmail ( self , subject , body , toAddress = False ) : if not toAddress : toAddress = self . toAddress toAddress = toAddress . split ( ';' ) message = MIMEText ( body ) message [ 'Subject' ] = subject message [ 'From' ] = self . fromAddress message [ 'To' ] = ',' . join ( toAddress ) if not self . testing : s = ... | sends an email using the agrcpythonemailer |
57,603 | def _get_completions ( self ) : completions = [ ] self . begidx = self . l_buffer . point self . endidx = self . l_buffer . point buf = self . l_buffer . line_buffer if self . completer : while self . begidx > 0 : self . begidx -= 1 if buf [ self . begidx ] in self . completer_delims : self . begidx += 1 break text = e... | Return a list of possible completions for the string ending at the point . Also set begidx and endidx in the process . |
57,604 | def complete ( self , e ) : u completions = self . _get_completions ( ) if completions : cprefix = commonprefix ( completions ) if len ( cprefix ) > 0 : rep = [ c for c in cprefix ] point = self . l_buffer . point self . l_buffer [ self . begidx : self . endidx ] = rep self . l_buffer . point = point + len ( rep ) - ( ... | u Attempt to perform completion on the text before point . The actual completion performed is application - specific . The default is filename completion . |
57,605 | def possible_completions ( self , e ) : u completions = self . _get_completions ( ) self . _display_completions ( completions ) self . finalize ( ) | u List the possible completions of the text before point . |
57,606 | def insert_completions ( self , e ) : u completions = self . _get_completions ( ) b = self . begidx e = self . endidx for comp in completions : rep = [ c for c in comp ] rep . append ( ' ' ) self . l_buffer [ b : e ] = rep b += len ( rep ) e = b self . line_cursor = b self . finalize ( ) | u Insert all completions of the text before point that would have been generated by possible - completions . |
57,607 | def insert_text ( self , string ) : u self . l_buffer . insert_text ( string , self . argument_reset ) self . finalize ( ) | u Insert text into the command line . |
57,608 | def delete_char ( self , e ) : u self . l_buffer . delete_char ( self . argument_reset ) self . finalize ( ) | u Delete the character at point . If point is at the beginning of the line there are no characters in the line and the last character typed was not bound to delete - char then return EOF . |
57,609 | def self_insert ( self , e ) : u if e . char and ord ( e . char ) != 0 : self . insert_text ( e . char ) self . finalize ( ) | u Insert yourself . |
57,610 | def paste ( self , e ) : u if self . enable_win32_clipboard : txt = clipboard . get_clipboard_text_and_convert ( False ) txt = txt . split ( "\n" ) [ 0 ] . strip ( "\r" ) . strip ( "\n" ) log ( "paste: >%s<" % map ( ord , txt ) ) self . insert_text ( txt ) self . finalize ( ) | u Paste windows clipboard . Assume single line strip other lines and end of line markers and trailing spaces |
57,611 | def dump_functions ( self , e ) : u print txt = "\n" . join ( self . rl_settings_to_string ( ) ) print txt self . _print_prompt ( ) self . finalize ( ) | u Print all of the functions and their key bindings to the Readline output stream . If a numeric argument is supplied the output is formatted in such a way that it can be made part of an inputrc file . This command is unbound by default . |
57,612 | def fit ( self , X , y = None ) : self . transmat , self . genmat , self . transcount , self . statetime = ctmc ( X , self . numstates , self . transintv , self . toltime , self . debug ) return self | Calls the ctmc . ctmc function |
57,613 | def RV_1 ( self ) : return self . orbpop_long . RV * ( self . orbpop_long . M2 / ( self . orbpop_long . M1 + self . orbpop_long . M2 ) ) | Instantaneous RV of star 1 with respect to system center - of - mass |
57,614 | def RV_2 ( self ) : return - self . orbpop_long . RV * ( self . orbpop_long . M1 / ( self . orbpop_long . M1 + self . orbpop_long . M2 ) ) + self . orbpop_short . RV_com1 | Instantaneous RV of star 2 with respect to system center - of - mass |
57,615 | def RV_3 ( self ) : return - self . orbpop_long . RV * ( self . orbpop_long . M1 / ( self . orbpop_long . M1 + self . orbpop_long . M2 ) ) + self . orbpop_short . RV_com2 | Instantaneous RV of star 3 with respect to system center - of - mass |
57,616 | def save_hdf ( self , filename , path = '' ) : self . orbpop_long . save_hdf ( filename , '{}/long' . format ( path ) ) self . orbpop_short . save_hdf ( filename , '{}/short' . format ( path ) ) | Save to . h5 file . |
57,617 | def Rsky ( self ) : return np . sqrt ( self . position . x ** 2 + self . position . y ** 2 ) | Projected sky separation of stars |
57,618 | def RV_com1 ( self ) : return self . RV * ( self . M2 / ( self . M1 + self . M2 ) ) | RVs of star 1 relative to center - of - mass |
57,619 | def RV_com2 ( self ) : return - self . RV * ( self . M1 / ( self . M1 + self . M2 ) ) | RVs of star 2 relative to center - of - mass |
57,620 | def save_hdf ( self , filename , path = '' ) : self . dataframe . to_hdf ( filename , '{}/df' . format ( path ) ) | Saves all relevant data to . h5 file ; so state can be restored . |
57,621 | def add_pii_permissions ( self , group , view_only = None ) : pii_model_names = [ m . split ( "." ) [ 1 ] for m in self . pii_models ] if view_only : permissions = Permission . objects . filter ( ( Q ( codename__startswith = "view" ) | Q ( codename__startswith = "display" ) ) , content_type__model__in = pii_model_names... | Adds PII model permissions . |
57,622 | def get_attribute_cardinality ( attribute ) : if attribute . kind == RESOURCE_ATTRIBUTE_KINDS . MEMBER : card = CARDINALITY_CONSTANTS . ONE elif attribute . kind == RESOURCE_ATTRIBUTE_KINDS . COLLECTION : card = CARDINALITY_CONSTANTS . MANY else : raise ValueError ( 'Can not determine cardinality for non-terminal ' 'at... | Returns the cardinality of the given resource attribute . |
57,623 | def setup ( path_config = "~/.config/scalar/config.yaml" , configuration_name = None ) : global config global client global token global room path_config = Path ( path_config ) . expanduser ( ) log . debug ( "load config {path}" . format ( path = path_config ) ) if not path_config . exists ( ) : log . error ( "no confi... | Load a configuration from a default or specified configuration file accessing a default or specified configuration name . |
57,624 | def worker_wrapper ( worker_instance , pid_path ) : def exit_handler ( * args ) : if len ( args ) > 0 : print ( "Exit py signal {signal}" . format ( signal = args [ 0 ] ) ) remove ( pid_path ) atexit . register ( exit_handler ) signal . signal ( signal . SIGINT , exit_handler ) signal . signal ( signal . SIGTERM , exit... | A wrapper to start RQ worker as a new process . |
57,625 | def collection ( self ) : if not self . include_collections : return None ctx = stack . top if ctx is not None : if not hasattr ( ctx , 'redislite_collection' ) : ctx . redislite_collection = Collection ( redis = self . connection ) return ctx . redislite_collection | Return the redis - collection instance . |
57,626 | def queue ( self ) : if not self . include_rq : return None ctx = stack . top if ctx is not None : if not hasattr ( ctx , 'redislite_queue' ) : ctx . redislite_queue = { } for queue_name in self . queues : ctx . redislite_queue [ queue_name ] = Queue ( queue_name , connection = self . connection ) return ctx . redislit... | The queue property . Return rq . Queue instance . |
57,627 | def start_worker ( self ) : if not self . include_rq : return None worker = Worker ( queues = self . queues , connection = self . connection ) worker_pid_path = current_app . config . get ( "{}_WORKER_PID" . format ( self . config_prefix ) , 'rl_worker.pid' ) try : worker_pid_file = open ( worker_pid_path , 'r' ) worke... | Trigger new process as a RQ worker . |
57,628 | def image_save_buffer_fix ( maxblock = 1048576 ) : before = ImageFile . MAXBLOCK ImageFile . MAXBLOCK = maxblock try : yield finally : ImageFile . MAXBLOCK = before | Contextmanager that change MAXBLOCK in ImageFile . |
57,629 | def upgrade_many ( upgrade = True , create_examples_all = True ) : urls = set ( ) def inst ( url ) : print ( 'upgrading %s' % url ) assert url not in urls urls . add ( url ) try : lib = install_lib ( url , upgrade ) print ( ' -> %s' % lib ) except Exception as e : print ( e ) inst ( 'https://github.com/sensorium/Mozzi/... | upgrade many libs . |
57,630 | def confirm ( self , batch_id = None , filename = None ) : if batch_id or filename : export_history = self . history_model . objects . using ( self . using ) . filter ( Q ( batch_id = batch_id ) | Q ( filename = filename ) , sent = True , confirmation_code__isnull = True , ) else : export_history = self . history_model... | Flags the batch as confirmed by updating confirmation_datetime on the history model for this batch . |
57,631 | def clean_single_word ( word , lemmatizing = "wordnet" ) : if lemmatizing == "porter" : porter = PorterStemmer ( ) lemma = porter . stem ( word ) elif lemmatizing == "snowball" : snowball = SnowballStemmer ( 'english' ) lemma = snowball . stem ( word ) elif lemmatizing == "wordnet" : wordnet = WordNetLemmatizer ( ) lem... | Performs stemming or lemmatizing on a single word . |
57,632 | def clean_document ( document , sent_tokenize , _treebank_word_tokenize , tagger , lemmatizer , lemmatize , stopset , first_cap_re , all_cap_re , digits_punctuation_whitespace_re , pos_set ) : try : tokenized_document = fast_word_tokenize ( document , sent_tokenize , _treebank_word_tokenize ) except LookupError : print... | Extracts a clean bag - of - words from a document . |
57,633 | def clean_corpus_serial ( corpus , lemmatizing = "wordnet" ) : list_of_bags_of_words = list ( ) append_bag_of_words = list_of_bags_of_words . append lemma_to_keywordbag_total = defaultdict ( lambda : defaultdict ( int ) ) for document in corpus : word_list , lemma_to_keywordbag = clean_document ( document = document , ... | Extracts a bag - of - words from each document in a corpus serially . |
57,634 | def extract_bag_of_words_from_corpus_parallel ( corpus , lemmatizing = "wordnet" ) : pool = Pool ( processes = get_threads_number ( ) * 2 , ) partitioned_corpus = chunks ( corpus , len ( corpus ) / get_threads_number ( ) ) list_of_bags_of_words , list_of_lemma_to_keywordset_maps = pool . map ( partial ( clean_corpus_se... | This extracts one bag - of - words from a list of strings . The documents are mapped to parallel processes . |
57,635 | def middleware ( func ) : @ wraps ( func ) def parse ( * args , ** kwargs ) : middleware = copy . deepcopy ( kwargs [ 'middleware' ] ) kwargs . pop ( 'middleware' ) if request . method == "OPTIONS" : return JsonResponse ( 200 ) if middleware is None : return func ( * args , ** kwargs ) for mware in middleware : ware = ... | Executes routes . py route middleware |
57,636 | def progress_bar_media ( ) : if PROGRESSBARUPLOAD_INCLUDE_JQUERY : js = [ "http://code.jquery.com/jquery-1.8.3.min.js" , ] else : js = [ ] js . append ( "js/progress_bar.js" ) m = Media ( js = js ) return m . render ( ) | progress_bar_media simple tag |
57,637 | def send ( MESSAGE , SOCKET , MESSAGE_ID = None , CODE_FILE = None , CODE_LINE = None , CODE_FUNC = None , ** kwargs ) : r args = [ 'MESSAGE=' + MESSAGE ] if MESSAGE_ID is not None : id = getattr ( MESSAGE_ID , 'hex' , MESSAGE_ID ) args . append ( 'MESSAGE_ID=' + id ) if CODE_LINE == CODE_FILE == CODE_FUNC == None : CO... | r Send a message to the journal . |
57,638 | def exists ( self ) : self_object = self . query . filter_by ( id = self . id ) . first ( ) if self_object is None : return False return True | Checks if item already exists in database |
57,639 | def delete ( self ) : try : if self . exists ( ) is False : return None self . db . session . delete ( self ) self . db . session . commit ( ) except ( Exception , BaseException ) as error : return None | Easy delete for db models |
57,640 | def row_to_dict ( self , row ) : constellation = self . parse_constellation ( row [ 0 ] ) name = self . parse_name ( row [ 1 ] ) ra , dec = self . parse_coordinates ( row [ 2 ] ) variable_type = row [ 3 ] . strip ( ) max_magnitude , symbol = self . parse_magnitude ( row [ 4 ] ) min_magnitude , symbol = self . parse_mag... | Converts a raw GCVS record to a dictionary of star data . |
57,641 | def parse_magnitude ( self , magnitude_str ) : symbol = magnitude_str [ 0 ] . strip ( ) magnitude = magnitude_str [ 1 : 6 ] . strip ( ) return float ( magnitude ) if magnitude else None , symbol | Converts magnitude field to a float value or None if GCVS does not list the magnitude . |
57,642 | def parse_period ( self , period_str ) : period = period_str . translate ( TRANSLATION_MAP ) [ 3 : 14 ] . strip ( ) return float ( period ) if period else None | Converts period field to a float value or None if there is no period in GCVS record . |
57,643 | def find_hwpack_dir ( root ) : root = path ( root ) log . debug ( 'files in dir: %s' , root ) for x in root . walkfiles ( ) : log . debug ( ' %s' , x ) hwpack_dir = None for h in ( root . walkfiles ( 'boards.txt' ) ) : assert not hwpack_dir hwpack_dir = h . parent log . debug ( 'found hwpack: %s' , hwpack_dir ) assert... | search for hwpack dir under root . |
57,644 | def install_hwpack ( url , replace_existing = False ) : d = tmpdir ( tmpdir ( ) ) f = download ( url ) Archive ( f ) . extractall ( d ) clean_dir ( d ) src_dhwpack = find_hwpack_dir ( d ) targ_dhwpack = hwpack_dir ( ) / src_dhwpack . name doaction = 0 if targ_dhwpack . exists ( ) : log . debug ( 'hwpack already exists:... | install hwpackrary from web or local files system . |
57,645 | def create ( self , volume_id , vtype , size , affinity ) : volume_id = volume_id or str ( uuid . uuid4 ( ) ) params = { 'volume_type_name' : vtype , 'size' : size , 'affinity' : affinity } return self . http_put ( '/volumes/%s' % volume_id , params = self . unused ( params ) ) | create a volume |
57,646 | def restore ( self , volume_id , ** kwargs ) : self . required ( 'create' , kwargs , [ 'backup' , 'size' ] ) volume_id = volume_id or str ( uuid . uuid4 ( ) ) kwargs [ 'volume_type_name' ] = kwargs [ 'volume_type_name' ] or 'vtype' kwargs [ 'size' ] = kwargs [ 'size' ] or 1 return self . http_put ( '/volumes/%s' % volu... | restore a volume from a backup |
57,647 | def create ( self , volume_id , backup_id ) : backup_id = backup_id or str ( uuid . uuid4 ( ) ) return self . http_put ( '/backups/%s' % backup_id , params = { 'volume' : volume_id } ) | create a backup |
57,648 | def delete ( self , volume_id , force = False ) : return self . http_delete ( '/volumes/%s/export' % volume_id , params = { 'force' : force } ) | delete an export |
57,649 | def update ( self , volume_id , ** kwargs ) : self . allowed ( 'update' , kwargs , [ 'status' , 'instance_id' , 'mountpoint' , 'ip' , 'initiator' , 'session_ip' , 'session_initiator' ] ) params = self . unused ( kwargs ) return self . http_post ( '/volumes/%s/export' % volume_id , params = params ) | update an export |
57,650 | def proto_refactor ( proto_filename , namespace , namespace_path ) : with open ( proto_filename ) as f : data = f . read ( ) if not re . search ( 'syntax = "proto2"' , data ) : insert_syntax = 'syntax = "proto2";\n' data = insert_syntax + data substitution = 'import "{}/\\1";' . format ( namespace_path ) data = re . su... | This method refactors a Protobuf file to import from a namespace that will map to the desired python package structure . It also ensures that the syntax is set to proto2 since protoc complains without it . |
57,651 | def proto_refactor_files ( dest_dir , namespace , namespace_path ) : for dn , dns , fns in os . walk ( dest_dir ) : for fn in fns : fn = os . path . join ( dn , fn ) if fnmatch . fnmatch ( fn , '*.proto' ) : data = proto_refactor ( fn , namespace , namespace_path ) with open ( fn , 'w' ) as f : f . write ( data ) | This method runs the refactoring on all the Protobuf files in the Dropsonde repo . |
57,652 | def clone_source_dir ( source_dir , dest_dir ) : if os . path . isdir ( dest_dir ) : print ( 'removing' , dest_dir ) shutil . rmtree ( dest_dir ) shutil . copytree ( source_dir , dest_dir ) | Copies the source Protobuf files into a build directory . |
57,653 | def are_budget_data_package_fields_filled_in ( self , resource ) : fields = [ 'country' , 'currency' , 'year' , 'status' ] return all ( [ self . in_resource ( f , resource ) for f in fields ] ) | Check if the budget data package fields are all filled in because if not then this can t be a budget data package |
57,654 | def generate_budget_data_package ( self , resource ) : if not self . are_budget_data_package_fields_filled_in ( resource ) : return try : resource [ 'schema' ] = self . data . schema except exceptions . NotABudgetDataPackageException : log . debug ( 'Resource is not a Budget Data Package' ) resource [ 'schema' ] = [ ] ... | Try to grab a budget data package schema from the resource . The schema only allows fields which are defined in the budget data package specification . If a field is found that is not in the specification this will return a NotABudgetDataPackageException and in that case we can just return and ignore the resource |
57,655 | def before_update ( self , context , current , resource ) : if not self . are_budget_data_package_fields_filled_in ( resource ) : return if resource . get ( 'upload' , '' ) == '' : if current [ 'url' ] == resource [ 'url' ] : return else : self . data . load ( resource [ 'url' ] ) else : self . data . load ( resource [... | If the resource has changed we try to generate a budget data package but if it hasn t then we don t do anything |
57,656 | def upload_directory_contents ( input_dict , environment_dict ) : if environment_dict [ "currentkeyname" ] is None : raise seash_exceptions . UserError ( ) if environment_dict [ "currenttarget" ] is None : raise seash_exceptions . UserError ( ) try : source_directory = input_dict [ "uploaddir" ] [ "children" ] . keys (... | This function serves to upload every file in a user - supplied source directory to all of the vessels in the current target group . It essentially calls seash s upload function repeatedly each time with a file name taken from the source directory . |
57,657 | def __load_file ( self , key_list ) -> str : file = str ( key_list [ 0 ] ) + self . extension key_list . pop ( 0 ) file_path = os . path . join ( self . path , file ) if os . path . exists ( file_path ) : return Json . from_file ( file_path ) else : raise FileNotFoundError ( file_path ) | Load a translator file |
57,658 | def remove_programmer ( programmer_id ) : log . debug ( 'remove %s' , programmer_id ) lines = programmers_txt ( ) . lines ( ) lines = filter ( lambda x : not x . strip ( ) . startswith ( programmer_id + '.' ) , lines ) programmers_txt ( ) . write_lines ( lines ) | remove programmer . |
57,659 | def load ( self , entity_class , entity ) : if self . __needs_flushing : self . flush ( ) if entity . id is None : raise ValueError ( 'Can not load entity without an ID.' ) cache = self . __get_cache ( entity_class ) sess_ent = cache . get_by_id ( entity . id ) if sess_ent is None : if self . __clone_on_load : sess_ent... | Load the given repository entity into the session and return a clone . If it was already loaded before look up the loaded entity and return it . |
57,660 | def onStart ( self , event ) : c = event . container print '+' * 5 , 'started:' , c kv = lambda s : s . split ( '=' , 1 ) env = { k : v for ( k , v ) in ( kv ( s ) for s in c . attrs [ 'Config' ] [ 'Env' ] ) } print env | Display the environment of a started container |
57,661 | def _identifier_data ( self ) : data = [ ff . name for ff in self . files ] data . sort ( ) data . append ( self . path . name ) data += self . _identifier_meta ( ) return hash_obj ( data ) | Return a unique identifier for the folder data |
57,662 | def _search_files ( path ) : path = pathlib . Path ( path ) fifo = [ ] for fp in path . glob ( "*" ) : if fp . is_dir ( ) : continue for fmt in formats : if not fmt . is_series and fmt . verify ( fp ) : fifo . append ( ( fp , fmt . __name__ ) ) break theformats = [ ff [ 1 ] for ff in fifo ] formset = set ( theformats )... | Search a folder for data files |
57,663 | def get_identifier ( self , idx ) : name = self . _get_cropped_file_names ( ) [ idx ] return "{}:{}:{}" . format ( self . identifier , name , idx + 1 ) | Return an identifier for the data at index idx |
57,664 | def verify ( path ) : valid = True fifo = SeriesFolder . _search_files ( path ) if len ( fifo ) == 0 : valid = False fifmts = [ ff [ 1 ] for ff in fifo ] if len ( set ( fifmts ) ) != 1 : valid = False return valid | Verify folder file format |
57,665 | def load_file ( path ) : path = pathlib . Path ( path ) data = path . open ( ) . readlines ( ) data = [ l for l in data if len ( l . strip ( ) ) and not l . startswith ( "#" ) ] n = len ( data ) m = len ( data [ 0 ] . strip ( ) . split ( ) ) res = np . zeros ( ( n , m ) , dtype = np . dtype ( float ) ) for ii in range ... | Load a txt data file |
57,666 | def emit ( self , record ) : if record . args and isinstance ( record . args , collections . Mapping ) : extra = dict ( self . _extra , ** record . args ) else : extra = self . _extra try : msg = self . format ( record ) pri = self . mapPriority ( record . levelno ) mid = getattr ( record , 'MESSAGE_ID' , None ) send (... | Write record as journal event . |
57,667 | def mapPriority ( levelno ) : if levelno <= _logging . DEBUG : return LOG_DEBUG elif levelno <= _logging . INFO : return LOG_INFO elif levelno <= _logging . WARNING : return LOG_WARNING elif levelno <= _logging . ERROR : return LOG_ERR elif levelno <= _logging . CRITICAL : return LOG_CRIT else : return LOG_ALERT | Map logging levels to journald priorities . |
57,668 | def get_args ( self , func ) : def reverse ( iterable ) : if iterable : iterable = list ( iterable ) while len ( iterable ) : yield iterable . pop ( ) args , varargs , varkw , defaults = inspect . getargspec ( func ) result = { } for default in reverse ( defaults ) : result [ args . pop ( ) ] = default for arg in rever... | Get the arguments of a method and return it as a dictionary with the supplied defaults method arguments with no default are assigned None |
57,669 | def guess_format ( path ) : for fmt in formats : if fmt . verify ( path ) : return fmt . __name__ else : msg = "Undefined file format: '{}'" . format ( path ) raise UnknownFileFormatError ( msg ) | Determine the file format of a folder or a file |
57,670 | def load_data ( path , fmt = None , bg_data = None , bg_fmt = None , meta_data = { } , holo_kw = { } , as_type = "float32" ) : path = pathlib . Path ( path ) . resolve ( ) for kk in meta_data : if kk not in qpimage . meta . DATA_KEYS : msg = "Meta data key not allowed: {}" . format ( kk ) raise ValueError ( msg ) for k... | Load experimental data |
57,671 | def duration ( seconds ) : if seconds < 1 : return 'less than 1 sec' seconds = int ( round ( seconds ) ) components = [ ] for magnitude , label in ( ( 3600 , 'hr' ) , ( 60 , 'min' ) , ( 1 , 'sec' ) ) : if seconds >= magnitude : components . append ( '{} {}' . format ( seconds // magnitude , label ) ) seconds %= magnitu... | Return a string of the form 1 hr 2 min 3 sec representing the given number of seconds . |
57,672 | def _get_shortcut_prefix ( self , user_agent , standart_prefix ) : if user_agent is not None : user_agent = user_agent . lower ( ) opera = 'opera' in user_agent mac = 'mac' in user_agent konqueror = 'konqueror' in user_agent spoofer = 'spoofer' in user_agent safari = 'applewebkit' in user_agent windows = 'windows' in u... | Returns the shortcut prefix of browser . |
57,673 | def _get_role_description ( self , role ) : parameter = 'role-' + role . lower ( ) if self . configure . has_parameter ( parameter ) : return self . configure . get_parameter ( parameter ) return None | Returns the description of role . |
57,674 | def _get_language_description ( self , language_code ) : language = language_code . lower ( ) parameter = 'language-' + language if self . configure . has_parameter ( parameter ) : return self . configure . get_parameter ( parameter ) elif '-' in language : codes = re . split ( r'\-' , language ) parameter = 'language-... | Returns the description of language . |
57,675 | def _get_description ( self , element ) : description = None if element . has_attribute ( 'title' ) : description = element . get_attribute ( 'title' ) elif element . has_attribute ( 'aria-label' ) : description = element . get_attribute ( 'aria-label' ) elif element . has_attribute ( 'alt' ) : description = element . ... | Returns the description of element . |
57,676 | def _generate_list_shortcuts ( self ) : id_container_shortcuts_before = ( AccessibleDisplayImplementation . ID_CONTAINER_SHORTCUTS_BEFORE ) id_container_shortcuts_after = ( AccessibleDisplayImplementation . ID_CONTAINER_SHORTCUTS_AFTER ) local = self . parser . find ( 'body' ) . first_result ( ) if local is not None : ... | Generate the list of shortcuts of page . |
57,677 | def _insert ( self , element , new_element , before ) : tag_name = element . get_tag_name ( ) append_tags = [ 'BODY' , 'A' , 'FIGCAPTION' , 'LI' , 'DT' , 'DD' , 'LABEL' , 'OPTION' , 'TD' , 'TH' ] controls = [ 'INPUT' , 'SELECT' , 'TEXTAREA' ] if tag_name == 'HTML' : body = self . parser . find ( 'body' ) . first_result... | Insert a element before or after other element . |
57,678 | def _force_read_simple ( self , element , text_before , text_after , data_of ) : self . id_generator . generate_id ( element ) identifier = element . get_attribute ( 'id' ) selector = '[' + data_of + '="' + identifier + '"]' reference_before = self . parser . find ( '.' + AccessibleDisplayImplementation . CLASS_FORCE_R... | Force the screen reader display an information of element . |
57,679 | def _force_read ( self , element , value , text_prefix_before , text_suffix_before , text_prefix_after , text_suffix_after , data_of ) : if ( text_prefix_before ) or ( text_suffix_before ) : text_before = text_prefix_before + value + text_suffix_before else : text_before = '' if ( text_prefix_after ) or ( text_suffix_a... | Force the screen reader display an information of element with prefixes or suffixes . |
57,680 | def provider ( func = None , * , singleton = False , injector = None ) : def decorator ( func ) : wrapped = _wrap_provider_func ( func , { 'singleton' : singleton } ) if injector : injector . register_provider ( wrapped ) return wrapped if func : return decorator ( func ) return decorator | Decorator to mark a function as a provider . |
57,681 | def inject ( * args , ** kwargs ) : def wrapper ( obj ) : if inspect . isclass ( obj ) or callable ( obj ) : _inject_object ( obj , * args , ** kwargs ) return obj raise DiayException ( "Don't know how to inject into %r" % obj ) return wrapper | Mark a class or function for injection meaning that a DI container knows that it should inject dependencies into it . |
57,682 | def register_plugin ( self , plugin : Plugin ) : if isinstance ( plugin , Plugin ) : lazy = False elif issubclass ( plugin , Plugin ) : lazy = True else : msg = 'plugin %r must be an object/class of type Plugin' % plugin raise DiayException ( msg ) predicate = inspect . isfunction if lazy else inspect . ismethod method... | Register a plugin . |
57,683 | def register_provider ( self , func ) : if 'provides' not in getattr ( func , '__di__' , { } ) : raise DiayException ( 'function %r is not a provider' % func ) self . factories [ func . __di__ [ 'provides' ] ] = func | Register a provider function . |
57,684 | def register_lazy_provider_method ( self , cls , method ) : if 'provides' not in getattr ( method , '__di__' , { } ) : raise DiayException ( 'method %r is not a provider' % method ) @ functools . wraps ( method ) def wrapper ( * args , ** kwargs ) : return getattr ( self . get ( cls ) , method . __name__ ) ( * args , *... | Register a class method lazily as a provider . |
57,685 | def set_factory ( self , thing : type , value , overwrite = False ) : if thing in self . factories and not overwrite : raise DiayException ( 'factory for %r already exists' % thing ) self . factories [ thing ] = value | Set the factory for something . |
57,686 | def set_instance ( self , thing : type , value , overwrite = False ) : if thing in self . instances and not overwrite : raise DiayException ( 'instance for %r already exists' % thing ) self . instances [ thing ] = value | Set an instance of a thing . |
57,687 | def get ( self , thing : type ) : if thing in self . instances : return self . instances [ thing ] if thing in self . factories : fact = self . factories [ thing ] ret = self . get ( fact ) if hasattr ( fact , '__di__' ) and fact . __di__ [ 'singleton' ] : self . instances [ thing ] = ret return ret if inspect . isclas... | Get an instance of some type . |
57,688 | def call ( self , func , * args , ** kwargs ) : guessed_kwargs = self . _guess_kwargs ( func ) for key , val in guessed_kwargs . items ( ) : kwargs . setdefault ( key , val ) try : return func ( * args , ** kwargs ) except TypeError as exc : msg = ( "tried calling function %r but failed, probably " "because it takes ar... | Call a function resolving any type - hinted arguments . |
57,689 | def do_load ( self , filename ) : try : self . __session . load ( filename ) except IOError as e : self . logger . error ( e . strerror ) | Load disk image for analysis |
57,690 | def do_session ( self , args ) : filename = 'Not specified' if self . __session . filename is None else self . __session . filename print ( '{0: <30}: {1}' . format ( 'Filename' , filename ) ) | Print current session information |
57,691 | def _convert_iterable ( self , iterable ) : if not callable ( self . _wrapper ) : return iterable return [ self . _wrapper ( x ) for x in iterable ] | Converts elements returned by an iterable into instances of self . _wrapper |
57,692 | def get ( self , ** kwargs ) : for x in self : if self . _check_element ( kwargs , x ) : return x kv_str = self . _stringify_kwargs ( kwargs ) raise QueryList . NotFound ( "Element not found with attributes: %s" % kv_str ) | Returns the first object encountered that matches the specified lookup parameters . |
57,693 | def runserver ( ctx , conf , port , foreground ) : config = read_config ( conf ) debug = config [ 'conf' ] . get ( 'debug' , False ) click . echo ( 'Debug mode {0}.' . format ( 'on' if debug else 'off' ) ) port = port or config [ 'conf' ] [ 'server' ] [ 'port' ] app_settings = { 'debug' : debug , 'auto_reload' : config... | Run the fnExchange server |
57,694 | def as_repository ( resource ) : reg = get_current_registry ( ) if IInterface in provided_by ( resource ) : resource = reg . getUtility ( resource , name = 'collection-class' ) return reg . getAdapter ( resource , IRepository ) | Adapts the given registered resource to its configured repository . |
57,695 | def commit_veto ( request , response ) : tm_header = response . headers . get ( 'x-tm' ) if not tm_header is None : result = tm_header != 'commit' else : result = not response . status . startswith ( '2' ) and not tm_header == 'commit' return result | Strict commit veto to use with the transaction manager . |
57,696 | def set ( cls , key , obj ) : with cls . _lock : if not cls . _globs . get ( key ) is None : raise ValueError ( 'Duplicate key "%s".' % key ) cls . _globs [ key ] = obj return cls . _globs [ key ] | Sets the given object as global object for the given key . |
57,697 | def as_representer ( resource , content_type ) : reg = get_current_registry ( ) rpr_reg = reg . queryUtility ( IRepresenterRegistry ) return rpr_reg . create ( type ( resource ) , content_type ) | Adapts the given resource and content type to a representer . |
57,698 | def data_element_tree_to_string ( data_element ) : def __dump ( data_el , stream , offset ) : name = data_el . __class__ . __name__ stream . write ( "%s%s" % ( ' ' * offset , name ) ) offset += 2 ifcs = provided_by ( data_el ) if ICollectionDataElement in ifcs : stream . write ( "[" ) first_member = True for member_dat... | Creates a string representation of the given data element tree . |
57,699 | def initialize_path ( self , path_num = None ) : for c in self . consumers : c . initialize_path ( path_num ) self . state = [ c . state for c in self . consumers ] | make the consumer_state ready for the next MC path |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.