idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
15,000 | def strategy ( self ) : 'Returns resulting strategy that generates configured char set' max_codepoint = None if self . _unicode else 127 strategies = [ ] if self . _negate : if self . _categories or self . _whitelist_chars : strategies . append ( hs . characters ( blacklist_categories = self . _categories | set ( [ 'Cc... | Returns resulting strategy that generates configured char set |
15,001 | def add_category ( self , category ) : if category == sre . CATEGORY_DIGIT : self . _categories |= UNICODE_DIGIT_CATEGORIES elif category == sre . CATEGORY_NOT_DIGIT : self . _categories |= UNICODE_CATEGORIES - UNICODE_DIGIT_CATEGORIES elif category == sre . CATEGORY_SPACE : self . _categories |= UNICODE_SPACE_CATEGORI... | Add unicode category to set |
15,002 | def add_chars ( self , chars ) : 'Add given chars to char set' for c in chars : if self . _ignorecase : self . _whitelist_chars . add ( c . lower ( ) ) self . _whitelist_chars . add ( c . upper ( ) ) else : self . _whitelist_chars . add ( c ) | Add given chars to char set |
15,003 | def str_traceback ( error , tb ) : if not isinstance ( tb , types . TracebackType ) : return tb return '' . join ( traceback . format_exception ( error . __class__ , error , tb ) ) | Returns a string representation of the traceback . |
15,004 | def filter_traceback ( error , tb , ignore_pkg = CURRENT_PACKAGE ) : if not isinstance ( tb , types . TracebackType ) : return tb def in_namespace ( n ) : return n and ( n . startswith ( ignore_pkg + '.' ) or n == ignore_pkg ) while tb and in_namespace ( tb . tb_frame . f_globals [ '__package__' ] ) : tb = tb . tb_next... | Filtered out all parent stacktraces starting with the given stacktrace that has a given variable name in its globals . |
15,005 | def get_true_function ( obj ) : "Returns the actual function and a boolean indicated if this is a method or not." if not callable ( obj ) : raise TypeError ( "%r is not callable." % ( obj , ) ) ismethod = inspect . ismethod ( obj ) if inspect . isfunction ( obj ) or ismethod : return obj , ismethod if hasattr ( obj , '... | Returns the actual function and a boolean indicated if this is a method or not . |
15,006 | def assert_valid_path ( self , path ) : if not isinstance ( path , str ) : raise NotFoundResourceException ( "Resource passed to load() method must be a file path" ) if not os . path . isfile ( path ) : raise NotFoundResourceException ( 'File "{0}" does not exist' . format ( path ) ) | Ensures that the path represents an existing file |
15,007 | def read_file ( self , path ) : self . assert_valid_path ( path ) with open ( path , 'rb' ) as file : contents = file . read ( ) . decode ( 'UTF-8' ) return contents | Reads a file into memory and returns it s contents |
15,008 | def flatten ( self , messages , parent_key = '' ) : items = [ ] sep = '.' for k , v in list ( messages . items ( ) ) : new_key = "{0}{1}{2}" . format ( parent_key , sep , k ) if parent_key else k if isinstance ( v , collections . MutableMapping ) : items . extend ( list ( self . flatten ( v , new_key ) . items ( ) ) ) ... | Flattens an nested array of translations . |
15,009 | def parse ( self , resource ) : try : import polib except ImportError as e : self . rethrow ( "You need to install polib to use PoFileLoader or MoFileLoader" , ImportError ) self . assert_valid_path ( resource ) messages = { } parsed = self . _load_contents ( polib , resource ) for item in parsed : if item . msgid_plur... | Loads given resource into a dict using polib |
15,010 | def arch ( self ) : if self . method in ( 'buildArch' , 'createdistrepo' , 'livecd' ) : return self . params [ 2 ] if self . method in ( 'createrepo' , 'runroot' ) : return self . params [ 1 ] if self . method == 'createImage' : return self . params [ 3 ] if self . method == 'indirectionimage' : return self . params [ ... | Return an architecture for this task . |
15,011 | def arches ( self ) : if self . method == 'image' : return self . params [ 2 ] if self . arch : return [ self . arch ] return [ ] | Return a list of architectures for this task . |
15,012 | def duration ( self ) : if not self . started : return None start = self . started end = self . completed if not end : end = datetime . utcnow ( ) return end - start | Return a timedelta for this task . |
15,013 | def estimate_completion ( self ) : if self . completion_ts : defer . returnValue ( self . completed ) if self . method == 'build' or self . method == 'image' : subtask_completion = yield self . estimate_descendents ( ) defer . returnValue ( subtask_completion ) if self . state == task_states . FREE : est_completion = y... | Estimate completion time for a task . |
15,014 | def _estimate_free ( self ) : capacity_deferred = self . channel . total_capacity ( ) open_tasks_deferred = self . channel . tasks ( state = [ task_states . OPEN ] ) avg_delta_deferred = self . estimate_duration ( ) deferreds = [ capacity_deferred , open_tasks_deferred , avg_delta_deferred ] results = yield defer . gat... | Estimate completion time for a free task . |
15,015 | def package ( self ) : if self . method == 'buildNotification' : return self . params [ 1 ] [ 'name' ] if self . method in ( 'createImage' , 'image' , 'livecd' ) : return self . params [ 0 ] if self . method == 'indirectionimage' : return self . params [ 0 ] [ 'name' ] if self . method not in ( 'build' , 'buildArch' , ... | Find a package name from a build task s parameters . |
15,016 | def params ( self ) : if isinstance ( self . request , list ) : return unmunchify ( self . request ) ( params , _ ) = xmlrpc . loads ( self . request ) return params | Return a list of parameters in this task s request . |
15,017 | def cmd ( send , _ , args ) : try : if exists ( join ( args [ 'handler' ] . confdir , '.git' ) ) : send ( do_pull ( srcdir = args [ 'handler' ] . confdir ) ) else : send ( do_pull ( repo = args [ 'config' ] [ 'api' ] [ 'githubrepo' ] ) ) except subprocess . CalledProcessError as ex : for line in ex . output . strip ( )... | Pull changes . |
15,018 | def _start_date_of_year ( year : int ) -> datetime . date : jan_one = datetime . date ( year , 1 , 1 ) diff = 7 * ( jan_one . isoweekday ( ) > 3 ) - jan_one . isoweekday ( ) return jan_one + datetime . timedelta ( days = diff ) | Return start date of the year using MMWR week rules |
15,019 | def date_to_epiweek ( date = datetime . date . today ( ) ) -> Epiweek : year = date . year start_dates = list ( map ( _start_date_of_year , [ year - 1 , year , year + 1 ] ) ) start_date = start_dates [ 1 ] if start_dates [ 1 ] > date : start_date = start_dates [ 0 ] elif date >= start_dates [ 2 ] : start_date = start_d... | Convert python date to Epiweek |
15,020 | def epiweeks_in_year ( year : int ) -> int : if date_to_epiweek ( epiweek_to_date ( Epiweek ( year , 53 ) ) ) . year == year : return 53 else : return 52 | Return number of epiweeks in a year |
15,021 | def parser ( self ) : if self . _command_parser is None : parents = [ ] if self . need_verbose : parents . append ( _verbose_parser ) if self . need_settings : parents . append ( _settings_parser ) self . _command_parser = self . _main_parser . add_parser ( self . name , help = self . help , parents = parents , formatt... | Returns the appropriate parser to use for adding arguments to your command . |
15,022 | def cmd ( send , _ , args ) : adminlist = [ ] for admin in args [ 'db' ] . query ( Permissions ) . order_by ( Permissions . nick ) . all ( ) : if admin . registered : adminlist . append ( "%s (V)" % admin . nick ) else : adminlist . append ( "%s (U)" % admin . nick ) send ( ", " . join ( adminlist ) , target = args [ '... | Returns a list of admins . |
15,023 | def run ( self ) : x , y = 1 , 0 num_steps = 0 while self . s . get_state ( ) != 'Halted' : self . s . command ( { 'name' : 'walk' , 'type' : 'move' , 'direction' : [ x , y ] } , self . a1 ) self . s . command ( { 'name' : 'walk' , 'type' : 'run' , 'direction' : [ x , y + 1 ] } , self . a2 ) num_steps += 1 if num_steps... | This AI simple moves the characters towards the opposite edges of the grid for 3 steps or until event halts the simulation |
15,024 | def validate ( schema_file , config_file , deprecation ) : result = validator_from_config_file ( config_file , schema_file ) result . validate ( error_on_deprecated = deprecation ) for error in result . errors ( ) : click . secho ( 'Error : %s' % error , err = True , fg = 'red' ) for warning in result . warnings ( ) ... | Validate a configuration file against a confirm schema . |
15,025 | def migrate ( schema_file , config_file ) : schema = load_schema_file ( open ( schema_file , 'r' ) ) config = load_config_file ( config_file , open ( config_file , 'r' ) . read ( ) ) config = append_existing_values ( schema , config ) migrated_config = generate_config_parser ( config ) migrated_config . write ( sys . s... | Migrates a configuration file using a confirm schema . |
15,026 | def document ( schema_file ) : schema = load_schema_file ( open ( schema_file , 'r' ) ) documentation = generate_documentation ( schema ) sys . stdout . write ( documentation ) | Generate reStructuredText documentation from a confirm schema . |
15,027 | def generate ( schema_file , all_options ) : schema = load_schema_file ( open ( schema_file , 'r' ) ) config_parser = generate_config_parser ( schema , include_all = all_options ) config_parser . write ( sys . stdout ) | Generates a template configuration file from a confirm schema . |
15,028 | def init ( config_file ) : schema = generate_schema_file ( open ( config_file , 'r' ) . read ( ) ) sys . stdout . write ( schema ) | Initialize a confirm schema from an existing configuration file . |
15,029 | def _init_random_gaussians ( self , X ) : n_samples = np . shape ( X ) [ 0 ] self . priors = ( 1 / self . k ) * np . ones ( self . k ) for _ in range ( self . k ) : params = { } params [ "mean" ] = X [ np . random . choice ( range ( n_samples ) ) ] params [ "cov" ] = calculate_covariance_matrix ( X ) self . parameters ... | Initialize gaussian randomly |
15,030 | def _get_likelihoods ( self , X ) : n_samples = np . shape ( X ) [ 0 ] likelihoods = np . zeros ( ( n_samples , self . k ) ) for i in range ( self . k ) : likelihoods [ : , i ] = self . multivariate_gaussian ( X , self . parameters [ i ] ) return likelihoods | Calculate the likelihood over all samples |
15,031 | def _expectation ( self , X ) : weighted_likelihoods = self . _get_likelihoods ( X ) * self . priors sum_likelihoods = np . expand_dims ( np . sum ( weighted_likelihoods , axis = 1 ) , axis = 1 ) self . responsibility = weighted_likelihoods / sum_likelihoods self . sample_assignments = self . responsibility . argmax ( ... | Calculate the responsibility |
15,032 | def _maximization ( self , X ) : for i in range ( self . k ) : resp = np . expand_dims ( self . responsibility [ : , i ] , axis = 1 ) mean = ( resp * X ) . sum ( axis = 0 ) / resp . sum ( ) covariance = ( X - mean ) . T . dot ( ( X - mean ) * resp ) / resp . sum ( ) self . parameters [ i ] [ "mean" ] , self . parameter... | Update the parameters and priors |
15,033 | def _converged ( self , X ) : if len ( self . responsibilities ) < 2 : return False diff = np . linalg . norm ( self . responsibilities [ - 1 ] - self . responsibilities [ - 2 ] ) return diff <= self . tolerance | Covergence if || likehood - last_likelihood || < tolerance |
15,034 | def cluster ( self , X ) : self . _init_random_gaussians ( X ) for _ in range ( self . max_iterations ) : self . _expectation ( X ) self . _maximization ( X ) if self . _converged ( X ) : break self . _expectation ( X ) return self . sample_assignments | Run GMM and return the cluster indices |
15,035 | def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--lang' , '--from' , default = None ) parser . add_argument ( '--to' , default = 'en' ) parser . add_argument ( 'msg' , nargs = '+' ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentExcep... | Translate something . |
15,036 | def cmd ( send , msg , _ ) : coin = [ 'heads' , 'tails' ] if not msg : send ( 'The coin lands on... %s' % choice ( coin ) ) elif not msg . lstrip ( '-' ) . isdigit ( ) : send ( "Not A Valid Positive Integer." ) else : msg = int ( msg ) if msg < 0 : send ( "Negative Flipping requires the (optional) quantum coprocessor."... | Flips a coin a number of times . |
15,037 | def is_admin ( self , send , nick , required_role = 'admin' ) : if not required_role : return True with self . db . session_scope ( ) as session : admin = session . query ( orm . Permissions ) . filter ( orm . Permissions . nick == nick ) . first ( ) if admin is None : return False if required_role == "owner" and admin... | Checks if a nick is a admin . |
15,038 | def get_admins ( self ) : if not self . config [ 'feature' ] . getboolean ( 'nickserv' ) : return with self . db . session_scope ( ) as session : for a in session . query ( orm . Permissions ) . all ( ) : if not a . registered : self . update_authstatus ( a . nick ) | Check verification for all admins . |
15,039 | def abusecheck ( self , send , nick , target , limit , cmd ) : if nick not in self . abuselist : self . abuselist [ nick ] = { } if cmd not in self . abuselist [ nick ] : self . abuselist [ nick ] [ cmd ] = [ datetime . now ( ) ] else : self . abuselist [ nick ] [ cmd ] . append ( datetime . now ( ) ) count = 0 for x i... | Rate - limits commands . |
15,040 | def do_log ( self , target , nick , msg , msgtype ) : if not isinstance ( msg , str ) : raise Exception ( "IRC doesn't like it when you send it a %s" % type ( msg ) . __name__ ) target = target . lower ( ) flags = 0 if target . startswith ( ( '+' , '@' ) ) : target = target [ 1 : ] with self . data_lock : if target in ... | Handles logging . |
15,041 | def do_part ( self , cmdargs , nick , target , msgtype , send , c ) : channel = self . config [ 'core' ] [ 'channel' ] botnick = self . config [ 'core' ] [ 'nick' ] if not cmdargs : if target == channel : send ( "%s must have a home." % botnick ) return else : cmdargs = target if not cmdargs . startswith ( ( '#' , '+' ... | Leaves a channel . |
15,042 | def do_join ( self , cmdargs , nick , msgtype , send , c ) : if not cmdargs : send ( "Join what?" ) return if cmdargs == '0' : send ( "I'm sorry, Dave. I'm afraid I can't do that." ) return if not cmdargs . startswith ( ( '#' , '+' , '@' ) ) : cmdargs = '#' + cmdargs cmd = cmdargs . split ( ) if cmd [ 0 ] in self . cha... | Join a channel . |
15,043 | def do_mode ( self , target , msg , nick , send ) : mode_changes = irc . modes . parse_channel_modes ( msg ) with self . data_lock : for change in mode_changes : if change [ 1 ] == 'v' : self . voiced [ target ] [ change [ 2 ] ] = True if change [ 0 ] == '+' else False if change [ 1 ] == 'o' : self . opers [ target ] [... | reop and handle guard violations . |
15,044 | def do_kick ( self , send , target , nick , msg , slogan = True ) : if not self . kick_enabled : return if target not in self . channels : send ( "%s: you're lucky, private message kicking hasn't been implemented yet." % nick ) return with self . data_lock : ops = [ k for k , v in self . opers [ target ] . items ( ) if... | Kick users . |
15,045 | def do_args ( self , modargs , send , nick , target , source , name , msgtype ) : realargs = { } args = { 'nick' : nick , 'handler' : self , 'db' : None , 'config' : self . config , 'source' : source , 'name' : name , 'type' : msgtype , 'botnick' : self . connection . real_nickname , 'target' : target if target [ 0 ] =... | Handle the various args that modules need . |
15,046 | def do_welcome ( self ) : self . rate_limited_send ( 'join' , self . config [ 'core' ] [ 'channel' ] ) self . rate_limited_send ( 'join' , self . config [ 'core' ] [ 'ctrlchan' ] , self . config [ 'auth' ] [ 'ctrlkey' ] ) self . workers . defer ( 5 , False , self . get_admins ) extrachans = self . config [ 'core' ] [ '... | Do setup when connected to server . |
15,047 | def get_filtered_send ( self , cmdargs , send , target ) : parser = arguments . ArgParser ( self . config ) parser . add_argument ( '--filter' ) try : filterargs , remainder = parser . parse_known_args ( cmdargs ) except arguments . ArgumentException as ex : return str ( ex ) , None cmdargs = ' ' . join ( remainder ) i... | Parse out any filters . |
15,048 | def handle_msg ( self , c , e ) : if e . type not in [ 'authenticate' , 'error' , 'join' , 'part' , 'quit' ] : nick = e . source . nick else : nick = e . source if e . arguments is None : msg = "" else : msg = " " . join ( e . arguments ) . strip ( ) target = nick if e . type == 'privmsg' else e . target def send ( msg... | The Heart and Soul of IrcBot . |
15,049 | def process_tag ( self , tag ) : try : if not self . _is_function ( tag ) : self . _tag_type_processor [ tag . data_type ] ( tag ) except KeyError as ex : raise Exception ( 'Tag type {0} not recognized for tag {1}' . format ( tag . data_type , tag . name ) , ex ) | Processes tag and detects which function to use |
15,050 | def process_boolean ( self , tag ) : tag . set_address ( self . normal_register . current_bit_address ) self . normal_register . move_to_next_bit_address ( ) | Process Boolean type tags |
15,051 | def process_boolean_array ( self , tag ) : array_size = tag . get_array_size ( ) tag . set_address ( self . normal_register . get_array ( array_size ) ) if self . is_sixteen_bit : self . normal_register . move_to_next_address ( ( array_size / 16 ) + 1 ) return self . normal_register . move_to_next_address ( ( array_siz... | Process Boolean array type tags |
15,052 | def process_byte ( self , tag ) : tag . set_address ( self . normal_register . current_address ) self . normal_register . move_to_next_address ( 1 ) | Process byte type tags |
15,053 | def process_string ( self , tag ) : tag . set_address ( self . string_register . current_address ) if self . is_sixteen_bit : self . string_register . move_to_next_address ( 1 ) return self . string_register . move_to_next_address ( 1 ) | Process string type tags |
15,054 | def cmd ( send , msg , args ) : nick = args [ 'nick' ] channel = args [ 'target' ] if args [ 'target' ] != 'private' else args [ 'config' ] [ 'core' ] [ 'channel' ] levels = { 1 : 'Whirr...' , 2 : 'Vrrm...' , 3 : 'Zzzzhhhh...' , 4 : 'SHFRRRRM...' , 5 : 'GEEEEZZSH...' , 6 : 'PLAAAAIIID...' , 7 : 'KKKRRRAAKKKAAKRAKKGGARG... | Microwaves something . |
15,055 | async def main ( ) : async with aiohttp . ClientSession ( ) as session : station = OpenSenseMap ( SENSOR_ID , loop , session ) await station . get_data ( ) print ( "Name:" , station . name ) print ( "Description:" , station . description ) print ( "Coordinates:" , station . coordinates ) print ( "PM 2.5:" , station . p... | Sample code to retrieve the data from an OpenSenseMap station . |
15,056 | def theme ( self , text ) : return self . theme_color + self . BRIGHT + text + self . RESET | Theme style . |
15,057 | def _label_desc ( self , label , desc , label_color = '' ) : return self . BRIGHT + label_color + label + self . RESET + desc | Generic styler for a line consisting of a label and description . |
15,058 | def error ( self , cmd , desc = '' ) : return self . _label_desc ( cmd , desc , self . error_color ) | Style for an error message . |
15,059 | def warn ( self , cmd , desc = '' ) : return self . _label_desc ( cmd , desc , self . warn_color ) | Style for warning message . |
15,060 | def success ( self , cmd , desc = '' ) : return self . _label_desc ( cmd , desc , self . success_color ) | Style for a success message . |
15,061 | def cmdloop ( self , intro = None ) : self . preloop ( ) if self . use_rawinput and self . completekey : try : import readline self . old_completer = readline . get_completer ( ) readline . set_completer ( self . complete ) readline . parse_and_bind ( self . completekey + ': complete' ) except ImportError : pass try : ... | Override the command loop to handle Ctrl - C . |
15,062 | def do_exit ( self , arg ) : if self . arm . is_connected ( ) : self . arm . disconnect ( ) print ( 'Bye!' ) return True | Exit the shell . |
15,063 | def do_ctrlc ( self , arg ) : print ( 'STOP' ) if self . arm . is_connected ( ) : self . arm . write ( 'STOP' ) | Ctrl - C sends a STOP command to the arm . |
15,064 | def do_status ( self , arg ) : info = self . arm . get_info ( ) max_len = len ( max ( info . keys ( ) , key = len ) ) print ( self . style . theme ( '\nArm Status' ) ) for key , value in info . items ( ) : print ( self . style . help ( key . ljust ( max_len + 2 ) , str ( value ) ) ) print ( ) | Print information about the arm . |
15,065 | def do_connect ( self , arg ) : if self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is already connected.' ) ) else : try : port = self . arm . connect ( ) print ( self . style . success ( 'Success: ' , 'Connected to \'{}\'.' . format ( port ) ) ) except r12 . ArmException as e : print ( ... | Connect to the arm . |
15,066 | def do_disconnect ( self , arg ) : if not self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is already disconnected.' ) ) else : self . arm . disconnect ( ) print ( self . style . success ( 'Success: ' , 'Disconnected.' ) ) | Disconnect from the arm . |
15,067 | def do_run ( self , arg ) : if not self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is not connected.' ) ) return try : with open ( arg ) as f : lines = [ line . strip ( ) for line in f . readlines ( ) ] except IOError : print ( self . style . error ( 'Error: ' , 'Could not load file \'{}... | Load and run an external FORTH script . |
15,068 | def do_dump ( self , arg ) : if not self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is not connected.' ) ) return print ( self . arm . dump ( ) ) | Output all bytes waiting in output queue . |
15,069 | def complete_run ( self , text , line , b , e ) : text = line . split ( ) [ - 1 ] forth_files = glob . glob ( text + '*.fs' ) if len ( forth_files ) == 0 : return [ f . split ( os . path . sep ) [ - 1 ] for f in glob . glob ( text + '*' ) ] forth_files = [ f . split ( os . path . sep ) [ - 1 ] for f in forth_files ] re... | Autocomplete file names with . forth ending . |
15,070 | def get_names ( self ) : return ( [ 'do_' + x for x in self . commands [ 'shell' ] ] + [ 'do_' + x for x in self . commands [ 'forth' ] ] ) | Get names for autocompletion . |
15,071 | def parse_help_text ( self , file_path ) : with open ( file_path ) as f : lines = f . readlines ( ) cmds = [ ] descs = [ ] for line in lines : line = line . strip ( ) if len ( line ) == 0 : cmds . append ( '' ) descs . append ( '' ) else : tokens = line . split ( ' ' ) cmds . append ( tokens [ 0 ] ) descs . append ( '... | Load of list of commands and descriptions from a file . |
15,072 | def load_forth_commands ( self , help_dir ) : try : help_file_path = os . path . join ( help_dir , 'roboforth.txt' ) commands , help_text = self . parse_help_text ( help_file_path ) except IOError : print ( self . style . warn ( 'Warning: ' , 'Failed to load ROBOFORTH help.' ) ) return self . commands [ 'forth' ] = com... | Load completion list for ROBOFORTH commands . |
15,073 | def preloop ( self ) : script_dir = os . path . dirname ( os . path . realpath ( __file__ ) ) help_dir = os . path . join ( script_dir , HELP_DIR_NAME ) self . load_forth_commands ( help_dir ) self . load_shell_commands ( help_dir ) | Executed before the command loop starts . |
15,074 | def bootstrap_legislative_office ( self , election ) : body = election . race . office . body body_division = election . race . office . body . jurisdiction . division office_division = election . race . office . division self . bootstrap_federal_body_type_page ( election ) self . bootstrap_state_body_type_page ( elect... | For legislative offices create page content for the legislative Body the Office belongs to AND the state - level Division . |
15,075 | def cmd ( send , msg , args ) : latest = get_latest ( ) if not msg : msg = randrange ( 1 , latest ) elif msg == 'latest' : msg = latest elif msg . isdigit ( ) : msg = int ( msg ) if msg > latest or msg < 1 : send ( "Number out of range" ) return else : send ( do_search ( msg , args [ 'config' ] [ 'api' ] [ 'googleapike... | Gets a xkcd comic . |
15,076 | def generate_config_parser ( config , include_all = False ) : config_parser = SafeConfigParser ( allow_no_value = True ) for section_name , option_name in _get_included_schema_sections_options ( config , include_all ) : if not config_parser . has_section ( section_name ) : config_parser . add_section ( section_name ) o... | Generates a config parser from a configuration dictionary . |
15,077 | def generate_documentation ( schema ) : documentation_title = "Configuration documentation" documentation = documentation_title + "\n" documentation += "=" * len ( documentation_title ) + '\n' for section_name in schema : section_created = False for option_name in schema [ section_name ] : option = schema [ section_nam... | Generates reStructuredText documentation from a Confirm file . |
15,078 | def append_existing_values ( schema , config ) : for section_name in config : for option_name in config [ section_name ] : option_value = config [ section_name ] [ option_name ] schema . setdefault ( section_name , { } ) . setdefault ( option_name , { } ) [ 'value' ] = option_value return schema | Adds the values of the existing config to the config dictionary . |
15,079 | def generate_schema_file ( config_file ) : config = utils . load_config_from_ini_file ( config_file ) schema = { } for section_name in config : for option_name in config [ section_name ] : schema . setdefault ( section_name , { } ) . setdefault ( option_name , { } ) schema [ section_name ] [ option_name ] [ 'descriptio... | Generates a basic confirm schema file from a configuration file . |
15,080 | def rankwithlist ( l , lwith , test = False ) : if not ( isinstance ( l , list ) and isinstance ( lwith , list ) ) : l , lwith = list ( l ) , list ( lwith ) from scipy . stats import rankdata if test : print ( l , lwith ) print ( rankdata ( l ) , rankdata ( lwith ) ) print ( rankdata ( l + lwith ) ) return rankdata ( l... | rank l wrt lwith |
15,081 | def dfbool2intervals ( df , colbool ) : df . index = range ( len ( df ) ) intervals = bools2intervals ( df [ colbool ] ) for intervali , interval in enumerate ( intervals ) : df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval id' ] = intervali df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} inte... | ds contains bool values |
15,082 | def normalize_kind ( self , kindlike ) : if kindlike is None : return ( object , ) elif isinstance ( kindlike , type ) : return ( kindlike , ) else : return tuple ( kindlike ) | Make a kind out of a possible shorthand . If the given argument is a sequence of types or a singular type it becomes a kind that accepts exactly those types . If the given argument is None it becomes a type that accepts anything . |
15,083 | def str_kind ( self , kind ) : if len ( kind ) == 0 : return 'Nothing' elif len ( kind ) == 1 : return kind [ 0 ] . __name__ elif len ( kind ) == 2 : return kind [ 0 ] . __name__ + ' or ' + kind [ 1 ] . __name__ else : return 'one of {' + ', ' . join ( t . __name__ for t in kind ) + '}' | Get a string describing a kind . |
15,084 | def checktype ( self , val , kind , ** kargs ) : if not isinstance ( val , kind ) : raise TypeError ( 'Expected {}; got {}' . format ( self . str_kind ( kind ) , self . str_valtype ( val ) ) ) | Raise TypeError if val does not satisfy kind . |
15,085 | def raises ( cls , sender , attrname , error , args = ANYTHING , kwargs = ANYTHING ) : "An alternative constructor which raises the given error" def raise_error ( ) : raise error return cls ( sender , attrname , returns = Invoke ( raise_error ) , args = ANYTHING , kwargs = ANYTHING ) | An alternative constructor which raises the given error |
15,086 | def and_raises ( self , * errors ) : "Expects an error or more to be raised from the given expectation." for error in errors : self . __expect ( Expectation . raises , error ) | Expects an error or more to be raised from the given expectation . |
15,087 | def and_calls ( self , * funcs ) : for fn in funcs : self . __expect ( Expectation , Invoke ( fn ) ) | Expects the return value from one or more functions to be raised from the given expectation . |
15,088 | def and_yields ( self , * values ) : def generator ( ) : for value in values : yield value self . __expect ( Expectation , Invoke ( generator ) ) | Expects the return value of the expectation to be a generator of the given values |
15,089 | def attribute_invoked ( self , sender , name , args , kwargs ) : "Handles the creation of ExpectationBuilder when an attribute is invoked." return ExpectationBuilder ( self . sender , self . delegate , self . add_invocation , self . add_expectations , '__call__' ) ( * args , ** kwargs ) | Handles the creation of ExpectationBuilder when an attribute is invoked . |
15,090 | def attribute_read ( self , sender , name ) : "Handles the creation of ExpectationBuilder when an attribute is read." return ExpectationBuilder ( self . sender , self . delegate , self . add_invocation , self . add_expectations , name ) | Handles the creation of ExpectationBuilder when an attribute is read . |
15,091 | def key_read ( self , sender , name ) : "Handles the creation of ExpectationBuilder when a dictionary item access." return ExpectationBuilder ( self . sender , self . delegate , self . add_invocation , self . add_expectations , '__getitem__' ) ( name ) | Handles the creation of ExpectationBuilder when a dictionary item access . |
15,092 | def friendly_load ( parser , token ) : bits = token . contents . split ( ) if len ( bits ) >= 4 and bits [ - 2 ] == "from" : name = bits [ - 1 ] try : lib = find_library ( parser , name ) subset = load_from_library ( lib , name , bits [ 1 : - 2 ] ) parser . add_library ( subset ) except TemplateSyntaxError : pass else ... | Tries to load a custom template tag set . Non existing tag libraries are ignored . |
15,093 | def off ( self ) : self . win . keypad ( 0 ) curses . nocbreak ( ) curses . echo ( ) try : curses . curs_set ( 1 ) except : pass curses . endwin ( ) | Turn off curses |
15,094 | def _move_agent ( self , agent , direction , wrap_allowed = True ) : x , y = agent . coords [ 'x' ] , agent . coords [ 'y' ] print ( 'moving agent ' , agent . name , 'to x,y=' , direction , 'wrap_allowed = ' , wrap_allowed ) agent . coords [ 'x' ] = x + direction [ 0 ] agent . coords [ 'y' ] = y + direction [ 1 ] | moves agent agent in direction |
15,095 | def key_func ( * keys , ** kwargs ) : ensure_argcount ( keys , min_ = 1 ) ensure_keyword_args ( kwargs , optional = ( 'default' , ) ) keys = list ( map ( ensure_string , keys ) ) if 'default' in kwargs : default = kwargs [ 'default' ] def getitems ( obj ) : for key in keys : try : obj = obj [ key ] except KeyError : re... | Creates a key function based on given keys . |
15,096 | def find_files ( path , patterns ) : if not isinstance ( patterns , ( list , tuple ) ) : patterns = [ patterns ] matches = [ ] for root , dirnames , filenames in os . walk ( path ) : for pattern in patterns : for filename in fnmatch . filter ( filenames , pattern ) : matches . append ( os . path . join ( root , filenam... | Returns all files from a given path that matches the pattern or list of patterns |
15,097 | def recursive_update ( _dict , _update ) : for k , v in _update . items ( ) : if isinstance ( v , collections . Mapping ) : r = recursive_update ( _dict . get ( k , { } ) , v ) _dict [ k ] = r else : _dict [ k ] = _update [ k ] return _dict | Same as dict . update but updates also nested dicts instead of overriding then |
15,098 | def validate ( self , value ) : if not self . blank and value == '' : self . error_message = 'Can not be empty. Please provide a value.' return False self . _choice = value return True | The most basic validation |
15,099 | def validate ( self , value ) : if '.' not in value : self . error_message = '%s is not a fully qualified domain name.' % value return False try : ipaddress = socket . gethostbyname ( value ) except socket . gaierror : self . error_message = '%s does not resolve.' % value return False try : socket . gethostbyaddr ( ipa... | Attempts a forward lookup via the socket library and if successful will try to do a reverse lookup to verify DNS is returning both lookups . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.