signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _num_samples ( x ) : """Return number of samples in array - like x ."""
if hasattr ( x , 'fit' ) : # Don ' t get num _ samples from an ensembles length ! raise TypeError ( 'Expected sequence or array-like, got ' 'estimator %s' % x ) if not hasattr ( x , '__len__' ) and not hasattr ( x , 'shape' ) : if hasattr ( x , '__array__' ) : x = np . asarray ( x ) else : r...
def _get_env ( self , key ) : """Wrapper around os . getenv ( ) which replaces characters in the original key . This allows env vars which have different keys than the config object keys ."""
if self . _env_key_replacer is not None : key = key . replace ( * self . _env_key_replacer ) return os . getenv ( key )
def make_grid_frame ( self , event ) : """Create a GridFrame for data type of the button that was clicked"""
if self . grid_frame : print ( '-I- You already have a grid frame open' ) pw . simple_warning ( "You already have a grid open" ) return try : grid_type = event . GetButtonObj ( ) . Name [ : - 4 ] # remove ' _ btn ' except AttributeError : grid_type = self . FindWindowById ( event . Id ) . Name [...
def validate ( self ) : """Validate that this instance matches its schema ."""
schema = Schema ( self . __class__ . SCHEMA ) resolver = RefResolver . from_schema ( schema , store = REGISTRY , ) validate ( self , schema , resolver = resolver )
def detach ( self ) : """Detach the underlying LLVM resource without disposing of it ."""
if not self . _closed : del self . _as_parameter_ self . _closed = True self . _ptr = None
def _insert_or_update ( self , resourcetype , source , mode = 'insert' , hhclass = 'Service' ) : """Insert or update a record in the repository"""
keywords = [ ] if self . filter is not None : catalog = Catalog . objects . get ( id = int ( self . filter . split ( ) [ - 1 ] ) ) try : if hhclass == 'Layer' : # TODO : better way of figuring out duplicates match = Layer . objects . filter ( name = source . name , title = source . title , abstract = so...
def conjugate ( self ) : """Complex conjugate of of the product"""
return self . __class__ . create ( * [ arg . conjugate ( ) for arg in reversed ( self . args ) ] )
def execute ( self ) : """Execute stemming process ; the result can be retrieved with result"""
# step 1 - 5 self . start_stemming_process ( ) # step 6 if self . dictionary . contains ( self . current_word ) : self . result = self . current_word else : self . result = self . original_word
def unicode_from_html ( content ) : """Attempts to decode an HTML string into unicode . If unsuccessful , the original content is returned ."""
encodings = get_encodings_from_content ( content ) for encoding in encodings : try : return unicode ( content , encoding ) except ( UnicodeError , TypeError ) : pass return content
def name ( self ) : """access to classic name attribute is hidden by this property"""
return self . NAME_SEPARATOR . join ( [ super ( InfinityVertex , self ) . name , self . NAME_SUFFIX ] )
def glob ( dpath , pattern = None , recursive = False , with_files = True , with_dirs = True , maxdepth = None , exclude_dirs = [ ] , fullpath = True , ** kwargs ) : r"""Globs directory for pattern DEPRICATED : use pathlib . glob instead Args : dpath ( str ) : directory path or pattern pattern ( str or li...
gen = iglob ( dpath , pattern , recursive = recursive , with_files = with_files , with_dirs = with_dirs , maxdepth = maxdepth , fullpath = fullpath , exclude_dirs = exclude_dirs , ** kwargs ) path_list = list ( gen ) return path_list
def cli ( env , package_keyname ) : """List Datacenters a package can be ordered in . Use the location Key Name to place orders"""
manager = ordering . OrderingManager ( env . client ) table = formatting . Table ( COLUMNS ) locations = manager . package_locations ( package_keyname ) for region in locations : for datacenter in region [ 'locations' ] : table . add_row ( [ datacenter [ 'location' ] [ 'id' ] , datacenter [ 'location' ] [ '...
def update ( self , configuration = values . unset , unique_name = values . unset ) : """Update the InstalledAddOnInstance : param dict configuration : The JSON object representing the configuration : param unicode unique _ name : The string that uniquely identifies this Add - on installation : returns : Upda...
data = values . of ( { 'Configuration' : serialize . object ( configuration ) , 'UniqueName' : unique_name , } ) payload = self . _version . update ( 'POST' , self . _uri , data = data , ) return InstalledAddOnInstance ( self . _version , payload , sid = self . _solution [ 'sid' ] , )
def binarySearchPos ( seq , item , cmpfunc = cmp ) : r"""Return the position of ` item ` in ordered sequence ` seq ` , using comparison function ` cmpfunc ` ( defaults to ` ` cmp ` ` ) and return the first found position of ` item ` , or - 1 if ` item ` is not in ` seq ` . The returned position is NOT guarant...
if not seq : return - 1 left , right = 0 , len ( seq ) - 1 if cmpfunc ( seq [ left ] , item ) == 1 and cmpfunc ( seq [ right ] , item ) == - 1 : return - 1 while left <= right : halfPoint = ( left + right ) // 2 comp = cmpfunc ( seq [ halfPoint ] , item ) if comp > 0 : right = halfPoint - 1 ...
def get_batch_input ( sentences , max_word_len , word_dict , char_dict , word_unknown = 1 , char_unknown = 1 , word_ignore_case = False , char_ignore_case = False ) : """Convert sentences to desired input tensors . : param sentences : A list of lists representing the input sentences . : param max _ word _ len :...
sentence_num = len ( sentences ) max_sentence_len = max ( map ( len , sentences ) ) word_embd_input = [ [ 0 ] * max_sentence_len for _ in range ( sentence_num ) ] char_embd_input = [ [ [ 0 ] * max_word_len for _ in range ( max_sentence_len ) ] for _ in range ( sentence_num ) ] for sentence_index , sentence in enumerate...
def short_description ( description ) : """Sets ' short _ description ' attribute ( this attribute is in exports to generate header name ) ."""
def decorator ( func ) : if isinstance ( func , property ) : func = func . fget func . short_description = description return func return decorator
def update ( self , data ) : """TODO"""
self . debug ( data ) url = "{base}/{uuid}" . format ( base = self . local_base_url , uuid = data . get ( 'uuid' ) ) return self . core . update ( url , data )
def get_namespace ( self , namespace , lowercase = True , trim_namespace = True ) : """Returns a dictionary containing a subset of configuration options that match the specified namespace / prefix . Example usage : app . config [ ' IMAGE _ STORE _ TYPE ' ] = ' fs ' app . config [ ' IMAGE _ STORE _ PATH ' ] = ...
rv = { } for key , value in six . iteritems ( self ) : if not key . startswith ( namespace ) : continue if trim_namespace : key = key [ len ( namespace ) : ] else : key = key if lowercase : key = key . lower ( ) rv [ key ] = value return rv
def v1_fc_put ( request , response , store , kvlclient , tfidf , cid ) : '''Store a single feature collection . The route for this endpoint is : ` ` PUT / dossier / v1 / feature - collections / < content _ id > ` ` . ` ` content _ id ` ` is the id to associate with the given feature collection . The feature...
tfidf = tfidf or None if request . headers . get ( 'content-type' , '' ) . startswith ( 'text/html' ) : url = urllib . unquote ( cid . split ( '|' , 1 ) [ 1 ] ) fc = etl . create_fc_from_html ( url , request . body . read ( ) , tfidf = tfidf ) logger . info ( 'created FC for %r' , cid ) store . put ( [ ...
def put ( self , file ) : """Create a new file on github : param file : File to create : return : File or self . ProxyError"""
input_ = { "message" : file . logs , "author" : file . author . dict ( ) , "content" : file . base64 , "branch" : file . branch } uri = "{api}/repos/{origin}/contents/{path}" . format ( api = self . github_api_url , origin = self . origin , path = file . path ) data = self . request ( "PUT" , uri , data = input_ ) if d...
def dirs ( self ) : """Get an iter of VenvDirs within the directory ."""
contents = self . paths contents = ( BinDir ( path . path ) for path in contents if path . is_dir ) return contents
def paint ( self , painter , option , index ) : """Uses the : meth : ` paint < sparkle . gui . stim . components . qcomponents . QStimulusComponent . paint > ` method of the component it represents to fill in an appropriately sized rectange . : qtdoc : ` Re - implemented < QStyledItemDelegate . paint > `"""
component = index . model ( ) . data ( index , role = QtCore . Qt . UserRole ) painter . drawRect ( option . rect ) component . paint ( painter , option . rect , option . palette )
def btc_tx_extend ( partial_tx_hex , new_inputs , new_outputs , ** blockchain_opts ) : """Given an unsigned serialized transaction , add more inputs and outputs to it . @ new _ inputs and @ new _ outputs will be virtualchain - formatted : * new _ inputs [ i ] will have { ' outpoint ' : { ' index ' : . . . , ' h...
# recover tx tx = btc_tx_deserialize ( partial_tx_hex ) tx_inputs , tx_outputs = tx [ 'ins' ] , tx [ 'outs' ] locktime , version = tx [ 'locktime' ] , tx [ 'version' ] tx_inputs += new_inputs tx_outputs += new_outputs new_tx = { 'ins' : tx_inputs , 'outs' : tx_outputs , 'locktime' : locktime , 'version' : version , } n...
def find_greeting ( s ) : """Return the the greeting string Hi , Hello , or Yo if it occurs at the beginning of a string > > > find _ greeting ( ' Hi Mr . Turing ! ' ) ' Hi ' > > > find _ greeting ( ' Hello , Rosa . ' ) ' Hello ' > > > find _ greeting ( " Yo , what ' s up ? " ) ' Yo ' > > > find _ gre...
if s [ 0 ] == 'H' : if s [ : 3 ] in [ 'Hi' , 'Hi ' , 'Hi,' , 'Hi!' ] : return s [ : 2 ] elif s [ : 6 ] in [ 'Hello' , 'Hello ' , 'Hello,' , 'Hello!' ] : return s [ : 5 ] elif s [ 0 ] == 'Y' : if s [ 1 ] == 'o' and s [ : 3 ] in [ 'Yo' , 'Yo,' , 'Yo ' , 'Yo!' ] : return s [ : 2 ] retur...
def find_resources ( client ) : """Detect dispensers and return corresponding resources ."""
wildcard = Keys . DISPENSER . format ( '*' ) pattern = re . compile ( Keys . DISPENSER . format ( '(.*)' ) ) return [ pattern . match ( d ) . group ( 1 ) for d in client . scan_iter ( wildcard ) ]
def new_project ( self , name , description , namespace = None , url = None , avatar_email = None , create_readme = False , private = False ) : """Create a new project on the pagure instance : param name : the name of the new project . : param description : A short description of the new project . : param nam...
request_url = "{}/api/0/new" . format ( self . instance ) payload = { 'name' : name , 'description' : description } if namespace is not None : payload [ 'namespace' ] = namespace if url is not None : payload [ 'url' ] = url if avatar_email is not None : payload [ 'avatar_email' ] = avatar_email payload [ 'c...
def InsertMessage ( self , message , timeout = None ) : """Inserts a message into the Fleetspeak server . Sets message . source , if unset . Args : message : common _ pb2 . Message The message to send . timeout : How many seconds to try for . Raises : grpc . RpcError : if the RPC fails . InvalidArgu...
if not isinstance ( message , common_pb2 . Message ) : raise InvalidArgument ( "Attempt to send unexpected message type: %s" % message . __class__ . __name__ ) if not message . HasField ( "source" ) : message . source . service_name = self . _service_name # Sometimes GRPC reports failure , even though the call ...
def _parse_team_abbreviation ( self , stats ) : """Parse the team abbreviation . The team abbreviation is embedded within the team name tag and should be special - parsed to extract it . Parameters stats : PyQuery object A PyQuery object containing the HTML from the player ' s stats page . Returns str...
team_tag = stats ( PLAYER_SCHEME [ 'team_abbreviation' ] ) team = re . sub ( r'.*/cbb/schools/' , '' , str ( team_tag ( 'a' ) ) ) team = re . sub ( r'/.*' , '' , team ) return team
def earth_accel2 ( RAW_IMU , ATTITUDE ) : '''return earth frame acceleration vector from AHRS2'''
r = rotation2 ( ATTITUDE ) accel = Vector3 ( RAW_IMU . xacc , RAW_IMU . yacc , RAW_IMU . zacc ) * 9.81 * 0.001 return r * accel
def set_env ( self , key , value ) : """Sets environment variables by prepending the app _ name to ` key ` . Also registers the environment variable with the instance object preventing an otherwise - required call to ` reload ( ) ` ."""
os . environ [ make_env_key ( self . appname , key ) ] = str ( value ) # must coerce to string self . _registered_env_keys . add ( key ) self . _clear_memoization ( )
def poisson_se_multiclust ( data , k , n_runs = 10 , ** se_params ) : """Initializes state estimation using a consensus of several fast clustering / dimensionality reduction algorithms . It does a consensus of 8 truncated SVD - k - means rounds , and uses the basic nmf _ init to create starting points ."""
clusters = [ ] norm_data = cell_normalize ( data ) if sparse . issparse ( data ) : log_data = data . log1p ( ) log_norm = norm_data . log1p ( ) else : log_data = np . log1p ( data ) log_norm = np . log1p ( norm_data ) tsvd_50 = TruncatedSVD ( 50 ) tsvd_k = TruncatedSVD ( k ) km = KMeans ( k ) tsvd1 = ts...
def _set_pmap_seq ( self , v , load = False ) : """Setter method for pmap _ seq , mapped from YANG variable / overlay _ policy _ map / pmap _ seq ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ pmap _ seq is considered as a private method . Backends looking t...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "pmap_seq_num overlay_class" , pmap_seq . pmap_seq , yang_name = "pmap-seq" , rest_name = "seq" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = '...
def write_hits_in_event_range ( hit_table_in , hit_table_out , event_start = None , event_stop = None , start_hit_word = 0 , chunk_size = 5000000 , condition = None ) : '''Selects the hits that occurred in given event range [ event _ start , event _ stop [ and write them to a pytable . This function reduces the in ...
logging . debug ( 'Write hits that exists in the given event range from + ' + str ( event_start ) + ' to ' + str ( event_stop ) + ' into a new hit table' ) table_size = hit_table_in . shape [ 0 ] for iHit in range ( 0 , table_size , chunk_size ) : hits = hit_table_in . read ( iHit , iHit + chunk_size ) last_eve...
def ol ( self , text ) : """* convert plain - text to MMD ordered list * * * Key Arguments : * * - ` ` text ` ` - - the text to convert to MMD ordered list * * Return : * * - ` ` ol ` ` - - the MMD ordered list * * Usage : * * To convert text to MMD ordered list : . . code - block : : python ol = md...
m = self . reWS . match ( text ) ol = [ ] for thisIndex , l in enumerate ( m . group ( 2 ) . split ( "\n" ) ) : thisIndex += 1 prefix , text , suffix = self . _snip_whitespace ( l ) ol . append ( "%(prefix)s%(thisIndex)s. %(text)s " % locals ( ) ) return ( "\n" ) . join ( ol ) + "\n\n"
def register_view ( self , view ) : """Called when the View was registered Can be used e . g . to connect signals . Here , the destroy signal is connected to close the application"""
super ( StateOutcomesListController , self ) . register_view ( view ) if isinstance ( view , StateOutcomesTreeView ) : self . connect_signal ( view [ 'to_state_combo' ] , "edited" , self . on_to_state_edited ) self . connect_signal ( view [ 'to_outcome_combo' ] , "edited" , self . on_to_outcome_edited ) if isin...
def parse_at_root ( self , root , # type : ET . Element state # type : _ ProcessorState ) : # type : ( . . . ) - > Any """Parse the root XML element as an array ."""
if not self . _nested : raise InvalidRootProcessor ( 'Non-nested array "{}" cannot be root element' . format ( self . alias ) ) parsed_array = [ ] # type : List array_element = _element_find_from_root ( root , self . _nested ) if array_element is not None : parsed_array = self . parse_at_element ( array_element...
def transmitToClient ( self , msg : Any , remoteName : str ) : """Transmit the specified message to the remote client specified by ` remoteName ` . : param msg : a message : param remoteName : the name of the remote"""
payload = self . prepForSending ( msg ) try : if isinstance ( remoteName , str ) : remoteName = remoteName . encode ( ) self . send ( payload , remoteName ) except Exception as ex : # TODO : This should not be an error since the client might not have # sent the request to all nodes but only some nodes a...
def insert_and_update_recursively ( self , parent_iter , state_model , with_expand = False ) : """Insert and / or update the handed state model in parent tree store element iterator : param parent _ iter : Parent tree store iterator the insert should be performed in : param StateModel state _ model : Model of s...
# the case handling of this method # 0 - create - common state # 0.1 - modify attributes of common state which is already in the list # 1 - create - library with show content - > add library root state # 2 - create - library without show content - > add library state # 3 - in as library with show content - > switch lib...
def createAndCleanTPED ( tped , tfam , samples , oldSamples , chosenSamples , prefix , completion , completionT , concordance , concordanceT ) : """Complete a TPED for duplicate samples . : param tped : the ` ` tped ` ` containing the duplicated samples . : param tfam : the ` ` tfam ` ` containing the duplicate...
zeroedOutFile = None try : zeroedOutFile = open ( prefix + ".zeroed_out" , "w" ) except IOError : msg = "%(prefix)s.zeroed_out: can't write file" % locals ( ) raise ProgramError ( msg ) print >> zeroedOutFile , "\t" . join ( [ "famID" , "indID" , "snpID" ] ) notGoodEnoughFile = None try : notGoodEnoughF...
def _traverse_relationship_rev_objs ( self , rel2dst2srcs , goobj_parent , goids_seen ) : """Traverse from source GO down children ."""
parent_id = goobj_parent . id goids_seen . add ( parent_id ) # # A self . go2obj [ parent _ id ] = goobj _ parent # Update goids _ seen and go2obj with parent alt _ ids for goid_altid in goobj_parent . alt_ids : goids_seen . add ( goid_altid ) # # A self . go2obj [ goid _ altid ] = goobj _ parent # Loop through...
def collection ( data , bins = 10 , * args , ** kwargs ) : """Create histogram collection with shared binnning ."""
from physt . histogram_collection import HistogramCollection if hasattr ( data , "columns" ) : data = { column : data [ column ] for column in data . columns } return HistogramCollection . multi_h1 ( data , bins , ** kwargs )
def get_channel_access ( self , channel = None , read_mode = 'volatile' ) : """Get channel access : param channel : number [ 1:7] : param read _ mode : non _ volatile = get non - volatile Channel Access volatile = get present volatile ( active ) setting of Channel Access : return : A Python dict with the ...
if channel is None : channel = self . get_network_channel ( ) data = [ ] data . append ( channel & 0b00001111 ) b = 0 read_modes = { 'non_volatile' : 1 , 'volatile' : 2 , } b |= ( read_modes [ read_mode ] << 6 ) & 0b11000000 data . append ( b ) response = self . raw_command ( netfn = 0x06 , command = 0x41 , data = ...
def __make_storeable_patch_patchable ( self , patch ) : """Replace all pipes with dots , transform back into the a namespace path . This is done before the $ set query is applied to the document : param dict patch : The patch that is to be prepared to be applied"""
new_patch = { } for key in patch : new_patch [ key . replace ( "|" , "." ) ] = patch [ key ] return new_patch
def user_create ( username , login = None , domain = '' , database = None , roles = None , options = None , ** kwargs ) : '''Creates a new user . If login is not specified , the user will be created without a login . domain , if provided , will be prepended to username . options can only be a list of strings ...
if domain and not login : return 'domain cannot be set without login' if user_exists ( username , domain , ** kwargs ) : return 'User {0} already exists' . format ( username ) if domain : username = '{0}\\{1}' . format ( domain , username ) login = '{0}\\{1}' . format ( domain , login ) if login else lo...
def allocate_seg_vlan ( self , net_id , is_fw_virt , direc , tenant_id ) : """allocate segmentation ID and VLAN ID . Allocate vlan , seg thereby storing NetID atomically . This saves an extra step to update DB with NetID after allocation . Also may save an extra step after restart , if process crashed after...
seg = self . alloc_seg ( net_id ) vlan = 0 # VLAN allocation is only needed for physical firewall case if not is_fw_virt : vlan = self . alloc_vlan ( net_id ) # Updating the local cache self . update_net_info ( tenant_id , direc , vlan , seg )
def _bitResponseToValue ( bytestring ) : """Convert a response string to a numerical value . Args : bytestring ( str ) : A string of length 1 . Can be for example ` ` \\ x01 ` ` . Returns : The converted value ( int ) . Raises : TypeError , ValueError"""
_checkString ( bytestring , description = 'bytestring' , minlength = 1 , maxlength = 1 ) RESPONSE_ON = '\x01' RESPONSE_OFF = '\x00' if bytestring == RESPONSE_ON : return 1 elif bytestring == RESPONSE_OFF : return 0 else : raise ValueError ( 'Could not convert bit response to a value. Input: {0!r}' . format ...
def _find_self ( param_names : List [ str ] , args : Tuple [ Any , ... ] , kwargs : Dict [ str , Any ] ) -> Any : """Find the instance of ` ` self ` ` in the arguments ."""
instance_i = param_names . index ( "self" ) if instance_i < len ( args ) : instance = args [ instance_i ] else : instance = kwargs [ "self" ] return instance
def lockout_response ( request ) : """if we are locked out , here is the response"""
if config . LOCKOUT_TEMPLATE : context = { 'cooloff_time_seconds' : config . COOLOFF_TIME , 'cooloff_time_minutes' : config . COOLOFF_TIME / 60 , 'failure_limit' : config . FAILURE_LIMIT , } return render ( request , config . LOCKOUT_TEMPLATE , context ) if config . LOCKOUT_URL : return HttpResponseRedirect...
def rename ( self , new_name ) : """Rename self to the given new _ name : return : self"""
if self . name == new_name : return self self . repo . git . remote ( "rename" , self . name , new_name ) self . name = new_name self . _clear_cache ( ) return self
def p_expr_post_incdec ( p ) : '''expr : variable INC | variable DEC'''
p [ 0 ] = ast . PostIncDecOp ( p [ 2 ] , p [ 1 ] , lineno = p . lineno ( 2 ) )
def longest_one_seg_prefix ( self , word ) : """Return longest IPA Unicode prefix of ` word ` Args : word ( unicode ) : word as IPA string Returns : unicode : longest single - segment prefix of ` word `"""
match = self . seg_regex . match ( word ) if match : return match . group ( 0 ) else : return ''
def get_all_properties ( self ) : """Get dictionary with all properties readable by this class ."""
properties = { prop_name : getattr ( self , prop_name ) for prop_name in self . _property_list } return properties
def industry_name ( self ) : """[ str ] 国民经济行业分类名称 ( 股票专用 )"""
try : return self . __dict__ [ "industry_name" ] except ( KeyError , ValueError ) : raise AttributeError ( "Instrument(order_book_id={}) has no attribute 'industry_name' " . format ( self . order_book_id ) )
def apply_tile_to_image ( image , size , tile , tile_size , tile_corner ) : """Copies a tile with a given offset onto an image : param image : The image the file is to be copied onto ( as a list of ( R , G , B ) tuples ) : param size : The size of the image as a tuple ( width , height ) : param tile : The til...
for y in range ( tile_size [ 1 ] ) : for x in range ( tile_size [ 0 ] ) : img_coords = ( x + tile_corner [ 0 ] , y + tile_corner [ 1 ] ) image [ coords_to_index ( img_coords , size [ 0 ] ) ] = tile [ coords_to_index ( ( x , y ) , tile_size [ 0 ] ) ]
def get_urlpatterns ( self ) : """Returns the URL patterns managed by the considered factory / application ."""
return [ path ( _ ( 'topics/' ) , self . latest_topics_feed ( ) , name = 'latest_topics' ) , path ( _ ( 'forum/<str:forum_slug>-<int:forum_pk>/topics/' ) , self . latest_topics_feed ( ) , name = 'forum_latest_topics' , ) , path ( _ ( 'forum/<str:forum_slug>-<int:forum_pk>/topics/all/' ) , self . latest_topics_feed ( ) ...
def grouped_parallel_split_combine ( args , split_fn , group_fn , parallel_fn , parallel_name , combine_name , file_key , combine_arg_keys , split_outfile_i = - 1 ) : """Parallel split runner that allows grouping of samples during processing . This builds on parallel _ split _ combine to provide the additional ab...
grouped_args = group_fn ( args ) split_args , combine_map , finished_out , extras = _get_split_tasks ( grouped_args , split_fn , file_key , split_outfile_i ) final_output = parallel_fn ( parallel_name , split_args ) combine_args , final_args = _organize_output ( final_output , combine_map , file_key , combine_arg_keys ...
def add ( self , name , attr = None , value = None ) : "Set values in constant"
if isinstance ( name , tuple ) or isinstance ( name , list ) : name , attr , value = self . __set_iter_value ( name ) if attr is None : attr = name if value is None : value = attr self . __data += ( self . get_const_string ( name = name , value = value ) , ) # set attribute as slugfiy self . __dict__ [ s_at...
def re_install_net_ctrl_paths ( self , vrf_table ) : """Re - installs paths from NC with current BGP policy . Iterates over known paths from NC installed in ` vrf4 _ table ` and adds new path with path attributes as per current VRF configuration ."""
assert vrf_table for dest in vrf_table . values ( ) : for path in dest . known_path_list : if path . source is None : vrf_table . insert_vrf_path ( nlri = path . nlri , next_hop = path . nexthop , gen_lbl = True ) LOG . debug ( 'Re-installed NC paths with current policy for table %s.' , vrf_tabl...
def load_data ( self , model_instance , * args , ** kwargs ) : """Apply units to model . : return : data"""
model_dict = copy_model_instance ( model_instance ) return super ( DjangoModelReader , self ) . load_data ( ** model_dict )
def CropBoxPosition ( self ) : """Retrieve position of / CropBox . Return ( 0,0 ) for non - PDF , or no / CropBox ."""
CheckParent ( self ) val = _fitz . Page_CropBoxPosition ( self ) val = Point ( val ) return val
def contains ( string , substring ) : """Returns true if the sequence of graphemes in substring is also present in string . This differs from the normal python ` in ` operator , since the python operator will return true if the sequence of codepoints are withing the other string without considering grapheme b...
if substring not in string : return False substr_graphemes = list ( graphemes ( substring ) ) if len ( substr_graphemes ) == 0 : return True elif len ( substr_graphemes ) == 1 : return substr_graphemes [ 0 ] in graphemes ( string ) else : str_iter = graphemes ( string ) str_sub_part = [ ] for _ ...
def openReadWrite ( filename ) : """Return a 2 - tuple of : ( whether the file existed before , open file object )"""
try : os . makedirs ( os . path . dirname ( filename ) ) except OSError : pass try : return file ( filename , 'rb+' ) except IOError : return file ( filename , 'wb+' )
def delete ( self ) : """Deletes one instance"""
if self . instance is None : raise CQLEngineException ( "DML Query instance attribute is None" ) ds = DeleteStatement ( self . column_family_name , timestamp = self . _timestamp , conditionals = self . _conditional , if_exists = self . _if_exists ) for name , col in self . model . _primary_keys . items ( ) : va...
def set_prior ( self , prior , warning = True ) : """Set the prior for this object to prior . : param : class : ` ~ GPy . priors . Prior ` prior : a prior to set for this parameter : param bool warning : whether to warn if another prior was set for this parameter"""
repriorized = self . unset_priors ( ) self . _add_to_index_operations ( self . priors , repriorized , prior , warning ) from paramz . domains import _REAL , _POSITIVE , _NEGATIVE if prior . domain is _POSITIVE : self . constrain_positive ( warning ) elif prior . domain is _NEGATIVE : self . constrain_negative (...
def all_down ( self ) : """Get the leaf object of this comparison . ( This is a convenient wrapper for following the down attribute as often as you can . ) : rtype : DiffLevel"""
level = self while level . down : level = level . down return level
def reverse_shortlex ( end , other , excludeend = False ) : """Yield all intersections of end with other in reverse shortlex order . > > > [ ' { : 03b } ' . format ( s ) for s in reverse _ shortlex ( 0b111 , [ 0b011 , 0b101 , 0b110 ] ) ] [ ' 111 ' , ' 011 ' , ' 101 ' , ' 110 ' , ' 001 ' , ' 010 ' , ' 100 ' , ' ...
if not excludeend : yield end queue = collections . deque ( [ ( end , other ) ] ) while queue : current , other = queue . popleft ( ) while other : first , other = other [ 0 ] , other [ 1 : ] result = current & first yield result if other : queue . append ( ( resu...
def _compute_register_list ( self , operand ) : """Return operand register list ."""
ret = [ ] for reg_range in operand . reg_list : if len ( reg_range ) == 1 : ret . append ( ReilRegisterOperand ( reg_range [ 0 ] . name , reg_range [ 0 ] . size ) ) else : reg_num = int ( reg_range [ 0 ] . name [ 1 : ] ) # Assuming the register is named with one letter + number r...
def get_instance ( self , payload ) : """Build an instance of PayloadInstance : param dict payload : Payload response from the API : returns : twilio . rest . api . v2010 . account . recording . add _ on _ result . payload . PayloadInstance : rtype : twilio . rest . api . v2010 . account . recording . add _ o...
return PayloadInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , reference_sid = self . _solution [ 'reference_sid' ] , add_on_result_sid = self . _solution [ 'add_on_result_sid' ] , )
def _edit ( self , pk ) : """Edit function logic , override to implement different logic returns Edit widget and related list or None"""
is_valid_form = True pages = get_page_args ( ) page_sizes = get_page_size_args ( ) orders = get_order_args ( ) get_filter_args ( self . _filters ) exclude_cols = self . _filters . get_relation_cols ( ) item = self . datamodel . get ( pk , self . _base_filters ) if not item : abort ( 404 ) # convert pk to correct ty...
def bleu ( eval_data , predictions , scores = 'ignored' , learner = 'ignored' ) : '''Return corpus - level BLEU score of ` predictions ` using the ` output ` field of the instances in ` eval _ data ` as references . This is returned as a length - 1 list of floats . This uses the NLTK unsmoothed implementation...
ref_groups = ( [ inst . output . split ( ) ] if isinstance ( inst . output , basestring ) else [ _maybe_tokenize ( r ) for r in inst . output ] for inst in eval_data ) return [ corpus_bleu ( ref_groups , [ p . split ( ) for p in predictions ] ) ]
def on_bus ( self , bus_idx ) : """Return the indices of elements on the given buses for shunt - connected elements : param bus _ idx : idx of the buses to which the elements are connected : return : idx of elements connected to bus _ idx"""
assert hasattr ( self , 'bus' ) ret = [ ] if isinstance ( bus_idx , ( int , float , str ) ) : bus_idx = [ bus_idx ] for item in bus_idx : idx = [ ] for e , b in enumerate ( self . bus ) : if b == item : idx . append ( self . idx [ e ] ) if len ( idx ) == 1 : idx = idx [ 0 ] ...
def _schedule_next_run ( self ) : """Compute the instant when this job should run next ."""
if self . unit not in ( 'seconds' , 'minutes' , 'hours' , 'days' , 'weeks' ) : raise ScheduleValueError ( 'Invalid unit' ) if self . latest is not None : if not ( self . latest >= self . interval ) : raise ScheduleError ( '`latest` is greater than `interval`' ) interval = random . randint ( self . i...
def reset_trace ( ) : """Resets all collected statistics . This is run automatically by start _ trace ( reset = True ) and when the module is loaded ."""
global call_dict global call_stack global func_count global func_count_max global func_time global func_time_max global call_stack_timer call_dict = { } # current call stack call_stack = [ '__main__' ] # counters for each function func_count = { } func_count_max = 0 # accumative time per function func_time = { } func_t...
def update_source_list ( self ) : """update ubuntu 16 source list : return :"""
with cd ( '/etc/apt' ) : sudo ( 'mv sources.list sources.list.bak' ) put ( StringIO ( bigdata_conf . ubuntu_source_list_16 ) , 'sources.list' , use_sudo = True ) sudo ( 'apt-get update -y --fix-missing' )
def materialize ( self ) : """Returns instance of ` ` TrackedModel ` ` created from current ` ` History ` ` snapshot . To rollback to current snapshot , simply call ` ` save ` ` on materialized object ."""
if self . action_type == ActionType . DELETE : # On deletion current state is dumped to change _ log # so it ' s enough to just restore it to object data = serializer . from_json ( self . change_log ) obj = serializer . restore_model ( self . _tracked_model , data ) return obj changes = History . objects . ...
def p_qualifier ( p ) : """qualifier : qualifierName | qualifierName ' : ' flavorList | qualifierName qualifierParameter | qualifierName qualifierParameter ' : ' flavorList"""
# pylint : disable = too - many - branches qname = p [ 1 ] ns = p . parser . handle . default_namespace qval = None flavorlist = [ ] if len ( p ) == 3 : qval = p [ 2 ] elif len ( p ) == 4 : flavorlist = p [ 3 ] elif len ( p ) == 5 : qval = p [ 2 ] flavorlist = p [ 4 ] try : qualdecl = p . parser . q...
def validate_type ( self , data ) : """Performs field validation against the schema context if values have been provided to SWAGManager via the swag . schema _ context config object . If the schema context for a given field is empty , then we assume any value is valid for the given schema field ."""
fields_to_validate = [ 'type' , 'environment' , 'owner' ] for field in fields_to_validate : value = data . get ( field ) allowed_values = self . context . get ( field ) if allowed_values and value not in allowed_values : raise ValidationError ( 'Must be one of {}' . format ( allowed_values ) , field...
def next_partname ( self , template ) : """Return a | PackURI | instance representing partname matching * template * . The returned part - name has the next available numeric suffix to distinguish it from other parts of its type . * template * is a printf ( % ) - style template string containing a single repl...
partnames = { part . partname for part in self . iter_parts ( ) } for n in range ( 1 , len ( partnames ) + 2 ) : candidate_partname = template % n if candidate_partname not in partnames : return PackURI ( candidate_partname )
def unique_index ( data , keys = None , fail_on_dup = True ) : """RETURN dict THAT USES KEYS TO INDEX DATA ONLY ONE VALUE ALLOWED PER UNIQUE KEY"""
o = UniqueIndex ( listwrap ( keys ) , fail_on_dup = fail_on_dup ) for d in data : try : o . add ( d ) except Exception as e : o . add ( d ) Log . error ( "index {{index}} is not unique {{key}} maps to both {{value1}} and {{value2}}" , index = keys , key = select ( [ d ] , keys ) [ 0 ] , ...
def get_serializer_class ( self , view , method_func ) : """Try to get the serializer class from view method . If view method don ' t have request serializer , fallback to serializer _ class on view class"""
if hasattr ( method_func , 'request_serializer' ) : return getattr ( method_func , 'request_serializer' ) if hasattr ( view , 'serializer_class' ) : return getattr ( view , 'serializer_class' ) if hasattr ( view , 'get_serializer_class' ) : return getattr ( view , 'get_serializer_class' ) ( ) return None
def add_fortran_to_env ( env ) : """Add Builders and construction variables for Fortran to an Environment ."""
try : FortranSuffixes = env [ 'FORTRANFILESUFFIXES' ] except KeyError : FortranSuffixes = [ '.f' , '.for' , '.ftn' ] # print ( " Adding % s to fortran suffixes " % FortranSuffixes ) try : FortranPPSuffixes = env [ 'FORTRANPPFILESUFFIXES' ] except KeyError : FortranPPSuffixes = [ '.fpp' , '.FPP' ] Dialec...
def apply ( self , resource ) : """Apply filter to resource : param resource : Image : return : Image"""
if not isinstance ( resource , Image . Image ) : raise ValueError ( 'Unknown resource format' ) resource_format = resource . format resource = resource . rotate ( self . angle , expand = True ) resource . format = resource_format return resource
def confusion_matrix ( predicted_essential , expected_essential , predicted_nonessential , expected_nonessential ) : """Compute a representation of the confusion matrix . Parameters predicted _ essential : set expected _ essential : set predicted _ nonessential : set expected _ nonessential : set Return...
true_positive = predicted_essential & expected_essential tp = len ( true_positive ) true_negative = predicted_nonessential & expected_nonessential tn = len ( true_negative ) false_positive = predicted_essential - expected_essential fp = len ( false_positive ) false_negative = predicted_nonessential - expected_nonessent...
def calc_tmean_v1 ( self ) : """Calculate the areal mean temperature of the subbasin . Required derived parameter : | RelZoneArea | Required flux sequence : | TC | Calculated flux sequences : | TMean | Examples : Prepare two zones , the first one being twice as large as the second one : > > > fr...
con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess flu . tmean = 0. for k in range ( con . nmbzones ) : flu . tmean += der . relzonearea [ k ] * flu . tc [ k ]
def BalanceFor ( self , assetId ) : """Get the balance for a given asset id . Args : assetId ( UInt256 ) : Returns : Fixed8 : balance value ."""
for key , fixed8 in self . Balances . items ( ) : if key == assetId : return fixed8 return Fixed8 ( 0 )
def send ( x , inter = 0 , loop = 0 , count = None , verbose = None , realtime = None , return_packets = False , socket = None , * args , ** kargs ) : """Send packets at layer 3 send ( packets , [ inter = 0 ] , [ loop = 0 ] , [ count = None ] , [ verbose = conf . verb ] , [ realtime = None ] , [ return _ packets ...
need_closing = socket is None socket = socket or conf . L3socket ( * args , ** kargs ) results = __gen_send ( socket , x , inter = inter , loop = loop , count = count , verbose = verbose , realtime = realtime , return_packets = return_packets ) if need_closing : socket . close ( ) return results
def getAppInfo ( self , verbose = None ) : """App version and other basic information will be provided . : param verbose : print more : returns : 200 : successful operation"""
surl = self . ___url sv = surl . split ( '/' ) [ - 1 ] surl = surl . rstrip ( sv + '/' ) response = api ( url = surl + '/cyndex2/v1' , method = "GET" , verbose = verbose , parse_params = False ) return response
def get_input ( context , conf ) : """Gets a user parameter , either from the console or from an outer submodule / system Assumes conf has name , default , prompt and debug"""
name = conf [ 'name' ] [ 'value' ] prompt = conf [ 'prompt' ] [ 'value' ] default = conf [ 'default' ] [ 'value' ] or conf [ 'debug' ] [ 'value' ] if context . submodule or context . inputs : value = context . inputs . get ( name , default ) elif not context . test : # we skip user interaction during tests raw ...
def get_key ( self , match_key , num_results = 1 , best = True , ** dfilter ) : """Get multiple fully - specified keys that match the provided query . Args : key ( DatasetID ) : DatasetID of query parameters to use for searching . Any parameter that is ` None ` is considered a wild card and any match is a...
return get_key ( match_key , self . keys ( ) , num_results = num_results , best = best , ** dfilter )
def get_relation_count_query ( self , query , parent ) : """Add the constraints for a relationship count query . : type query : eloquent . orm . Builder : type parent : eloquent . orm . Builder : rtype : eloquent . orm . Builder"""
query = super ( MorphToMany , self ) . get_relation_count_query ( query , parent ) return query . where ( '%s.%s' % ( self . _table , self . _morph_type ) , self . _morph_class )
def eventFilter ( self , object , event ) : """Filters the events for the inputed object through this edit . : param object | < QObject > event | < QEvent > : return < bool > | consumed"""
if ( event . type ( ) == event . KeyPress ) : if ( event . key ( ) == Qt . Key_Escape ) : self . _completerTree . hide ( ) self . completer ( ) . popup ( ) . hide ( ) self . cancelEdit ( ) elif ( event . key ( ) in ( Qt . Key_Return , Qt . Key_Enter ) ) : self . acceptEdit ( ) ...
def bezout ( a , b ) : """Bezout coefficients for a and b : param a , b : non - negative integers : complexity : O ( log a + log b )"""
if b == 0 : return ( 1 , 0 ) else : u , v = bezout ( b , a % b ) return ( v , u - ( a // b ) * v )
def log_mean_exp ( v , W = None ) : """Returns log of ( weighted ) mean of exp ( v ) . Parameters v : ndarray data , should be such that v . shape [ 0 ] = N W : ( N , ) ndarray , optional normalised weights ( > = 0 , sum to one ) Returns ndarray mean ( or weighted mean , if W is provided ) of vector...
m = v . max ( ) V = np . exp ( v - m ) if W is None : return m + np . log ( np . mean ( V ) ) else : return m + np . log ( np . average ( V , weights = W ) )
def sort_by_successors ( l , succsOf ) : """Sorts a list , such that if l [ b ] in succsOf ( l [ a ] ) then a < b"""
rlut = dict ( ) nret = 0 todo = list ( ) for i in l : rlut [ i ] = set ( ) for i in l : for j in succsOf ( i ) : rlut [ j ] . add ( i ) for i in l : if len ( rlut [ i ] ) == 0 : todo . append ( i ) while len ( todo ) > 0 : i = todo . pop ( ) nret += 1 yield i for j in succsOf...
def arg_parser ( self , passed_args = None ) : """Setup argument Parsing . If preset args are to be specified use the ` ` passed _ args ` ` tuple . : param passed _ args : ` ` list ` ` : return : ` ` dict ` `"""
parser , subpar , remaining_argv = self . _setup_parser ( ) if not isinstance ( passed_args , list ) : passed_args = list ( ) # Extend the passed args with the remaining parsed args if remaining_argv : passed_args . extend ( remaining_argv ) optional_args = self . arguments . get ( 'optional_args' ) if optional...
def sense ( self ) : """Launch a command in the ' senses ' List , and update the current state ."""
cmd_name = random . choice ( self . senses ) param = '' if cmd_name == 'ls' : if random . randint ( 0 , 1 ) : param = '-l' elif cmd_name == 'uname' : # Choose options from predefined ones opts = 'asnrvmpio' start = random . randint ( 0 , len ( opts ) - 2 ) end = random . randint ( start + 1 , le...
def _on_process_started ( self ) : """Logs process started"""
comm ( 'backend process started' ) if self is None : return self . starting = False self . running = True
def box ( text ) : r"""Wrap a chunk of text in a box . Example : > > > print ( box ( ' line1 \ nline2 ' ) ) │ line1 │ │ line2 │"""
lines = text . split ( '\n' ) width = max ( len ( l ) for l in lines ) top_bar = ( TOP_LEFT_CORNER + HORIZONTAL_BAR * ( 2 + width ) + TOP_RIGHT_CORNER ) bottom_bar = ( BOTTOM_LEFT_CORNER + HORIZONTAL_BAR * ( 2 + width ) + BOTTOM_RIGHT_CORNER ) lines = [ LINES_FORMAT_STR . format ( line = line , width = width ) for line...
def fill ( text , delimiter = "" , width = 70 ) : """Wrap text with width per line"""
texts = [ ] for i in xrange ( 0 , len ( text ) , width ) : t = delimiter . join ( text [ i : i + width ] ) texts . append ( t ) return "\n" . join ( texts )
def add_variant ( self , chrom , pos , rs_id , ref , alt , qual , filt , info , form = None , genotypes = [ ] ) : """Add a variant to the parser . This function is for building a vcf . It takes the relevant parameters and make a vcf variant in the proper format ."""
variant_info = [ chrom , pos , rs_id , ref , alt , qual , filt , info ] if form : variant_info . append ( form ) for individual in genotypes : variant_info . append ( individual ) variant_line = '\t' . join ( variant_info ) variant = format_variant ( line = variant_line , header_parser = self . metadata , check...