idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
15,300
def remove ( self , w ) : if w not in self . f2i : raise ValueError ( "'{}' does not exist." . format ( w ) ) if w in self . reserved : raise ValueError ( "'{}' is one of the reserved words, and thus" "cannot be removed." . format ( w ) ) index = self . f2i [ w ] del self . f2i [ w ] del self . i2f [ index ] self . wor...
Removes a word from the vocab . The indices are unchanged .
15,301
def reconstruct_indices ( self ) : del self . i2f , self . f2i self . f2i , self . i2f = { } , { } for i , w in enumerate ( self . words ) : self . f2i [ w ] = i self . i2f [ i ] = w
Reconstruct word indices in case of word removals . Vocabulary does not handle empty indices when words are removed hence it need to be told explicity about when to reconstruct them .
15,302
def run ( self , data ) : result_type = namedtuple ( 'Result' , 'code messages' ) if self . passes is True : result = result_type ( Checker . Code . PASSED , '' ) elif self . passes is False : if self . allow_failure : result = result_type ( Checker . Code . IGNORED , '' ) else : result = result_type ( Checker . Code ....
Run the check method and format the result for analysis .
15,303
def is_numeric ( value ) : return type ( value ) in [ int , float , np . int8 , np . int16 , np . int32 , np . int64 , np . float16 , np . float32 , np . float64 , np . float128 ]
Test if a value is numeric .
15,304
def cmd ( send , msg , args ) : if msg == 'list' : fortunes = list_fortunes ( ) + list_fortunes ( True ) send ( " " . join ( fortunes ) , ignore_length = True ) else : output = get_fortune ( msg , args [ 'name' ] ) for line in output . splitlines ( ) : send ( line )
Returns a fortune .
15,305
def compile_theme ( theme_id = None ) : from engineer . processors import convert_less from engineer . themes import ThemeManager if theme_id is None : themes = ThemeManager . themes ( ) . values ( ) else : themes = [ ThemeManager . theme ( theme_id ) ] with ( indent ( 2 ) ) : puts ( colored . yellow ( "Compiling %s th...
Compiles a theme .
15,306
def list_theme ( ) : from engineer . themes import ThemeManager themes = ThemeManager . themes ( ) col1 , col2 = map ( max , zip ( * [ ( len ( t . id ) + 2 , len ( t . root_path ) + 2 ) for t in themes . itervalues ( ) ] ) ) themes = ThemeManager . themes_by_finder ( ) for finder in sorted ( themes . iterkeys ( ) ) : i...
List all available Engineer themes .
15,307
def quantile_norm ( X ) : quantiles = np . mean ( np . sort ( X , axis = 0 ) , axis = 1 ) ranks = np . apply_along_axis ( stats . rankdata , 0 , X ) rank_indices = ranks . astype ( int ) - 1 Xn = quantiles [ rank_indices ] return ( Xn )
Normalize the columns of X to each have the same distribution .
15,308
def corrdfs ( df1 , df2 , method ) : dcorr = pd . DataFrame ( columns = df1 . columns , index = df2 . columns ) dpval = pd . DataFrame ( columns = df1 . columns , index = df2 . columns ) for c1 in df1 : for c2 in df2 : if method == 'spearman' : dcorr . loc [ c2 , c1 ] , dpval . loc [ c2 , c1 ] = spearmanr ( df1 [ c1 ] ...
df1 in columns df2 in rows
15,309
def pretty_description ( description , wrap_at = None , indent = 0 ) : if wrap_at is None or wrap_at < 0 : width = console_width ( default = 79 ) if wrap_at is None : wrap_at = width else : wrap_at += width indent = ' ' * indent text_wrapper = textwrap . TextWrapper ( width = wrap_at , replace_whitespace = False , init...
Return a pretty formatted string given some text .
15,310
def print_name ( self , indent = 0 , end = '\n' ) : print ( Style . BRIGHT + ' ' * indent + self . name , end = end )
Print name with optional indent and end .
15,311
def print ( self ) : print ( '{dim}Identifier:{none} {cyan}{identifier}{none}\n' '{dim}Name:{none} {name}\n' '{dim}Description:{none}\n{description}' . format ( dim = Style . DIM , cyan = Fore . CYAN , none = Style . RESET_ALL , identifier = self . identifier , name = self . name , description = pretty_description ( se...
Print self .
15,312
def filter ( self , value , table = None ) : if table is not None : filterable = self . filterable_func ( value , table ) else : filterable = self . filterable_func ( value ) return filterable
Return True if the value should be pruned ; False otherwise .
15,313
def get_data ( self , file_path = sys . stdin , delimiter = ',' , categories_delimiter = None ) : if file_path == sys . stdin : logger . info ( 'Read data from standard input' ) lines = [ line . replace ( '\n' , '' ) for line in file_path ] else : logger . info ( 'Read data from file ' + file_path ) with open ( file_pa...
Implement get_dsm method from Provider class .
15,314
def parse_tags ( self ) : tags = [ ] try : for tag in self . _tag_group_dict [ "tags" ] : tags . append ( Tag ( tag ) ) except : return tags return tags
Parses tags in tag group
15,315
def update ( self ) : if self . _is_ignored or "tags" not in self . _tag_group_dict : return for i in range ( len ( self . _tag_group_dict [ "tags" ] ) ) : tag_dict = self . _tag_group_dict [ "tags" ] [ i ] for tag in self . _tags : if tag . name == tag_dict [ "common.ALLTYPES_NAME" ] : self . _tag_group_dict [ "tags" ...
Updates the dictionary of the tag group
15,316
def cmd ( send , msg , args ) : if not msg : send ( "Evaluate what?" ) return params = { 'format' : 'plaintext' , 'reinterpret' : 'true' , 'input' : msg , 'appid' : args [ 'config' ] [ 'api' ] [ 'wolframapikey' ] } req = get ( 'http://api.wolframalpha.com/v2/query' , params = params ) if req . status_code == 403 : send...
Queries WolframAlpha .
15,317
def _get_soup ( page ) : request = requests . get ( page ) data = request . text return bs4 . BeautifulSoup ( data )
Return BeautifulSoup object for given page
15,318
def search ( term , category = Categories . ALL , pages = 1 , sort = None , order = None ) : s = Search ( ) s . search ( term = term , category = category , pages = pages , sort = sort , order = order ) return s
Return a search result for term in category . Can also be sorted and span multiple pages .
15,319
def popular ( category = None , sortOption = "title" ) : s = Search ( ) s . popular ( category , sortOption ) return s
Return a search result containing torrents appearing on the KAT home page . Can be categorized . Cannot be sorted or contain multiple pages
15,320
def recent ( category = None , pages = 1 , sort = None , order = None ) : s = Search ( ) s . recent ( category , pages , sort , order ) return s
Return most recently added torrents . Can be sorted and categorized and contain multiple pages .
15,321
def print_details ( self ) : print ( "Title:" , self . title ) print ( "Category:" , self . category ) print ( "Page: " , self . page ) print ( "Size: " , self . size ) print ( "Files: " , self . files ) print ( "Age: " , self . age ) print ( "Seeds:" , self . seeders ) print ( "Leechers: " , self . leechers ) print ( ...
Print torrent details
15,322
def search ( self , term = None , category = None , pages = 1 , url = search_url , sort = None , order = None ) : if not self . current_url : self . current_url = url if self . current_url == Search . base_url : results = self . _get_results ( self . current_url ) self . _add_results ( results ) else : search = self . ...
Search a given URL for torrent results .
15,323
def _categorize ( self , category ) : self . torrents = [ result for result in self . torrents if result . category == category ]
Remove torrents with unwanted category from self . torrents
15,324
def page ( self , i ) : self . torrents = list ( ) self . _current_page = i self . search ( term = self . term , category = self . category , sort = self . sort , order = self . order )
Get page i of search results
15,325
def _get_results ( self , page ) : soup = _get_soup ( page ) details = soup . find_all ( "tr" , class_ = "odd" ) even = soup . find_all ( "tr" , class_ = "even" ) for i in range ( len ( even ) ) : details . insert ( ( i * 2 ) + 1 , even [ i ] ) return self . _parse_details ( details )
Find every div tag containing torrent details on given page then parse the results into a list of Torrents and return them
15,326
def _parse_details ( self , tag_list ) : result = list ( ) for i , item in enumerate ( tag_list ) : title = item . find ( "a" , class_ = "cellMainLink" ) title_text = title . text link = title . get ( "href" ) tds = item . find_all ( "td" , class_ = "center" ) size = tds [ 0 ] . text files = tds [ 1 ] . text age = tds ...
Given a list of tags from either a search page or the KAT home page parse the details and return a list of Torrents
15,327
def init_weights ( self ) : self . W = np . random . randn ( self . n_neurons , self . n_inputs ) * np . sqrt ( 2 / self . n_inputs ) self . b = np . zeros ( ( self . n_neurons , 1 ) )
Performs He initialization
15,328
def bootstrap_executive_office_states ( self , election ) : content_type = ContentType . objects . get_for_model ( election . race . office ) for division in Division . objects . filter ( level = self . STATE_LEVEL ) : PageContent . objects . get_or_create ( content_type = content_type , object_id = election . race . o...
Create state page content exclusively for the U . S . president .
15,329
def average_last_builds ( connection , package , limit = 5 ) : state = build_states . COMPLETE opts = { 'limit' : limit , 'order' : '-completion_time' } builds = yield connection . listBuilds ( package , state = state , queryOpts = opts ) if not builds : defer . returnValue ( None ) durations = [ build . duration for b...
Find the average duration time for the last couple of builds .
15,330
def model_resources ( self ) : response = jsonify ( { 'apiVersion' : '0.1' , 'swaggerVersion' : '1.1' , 'basePath' : '%s%s' % ( self . base_uri ( ) , self . api . url_prefix ) , 'apis' : self . get_model_resources ( ) } ) response . headers . add ( 'Cache-Control' , 'max-age=0' ) return response
Listing of all supported resources .
15,331
def model_resource ( self , resource_name ) : resource = first ( [ resource for resource in self . api . _registry . values ( ) if resource . get_api_name ( ) == resource_name ] ) data = { 'apiVersion' : '0.1' , 'swaggerVersion' : '1.1' , 'basePath' : '%s%s' % ( self . base_uri ( ) , self . api . url_prefix ) , 'resour...
Details of a specific model resource .
15,332
def _high_dim_sim ( self , v , w , normalize = False , X = None , idx = 0 ) : sim = np . exp ( ( - np . linalg . norm ( v - w ) ** 2 ) / ( 2 * self . _sigma [ idx ] ** 2 ) ) if normalize : return sim / sum ( map ( lambda x : x [ 1 ] , self . _knn ( idx , X , high_dim = True ) ) ) else : return sim
Similarity measurement based on Gaussian Distribution
15,333
def init ( confdir = "/etc/cslbot" ) : multiprocessing . set_start_method ( 'spawn' ) parser = argparse . ArgumentParser ( ) parser . add_argument ( '-d' , '--debug' , help = 'Enable debug logging.' , action = 'store_true' ) parser . add_argument ( '--validate' , help = 'Initialize the db and perform other sanity check...
The bot s main entry point .
15,334
def get_version ( self ) : _ , version = misc . get_version ( self . confdir ) if version is None : return "Can't get the version." else : return "cslbot - %s" % version
Get the version .
15,335
def shutdown_mp ( self , clean = True ) : if hasattr ( self , 'server' ) : try : self . server . socket . shutdown ( socket . SHUT_RDWR ) except OSError : pass self . server . socket . close ( ) self . server . shutdown ( ) if hasattr ( self , 'handler' ) : self . handler . workers . stop_workers ( clean )
Shutdown all the multiprocessing .
15,336
def handle_msg ( self , c , e ) : try : self . handler . handle_msg ( c , e ) except Exception as ex : backtrace . handle_traceback ( ex , c , self . get_target ( e ) , self . config )
Handles all messages .
15,337
def reload_handler ( self , c , e ) : cmd = self . is_reload ( e ) cmdchar = self . config [ 'core' ] [ 'cmdchar' ] if cmd is not None : if self . reload_event . set ( ) : admins = [ self . config [ 'auth' ] [ 'owner' ] ] else : with self . handler . db . session_scope ( ) as session : admins = [ x . nick for x in sess...
This handles reloads .
15,338
def _options_to_dict ( df ) : kolums = [ "k1" , "k2" , "value" ] d = df [ kolums ] . values . tolist ( ) dc = { } for x in d : dc . setdefault ( x [ 0 ] , { } ) dc [ x [ 0 ] ] [ x [ 1 ] ] = x [ 2 ] return dc
Make a dictionary to print .
15,339
def _get_repo ( ) : command = [ 'git' , 'rev-parse' , '--show-toplevel' ] if six . PY2 : try : return check_output ( command ) . decode ( 'utf-8' ) . strip ( ) except CalledProcessError : return '' else : return ( run ( command , stdout = PIPE , stderr = PIPE ) . stdout . decode ( 'utf-8' ) . strip ( ) )
Identify the path to the repository origin .
15,340
def _entry_must_exist ( df , k1 , k2 ) : count = df [ ( df [ 'k1' ] == k1 ) & ( df [ 'k2' ] == k2 ) ] . shape [ 0 ] if count == 0 : raise NotRegisteredError ( "Option {0}.{1} not registered" . format ( k1 , k2 ) )
Evaluate key - subkey existence .
15,341
def _entry_must_not_exist ( df , k1 , k2 ) : count = df [ ( df [ 'k1' ] == k1 ) & ( df [ 'k2' ] == k2 ) ] . shape [ 0 ] if count > 0 : raise AlreadyRegisteredError ( "Option {0}.{1} already registered" . format ( k1 , k2 ) )
Evaluate key - subkey non - existence .
15,342
def register_option ( self , key , subkey , default , _type , definition , values = None , locked = False ) : if not self . open : return key , subkey = _lower_keys ( key , subkey ) _entry_must_not_exist ( self . gc , key , subkey ) ev . value_eval ( default , _type ) values = None if values is False else values new_op...
Create a new option .
15,343
def unregister_option ( self , key , subkey ) : if not self . open : return key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) self . gc = self . gc [ ~ ( ( self . gc [ 'k1' ] == key ) & ( self . gc [ 'k2' ] == subkey ) ) ]
Removes an option from the manager .
15,344
def get_option ( self , key , subkey , in_path_none = False ) : key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) df = self . gc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) ] if df [ "type" ] . values [ 0 ] == "bool" : return bool ( df [ "value" ] . values...
Get the current value of the option .
15,345
def get_option_default ( self , key , subkey ) : key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) df = self . gc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) ] if df [ "type" ] . values [ 0 ] == "bool" : return bool ( df [ "default" ] . values [ 0 ] ) elif...
Get the default value of the option .
15,346
def get_option_description ( self , key , subkey ) : key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) return self . gc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) ] [ "description" ] . values [ 0 ]
Get the string describing a particular option .
15,347
def get_option_type ( self , key , subkey ) : key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) return self . gc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) ] [ "type" ] . values [ 0 ]
Get the type of a particular option .
15,348
def get_option_alternatives ( self , key , subkey ) : key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) return self . gc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) ] [ "values" ] . values [ 0 ]
Get list of available values for an option .
15,349
def set_option ( self , key , subkey , value ) : key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) df = self . gc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) ] if df [ "locked" ] . values [ 0 ] : raise ValueError ( "{0}.{1} option is locked" . format ( key...
Sets the value of an option .
15,350
def check_option ( self , key , subkey , value ) : key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) df = self . gc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) ] ev . value_eval ( value , df [ "type" ] . values [ 0 ] ) if df [ "values" ] . values [ 0 ] is ...
Evaluate if a given value fits the option .
15,351
def reset_option ( self , key , subkey ) : if not self . open : return key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) df = self . gc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) ] if df [ "locked" ] . values [ 0 ] : raise ValueError ( "{0}.{1} option is ...
Resets a single option to the default values .
15,352
def lock_option ( self , key , subkey ) : key , subkey = _lower_keys ( key , subkey ) _entry_must_exist ( self . gc , key , subkey ) self . gc . loc [ ( self . gc [ "k1" ] == key ) & ( self . gc [ "k2" ] == subkey ) , "locked" ] = True
Make an option unmutable .
15,353
def reset_options ( self , empty = True ) : if empty : self . gc = pd . DataFrame ( columns = self . clmn ) else : self . gc [ "value" ] = self . gc [ "default" ]
Empty ALL options .
15,354
def set_options_from_file ( self , filename , file_format = 'yaml' ) : if file_format . lower ( ) == 'yaml' : return self . set_options_from_YAML ( filename ) elif file_format . lower ( ) == 'json' : return self . set_options_from_JSON ( filename ) else : raise ValueError ( 'Unknown format {}' . format ( file_format ) ...
Load options from file .
15,355
def set_options_from_dict ( self , data_dict , filename = None ) : if filename is not None : filename = os . path . dirname ( filename ) for k in data_dict : if not isinstance ( data_dict [ k ] , dict ) : raise ValueError ( "The input data has to be a dict of dict" ) for sk in data_dict [ k ] : if self . gc [ ( self . ...
Load options from a dictionary .
15,356
def write_options_to_file ( self , filename , file_format = 'yaml' ) : if file_format . lower ( ) == 'yaml' : self . write_options_to_YAML ( filename ) elif file_format . lower ( ) == 'json' : self . write_options_to_JSON ( filename ) else : raise ValueError ( 'Unknown format {}' . format ( file_format ) )
Write options to file .
15,357
def write_options_to_YAML ( self , filename ) : fd = open ( filename , "w" ) yaml . dump ( _options_to_dict ( self . gc ) , fd , default_flow_style = False ) fd . close ( )
Writes the options in YAML format to a file .
15,358
def write_options_to_JSON ( self , filename ) : fd = open ( filename , "w" ) fd . write ( json . dumps ( _options_to_dict ( self . gc ) , indent = 2 , separators = ( ',' , ': ' ) ) ) fd . close ( )
Writes the options in JSON format to a file .
15,359
def document_options ( self ) : k1 = max ( [ len ( _ ) for _ in self . gc [ 'k1' ] ] ) + 4 k1 = max ( [ k1 , len ( 'Option Class' ) ] ) k2 = max ( [ len ( _ ) for _ in self . gc [ 'k2' ] ] ) + 4 k2 = max ( [ k2 , len ( 'Option ID' ) ] ) separators = " " . join ( [ "" . join ( [ "=" , ] * k1 ) , "" . join ( [ "=" , ] *...
Generates a docstring table to add to the library documentation .
15,360
def get_local_config_file ( cls , filename ) : if os . path . isfile ( filename ) : return filename else : try : config_repo = _get_repo ( ) if len ( config_repo ) == 0 : raise Exception ( ) config_repo = os . path . join ( config_repo , filename ) if os . path . isfile ( config_repo ) : return config_repo else : raise...
Find local file to setup default values .
15,361
def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'section' , nargs = '?' ) parser . add_argument ( 'command' ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if cmdargs . section : html = get (...
Gets a man page .
15,362
def cmd ( send , msg , args ) : key = args [ 'config' ] [ 'api' ] [ 'bitlykey' ] parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--blacklist' ) parser . add_argument ( '--unblacklist' ) try : cmdargs , msg = parser . parse_known_args ( msg ) msg = ' ' . join ( msg ) except arguments . Argu...
Gets a definition from urban dictionary .
15,363
def people ( self ) : people_response = self . get_request ( 'people/' ) return [ Person ( self , pjson [ 'user' ] ) for pjson in people_response ]
Generates a list of all People .
15,364
def tasks ( self ) : tasks_response = self . get_request ( 'tasks/' ) return [ Task ( self , tjson [ 'task' ] ) for tjson in tasks_response ]
Generates a list of all Tasks .
15,365
def clients ( self ) : clients_response = self . get_request ( 'clients/' ) return [ Client ( self , cjson [ 'client' ] ) for cjson in clients_response ]
Generates a list of all Clients .
15,366
def get_client ( self , client_id ) : client_response = self . get_request ( 'clients/%s' % client_id ) return Client ( self , client_response [ 'client' ] )
Gets a single client by id .
15,367
def get_project ( self , project_id ) : project_response = self . get_request ( 'projects/%s' % project_id ) return Project ( self , project_response [ 'project' ] )
Gets a single project by id .
15,368
def create_person ( self , first_name , last_name , email , department = None , default_rate = None , admin = False , contractor = False ) : person = { 'user' : { 'first_name' : first_name , 'last_name' : last_name , 'email' : email , 'department' : department , 'default_hourly_rate' : default_rate , 'is_admin' : admin...
Creates a Person with the given information .
15,369
def create_project ( self , name , client_id , budget = None , budget_by = 'none' , notes = None , billable = True ) : project = { 'project' : { 'name' : name , 'client_id' : client_id , 'budget_by' : budget_by , 'budget' : budget , 'notes' : notes , 'billable' : billable , } } response = self . post_request ( 'project...
Creates a Project with the given information .
15,370
def create_client ( self , name ) : client = { 'client' : { 'name' : name , } } response = self . post_request ( 'clients/' , client , follow = True ) if response : return Client ( self , response [ 'client' ] )
Creates a Client with the given information .
15,371
def delete ( self ) : response = self . hv . delete_request ( 'people/' + str ( self . id ) ) return response
Deletes the person immediately .
15,372
def task_assignments ( self ) : url = str . format ( 'projects/{}/task_assignments' , self . id ) response = self . hv . get_request ( url ) return [ TaskAssignment ( self . hv , tj [ 'task_assignment' ] ) for tj in response ]
Retrieves all tasks currently assigned to this project .
15,373
def partial ( cls , prefix , source ) : match = prefix + "." matches = cls ( [ ( key [ len ( match ) : ] , source [ key ] ) for key in source if key . startswith ( match ) ] ) if not matches : raise ValueError ( ) return matches
Strip a prefix from the keys of another dictionary returning a Bunch containing only valid key value pairs .
15,374
def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--nick' , action = arguments . NickParser ) parser . add_argument ( '--ignore-case' , '-i' , action = 'store_true' ) parser . add_argument ( 'string' , nargs = '*' ) try : cmdargs = parser . parse_args ( msg ) ...
Greps the log for a string .
15,375
def pick_action_todo ( ) : for ndx , todo in enumerate ( things_to_do ) : if roll_dice ( todo [ "chance" ] ) : cur_act = actions [ get_action_by_name ( todo [ "name" ] ) ] if todo [ "WHERE_COL" ] == "energy" and my_char [ "energy" ] > todo [ "WHERE_VAL" ] : return cur_act if todo [ "WHERE_COL" ] == "gold" and my_char [...
only for testing and AI - user will usually choose an action Sort of works
15,376
def do_action ( character , action ) : stats = "Energy=" + str ( round ( character [ "energy" ] , 0 ) ) + ", " stats += "Gold=" + str ( round ( character [ "gold" ] , 0 ) ) + ", " ndx_action_skill = get_skill_by_name ( action [ "name" ] , character ) stats += "Skill=" + str ( round ( character [ "skills" ] [ ndx_action...
called by main game loop to run an action
15,377
def get_inventory_by_name ( nme , character ) : for ndx , sk in enumerate ( character [ "inventory" ] ) : if sk [ "name" ] == nme : return ndx return 0
returns the inventory index by name
15,378
def get_skill_by_name ( nme , character ) : for ndx , sk in enumerate ( character [ "skills" ] ) : if sk [ "name" ] == nme : return ndx return 0
returns the skill by name in a character
15,379
def attribute_checker ( operator , attribute , value = '' ) : return { '=' : lambda el : el . get ( attribute ) == value , '~' : lambda el : value in el . get ( attribute , '' ) . split ( ) , '^' : lambda el : el . get ( attribute , '' ) . startswith ( value ) , '$' : lambda el : el . get ( attribute , '' ) . endswith ...
Takes an operator attribute and optional value ; returns a function that will return True for elements that match that combination .
15,380
def select ( soup , selector ) : tokens = selector . split ( ) current_context = [ soup ] for token in tokens : m = attribselect_re . match ( token ) if m : tag , attribute , operator , value = m . groups ( ) if not tag : tag = True checker = attribute_checker ( operator , attribute , value ) found = [ ] for context in...
soup should be a BeautifulSoup instance ; selector is a CSS selector specifying the elements you want to retrieve .
15,381
def gradient ( self , P , Q , Y , i ) : return 4 * sum ( [ ( P [ i , j ] - Q [ i , j ] ) * ( Y [ i ] - Y [ j ] ) * ( 1 + np . linalg . norm ( Y [ i ] - Y [ j ] ) ** 2 ) ** - 1 for j in range ( Y . shape [ 0 ] ) ] )
Computes the gradient of KL divergence with respect to the i th example of Y
15,382
def try_ ( block , except_ = None , else_ = None , finally_ = None ) : ensure_callable ( block ) if not ( except_ or else_ or finally_ ) : raise TypeError ( "at least one of `except_`, `else_` or `finally_` " "functions must be provided" ) if else_ and not except_ : raise TypeError ( "`else_` can only be provided along...
Emulate a try block .
15,383
def with_ ( contextmanager , do ) : ensure_contextmanager ( contextmanager ) ensure_callable ( do ) with contextmanager as value : return do ( value )
Emulate a with statement performing an operation within context .
15,384
def _cast_repr ( self , caster , * args , ** kwargs ) : if self . __repr_content is None : self . __repr_content = hash_and_truncate ( self ) assert self . __uses_default_repr return caster ( self . __repr_content , * args , ** kwargs )
Will cast this constant with the provided caster passing args and kwargs .
15,385
def cmd ( send , * _ ) : thread_names = [ ] for x in sorted ( threading . enumerate ( ) , key = lambda k : k . name ) : res = re . match ( r'Thread-(\d+$)' , x . name ) if res : tid = int ( res . group ( 1 ) ) if x . _target . __name__ == '_worker' : thread_names . append ( ( tid , "%s running server thread" % x . name...
Enumerate threads .
15,386
def pipe ( ) : try : from os import pipe return pipe ( ) except : pipe = Pipe ( ) return pipe . reader_fd , pipe . writer_fd
Return the optimum pipe implementation for the capabilities of the active system .
15,387
def read ( self ) : try : return self . reader . recv ( 1 ) except socket . error : ex = exception ( ) . exception if ex . args [ 0 ] == errno . EWOULDBLOCK : raise IOError raise
Emulate a file descriptors read method
15,388
def replace_all ( text , dic ) : for i , j in dic . iteritems ( ) : text = text . replace ( i , j ) return text
Takes a string and dictionary . replaces all occurrences of i with j
15,389
def replace_u_start_month ( month ) : month = month . lstrip ( '-' ) if month == 'uu' or month == '0u' : return '01' if month == 'u0' : return '10' return month . replace ( 'u' , '0' )
Find the earliest legitimate month .
15,390
def replace_u_end_month ( month ) : month = month . lstrip ( '-' ) if month == 'uu' or month == '1u' : return '12' if month == 'u0' : return '10' if month == '0u' : return '09' if month [ 1 ] in [ '1' , '2' ] : return month . replace ( 'u' , '1' ) return month . replace ( 'u' , '0' )
Find the latest legitimate month .
15,391
def replace_u_start_day ( day ) : day = day . lstrip ( '-' ) if day == 'uu' or day == '0u' : return '01' if day == 'u0' : return '10' return day . replace ( 'u' , '0' )
Find the earliest legitimate day .
15,392
def replace_u_end_day ( day , year , month ) : day = day . lstrip ( '-' ) year = int ( year ) month = int ( month . lstrip ( '-' ) ) if day == 'uu' or day == '3u' : return str ( calendar . monthrange ( year , month ) [ 1 ] ) if day == '0u' or day == '1u' : return day . replace ( 'u' , '9' ) if day == '2u' or day == 'u9...
Find the latest legitimate day .
15,393
def replace_u ( matchobj ) : pieces = list ( matchobj . groups ( '' ) ) if 'u' in pieces [ 1 ] : pieces [ 1 ] = pieces [ 1 ] . replace ( 'u' , '0' ) if 'u' in pieces [ 5 ] : pieces [ 5 ] = pieces [ 5 ] . replace ( 'u' , '9' ) if 'u' in pieces [ 2 ] : pieces [ 2 ] = '-' + replace_u_start_month ( pieces [ 2 ] ) if 'u' in...
Break the interval into parts and replace u s .
15,394
def zero_year_special_case ( from_date , to_date , start , end ) : if start == 'pos' and end == 'pos' : if from_date . startswith ( '0000' ) and not to_date . startswith ( '0000' ) : return True if not from_date . startswith ( '0000' ) and to_date . startswith ( '0000' ) : return False if from_date . startswith ( '0000...
strptime does not resolve a 0000 year we must handle this .
15,395
def is_valid_interval ( edtf_candidate ) : from_date = None to_date = None end , start = 'pos' , 'pos' if edtf_candidate . count ( '/' ) == 1 : edtf_candidate = replace_all ( edtf_candidate , interval_replacements ) edtf_candidate = re . sub ( U_PATTERN , replace_u , edtf_candidate ) parts = edtf_candidate . split ( '/...
Test to see if the edtf candidate is a valid interval
15,396
def isLevel2 ( edtf_candidate ) : if "[" in edtf_candidate or "{" in edtf_candidate : result = edtf_candidate == level2Expression elif " " in edtf_candidate : result = False else : result = edtf_candidate == level2Expression return result
Checks to see if the date is level 2 valid
15,397
def is_valid ( edtf_candidate ) : if ( isLevel0 ( edtf_candidate ) or isLevel1 ( edtf_candidate ) or isLevel2 ( edtf_candidate ) ) : if '/' in edtf_candidate : return is_valid_interval ( edtf_candidate ) else : return True else : return False
isValid takes a candidate date and returns if it is valid or not
15,398
def is_direct_subclass ( class_ , of ) : ensure_class ( class_ ) ensure_class ( of ) return of in class_ . __bases__
Check whether given class is a direct subclass of the other .
15,399
def ensure_direct_subclass ( class_ , of ) : if not is_direct_subclass ( class_ , of ) : raise TypeError ( "expected a direct subclass of %r, got %s instead" % ( of , class_ . __name__ ) ) return class_
Check whether given class is a direct subclass of another .