idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
15,100 | def validate ( self , value ) : try : self . _choice = IPAddress ( value ) return True except ( ValueError , AddrFormatError ) : self . error_message = '%s is not a valid IP address.' % value return False | Return a boolean if the value is valid |
15,101 | def validate ( self , value ) : try : self . _choice = IPAddress ( value ) except ( ValueError , AddrFormatError ) : self . error_message = '%s is not a valid IP address.' % value return False if self . _choice . is_netmask ( ) : return True else : self . error_message = '%s is not a valid IP netmask.' % value return F... | Return a boolean if the value is a valid netmask . |
15,102 | def validate ( self , value ) : if self . blank and value == '' : return True if URIValidator . uri_regex . match ( value ) : self . _choice = value return True else : self . error_message = '%s is not a valid URI' % value return False | Return a boolean indicating if the value is a valid URI |
15,103 | def validate ( self , value ) : if value in list ( self . choices . keys ( ) ) : self . _choice = value return True try : self . _choice = list ( self . choices . keys ( ) ) [ int ( value ) ] return True except ( ValueError , IndexError ) : self . error_message = '%s is not a valid choice.' % value return False | Return a boolean if the choice is a number in the enumeration |
15,104 | def validate ( self , value ) : try : int_value = int ( value ) self . _choice = int_value return True except ValueError : self . error_message = '%s is not a valid integer.' % value return False | Return True if the choice is an integer ; False otherwise . |
15,105 | def main ( ) : e = mod_env . Internet ( 'VAIS - Load testing' , 'Simulation of several websites' ) e . create ( 800 ) print ( e ) print ( npc . web_users . params ) | generates a virtual internet sets pages and runs web_users on it |
15,106 | def create ( project , skel ) : app = project_name ( project ) header ( "Create New Project ..." ) print ( "- Project: %s " % app ) create_project ( app , skel ) print ( "" ) print ( "----- That's Juicy! ----" ) print ( "" ) print ( "- Your new project [ %s ] has been created" % app ) print ( "- Location: [ application... | Create a new Project in the current directory |
15,107 | def deploy ( remote , assets_to_s3 ) : header ( "Deploying..." ) if assets_to_s3 : for mod in get_deploy_assets2s3_list ( CWD ) : _assets2s3 ( mod ) remote_name = remote or "ALL" print ( "Pushing application's content to remote: %s " % remote_name ) hosts = get_deploy_hosts_list ( CWD , remote or None ) git_push_to_mas... | To DEPLOY your application |
15,108 | def write_relationships ( self , file_name , flat = True ) : with open ( file_name , 'w' ) as writer : if flat : self . _write_relationships_flat ( writer ) else : self . _write_relationships_non_flat ( writer ) | This module will output the eDNA tags which are used inside each calculation . |
15,109 | def cmd ( send , msg , args ) : nickregex = args [ 'config' ] [ 'core' ] [ 'nickregex' ] setmode = args [ 'handler' ] . connection . mode channel = args [ 'target' ] with args [ 'handler' ] . data_lock : ops = args [ 'handler' ] . opers [ channel ] . copy ( ) if args [ 'botnick' ] not in ops : send ( "Bot must be an op... | Quiets a user then unquiets them after the specified period of time . |
15,110 | async def _update_config ( self ) : if self . config [ 'data' ] is None or self . config_expired : data = await self . get_data ( self . url_builder ( 'configuration' ) ) self . config = dict ( data = data , last_update = datetime . now ( ) ) | Update configuration data if required . |
15,111 | async def find_movie ( self , query ) : params = OrderedDict ( [ ( 'query' , query ) , ( 'include_adult' , False ) , ] ) url = self . url_builder ( 'search/movie' , { } , params ) data = await self . get_data ( url ) if data is None : return return [ Movie . from_json ( item , self . config [ 'data' ] . get ( 'images' ... | Retrieve movie data by search query . |
15,112 | async def find_person ( self , query ) : url = self . url_builder ( 'search/person' , dict ( ) , url_params = OrderedDict ( [ ( 'query' , query ) , ( 'include_adult' , False ) ] ) , ) data = await self . get_data ( url ) if data is None : return return [ Person . from_json ( item , self . config [ 'data' ] . get ( 'ima... | Retrieve person data by search query . |
15,113 | async def get_movie ( self , id_ ) : url = self . url_builder ( 'movie/{movie_id}' , dict ( movie_id = id_ ) , url_params = OrderedDict ( append_to_response = 'credits' ) , ) data = await self . get_data ( url ) if data is None : return return Movie . from_json ( data , self . config [ 'data' ] . get ( 'images' ) ) | Retrieve movie data by ID . |
15,114 | async def get_person ( self , id_ ) : data = await self . _get_person_json ( id_ , OrderedDict ( append_to_response = 'movie_credits' ) ) return Person . from_json ( data , self . config [ 'data' ] . get ( 'images' ) ) | Retrieve person data by ID . |
15,115 | async def _get_person_json ( self , id_ , url_params = None ) : url = self . url_builder ( 'person/{person_id}' , dict ( person_id = id_ ) , url_params = url_params or OrderedDict ( ) , ) data = await self . get_data ( url ) return data | Retrieve raw person JSON by ID . |
15,116 | async def get_random_popular_person ( self , limit = 500 ) : index = random . randrange ( limit ) data = await self . _get_popular_people_page ( ) if data is None : return if index >= len ( data [ 'results' ] ) : page , index = self . _calculate_page_index ( index , data ) data = await self . _get_popular_people_page (... | Randomly select a popular person . |
15,117 | async def _get_popular_people_page ( self , page = 1 ) : return await self . get_data ( self . url_builder ( 'person/popular' , url_params = OrderedDict ( page = page ) , ) ) | Get a specific page of popular person data . |
15,118 | def _calculate_page_index ( index , data ) : if index > data [ 'total_results' ] : raise ValueError ( 'index not in paged data' ) page_length = len ( data [ 'results' ] ) return ( index // page_length ) + 1 , ( index % page_length ) - 1 | Determine the location of a given index in paged data . |
15,119 | def cmd ( send , msg , args ) : if not msg : send ( "NATO what?" ) return nato = gen_nato ( msg ) if len ( nato ) > 100 : send ( "Your NATO is too long. Have you considered letters?" ) else : send ( nato ) | Converts text into NATO form . |
15,120 | def cmd ( send , msg , _ ) : bold = '\x02' if not msg : msg = bold + "Date: " + bold + "%A, %m/%d/%Y" + bold + " Time: " + bold + "%H:%M:%S" send ( time . strftime ( msg ) ) | Tells the time . |
15,121 | def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--channel' , nargs = '?' , action = arguments . ChanParser ) parser . add_argument ( 'nick' , nargs = '?' , action = arguments . NickParser , default = args [ 'nick' ] ) try : cmdargs = parser . parse_args ( ms... | When a nick was last pinged . |
15,122 | def output_traceback ( ex ) : output = "" . join ( traceback . format_exc ( ) ) . strip ( ) for line in output . split ( '\n' ) : logging . error ( line ) trace_obj = traceback . extract_tb ( ex . __traceback__ ) [ - 1 ] trace = [ basename ( trace_obj [ 0 ] ) , trace_obj [ 1 ] ] name = type ( ex ) . __name__ output = s... | Returns a tuple of a prettyprinted error message and string representation of the error . |
15,123 | def release ( no_master , release_type ) : try : locale . setlocale ( locale . LC_ALL , '' ) except : print ( "Warning: Unable to set locale. Expect encoding problems." ) git . is_repo_clean ( master = ( not no_master ) ) config = utils . get_config ( ) config . update ( utils . get_dist_metadata ( ) ) config [ 'proje... | Releases a new version |
15,124 | def _set_types ( self ) : for c in ( self . x , self . y ) : if not ( isinstance ( c , int ) or isinstance ( c , float ) ) : raise ( RuntimeError ( 'x, y coords should be int or float' ) ) if isinstance ( self . x , int ) and isinstance ( self . y , int ) : self . _dtype = "int" else : self . x = float ( self . x ) sel... | Make sure that x y have consistent types and set dtype . |
15,125 | def magnitude ( self ) : return math . sqrt ( self . x * self . x + self . y * self . y ) | Return the magnitude when treating the point as a vector . |
15,126 | def unit_vector ( self ) : return Point2D ( self . x / self . magnitude , self . y / self . magnitude ) | Return the unit vector . |
15,127 | def astype ( self , dtype ) : if dtype == "int" : return Point2D ( int ( round ( self . x , 0 ) ) , int ( round ( self . y , 0 ) ) ) elif dtype == "float" : return Point2D ( float ( self . x ) , float ( self . y ) ) else : raise ( RuntimeError ( "Invalid dtype: {}" . format ( dtype ) ) ) | Return a point of the specified dtype . |
15,128 | def free ( self , local_path ) : config = self . get_config ( ) folder = st_util . find_folder_with_path ( local_path , config ) self . delete_folder ( local_path , config ) pruned = st_util . prune_devices ( folder , config ) self . set_config ( config ) if pruned : self . restart ( ) dir_config = self . adapter . get... | Stop synchronization of local_path |
15,129 | def tag ( self , path , name ) : if not path [ len ( path ) - 1 ] == '/' : path += '/' config = self . get_config ( ) folder = self . find_folder ( { 'path' : path } , config ) if not folder : raise custom_errors . FileNotInConfig ( path ) old_name = folder [ 'label' ] folder [ 'label' ] = name dir_config = self . adap... | Change name associated with path |
15,130 | def cmd ( send , _ , args ) : with args [ 'handler' ] . data_lock : channels = ", " . join ( sorted ( args [ 'handler' ] . channels ) ) send ( channels ) | Returns a listing of the current channels . |
15,131 | def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'stock' , nargs = '?' , default = random_stock ( ) ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return send ( gen_stock ( cmdargs . stock ) ) | Gets a stock quote . |
15,132 | def get_elections ( self , obj ) : election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] ) elections = list ( obj . elections . filter ( election_day = election_day ) ) district = DivisionLevel . objects . get ( name = DivisionLevel . DISTRICT ) for district in obj . children . filter (... | All elections in division . |
15,133 | def get_content ( self , obj ) : election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] ) division = obj if obj . level . name == DivisionLevel . DISTRICT : division = obj . parent special = True if self . context . get ( 'special' ) else False return PageContent . objects . division_con... | All content for a state s page on an election day . |
15,134 | def bootstrap_executive_office ( self , election ) : division = election . race . office . jurisdiction . division content_type = ContentType . objects . get_for_model ( election . race . office ) PageContent . objects . get_or_create ( content_type = content_type , object_id = election . race . office . pk , election_... | For executive offices create page content for the office . |
15,135 | def cmd ( send , msg , args ) : req = get ( 'http://www.imdb.com/random/title' ) html = fromstring ( req . text ) name = html . find ( 'head/title' ) . text . split ( '-' ) [ 0 ] . strip ( ) key = args [ 'config' ] [ 'api' ] [ 'bitlykey' ] send ( "%s -- %s" % ( name , get_short ( req . url , key ) ) ) | Gets a random movie . |
15,136 | def get ( number , locale ) : if locale == 'pt_BR' : locale = 'xbr' if len ( locale ) > 3 : locale = locale . split ( "_" ) [ 0 ] rule = PluralizationRules . _rules . get ( locale , lambda _ : 0 ) _return = rule ( number ) if not isinstance ( _return , int ) or _return < 0 : return 0 return _return | Returns the plural position to use for the given locale and number . |
15,137 | def set ( rule , locale ) : if locale == 'pt_BR' : locale = 'xbr' if len ( locale ) > 3 : locale = locale . split ( "_" ) [ 0 ] if not hasattr ( rule , '__call__' ) : raise ValueError ( 'The given rule can not be called' ) PluralizationRules . _rules [ locale ] = rule | Overrides the default plural rule for a given locale . |
15,138 | def cmd ( send , msg , _ ) : if not msg : send ( "What acronym?" ) return words = get_list ( ) letters = [ c for c in msg . lower ( ) if c in string . ascii_lowercase ] output = " " . join ( [ choice ( words [ c ] ) for c in letters ] ) if output : send ( '%s: %s' % ( msg , output . title ( ) ) ) else : send ( "No acro... | Generates a meaning for the specified acronym . |
15,139 | def get_boundargs ( cls , * args , ** kargs ) : boundargs = cls . _signature . bind ( * args , ** kargs ) for param in cls . _signature . parameters . values ( ) : if ( param . name not in boundargs . arguments and param . default is not param . empty ) : boundargs . arguments [ param . name ] = param . default return ... | Return an inspect . BoundArguments object for the application of this Struct s signature to its arguments . Add missing values for default fields as keyword arguments . |
15,140 | def _asdict ( self ) : return OrderedDict ( ( f . name , getattr ( self , f . name ) ) for f in self . _struct ) | Return an OrderedDict of the fields . |
15,141 | def _replace ( self , ** kargs ) : fields = { f . name : getattr ( self , f . name ) for f in self . _struct } fields . update ( kargs ) return type ( self ) ( ** fields ) | Return a copy of this Struct with the same fields except with the changes specified by kargs . |
15,142 | def get_one ( self , qry , tpl ) : self . cur . execute ( qry + ' LIMIT 1' , tpl ) result = self . cur . fetchone ( ) if type ( result ) is tuple and len ( result ) == 1 : result = result [ 0 ] return result | get a single from from a query limit 1 is automatically added |
15,143 | def get_all ( self , qry , tpl ) : self . cur . execute ( qry , tpl ) result = self . cur . fetchall ( ) return result | get all rows for a query |
15,144 | def set_level ( level ) : Logger . level = level for logger in Logger . loggers . values ( ) : logger . setLevel ( level ) | Set level of logging for all loggers . |
15,145 | def get_logger ( name , level = None , fmt = ':%(lineno)d: %(message)s' ) : if name not in Logger . loggers : if Logger . level is None and level is None : Logger . level = level = logging . ERROR elif Logger . level is None : Logger . level = level elif level is None : level = Logger . level logger = logging . getLogg... | Return a logger . |
15,146 | def format ( self , record ) : if record . levelno == logging . DEBUG : string = Back . WHITE + Fore . BLACK + ' debug ' elif record . levelno == logging . INFO : string = Back . BLUE + Fore . WHITE + ' info ' elif record . levelno == logging . WARNING : string = Back . YELLOW + Fore . BLACK + ' warning ' elif record .... | Override default format method . |
15,147 | def log ( self , source : str , target : str , flags : int , msg : str , mtype : str ) -> None : entry = Log ( source = str ( source ) , target = target , flags = flags , msg = msg , type = mtype , time = datetime . now ( ) ) with self . session_scope ( ) as session : session . add ( entry ) session . flush ( ) | Logs a message to the database . |
15,148 | def get_domains ( self ) : if self . domains is None : self . domains = list ( set ( self . source . get_domains ( ) + self . target . get_domains ( ) ) ) return self . domains | Returns domains affected by operation . |
15,149 | def get_messages ( self , domain ) : if domain not in self . domains : raise ValueError ( 'Invalid domain: {0}' . format ( domain ) ) if domain not in self . messages or 'all' not in self . messages [ domain ] : self . _process_domain ( domain ) return self . messages [ domain ] [ 'all' ] | Returns all valid messages after operation . |
15,150 | def get_new_messages ( self , domain ) : if domain not in self . domains : raise ValueError ( 'Invalid domain: {0}' . format ( domain ) ) if domain not in self . messages or 'new' not in self . messages [ domain ] : self . _process_domain ( domain ) return self . messages [ domain ] [ 'new' ] | Returns new valid messages after operation . |
15,151 | def get_obsolete_messages ( self , domain ) : if domain not in self . domains : raise ValueError ( 'Invalid domain: {0}' . format ( domain ) ) if domain not in self . messages or 'obsolete' not in self . messages [ domain ] : self . _process_domain ( domain ) return self . messages [ domain ] [ 'obsolete' ] | Returns obsolete valid messages after operation . |
15,152 | def get_result ( self ) : for domain in self . domains : if domain not in self . messages : self . _process_domain ( domain ) return self . result | Returns resulting catalogue |
15,153 | def setup_db ( session , botconfig , confdir ) : Base . metadata . create_all ( session . connection ( ) ) if not session . get_bind ( ) . has_table ( 'alembic_version' ) : conf_obj = config . Config ( ) conf_obj . set_main_option ( 'bot_config_path' , confdir ) with resources . path ( 'cslbot' , botconfig [ 'alembic' ... | Sets up the database . |
15,154 | def sumvalues ( self , q = 0 ) : if q == 0 : return self . _totalf else : return - np . partition ( - self . _freq_list , q ) [ : q ] . sum ( ) | Sum of top q passowrd frequencies |
15,155 | def iterpws ( self , n ) : for _id in np . argsort ( self . _freq_list ) [ : : - 1 ] [ : n ] : pw = self . _T . restore_key ( _id ) if self . _min_pass_len <= len ( pw ) <= self . _max_pass_len : yield _id , pw , self . _freq_list [ _id ] | Returns passwords in order of their frequencies . |
15,156 | def cmd ( send , msg , args ) : if not msg : send ( "Need a CIDR range." ) return try : ipn = ip_network ( msg ) except ValueError : send ( "Not a valid CIDR range." ) return send ( "%s - %s" % ( ipn [ 0 ] , ipn [ - 1 ] ) ) | Gets a CIDR range . |
15,157 | def get_environment_requirements_list ( ) : requirement_list = [ ] requirements = check_output ( [ sys . executable , '-m' , 'pip' , 'freeze' ] ) for requirement in requirements . split ( ) : requirement_list . append ( requirement . decode ( "utf-8" ) ) return requirement_list | Take the requirements list from the current running environment |
15,158 | def parse_requirements_list ( requirements_list ) : req_list = [ ] for requirement in requirements_list : requirement_no_comments = requirement . split ( '#' ) [ 0 ] . strip ( ) req_match = re . match ( r'\s*(?P<package>[^\s\[\]]+)(?P<extras>\[\S+\])?==(?P<version>\S+)' , requirement_no_comments ) if req_match : req_li... | Take a list and return a list of dicts with { package versions ) based on the requirements specs |
15,159 | def get_pypi_package_data ( package_name , version = None ) : pypi_url = 'https://pypi.org/pypi' if version : package_url = '%s/%s/%s/json' % ( pypi_url , package_name , version , ) else : package_url = '%s/%s/json' % ( pypi_url , package_name , ) try : response = requests . get ( package_url ) except requests . Connec... | Get package data from pypi by the package name |
15,160 | def get_package_update_list ( package_name , version ) : package_version = semantic_version . Version . coerce ( version ) package_data = get_pypi_package_data ( package_name ) version_data = get_pypi_package_data ( package_name , version ) current_release = '' current_release_license = '' latest_release = '' latest_re... | Return update information of a package from a given version |
15,161 | def __list_package_updates ( package_name , version ) : updates = get_package_update_list ( package_name , version ) if updates [ 'newer_releases' ] or updates [ 'pre_releases' ] : print ( '%s (%s)' % ( package_name , version ) ) __list_updates ( 'Major releases' , updates [ 'major_updates' ] ) __list_updates ( 'Minor ... | Function used to list all package updates in console |
15,162 | def __list_updates ( update_type , update_list ) : if len ( update_list ) : print ( " %s:" % update_type ) for update_item in update_list : print ( " -- %(version)s on %(upload_time)s" % update_item ) | Function used to list package updates by update type in console |
15,163 | def __updatable ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( 'file' , nargs = '?' , type = argparse . FileType ( ) , default = None , help = 'Requirements file' ) args = parser . parse_args ( ) if args . file : packages = parse_requirements_list ( args . file ) else : packages = get_parsed_envir... | Function used to output packages update information in the console |
15,164 | def handle ( send , msg , args ) : worker = args [ "handler" ] . workers result = worker . run_pool ( get_urls , [ msg ] ) try : urls = result . get ( 5 ) except multiprocessing . TimeoutError : worker . restart_pool ( ) send ( "Url regex timed out." , target = args [ "config" ] [ "core" ] [ "ctrlchan" ] ) return for u... | Get titles for urls . |
15,165 | def page_location_template ( self ) : cycle = self . election_day . cycle . name model_class = self . model_type . model_class ( ) if model_class == ElectionDay : return "/{}/" . format ( cycle ) if model_class == Office : if self . jurisdiction : if self . division_level . name == DivisionLevel . STATE : return "/{}/p... | Returns the published URL template for a page type . |
15,166 | def cmd ( send , msg , _ ) : if not msg : url = 'http://tjbash.org/random1.html' params = { } else : targs = msg . split ( ) if len ( targs ) == 1 and targs [ 0 ] . isnumeric ( ) : url = 'http://tjbash.org/%s' % targs [ 0 ] params = { } else : url = 'http://tjbash.org/search.html' params = { 'query' : 'tag:%s' % '+' . ... | Finds a random quote from tjbash . org given search criteria . |
15,167 | def get_queryset ( self ) : try : date = ElectionDay . objects . get ( date = self . kwargs [ 'date' ] ) except Exception : raise APIException ( 'No elections on {}.' . format ( self . kwargs [ 'date' ] ) ) body_ids = [ ] for election in date . elections . all ( ) : body = election . race . office . body if body : body... | Returns a queryset of all bodies holding an election on a date . |
15,168 | def configure_engine ( cls , url : Union [ str , URL , Dict [ str , Any ] ] = None , bind : Union [ Connection , Engine ] = None , session : Dict [ str , Any ] = None , ready_callback : Union [ Callable [ [ Engine , sessionmaker ] , Any ] , str ] = None , poolclass : Union [ str , Pool ] = None , ** engine_args ) : ass... | Create an engine and selectively apply certain hacks to make it Asphalt friendly . |
15,169 | def valid_file ( value ) : if not value : raise argparse . ArgumentTypeError ( "'' is not a valid file path" ) elif not os . path . exists ( value ) : raise argparse . ArgumentTypeError ( "%s is not a valid file path" % value ) elif os . path . isdir ( value ) : raise argparse . ArgumentTypeError ( "%s is a directory, ... | Check if given file exists and is a regular file . |
15,170 | def valid_level ( value ) : value = value . upper ( ) if getattr ( logging , value , None ) is None : raise argparse . ArgumentTypeError ( "%s is not a valid level" % value ) return value | Validation function for parser logging level argument . |
15,171 | def get_logger ( cls , custom_name = None ) : name = custom_name or cls . get_name ( ) return logging . getLogger ( name ) | Returns a logger for the plugin . |
15,172 | def all ( self , domain = None ) : if domain is None : return { k : dict ( v ) for k , v in list ( self . messages . items ( ) ) } return dict ( self . messages . get ( domain , { } ) ) | Gets the messages within a given domain . |
15,173 | def set ( self , id , translation , domain = 'messages' ) : assert isinstance ( id , ( str , unicode ) ) assert isinstance ( translation , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) self . add ( { id : translation } , domain ) | Sets a message translation . |
15,174 | def has ( self , id , domain ) : assert isinstance ( id , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) if self . defines ( id , domain ) : return True if self . fallback_catalogue is not None : return self . fallback_catalogue . has ( id , domain ) return False | Checks if a message has a translation . |
15,175 | def get ( self , id , domain = 'messages' ) : assert isinstance ( id , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) if self . defines ( id , domain ) : return self . messages [ domain ] [ id ] if self . fallback_catalogue is not None : return self . fallback_catalogue . get ( id , domain ) retur... | Gets a message translation . |
15,176 | def replace ( self , messages , domain = 'messages' ) : assert isinstance ( messages , ( dict , CaseInsensitiveDict ) ) assert isinstance ( domain , ( str , unicode ) ) self . messages [ domain ] = CaseInsensitiveDict ( { } ) self . add ( messages , domain ) | Sets translations for a given domain . |
15,177 | def add_catalogue ( self , catalogue ) : assert isinstance ( catalogue , MessageCatalogue ) if catalogue . locale != self . locale : raise ValueError ( 'Cannot add a catalogue for locale "%s" as the ' 'current locale for this catalogue is "%s"' % ( catalogue . locale , self . locale ) ) for domain , messages in list ( ... | Merges translations from the given Catalogue into the current one . The two catalogues must have the same locale . |
15,178 | def add_fallback_catalogue ( self , catalogue ) : assert isinstance ( catalogue , MessageCatalogue ) c = self while True : if c . locale == catalogue . locale : raise ValueError ( 'Circular reference detected when adding a ' 'fallback catalogue for locale "%s".' % catalogue . locale ) c = c . parent if c is None : brea... | Merges translations from the given Catalogue into the current one only when the translation does not exist . |
15,179 | def trans ( self , id , parameters = None , domain = None , locale = None ) : if parameters is None : parameters = { } assert isinstance ( parameters , dict ) if locale is None : locale = self . locale else : self . _assert_valid_locale ( locale ) if domain is None : domain = 'messages' msg = self . get_catalogue ( loc... | Translates the given message . |
15,180 | def set_fallback_locales ( self , locales ) : self . catalogues = { } for locale in locales : self . _assert_valid_locale ( locale ) self . fallback_locales = locales | Sets the fallback locales . |
15,181 | def get_messages ( self , locale = None ) : if locale is None : locale = self . locale if locale not in self . catalogues : self . _load_catalogue ( locale ) catalogues = [ self . catalogues [ locale ] ] catalogue = catalogues [ 0 ] while True : catalogue = catalogue . fallback_catalogue if catalogue is None : break ca... | Collects all messages for the given locale . |
15,182 | def trans ( self , id , parameters = None , domain = None , locale = None ) : if parameters is None : parameters = { } if locale is None : locale = self . locale else : self . _assert_valid_locale ( locale ) if domain is None : domain = 'messages' catalogue = self . get_catalogue ( locale ) if not catalogue . has ( id ... | Throws RuntimeError whenever a message is missing |
15,183 | def transchoice ( self , id , number , parameters = None , domain = None , locale = None ) : if parameters is None : parameters = { } if locale is None : locale = self . locale else : self . _assert_valid_locale ( locale ) if domain is None : domain = 'messages' catalogue = self . get_catalogue ( locale ) while not cat... | Raises a RuntimeError whenever a message is missing |
15,184 | def get_catalogue ( self , locale ) : if locale is None : locale = self . locale if locale not in self . catalogues or datetime . now ( ) - self . last_reload > timedelta ( seconds = 1 ) : self . _load_catalogue ( locale ) self . last_reload = datetime . now ( ) return self . catalogues [ locale ] | Reloads messages catalogue if requested after more than one second since last reload |
15,185 | def do_reload ( bot , target , cmdargs , server_send = None ) : def send ( msg ) : if server_send is not None : server_send ( "%s\n" % msg ) else : do_log ( bot . connection , bot . get_target ( target ) , msg ) confdir = bot . handler . confdir if cmdargs == 'pull' : if isinstance ( target , irc . client . Event ) and... | The reloading magic . |
15,186 | def is_method ( arg ) : if inspect . ismethod ( arg ) : return True if isinstance ( arg , NonInstanceMethod ) : return True if inspect . isfunction ( arg ) : return _get_first_arg_name ( arg ) == 'self' return False | Checks whether given object is a method . |
15,187 | def _ask ( self , answers ) : if isinstance ( self . validator , list ) : for v in self . validator : v . answers = answers else : self . validator . answers = answers while ( True ) : q = self . question % answers if not self . choices ( ) : logger . warn ( 'No choices were supplied for "%s"' % q ) return None if self... | Really ask the question . |
15,188 | def ask ( self , answers = None ) : if answers is None : answers = { } _answers = { } if self . multiple : print ( ( bold ( 'Multiple answers are supported for this question. ' + 'Please enter a "." character to finish.' ) ) ) _answers [ self . value ] = [ ] answer = self . _ask ( answers ) while answer is not None :... | Ask the question then ask any sub - questions . |
15,189 | def answer ( self ) : if isinstance ( self . validator , list ) : return self . validator [ 0 ] . choice ( ) return self . validator . choice ( ) | Return the answer for the question from the validator . |
15,190 | def choices ( self ) : if isinstance ( self . validator , list ) : return self . validator [ 0 ] . print_choices ( ) return self . validator . print_choices ( ) | Print the choices for this question . |
15,191 | def _timing ( f , logs_every = 100 ) : @ functools . wraps ( f ) def wrap ( * args , ** kw ) : ts = _time . time ( ) result = f ( * args , ** kw ) te = _time . time ( ) qj . _call_counts [ f ] += 1 qj . _timings [ f ] += ( te - ts ) count = qj . _call_counts [ f ] if count % logs_every == 0 : qj ( x = '%2.4f seconds' %... | Decorator to time function calls and log the stats . |
15,192 | def _catch ( f , exception_type ) : if not ( inspect . isclass ( exception_type ) and issubclass ( exception_type , Exception ) ) : exception_type = Exception @ functools . wraps ( f ) def wrap ( * args , ** kw ) : try : return f ( * args , ** kw ) except exception_type as e : qj ( e , 'Caught an exception in %s' % f ,... | Decorator to drop into the debugger if a function throws an exception . |
15,193 | def _annotate_fn_args ( stack , fn_opname , nargs , nkw = - 1 , consume_fn_name = True ) : kwarg_names = [ ] if nkw == - 1 : if sys . version_info [ 0 ] < 3 : nargs , nkw = ( nargs % 256 , 2 * nargs // 256 ) else : if fn_opname == 'CALL_FUNCTION_KW' : if qj . _DEBUG_QJ : assert len ( stack ) and stack [ - 1 ] . opname ... | Add commas and equals as appropriate to function argument lists in the stack . |
15,194 | def generate_mediation_matrix ( dsm ) : cat = dsm . categories ent = dsm . entities size = dsm . size [ 0 ] if not cat : cat = [ 'appmodule' ] * size packages = [ e . split ( '.' ) [ 0 ] for e in ent ] mediation_matrix = [ [ 0 for _ in range ( size ) ] for _ in range ( size ) ] for i in range ( 0 , size ) : for j in ra... | Generate the mediation matrix of the given matrix . |
15,195 | def check ( self , dsm , simplicity_factor = 2 , ** kwargs ) : economy_of_mechanism = False message = '' data = dsm . data categories = dsm . categories dsm_size = dsm . size [ 0 ] if not categories : categories = [ 'appmodule' ] * dsm_size dependency_number = 0 for i in range ( 0 , dsm_size ) : for j in range ( 0 , ds... | Check economy of mechanism . |
15,196 | def check ( self , dsm , independence_factor = 5 , ** kwargs ) : least_common_mechanism = False message = '' data = dsm . data categories = dsm . categories dsm_size = dsm . size [ 0 ] if not categories : categories = [ 'appmodule' ] * dsm_size dependent_module_number = [ ] for j in range ( 0 , dsm_size ) : dependent_m... | Check least common mechanism . |
15,197 | def check ( self , dsm , ** kwargs ) : layered_architecture = True messages = [ ] categories = dsm . categories dsm_size = dsm . size [ 0 ] if not categories : categories = [ 'appmodule' ] * dsm_size for i in range ( 0 , dsm_size - 1 ) : for j in range ( i + 1 , dsm_size ) : if ( categories [ i ] != 'broker' and catego... | Check layered architecture . |
15,198 | def check ( self , dsm , ** kwargs ) : logger . debug ( 'Entities = %s' % dsm . entities ) messages = [ ] code_clean = True threshold = kwargs . pop ( 'threshold' , 1 ) rows , _ = dsm . size for i in range ( 0 , rows ) : if dsm . data [ i ] [ 0 ] > threshold : messages . append ( 'Number of issues (%d) in module %s ' '... | Check code clean . |
15,199 | def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'date' , nargs = '*' , action = arguments . DateParser ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if not cmdargs . date : send ( "Time unt... | Reports the difference between now and some specified time . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.