idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
15,400 | def serialisable ( cls , key , obj ) : # ignore class method names if key . startswith ( '_Serialisable' . format ( cls . __name__ ) ) : return False if key in obj . __whitelist : return True # class variables will be prefixed with '_<cls.__name__>__variable' # so let's remove these too #if key.startswith('__'): if '__' in key : return False # ignore our own class variables #if key in ['_Serialisable__whitelist', '_Serialisable__blacklist']: # return False if key in obj . __blacklist : return False if callable ( getattr ( obj , key ) ) : return False # check for properties if hasattr ( obj . __class__ , key ) : if isinstance ( getattr ( obj . __class__ , key ) , property ) : return False return True | Determines what can be serialised and what shouldn t | 200 | 12 |
15,401 | def normalise ( array ) : min_val = array . min ( ) max_val = array . max ( ) array_range = max_val - min_val if array_range == 0 : # min_val == max_val if min_val > 0 : return np . ones ( array . shape , dtype = np . float ) return np . zeros ( array . shape , dtype = np . float ) return ( array . astype ( np . float ) - min_val ) / array_range | Return array normalised such that all values are between 0 and 1 . | 111 | 14 |
15,402 | def reduce_stack ( array3D , z_function ) : xmax , ymax , _ = array3D . shape projection = np . zeros ( ( xmax , ymax ) , dtype = array3D . dtype ) for x in range ( xmax ) : for y in range ( ymax ) : projection [ x , y ] = z_function ( array3D [ x , y , : ] ) return projection | Return 2D array projection of the input 3D array . | 94 | 12 |
15,403 | def map_stack ( array3D , z_function ) : _ , _ , zdim = array3D . shape return np . dstack ( [ z_function ( array3D [ : , : , z ] ) for z in range ( zdim ) ] ) | Return 3D array where each z - slice has had the function applied to it . | 58 | 17 |
15,404 | def check_dtype ( array , allowed ) : if not hasattr ( allowed , "__iter__" ) : allowed = [ allowed , ] if array . dtype not in allowed : raise ( TypeError ( "Invalid dtype {}. Allowed dtype(s): {}" . format ( array . dtype , allowed ) ) ) | Raises TypeError if the array is not of an allowed dtype . | 72 | 15 |
15,405 | def handle_ctrlchan ( handler , msg , nick , send ) : with handler . db . session_scope ( ) as db : parser = init_parser ( send , handler , nick , db ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : # FIXME: figure out a better way to allow non-commands without spamming the channel. err_str = r"invalid choice: .* \(choose from 'quote', 'help', 'chanserv', 'cs', 'disable', 'enable', 'guard', 'unguard', 'show', 'accept', 'reject'\)" if not re . match ( err_str , str ( e ) ) : send ( str ( e ) ) return cmdargs . func ( cmdargs ) | Handle the control channel . | 172 | 5 |
15,406 | def cmd ( send , msg , args ) : incidents = get_incidents ( args [ 'config' ] [ 'api' ] [ 'wmatakey' ] ) if not incidents : send ( "No incidents found. Sure you picked the right metro system?" ) return for t , i in incidents . items ( ) : send ( "%s:" % get_type ( t ) ) for desc in i : send ( desc ) | Provides Metro Info . | 91 | 5 |
15,407 | def page_location ( self ) : cycle = self . election_day . cycle . name if self . content_type . model_class ( ) == PageType : print ( self . content_object ) return self . content_object . page_location_template ( ) elif self . content_type . model_class ( ) == Division : if self . content_object . level . name == DivisionLevel . STATE : if self . special_election : # /{state}/special-election/{month-day}/ path = os . path . join ( self . content_object . slug , "special-election" , self . election_day . special_election_datestring ( ) , ) else : # /{state}/ path = self . content_object . slug else : # / National path = "" # Offices and Bodies else : if self . division . level . name == DivisionLevel . STATE : if not self . content_object . body : path = os . path . join ( self . division . slug , "governor" ) else : path = os . path . join ( self . division . slug , self . content_object . slug ) else : path = self . content_object . slug return ( os . sep + os . path . normpath ( os . path . join ( cycle , path ) ) + os . sep ) | Returns the published URL for page . | 291 | 7 |
15,408 | def _get_object ( self , name ) : clean_name = self . _clean_name ( name ) try : return self . driver . get_object ( self . bucket , clean_name ) except ObjectDoesNotExistError : return None | Get object by its name . Return None if object not found | 53 | 12 |
15,409 | def delete ( self , name ) : obj = self . _get_object ( name ) if obj : return self . driver . delete_object ( obj ) | Delete object on remote | 33 | 4 |
15,410 | def listdir ( self , path = '/' ) : container = self . _get_bucket ( ) objects = self . driver . list_container_objects ( container ) path = self . _clean_name ( path ) if not path . endswith ( '/' ) : path = "%s/" % path files = [ ] dirs = [ ] # TOFIX: better algorithm to filter correctly # (and not depend on google-storage empty folder naming) for o in objects : if path == '/' : if o . name . count ( '/' ) == 0 : files . append ( o . name ) elif o . name . count ( '/' ) == 1 : dir_name = o . name [ : o . name . index ( '/' ) ] if dir_name not in dirs : dirs . append ( dir_name ) elif o . name . startswith ( path ) : if o . name . count ( '/' ) <= path . count ( '/' ) : # TOFIX : special case for google storage with empty dir if o . name . endswith ( '_$folder$' ) : name = o . name [ : - 9 ] name = name [ len ( path ) : ] dirs . append ( name ) else : name = o . name [ len ( path ) : ] files . append ( name ) return ( dirs , files ) | Lists the contents of the specified path returning a 2 - tuple of lists ; the first item being directories the second item being files . | 296 | 27 |
15,411 | def name ( cls , func ) : cls . count = cls . count + 1 fpath = '{}_{}{}' . format ( cls . count , func . __name__ , cls . suffix ) if cls . directory : fpath = os . path . join ( cls . directory , fpath ) return fpath | Return auto generated file name . | 75 | 6 |
15,412 | def split_pattern ( self ) : patterns = [ ] for p in self . split_order : patterns . append ( '_{}%{}' . format ( p . capitalize ( ) , p ) ) return '' . join ( patterns ) | Pattern used to split the input file . | 51 | 8 |
15,413 | def pick_random_target ( self ) : start_x = math . floor ( self . grd . grid_height / 2 ) start_y = math . floor ( self . grd . grid_width / 2 ) min_dist_from_x = 3 min_dist_from_y = 5 move_random_x = randint ( 1 , math . floor ( self . grd . grid_height / 2 ) ) move_random_y = randint ( 1 , math . floor ( self . grd . grid_width / 2 ) ) x = start_x + move_random_x - min_dist_from_x y = start_y + move_random_y - min_dist_from_y return [ x , y ] | returns coords of a randomly generated starting position mostly over to the right hand side of the world | 164 | 20 |
15,414 | def expand_seed ( self , start_seed , num_iterations , val ) : self . grd . set_tile ( start_seed [ 0 ] , start_seed [ 1 ] , val ) cur_pos = [ start_seed [ 0 ] , start_seed [ 1 ] ] while num_iterations > 0 : # don't use loop as it will hit boundaries often num_iterations -= 1 for y in range ( cur_pos [ 0 ] - randint ( 0 , 2 ) , cur_pos [ 0 ] + randint ( 0 , 2 ) ) : for x in range ( cur_pos [ 1 ] - randint ( 0 , 2 ) , cur_pos [ 1 ] + randint ( 0 , 2 ) ) : if x < self . grd . grid_width and x >= 0 and y >= 0 and y < self . grd . grid_height : #print(x,y,val) if self . grd . get_tile ( y , x ) != val : self . grd . set_tile ( y , x , TERRAIN_LAND ) num_iterations -= 1 new_x = cur_pos [ 0 ] + randint ( 0 , 3 ) - 2 new_y = cur_pos [ 1 ] + randint ( 0 , 3 ) - 2 if new_x > self . grd . grid_width - 1 : new_x = 0 if new_y > self . grd . grid_height - 1 : new_y = 0 if new_x < 0 : new_x = self . grd . grid_width - 1 if new_y < 0 : new_y = self . grd . grid_height - 1 cur_pos = [ new_y , new_x ] | takes a seed start point and grows out in random directions setting cell points to val | 379 | 17 |
15,415 | def denoise_grid ( self , val , expand = 1 ) : updated_grid = [ [ self . grd . get_tile ( y , x ) for x in range ( self . grd . grid_width ) ] for y in range ( self . grd . grid_height ) ] for row in range ( self . grd . get_grid_height ( ) - expand ) : for col in range ( self . grd . get_grid_width ( ) - expand ) : updated_grid [ row ] [ col ] = self . grd . get_tile ( row , col ) # set original point if self . grd . get_tile ( row , col ) == val : for y in range ( - expand , expand ) : for x in range ( - expand , expand ) : new_x = col + x new_y = row + y if new_x < 0 : new_x = 0 if new_y < 0 : new_y = 0 if new_x > self . grd . get_grid_width ( ) - 1 : new_x = self . grd . get_grid_width ( ) - 1 if new_y > self . grd . get_grid_height ( ) - 1 : new_y = self . grd . get_grid_height ( ) - 1 # randomly NOT denoise to make interesting edges if expand > 0 : if randint ( 1 , expand * 2 ) > ( expand + 1 ) : updated_grid [ new_y ] [ new_x ] = val else : updated_grid [ new_y ] [ new_x ] = val self . grd . replace_grid ( updated_grid ) | for every cell in the grid of val fill all cells around it to de noise the grid | 362 | 18 |
15,416 | def add_mountains ( self ) : from noise import pnoise2 import random random . seed ( ) octaves = ( random . random ( ) * 0.5 ) + 0.5 freq = 17.0 * octaves # for y in range ( self . grd . grid_height - 1 ) : for x in range ( self . grd . grid_width - 1 ) : pixel = self . grd . get_tile ( y , x ) if pixel == 'X' : # denoise blocks of mountains n = int ( pnoise2 ( x / freq , y / freq , 1 ) * 11 + 5 ) if n < 1 : self . grd . set_tile ( y , x , '#' ) | instead of the add_blocks function which was to produce line shaped walls for blocking path finding agents this function creates more natural looking blocking areas like mountains | 161 | 29 |
15,417 | def add_block ( self ) : row_max = self . grd . get_grid_height ( ) - 15 if row_max < 2 : row_max = 2 row = randint ( 0 , row_max ) col_max = self . grd . get_grid_width ( ) - 10 if col_max < 2 : col_max = 2 col = randint ( 0 , col_max ) direction = randint ( 1 , 19 ) - 10 if direction > 0 : y_len = 10 * ( math . floor ( self . grd . get_grid_height ( ) / 120 ) + 1 ) x_len = 1 * ( math . floor ( self . grd . get_grid_width ( ) / 200 ) + 1 ) else : y_len = 1 * ( math . floor ( self . grd . get_grid_height ( ) / 200 ) + 1 ) x_len = 10 * ( math . floor ( self . grd . get_grid_width ( ) / 120 ) + 1 ) print ( "Adding block to " , row , col , direction ) for r in range ( row , row + y_len ) : for c in range ( col , col + x_len ) : self . grd . set_tile ( r , c , TERRAIN_BLOCKED ) | adds a random size block to the map | 287 | 9 |
15,418 | def run ( self , num_runs , show_trails , log_file_base ) : print ( "--------------------------------------------------" ) print ( "Starting Simulation - target = " , self . agent_list [ 0 ] . target_y , self . agent_list [ 0 ] . target_x ) self . world . grd . set_tile ( self . agent_list [ 0 ] . target_y , self . agent_list [ 0 ] . target_x , 'T' ) self . highlight_cell_surroundings ( self . agent_list [ 0 ] . target_y , self . agent_list [ 0 ] . target_x ) self . start_all_agents ( ) # save the agents results here try : with open ( log_file_base + '__agents.txt' , "w" ) as f : f . write ( "Starting World = \n" ) f . write ( str ( self . world . grd ) ) except Exception : print ( 'Cant save log results to ' + log_file_base ) for cur_run in range ( 0 , num_runs ) : print ( "WorldSimulation:run#" , cur_run ) for num , agt in enumerate ( self . agent_list ) : if show_trails == 'Y' : if len ( self . agent_list ) == 1 or len ( self . agent_list ) > 9 : self . world . grd . set_tile ( agt . current_y , agt . current_x , 'o' ) else : self . world . grd . set_tile ( agt . current_y , agt . current_x , str ( num ) ) agt . do_your_job ( ) self . world . grd . set_tile ( agt . current_y , agt . current_x , 'A' ) # update the main world grid with agents changes # save grid after each run if required if log_file_base != 'N' : self . world . grd . save ( log_file_base + '_' + str ( cur_run ) + '.log' ) # save the agents results here with open ( log_file_base + '__agents.txt' , "a" ) as f : f . write ( "\nWorld tgt= [" + str ( self . agent_list [ 0 ] . target_y ) + "," + str ( self . agent_list [ 0 ] . target_x ) + "]\n" ) f . write ( str ( self . world . grd ) ) f . write ( '\n\nAgent Name , starting, num Steps , num Climbs\n' ) for num , agt in enumerate ( self . agent_list ) : res = agt . name + ' , [' + str ( agt . start_y ) + ', ' + str ( agt . start_x ) + '], ' res += str ( agt . num_steps ) + ' , ' + str ( agt . num_climbs ) + ' , ' res += '' . join ( [ a for a in agt . results ] ) f . write ( res + '\n' ) | Run each agent in the world for num_runs iterations Optionally saves grid results to file if base name is passed to method . | 695 | 26 |
15,419 | def highlight_cell_surroundings ( self , target_y , target_x ) : #print('SELF_WORLD', self.world) #print('target_y, target_x, self.world.grd.grid_height, self.world.grd.grid_width ', target_y, target_x, self.#world.grd.grid_height, self.world.grd.grid_width ) #exit(0) if target_y < 1 : print ( "target too close to top" ) if target_y > self . world . grd . grid_height - 1 : print ( "target too close to bottom" ) if target_x < 1 : print ( "target too close to left" ) if target_x < self . world . grd . grid_width : print ( "target too close to right" ) #valid_cells = ['\\', '-', '|', '/'] self . world . grd . set_tile ( target_y - 1 , target_x - 1 , '\\' ) self . world . grd . set_tile ( target_y - 0 , target_x - 1 , '-' ) self . world . grd . set_tile ( target_y + 1 , target_x - 1 , '/' ) self . world . grd . set_tile ( target_y - 1 , target_x - 0 , '|' ) self . world . grd . set_tile ( target_y + 1 , target_x - 0 , '|' ) self . world . grd . set_tile ( target_y - 1 , target_x + 1 , '/' ) self . world . grd . set_tile ( target_y - 0 , target_x + 1 , '-' ) self . world . grd . set_tile ( target_y + 1 , target_x + 1 , '\\' ) | highlights the cells around a target to make it simpler to see on a grid . Currently assumes the target is within the boundary by 1 on all sides | 417 | 30 |
15,420 | def cmd ( send , _ , args ) : def lenny_send ( msg ) : send ( gen_lenny ( msg ) ) key = args [ 'config' ] [ 'api' ] [ 'bitlykey' ] cmds = [ lambda : gen_fortune ( lenny_send ) , lambda : gen_urban ( lenny_send , args [ 'db' ] , key ) ] choice ( cmds ) ( ) | Abuses the bot . | 93 | 5 |
15,421 | def hamming_distance ( s1 , s2 ) : # print(s1,s2) if len ( s1 ) != len ( s2 ) : raise ValueError ( "Undefined for sequences of unequal length" ) return sum ( el1 != el2 for el1 , el2 in zip ( s1 . upper ( ) , s2 . upper ( ) ) ) | Return the Hamming distance between equal - length sequences | 81 | 10 |
15,422 | def cmd ( send , msg , args ) : if not msg : send ( "Explain What?" ) return msg = msg . replace ( ' ' , '+' ) msg = 'http://lmgtfy.com/?q=%s' % msg key = args [ 'config' ] [ 'api' ] [ 'bitlykey' ] send ( get_short ( msg , key ) ) | Explain things . | 86 | 4 |
15,423 | def split_msg ( msgs : List [ bytes ] , max_len : int ) -> Tuple [ str , List [ bytes ] ] : msg = "" while len ( msg . encode ( ) ) < max_len : if len ( msg . encode ( ) ) + len ( msgs [ 0 ] ) > max_len : return msg , msgs char = msgs . pop ( 0 ) . decode ( ) # If we have a space within 15 chars of the length limit, split there to avoid words being broken up. if char == " " and len ( msg . encode ( ) ) > max_len - 15 : return msg , msgs msg += char return msg , msgs | Splits as close to the end as possible . | 146 | 10 |
15,424 | def check ( self , order , sids ) : payload = "{}" #TODO store hashes {'intuition': {'id1': value, 'id2': value}} # Block self.timeout seconds on self.channel for a message raw_msg = self . client . blpop ( self . channel , timeout = self . timeout ) if raw_msg : _ , payload = raw_msg msg = json . loads ( payload . replace ( "'" , '"' ) , encoding = 'utf-8' ) for sid in msg . keys ( ) : #TODO Harmonize lower() and upper() symbols if sid . lower ( ) in map ( str . lower , sids ) : print ( 'ordering {} of {}' . format ( msg [ sid ] , sid ) ) #order(sid.upper(), msg[sid]) order ( sid , msg [ sid ] ) else : print ( 'skipping unknown symbol {}' . format ( sid ) ) | Check if a message is available | 205 | 6 |
15,425 | def cmd ( send , msg , args ) : if not msg : send ( "This tastes yummy!" ) elif msg == args [ 'botnick' ] : send ( "wyang says Cannibalism is generally frowned upon." ) else : send ( "%s tastes yummy!" % msg . capitalize ( ) ) | Causes the bot to snack on something . | 67 | 9 |
15,426 | def next ( self ) : if not self . _cache : self . _cache = self . _get_results ( ) self . _retrieved += len ( self . _cache ) # If we don't have any other data to return, we just # stop the iteration. if not self . _cache : raise StopIteration ( ) # Consuming the cache and updating the "cursor" return self . _cache . pop ( 0 ) | Provide iteration capabilities | 93 | 4 |
15,427 | def cmd ( send , msg , args ) : users = get_users ( args ) if " into " in msg and msg != "into" : match = re . match ( '(.*) into (.*)' , msg ) if match : msg = 'throws %s into %s' % ( match . group ( 1 ) , match . group ( 2 ) ) send ( msg , 'action' ) else : return elif " at " in msg and msg != "at" : match = re . match ( '(.*) at (.*)' , msg ) if match : msg = 'throws %s at %s' % ( match . group ( 1 ) , match . group ( 2 ) ) send ( msg , 'action' ) else : return elif msg : msg = 'throws %s at %s' % ( msg , choice ( users ) ) send ( msg , 'action' ) else : send ( "Throw what?" ) return | Throw something . | 201 | 3 |
15,428 | def wrap ( self , function ) : func = inspect . getfullargspec ( function ) needed_arguments = func . args + func . kwonlyargs @ wraps ( function ) def wrapper ( * args , * * kwargs ) : arguments = kwargs . copy ( ) missing_arguments = needed_arguments - arguments . keys ( ) for arg in missing_arguments : try : arguments [ arg ] = self . _get_argument ( arg ) except KeyError : pass return function ( * args , * * arguments ) return wrapper | Wraps a function so that all unspecified arguments will be injected if possible . Specified arguments always have precedence . | 117 | 22 |
15,429 | def call ( self , func , * args , * * kwargs ) : wrapped = self . wrap ( func ) return wrapped ( * args , * * kwargs ) | Calls a specified function using the provided arguments and injectable arguments . | 37 | 14 |
15,430 | def png ( self ) : use_plugin ( 'freeimage' ) with TemporaryFilePath ( suffix = '.png' ) as tmp : safe_range_im = 255 * normalise ( self ) imsave ( tmp . fpath , safe_range_im . astype ( np . uint8 ) ) with open ( tmp . fpath , 'rb' ) as fh : return fh . read ( ) | Return png string of image . | 89 | 7 |
15,431 | def is_me ( self , s , c , z , t ) : if ( self . series == s and self . channel == c and self . zslice == z and self . timepoint == t ) : return True return False | Return True if arguments match my meta data . | 49 | 9 |
15,432 | def in_zstack ( self , s , c , t ) : if ( self . series == s and self . channel == c and self . timepoint == t ) : return True return False | Return True if I am in the zstack . | 41 | 10 |
15,433 | def find_specs ( self , directory ) : specs = [ ] spec_files = self . file_finder . find ( directory ) for spec_file in spec_files : specs . extend ( self . spec_finder . find ( spec_file . module ) ) return specs | Finds all specs in a given directory . Returns a list of Example and ExampleGroup instances . | 59 | 19 |
15,434 | def flip ( f ) : ensure_callable ( f ) result = lambda * args , * * kwargs : f ( * reversed ( args ) , * * kwargs ) functools . update_wrapper ( result , f , ( '__name__' , '__module__' ) ) return result | Flip the order of positonal arguments of given function . | 67 | 12 |
15,435 | def compose ( * fs ) : ensure_argcount ( fs , min_ = 1 ) fs = list ( imap ( ensure_callable , fs ) ) if len ( fs ) == 1 : return fs [ 0 ] if len ( fs ) == 2 : f1 , f2 = fs return lambda * args , * * kwargs : f1 ( f2 ( * args , * * kwargs ) ) if len ( fs ) == 3 : f1 , f2 , f3 = fs return lambda * args , * * kwargs : f1 ( f2 ( f3 ( * args , * * kwargs ) ) ) fs . reverse ( ) def g ( * args , * * kwargs ) : x = fs [ 0 ] ( * args , * * kwargs ) for f in fs [ 1 : ] : x = f ( x ) return x return g | Creates composition of the functions passed in . | 191 | 9 |
15,436 | def merge ( arg , * rest , * * kwargs ) : ensure_keyword_args ( kwargs , optional = ( 'default' , ) ) has_default = 'default' in kwargs if has_default : default = ensure_callable ( kwargs [ 'default' ] ) # if more than one argument was given, they must all be functions; # result will be a function that takes multiple arguments (rather than # a single collection) and returns a tuple unary_result = True if rest : fs = ( ensure_callable ( arg ) , ) + tuple ( imap ( ensure_callable , rest ) ) unary_result = False else : fs = arg if is_mapping ( fs ) : if has_default : return lambda arg_ : fs . __class__ ( ( k , fs . get ( k , default ) ( arg_ [ k ] ) ) for k in arg_ ) else : return lambda arg_ : fs . __class__ ( ( k , fs [ k ] ( arg_ [ k ] ) ) for k in arg_ ) else : ensure_sequence ( fs ) if has_default : # we cannot use ``izip_longest(fs, arg_, fillvalue=default)``, # because we want to terminate the generator # only when ``arg_`` is exhausted (not when just ``fs`` is) func = lambda arg_ : fs . __class__ ( ( fs [ i ] if i < len ( fs ) else default ) ( x ) for i , x in enumerate ( arg_ ) ) else : # we cannot use ``izip(fs, arg_)`` because it would short-circuit # if ``arg_`` is longer than ``fs``, rather than raising # the required ``IndexError`` func = lambda arg_ : fs . __class__ ( fs [ i ] ( x ) for i , x in enumerate ( arg_ ) ) return func if unary_result else lambda * args : func ( args ) | Merge a collection with functions as items into a single function that takes a collection and maps its items through corresponding functions . | 431 | 24 |
15,437 | def and_ ( * fs ) : ensure_argcount ( fs , min_ = 1 ) fs = list ( imap ( ensure_callable , fs ) ) if len ( fs ) == 1 : return fs [ 0 ] if len ( fs ) == 2 : f1 , f2 = fs return lambda * args , * * kwargs : ( f1 ( * args , * * kwargs ) and f2 ( * args , * * kwargs ) ) if len ( fs ) == 3 : f1 , f2 , f3 = fs return lambda * args , * * kwargs : ( f1 ( * args , * * kwargs ) and f2 ( * args , * * kwargs ) and f3 ( * args , * * kwargs ) ) def g ( * args , * * kwargs ) : for f in fs : if not f ( * args , * * kwargs ) : return False return True return g | Creates a function that returns true for given arguments iff every given function evalutes to true for those arguments . | 208 | 23 |
15,438 | def get_stats ( self ) : try : query = { # We only care about the aggregations, so don't return the hits 'size' : 0 , 'aggs' : { 'num_packages' : { 'value_count' : { 'field' : 'id' , } , } , 'num_records' : { 'sum' : { 'field' : 'package.count_of_rows' , } , } , 'num_countries' : { 'cardinality' : { 'field' : 'package.countryCode.keyword' , } , } , } , } aggregations = self . es . search ( index = self . index_name , body = query ) [ 'aggregations' ] return { key : int ( value [ 'value' ] ) for key , value in aggregations . items ( ) } except NotFoundError : return { } | Get some stats on the packages in the registry | 194 | 9 |
15,439 | def cmd ( send , msg , args ) : req = get ( "http://api.fmylife.com/view/random" , params = { 'language' : 'en' , 'key' : args [ 'config' ] [ 'api' ] [ 'fmlkey' ] } ) doc = fromstring ( req . content ) send ( doc . xpath ( '//text' ) [ 0 ] . text ) | Gets a random FML post . | 91 | 7 |
15,440 | def cmd ( send , msg , args ) : if not args [ 'config' ] [ 'feature' ] . getboolean ( 'hooks' ) : send ( "Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s)." ) return session = args [ 'db' ] parser = arguments . ArgParser ( args [ 'config' ] ) group = parser . add_mutually_exclusive_group ( ) group . add_argument ( '--high' , action = 'store_true' ) group . add_argument ( '--low' , action = 'store_true' ) group . add_argument ( 'nick' , nargs = '?' , action = arguments . NickParser ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if cmdargs . high : data = session . query ( Scores ) . order_by ( Scores . score . desc ( ) ) . limit ( 3 ) . all ( ) send ( 'High Scores:' ) for x in data : send ( "%s: %s" % ( x . nick , x . score ) ) elif cmdargs . low : data = session . query ( Scores ) . order_by ( Scores . score ) . limit ( 3 ) . all ( ) send ( 'Low Scores:' ) for x in data : send ( "%s: %s" % ( x . nick , x . score ) ) elif cmdargs . nick : name = cmdargs . nick . lower ( ) if name == 'c' : send ( "We all know you love C better than anything else, so why rub it in?" ) return score = session . query ( Scores ) . filter ( Scores . nick == name ) . scalar ( ) if score is not None : plural = '' if abs ( score . score ) == 1 else 's' if name == args [ 'botnick' ] . lower ( ) : emote = ':)' if score . score > 0 else ':(' if score . score < 0 else ':|' output = 'has %s point%s! %s' % ( score . score , plural , emote ) send ( output , 'action' ) else : send ( "%s has %i point%s!" % ( name , score . score , plural ) ) else : send ( "Nobody cares about %s" % name ) else : if session . query ( Scores ) . count ( ) == 0 : send ( "Nobody cares about anything =(" ) else : query = session . query ( Scores ) . order_by ( func . random ( ) ) . first ( ) plural = '' if abs ( query . score ) == 1 else 's' send ( "%s has %i point%s!" % ( query . nick , query . score , plural ) ) | Gets scores . | 609 | 4 |
15,441 | def add_affect ( self , name , src , dest , val , condition = None ) : self . affects . append ( ParamAffects ( name , src , dest , val , condition ) ) | adds how param src affects param dest to the list | 43 | 11 |
15,442 | def get_by_name ( self , nme ) : for p in self . params : if p . name == nme : return p return None | searches list of all parameters and returns the first param that matches on name | 32 | 16 |
15,443 | def get_affects_for_param ( self , nme ) : res = [ ] for a in self . affects : if a . name == nme : res . append ( a ) return res | searches all affects and returns a list that affect the param named nme | 44 | 16 |
15,444 | def buildPrices ( data , roles = None , regex = default_price_regex , default = None , additional = { } ) : if isinstance ( data , dict ) : data = [ ( item [ 0 ] , convertPrice ( item [ 1 ] ) ) for item in data . items ( ) ] return dict ( [ v for v in data if v [ 1 ] is not None ] ) elif isinstance ( data , ( str , float , int ) ) and not isinstance ( data , bool ) : if default is None : raise ValueError ( 'You have to call setAdditionalCharges ' 'before it is possible to pass a string as price' ) basePrice = convertPrice ( data ) if basePrice is None : return { } prices = { default : basePrice } for role in additional : extraCharge = convertPrice ( additional [ role ] ) if extraCharge is None : continue prices [ role ] = basePrice + extraCharge return prices elif roles : prices = { } priceRoles = iter ( roles ) for priceData in data : price = convertPrice ( priceData ) if price is None : continue prices [ next ( priceRoles ) ] = price return prices else : raise TypeError ( 'This type is for prices not supported!' ) | Create a dictionary with price information . Multiple ways are supported . | 266 | 12 |
15,445 | def buildLegend ( legend = None , text = None , regex = None , key = lambda v : v ) : if legend is None : legend = { } if text is not None : for match in re . finditer ( regex or default_legend_regex , text , re . UNICODE ) : legend [ key ( match . group ( 'name' ) ) ] = match . group ( 'value' ) . strip ( ) return legend | Helper method to build or extend a legend from a text . The given regex will be used to find legend inside the text . | 95 | 25 |
15,446 | def toTag ( self , output ) : feed = output . createElement ( 'feed' ) feed . setAttribute ( 'name' , self . name ) feed . setAttribute ( 'priority' , str ( self . priority ) ) # schedule schedule = output . createElement ( 'schedule' ) schedule . setAttribute ( 'dayOfMonth' , self . dayOfMonth ) schedule . setAttribute ( 'dayOfWeek' , self . dayOfWeek ) schedule . setAttribute ( 'hour' , self . hour ) schedule . setAttribute ( 'minute' , self . minute ) if self . retry : schedule . setAttribute ( 'retry' , self . retry ) feed . appendChild ( schedule ) # url url = output . createElement ( 'url' ) url . appendChild ( output . createTextNode ( self . url ) ) feed . appendChild ( url ) # source if self . source : source = output . createElement ( 'source' ) source . appendChild ( output . createTextNode ( self . source ) ) feed . appendChild ( source ) return feed | This methods returns all data of this feed as feed xml tag | 230 | 12 |
15,447 | def hasMealsFor ( self , date ) : date = self . _handleDate ( date ) if date not in self . _days or self . _days [ date ] is False : return False return len ( self . _days [ date ] ) > 0 | Checks whether for this day are information stored . | 55 | 10 |
15,448 | def toXMLFeed ( self ) : feed = self . toXML ( ) xml_header = '<?xml version="1.0" encoding="UTF-8"?>\n' return xml_header + feed . toprettyxml ( indent = ' ' ) | Convert this cateen information into string which is a valid OpenMensa v2 xml feed | 57 | 21 |
15,449 | def toTag ( self , output ) : # create canteen tag, which represents our data canteen = output . createElement ( 'canteen' ) if self . _name is not None : canteen . appendChild ( self . _buildStringTag ( 'name' , self . _name , output ) ) if self . _address is not None : canteen . appendChild ( self . _buildStringTag ( 'address' , self . _address , output ) ) if self . _city is not None : canteen . appendChild ( self . _buildStringTag ( 'city' , self . _city , output ) ) if self . _phone is not None : canteen . appendChild ( self . _buildStringTag ( 'phone' , self . _phone , output ) ) if self . _email is not None : canteen . appendChild ( self . _buildStringTag ( 'email' , self . _email , output ) ) if self . _location is not None : canteen . appendChild ( self . _buildLocationTag ( self . _location , output ) ) if self . _availability is not None : canteen . appendChild ( self . _buildStringTag ( 'availability' , self . _availability , output ) ) # iterate above all feeds: for feed in sorted ( self . feeds , key = lambda v : v . priority ) : canteen . appendChild ( feed . toTag ( output ) ) # iterate above all days (sorted): for date in sorted ( self . _days . keys ( ) ) : day = output . createElement ( 'day' ) day . setAttribute ( 'date' , str ( date ) ) if self . _days [ date ] is False : # canteen closed closed = output . createElement ( 'closed' ) day . appendChild ( closed ) canteen . appendChild ( day ) continue # canteen is open for categoryname in self . _days [ date ] : day . appendChild ( self . _buildCategoryTag ( categoryname , self . _days [ date ] [ categoryname ] , output ) ) canteen . appendChild ( day ) return canteen | This methods adds all data of this canteen as canteen xml tag to the given xml Document . | 457 | 20 |
15,450 | def add_session ( self , session , input_dataset = True , summary_table = True , recommendation_details = True , recommended_model = True , all_models = False , ) : self . doc . add_paragraph ( session . dataset . _get_dataset_name ( ) , self . styles . header_1 ) self . doc . add_paragraph ( "BMDS version: {}" . format ( session . version_pretty ) ) if input_dataset : self . _add_dataset ( session ) self . doc . add_paragraph ( ) if summary_table : self . _add_session_summary_table ( session ) self . doc . add_paragraph ( ) if recommendation_details : self . _add_recommendation_details_table ( session ) self . doc . add_paragraph ( ) if recommended_model and all_models : self . _add_recommended_model ( session ) self . _add_all_models ( session , except_recommended = True ) self . doc . add_paragraph ( ) elif recommended_model : self . _add_recommended_model ( session ) self . doc . add_paragraph ( ) elif all_models : self . _add_all_models ( session , except_recommended = False ) self . doc . add_paragraph ( ) self . doc . add_page_break ( ) | Add an existing session to a Word report . | 301 | 9 |
15,451 | def save ( self , filename ) : self . doc . save ( os . path . expanduser ( filename ) ) | Save document to a file . | 24 | 6 |
15,452 | def _get_session_for_table ( self , base_session ) : if base_session . recommended_model is None and base_session . doses_dropped > 0 : return base_session . doses_dropped_sessions [ 0 ] return base_session | Only present session for modeling when doses were dropped if it s succesful ; otherwise show the original modeling session . | 58 | 23 |
15,453 | def set_driver_simulated ( self ) : self . _device_dict [ "servermain.MULTIPLE_TYPES_DEVICE_DRIVER" ] = "Simulator" if self . _is_sixteen_bit : self . _device_dict [ "servermain.DEVICE_MODEL" ] = 0 else : self . _device_dict [ "servermain.DEVICE_MODEL" ] = 1 self . _device_dict [ "servermain.DEVICE_ID_OCTAL" ] = 1 | Sets the device driver type to simulated | 119 | 8 |
15,454 | def parse_tag_groups ( self ) : tag_groups = [ ] if 'tag_groups' not in self . _device_dict : return tag_groups to_remove = [ ] for tag_group in self . _device_dict [ 'tag_groups' ] : if tag_group [ 'common.ALLTYPES_NAME' ] in self . _ignore_list : to_remove . append ( tag_group ) continue tag_groups . append ( TagGroup ( tag_group ) ) for removable in to_remove : self . _device_dict [ 'tag_groups' ] . remove ( removable ) return tag_groups | Gets an array of TagGroup objects in the Kepware device | 138 | 14 |
15,455 | def update ( self ) : if "tag_groups" not in self . _device_dict : return for group in self . tag_groups : group . update ( ) for i in range ( len ( self . _device_dict [ "tag_groups" ] ) ) : tag_group_dict = self . _device_dict [ "tag_groups" ] [ i ] for group in self . tag_groups : if group . name == tag_group_dict [ "common.ALLTYPES_NAME" ] : self . _device_dict [ "tag_groups" ] [ i ] = group . as_dict ( ) | Updates the dictionary of the device | 137 | 7 |
15,456 | def AddAnalogShortIdMsecRecord ( site_service , tag , time_value , msec , value , low_warn = False , high_warn = False , low_alarm = False , high_alarm = False , oor_low = False , oor_high = False , unreliable = False , manual = False ) : # Define all required variables in the correct ctypes format szService = c_char_p ( site_service . encode ( 'utf-8' ) ) szPointId = c_char_p ( tag . encode ( 'utf-8' ) ) tTime = c_long ( int ( time_value ) ) dValue = c_double ( value ) bLowWarning = c_int ( int ( low_warn ) ) bHighWarning = c_int ( int ( high_warn ) ) bLowAlarm = c_int ( int ( low_alarm ) ) bHighAlarm = c_int ( int ( high_alarm ) ) bOutOfRangeLow = c_int ( int ( oor_low ) ) bOutOfRangeHigh = c_int ( int ( oor_high ) ) bUnReliable = c_int ( int ( unreliable ) ) bManual = c_int ( int ( manual ) ) usMsec = c_ushort ( msec ) # Try to push the data. Function will return 0 if successful. nRet = dnaserv_dll . DnaAddAnalogShortIdMsecRecord ( szService , szPointId , tTime , dValue , bLowWarning , bHighWarning , bLowAlarm , bHighAlarm , bOutOfRangeLow , bOutOfRangeHigh , bUnReliable , bManual , usMsec ) return nRet | This function will add an analog value to the specified eDNA service and tag with many optional status definitions . | 386 | 21 |
15,457 | def FlushShortIdRecords ( site_service ) : # Define all required variables in the correct ctypes format szService = c_char_p ( site_service . encode ( 'utf-8' ) ) szMessage = create_string_buffer ( b" " ) nMessage = c_ushort ( 20 ) # Try to flush the data. Function will return message regarding success. nRet = dnaserv_dll . DnaFlushShortIdRecords ( szService , byref ( szMessage ) , nMessage ) return str ( nRet ) + szMessage . value . decode ( 'utf-8' ) | Flush all the queued records . | 140 | 8 |
15,458 | def set_scheduler ( self , host , username = 'root' , password = None , private_key = None , private_key_pass = None ) : self . _remote = RemoteClient ( host , username , password , private_key , private_key_pass ) self . _remote_id = uuid . uuid4 ( ) . hex | Defines the remote scheduler | 77 | 6 |
15,459 | def set_cwd ( fn ) : def wrapped ( self , * args , * * kwargs ) : log . info ( 'Calling function: %s with args=%s' , fn , args if args else [ ] ) cwd = os . getcwd ( ) log . info ( 'Saved cwd: %s' , cwd ) os . chdir ( self . _cwd ) log . info ( 'Changing working directory to: %s' , self . _cwd ) try : return fn ( self , * args , * * kwargs ) finally : os . chdir ( cwd ) log . info ( 'Restored working directory to: %s' , cwd ) return wrapped | Decorator to set the specified working directory to execute the function and then restore the previous cwd . | 154 | 21 |
15,460 | def remove ( self , options = [ ] , sub_job_num = None ) : args = [ 'condor_rm' ] args . extend ( options ) job_id = '%s.%s' % ( self . cluster_id , sub_job_num ) if sub_job_num else str ( self . cluster_id ) args . append ( job_id ) out , err = self . _execute ( args ) return out , err | Removes a job from the job queue or from being executed . | 98 | 13 |
15,461 | def close_remote ( self ) : if self . _remote : try : # first see if remote dir is still there self . _remote . execute ( 'ls %s' % ( self . _remote_id , ) ) if self . status != 'Completed' : self . remove ( ) self . _remote . execute ( 'rm -rf %s' % ( self . _remote_id , ) ) except RuntimeError : pass self . _remote . close ( ) del self . _remote | Cleans up and closes connection to remote server if defined . | 105 | 12 |
15,462 | def gini_impurity ( s ) : return 1 - sum ( prop ( s [ i ] , s ) ** 2 for i in range ( len ( s ) ) ) | Calculate the Gini Impurity for a list of samples . | 37 | 14 |
15,463 | def entropy ( s ) : return - sum ( p * np . log ( p ) for i in range ( len ( s ) ) for p in [ prop ( s [ i ] , s ) ] ) | Calculate the Entropy Impurity for a list of samples . | 43 | 14 |
15,464 | def info_gain ( current_impurity , true_branch , false_branch , criterion ) : measure_impurity = gini_impurity if criterion == "gini" else entropy p = float ( len ( true_branch ) ) / ( len ( true_branch ) + len ( false_branch ) ) return current_impurity - p * measure_impurity ( true_branch ) - ( 1 - p ) * measure_impurity ( false_branch ) | Information Gain . The uncertainty of the starting node minus the weighted impurity of two child nodes . | 107 | 19 |
15,465 | def _update_statuses ( self , sub_job_num = None ) : # initialize status dictionary status_dict = dict ( ) for val in CONDOR_JOB_STATUSES . values ( ) : status_dict [ val ] = 0 for node in self . node_set : job = node . job try : job_status = job . status status_dict [ job_status ] += 1 except ( KeyError , HTCondorError ) : status_dict [ 'Unexpanded' ] += 1 return status_dict | Update statuses of jobs nodes in workflow . | 116 | 9 |
15,466 | def update_node_ids ( self , sub_job_num = None ) : # Build condor_q and condor_history commands dag_id = '%s.%s' % ( self . cluster_id , sub_job_num ) if sub_job_num else str ( self . cluster_id ) job_delimiter = '+++' attr_delimiter = ';;;' format = [ '-format' , '"%d' + attr_delimiter + '"' , 'ClusterId' , '-format' , '"%v' + attr_delimiter + '"' , 'Cmd' , '-format' , '"%v' + attr_delimiter + '"' , 'Args' , # Old way '-format' , '"%v' + job_delimiter + '"' , 'Arguments' # New way ] # Get ID, Executable, and Arguments for each job that is either started to be processed or finished in the workflow cmd = 'condor_q -constraint DAGManJobID=={0} {1} && condor_history -constraint DAGManJobID=={0} {1}' . format ( dag_id , ' ' . join ( format ) ) # 'condor_q -constraint DAGManJobID==1018 -format "%d\n" ClusterId -format "%s\n" CMD -format "%s\n" ARGS && condor_history -constraint DAGManJobID==1018 -format "%d\n" ClusterId -format "%s\n" CMD -format "%s\n" ARGS' _args = [ cmd ] out , err = self . _execute ( _args , shell = True , run_in_job_dir = False ) if err : log . error ( 'Error while associating ids for jobs dag %s: %s' , dag_id , err ) raise HTCondorError ( err ) if not out : log . warning ( 'Error while associating ids for jobs in dag %s: No jobs found for dag.' , dag_id ) try : # Split into one line per job jobs_out = out . split ( job_delimiter ) # Match node to cluster id using combination of cmd and arguments for node in self . _node_set : job = node . job # Skip jobs that already have cluster id defined if job . cluster_id != job . NULL_CLUSTER_ID : continue for job_out in jobs_out : if not job_out or attr_delimiter not in job_out : continue # Split line by attributes cluster_id , cmd , _args , _arguments = job_out . split ( attr_delimiter ) # If new form of arguments is used, _args will be 'undefined' and _arguments will not if _args == 'undefined' and _arguments != 'undefined' : args = _arguments . strip ( ) # If both are undefined, then there are no arguments elif _args == 'undefined' and _arguments == 'undefined' : args = None # Otherwise, using old form and _arguments will be 'undefined' and _args will not. else : args = _args . strip ( ) job_cmd = job . executable job_args = job . arguments . strip ( ) if job . arguments else None if job_cmd in cmd and job_args == args : log . info ( 'Linking cluster_id %s to job with command and arguments: %s %s' , cluster_id , job_cmd , job_args ) job . _cluster_id = int ( cluster_id ) break except ValueError as e : log . warning ( str ( e ) ) | Associate Jobs with respective cluster ids . | 834 | 9 |
15,467 | def submit ( self , options = [ ] ) : self . complete_node_set ( ) self . _write_job_file ( ) args = [ 'condor_submit_dag' ] args . extend ( options ) args . append ( self . dag_file ) log . info ( 'Submitting workflow %s with options: %s' , self . name , args ) return super ( Workflow , self ) . submit ( args ) | ensures that all relatives of nodes in node_set are also added to the set before submitting | 95 | 19 |
15,468 | def safe_reload ( modname : types . ModuleType ) -> Union [ None , str ] : try : importlib . reload ( modname ) return None except Exception as e : logging . error ( "Failed to reimport module: %s" , modname ) msg , _ = backtrace . output_traceback ( e ) return msg | Catch and log any errors that arise from reimporting a module but do not die . | 74 | 19 |
15,469 | def safe_load ( modname : str ) -> Union [ None , str ] : try : importlib . import_module ( modname ) return None except Exception as ex : logging . error ( "Failed to import module: %s" , modname ) msg , _ = backtrace . output_traceback ( ex ) return msg | Load a module logging errors instead of dying if it fails to load . | 71 | 14 |
15,470 | def scan_and_reimport ( mod_type : str ) -> List [ Tuple [ str , str ] ] : mod_enabled , mod_disabled = get_modules ( mod_type ) errors = [ ] for mod in mod_enabled + mod_disabled : if mod in sys . modules : msg = safe_reload ( sys . modules [ mod ] ) else : msg = safe_load ( mod ) if msg is not None : errors . append ( ( mod , msg ) ) return errors | Scans folder for modules . | 106 | 6 |
15,471 | def _ranging ( self ) : agg_ranges = [ ] for i , val in enumerate ( self . range_list ) : if i == 0 : agg_ranges . append ( { "to" : val } ) else : previous = self . range_list [ i - 1 ] agg_ranges . append ( { "from" : previous , "to" : val } ) if i + 1 == len ( self . range_list ) : agg_ranges . append ( { "from" : val } ) return agg_ranges | Should be a list of values to designate the buckets | 118 | 10 |
15,472 | def get_random_surah ( self , lang = 'id' ) : # Ensure the language supported. if lang not in self . SUPPORTED_LANGUAGES : message = 'Currently your selected language not yet supported.' raise ODOAException ( message ) # Get random surah and construct the url. rand_surah = random . randint ( 1 , self . TOTAL_SURAH ) surah_url = '{base}/surah/surah_{pages}.json' . format ( base = self . BASE_API , pages = rand_surah ) try : response = urlopen ( surah_url ) # Fetch data from given url. data = json . loads ( response . read ( ) . decode ( 'utf-8' ) ) # Get response and convert to dict. except IOError : traceback . print_exc ( file = sys . stdout ) raise ODOAException else : # Get random ayat. random_ayah = random . randint ( 1 , int ( data . get ( 'count' ) ) ) ayah_key = 'verse_{index}' . format ( index = random_ayah ) ayah = data [ 'verse' ] [ ayah_key ] . encode ( 'utf-8' ) surah_index = data . get ( 'index' ) surah_name = data . get ( 'name' ) # Get translation and sound url. translation = self . __get_translation ( surah = surah_index , ayah = ayah_key , lang = lang ) sound = self . __get_sound ( surah = surah_index , ayah = random_ayah ) desc = '{name}:{ayah}' . format ( name = surah_name , ayah = random_ayah ) meta = Metadata ( ayah , desc , translation , sound ) return meta | Perform http request to get random surah . | 405 | 10 |
15,473 | def __get_translation ( self , surah , ayah , lang ) : # Construct url to fetch translation data. url = '{base}/translations/{lang}/{lang}_translation_{surah}.json' . format ( base = self . BASE_API , lang = lang , surah = int ( surah ) ) try : response = urlopen ( url ) # Fetch data from give url. data = json . loads ( response . read ( ) . decode ( 'utf-8' ) ) # Get response and convert to dict. translation = data [ 'verse' ] [ ayah ] except ODOAException : return None else : return translation | Perform http request to get translation from given surah ayah and language . | 144 | 16 |
15,474 | def __get_sound ( self , surah , ayah ) : # Formatting ayah with 0 leading. # http://stackoverflow.com/questions/17118071/python-add-leading-zeroes-using-str-format format_ayah = '{0:0>3}' . format ( ayah ) sound_url = '{base}/sounds/{surah}/{ayah}.mp3' . format ( base = self . BASE_API , surah = surah , ayah = format_ayah ) return sound_url | Perform http request to get sound from given surah and ayah . | 128 | 15 |
15,475 | def get_fipscode ( self , obj ) : if obj . division . level . name == DivisionLevel . COUNTY : return obj . division . code return None | County FIPS code | 35 | 5 |
15,476 | def get_statepostal ( self , obj ) : if obj . division . level . name == DivisionLevel . STATE : return us . states . lookup ( obj . division . code ) . abbr elif obj . division . level . name == DivisionLevel . COUNTY : return us . states . lookup ( obj . division . parent . code ) . abbr return None | State postal abbreviation if county or state else None . | 77 | 11 |
15,477 | def get_polid ( self , obj ) : ap_id = obj . candidate_election . candidate . ap_candidate_id if 'polid-' in ap_id : return ap_id . replace ( 'polid-' , '' ) return None | AP polid minus polid prefix if polid else None . | 55 | 13 |
15,478 | def get_polnum ( self , obj ) : ap_id = obj . candidate_election . candidate . ap_candidate_id if 'polnum-' in ap_id : return ap_id . replace ( 'polnum-' , '' ) return None | AP polnum minus polnum prefix if polnum else None . | 58 | 13 |
15,479 | def get_precinctsreporting ( self , obj ) : if obj . division . level == obj . candidate_election . election . division . level : return obj . candidate_election . election . meta . precincts_reporting return None | Precincts reporting if vote is top level result else None . | 49 | 14 |
15,480 | def get_precinctsreportingpct ( self , obj ) : if obj . division . level == obj . candidate_election . election . division . level : return obj . candidate_election . election . meta . precincts_reporting_pct return None | Precincts reporting percent if vote is top level result else None . | 54 | 15 |
15,481 | def get_precinctstotal ( self , obj ) : if obj . division . level == obj . candidate_election . election . division . level : return obj . candidate_election . election . meta . precincts_total return None | Precincts total if vote is top level result else None . | 49 | 14 |
15,482 | def load ( self , tableName = 'rasters' , rasters = [ ] ) : # Create table if necessary Base . metadata . create_all ( self . _engine ) # Create a session Session = sessionmaker ( bind = self . _engine ) session = Session ( ) for raster in rasters : # Must read in using the raster2pgsql commandline tool. rasterPath = raster [ 'path' ] if 'srid' in raster : srid = str ( raster [ 'srid' ] ) else : srid = '4326' if 'no-data' in raster : noData = str ( raster [ 'no-data' ] ) else : noData = '-1' wellKnownBinary = RasterLoader . rasterToWKB ( rasterPath , srid , noData , self . _raster2pgsql ) rasterBinary = wellKnownBinary # Get the filename filename = os . path . split ( rasterPath ) [ 1 ] # Populate raster record mapKitRaster = MapKitRaster ( ) mapKitRaster . filename = filename mapKitRaster . raster = rasterBinary if 'timestamp' in raster : mapKitRaster . timestamp = raster [ 'timestamp' ] # Add to session session . add ( mapKitRaster ) session . commit ( ) | Accepts a list of paths to raster files to load into the database . Returns the ids of the rasters loaded successfully in the same order as the list passed in . | 299 | 36 |
15,483 | def rasterToWKB ( cls , rasterPath , srid , noData , raster2pgsql ) : raster2pgsqlProcess = subprocess . Popen ( [ raster2pgsql , '-s' , srid , '-N' , noData , rasterPath , 'n_a' ] , stdout = subprocess . PIPE ) # This commandline tool generates the SQL to load the raster into the database # However, we want to use SQLAlchemy to load the values into the database. # We do this by extracting the value from the sql that is generated. sql , error = raster2pgsqlProcess . communicate ( ) if sql : # This esoteric line is used to extract only the value of the raster (which is stored as a Well Know Binary string) # Example of Output: # BEGIN; # INSERT INTO "idx_index_maps" ("rast") VALUES ('0100...56C096CE87'::raster); # END; # The WKB is wrapped in single quotes. Splitting on single quotes isolates it as the # second item in the resulting list. wellKnownBinary = sql . split ( "'" ) [ 1 ] else : print ( error ) raise return wellKnownBinary | Accepts a raster file and converts it to Well Known Binary text using the raster2pgsql executable that comes with PostGIS . This is the format that rasters are stored in a PostGIS database . | 274 | 45 |
15,484 | def grassAsciiRasterToWKB ( cls , session , grassRasterPath , srid , noData = 0 ) : # Constants NUM_HEADER_LINES = 6 # Defaults north = 0.0 east = 0.0 west = 0.0 rows = 0 columns = 0 if grassRasterPath is not None : # If the path to the file is given, open the file and extract contents. with open ( grassRasterPath , 'r' ) as f : rasterLines = f . readlines ( ) else : print ( "RASTER LOAD ERROR: Must provide the path the raster." ) raise # Extract the headers from the file and derive metadata for line in rasterLines [ 0 : NUM_HEADER_LINES ] : spline = line . split ( ) if 'north' in spline [ 0 ] . lower ( ) : north = float ( spline [ 1 ] ) elif 'east' in spline [ 0 ] . lower ( ) : east = float ( spline [ 1 ] ) elif 'west' in spline [ 0 ] . lower ( ) : west = float ( spline [ 1 ] ) elif 'rows' in spline [ 0 ] . lower ( ) : rows = int ( spline [ 1 ] ) elif 'cols' in spline [ 0 ] . lower ( ) : columns = int ( spline [ 1 ] ) # Define raster metadata from headers width = columns height = rows upperLeftX = west upperLeftY = north cellSizeX = int ( abs ( west - east ) / columns ) cellSizeY = - 1 * cellSizeX # Assemble the data array string dataArrayList = [ ] for line in rasterLines [ NUM_HEADER_LINES : len ( rasterLines ) ] : dataArrayList . append ( '[{0}]' . format ( ', ' . join ( line . split ( ) ) ) ) dataArrayString = '[{0}]' . format ( ', ' . join ( dataArrayList ) ) # Create well known binary raster wellKnownBinary = cls . makeSingleBandWKBRaster ( session = session , width = width , height = height , upperLeftX = upperLeftX , upperLeftY = upperLeftY , cellSizeX = cellSizeX , cellSizeY = cellSizeY , skewX = 0 , skewY = 0 , srid = srid , dataArray = dataArrayString , noDataValue = noData ) return wellKnownBinary | Load GRASS ASCII rasters directly using the makeSingleBandWKBRaster method . Do this to eliminate the raster2pgsql dependency . | 545 | 30 |
15,485 | def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'delay' ) parser . add_argument ( 'msg' , nargs = '+' ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if isinstance ( cmdargs . msg , list ) : cmdargs . msg = ' ' . join ( cmdargs . msg ) cmdargs . delay = parse_time ( cmdargs . delay ) if cmdargs . delay is None : send ( "Invalid unit." ) elif cmdargs . delay < 0 : send ( "Time travel not yet implemented, sorry." ) else : ident = args [ 'handler' ] . workers . defer ( cmdargs . delay , False , send , cmdargs . msg ) send ( "Message deferred, ident: %s" % ident ) | Says something at a later time . | 200 | 8 |
15,486 | def _replace ( self , * * kwds ) : result = self . _make ( map ( kwds . pop , self . _fields , self ) ) if kwds : raise ValueError ( 'Got unexpected field names: %r' % kwds . keys ( ) ) return result | Return a new NamedTuple object replacing specified fields with new values | 65 | 13 |
15,487 | def concat_cols ( df1 , df2 , idx_col , df1_cols , df2_cols , df1_suffix , df2_suffix , wc_cols = [ ] , suffix_all = False ) : df1 = df1 . set_index ( idx_col ) df2 = df2 . set_index ( idx_col ) if not len ( wc_cols ) == 0 : for wc in wc_cols : df1_cols = df1_cols + [ c for c in df1 . columns if wc in c ] df2_cols = df2_cols + [ c for c in df2 . columns if wc in c ] combo = pd . concat ( [ df1 . loc [ : , df1_cols ] , df2 . loc [ : , df2_cols ] ] , axis = 1 ) # find common columns and rename them # print df1_cols # print df2_cols if suffix_all : df1_cols = [ "%s%s" % ( c , df1_suffix ) for c in df1_cols ] df2_cols = [ "%s%s" % ( c , df2_suffix ) for c in df2_cols ] # df1_cols[df1_cols.index(col)]="%s%s" % (col,df1_suffix) # df2_cols[df2_cols.index(col)]="%s%s" % (col,df2_suffix) else : common_cols = [ col for col in df1_cols if col in df2_cols ] for col in common_cols : df1_cols [ df1_cols . index ( col ) ] = "%s%s" % ( col , df1_suffix ) df2_cols [ df2_cols . index ( col ) ] = "%s%s" % ( col , df2_suffix ) combo . columns = df1_cols + df2_cols combo . index . name = idx_col return combo | Concatenates two pandas tables | 488 | 8 |
15,488 | def get_colmin ( data ) : data = data . T colmins = [ ] for col in data : colmins . append ( data [ col ] . idxmin ( ) ) return colmins | Get rowwise column names with minimum values | 43 | 9 |
15,489 | def fhs2data_combo_appended ( fhs , cols = None , labels = None , labels_coln = 'labels' , sep = ',' , error_bad_lines = True ) : if labels is None : labels = [ basename ( fh ) for fh in fhs ] if len ( fhs ) > 0 : data_all = pd . DataFrame ( columns = cols ) for fhi , fh in enumerate ( fhs ) : label = labels [ fhi ] try : data = pd . read_csv ( fh , sep = sep , error_bad_lines = error_bad_lines ) except : raise ValueError ( f"something wrong with file pd.read_csv({fh},sep={sep})" ) if len ( data ) != 0 : data . loc [ : , labels_coln ] = label if not cols is None : data = data . loc [ : , cols ] data_all = data_all . append ( data , sort = True ) return del_Unnamed ( data_all ) | to be deprecated Collates data from multiple csv files vertically | 239 | 12 |
15,490 | def rename_cols ( df , names , renames = None , prefix = None , suffix = None ) : if not prefix is None : renames = [ "%s%s" % ( prefix , s ) for s in names ] if not suffix is None : renames = [ "%s%s" % ( s , suffix ) for s in names ] if not renames is None : for i , name in enumerate ( names ) : # names=[renames[i] if s==names[i] else s for s in names] rename = renames [ i ] df . loc [ : , rename ] = df . loc [ : , name ] df = df . drop ( names , axis = 1 ) return df | rename columns of a pandas table | 154 | 8 |
15,491 | def reorderbydf ( df2 , df1 ) : df3 = pd . DataFrame ( ) for idx , row in df1 . iterrows ( ) : df3 = df3 . append ( df2 . loc [ idx , : ] ) return df3 | Reorder rows of a dataframe by other dataframe | 59 | 11 |
15,492 | def df2unstack ( df , coln = 'columns' , idxn = 'index' , col = 'value' ) : return dmap2lin ( df , idxn = idxn , coln = coln , colvalue_name = col ) | will be deprecated | 60 | 3 |
15,493 | def get_offdiag_vals ( dcorr ) : del_indexes = [ ] for spc1 in np . unique ( dcorr . index . get_level_values ( 0 ) ) : for spc2 in np . unique ( dcorr . index . get_level_values ( 0 ) ) : if ( not ( spc1 , spc2 ) in del_indexes ) and ( not ( spc2 , spc1 ) in del_indexes ) : del_indexes . append ( ( spc1 , spc2 ) ) # break for spc1 in np . unique ( dcorr . index . get_level_values ( 0 ) ) : for spc2 in np . unique ( dcorr . index . get_level_values ( 0 ) ) : if spc1 == spc2 : del_indexes . append ( ( spc1 , spc2 ) ) return dcorr . drop ( del_indexes ) | for lin dcorr i guess | 215 | 7 |
15,494 | def from_dict ( data ) : data = deepcopy ( data ) created_at = data . get ( 'created_at' , None ) if created_at is not None : data [ 'created_at' ] = dateutil . parser . parse ( created_at ) return Image ( * * data ) | Create a new instance from dict | 66 | 6 |
15,495 | def to_json ( self , indent = None , sort_keys = True ) : return json . dumps ( self . to_dict ( ) , indent = indent , sort_keys = sort_keys ) | Return a JSON string representation of this instance | 43 | 8 |
15,496 | def to_dict ( self ) : data = { } if self . created_at : data [ 'created_at' ] = self . created_at . strftime ( '%Y-%m-%dT%H:%M:%S%z' ) if self . image_id : data [ 'image_id' ] = self . image_id if self . permalink_url : data [ 'permalink_url' ] = self . permalink_url if self . thumb_url : data [ 'thumb_url' ] = self . thumb_url if self . type : data [ 'type' ] = self . type if self . url : data [ 'url' ] = self . url return data | Return a dict representation of this instance | 158 | 7 |
15,497 | def download ( self ) : if self . url : try : return requests . get ( self . url ) . content except requests . RequestException as e : raise GyazoError ( str ( e ) ) return None | Download an image file if it exists | 44 | 7 |
15,498 | def download_thumb ( self ) : try : return requests . get ( self . thumb_url ) . content except requests . RequestException as e : raise GyazoError ( str ( e ) ) | Download a thumbnail image file | 42 | 5 |
15,499 | def has_next_page ( self ) : return self . current_page < math . ceil ( self . total_count / self . per_page ) | Whether there is a next page or not | 34 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.