signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def from_json ( data ) : """Decode event encoded as JSON by processor"""
parsed_data = json . loads ( data ) trigger = TriggerInfo ( parsed_data [ 'trigger' ] [ 'class' ] , parsed_data [ 'trigger' ] [ 'kind' ] , ) # extract content type , needed to decode body content_type = parsed_data [ 'content_type' ] return Event ( body = Event . decode_body ( parsed_data [ 'body' ] , content_type ) , ...
def has_pfn ( self , url , site = None ) : """Wrapper of the pegasus hasPFN function , that allows it to be called outside of specific pegasus functions ."""
curr_pfn = dax . PFN ( url , site ) return self . hasPFN ( curr_pfn )
def apply_change ( self , path , * args ) : # type : ( List [ str ] , Any ) - > None """Take a single change from a Delta and apply it to this model"""
if len ( path ) > 1 : # This is for a child self [ path [ 0 ] ] . apply_change ( path [ 1 : ] , * args ) else : # This is for us assert len ( path ) == 1 and len ( args ) == 1 , "Cannot process change %s" % ( [ self . path + path ] + list ( args ) ) getattr ( self , "set_%s" % path [ 0 ] ) ( args [ 0 ] )
def handle_request ( self ) : """Override of TCPServer . handle _ request ( ) that provides locking . Calling this method has the effect of " maybe " ( if the socket does not time out first ) accepting a request and ( because we mixin in ThreadingMixIn ) spawning it on a thread . It should always return withi...
timeout = self . socket . gettimeout ( ) if timeout is None : timeout = self . timeout elif self . timeout is not None : timeout = min ( timeout , self . timeout ) fd_sets = safe_select ( [ self ] , [ ] , [ ] , timeout ) if not fd_sets [ 0 ] : self . handle_timeout ( ) return # After select tells us we ...
def find_lines_with ( cls , lines , what ) : """returns all lines that contain what : param lines : : param what : : return :"""
result = [ ] for line in lines : if what in line : result = result + [ line ] return result
def longest_table ( dfs ) : """Return this single longest DataFrame that among an array / list / tuple of DataFrames Useful for automagically finding the DataFrame you want when using pd . read _ html ( ) on a Wikipedia page ."""
sorted_indices = sorted ( ( len ( df if hasattr ( df , '__len__' ) else [ ] ) , i ) for i , df in enumerate ( dfs ) ) return dfs [ sorted_indices [ - 1 ] [ 1 ] ]
def mask_table ( region , table , negate = False , racol = 'ra' , deccol = 'dec' ) : """Apply a given mask ( region ) to the table , removing all the rows with ra / dec inside the region If negate = False then remove the rows with ra / dec outside the region . Parameters region : : class : ` AegeanTools . reg...
inside = region . sky_within ( table [ racol ] , table [ deccol ] , degin = True ) if not negate : mask = np . bitwise_not ( inside ) else : mask = inside return table [ mask ]
def total_members_in_score_range ( self , min_score , max_score ) : '''Retrieve the total members in a given score range from the leaderboard . @ param min _ score [ float ] Minimum score . @ param max _ score [ float ] Maximum score . @ return the total members in a given score range from the leaderboard .''...
return self . total_members_in_score_range_in ( self . leaderboard_name , min_score , max_score )
def create_detailed_results ( result ) : """Use the result from the API call to create an organized single string output for printing to the console . : param dict result : Results from API call for one file : return str string : Organized results for printing"""
string = "" # Validation Response output # string + = " VALIDATION RESPONSE \ n " string += "STATUS: {}\n" . format ( result [ "status" ] ) if result [ "feedback" ] : string += "WARNINGS: {}\n" . format ( len ( result [ "feedback" ] [ "wrnMsgs" ] ) ) # Loop through and output the Warnings for msg in result ...
def event_gen ( self , timeout_s = None , yield_nones = True , filter_predicate = None , terminal_events = _DEFAULT_TERMINAL_EVENTS ) : """Yield one event after another . If ` timeout _ s ` is provided , we ' ll break when no event is received for that many seconds ."""
# We will either return due to the optional filter or because of a # timeout . The former will always set this . The latter will never set # this . self . __last_success_return = None last_hit_s = time . time ( ) while True : block_duration_s = self . __get_block_duration ( ) # Poll , but manage signal - relate...
def bootstrap_indexes ( data , n_samples = 10000 ) : """Given data points data , where axis 0 is considered to delineate points , return an generator for sets of bootstrap indexes . This can be used as a list of bootstrap indexes ( with list ( bootstrap _ indexes ( data ) ) ) as well ."""
for _ in xrange ( n_samples ) : yield randint ( data . shape [ 0 ] , size = ( data . shape [ 0 ] , ) )
def __find_executables ( path ) : """Used by find _ graphviz path - single directory as a string If any of the executables are found , it will return a dictionary containing the program names as keys and their paths as values . Otherwise returns None"""
success = False progs = { "dot" : "" , "twopi" : "" , "neato" : "" , "circo" : "" , "fdp" : "" , "sfdp" : "" , } was_quoted = False path = path . strip ( ) if path . startswith ( '"' ) and path . endswith ( '"' ) : path = path [ 1 : - 1 ] was_quoted = True if not os . path . isdir ( path ) : return None for...
def _permute_two_sample_iscs ( iscs , group_parameters , i , pairwise = False , summary_statistic = 'median' , exact_permutations = None , prng = None ) : """Applies two - sample permutations to ISC data Input ISCs should be n _ subjects ( leave - one - out approach ) or n _ pairs ( pairwise approach ) by n _ v...
# Shuffle the group assignments if exact_permutations : group_shuffler = np . array ( exact_permutations [ i ] ) elif not exact_permutations and pairwise : group_shuffler = prng . permutation ( np . arange ( len ( np . array ( group_parameters [ 'group_assignment' ] ) [ group_parameters [ 'sorter' ] ] ) ) ) eli...
def run_once ( ) : """Make a pass through the scheduled tasks and deferred functions just like the run ( ) function but without the asyncore call ( so there is no socket IO actviity ) and the timers ."""
if _debug : run_once . _debug ( "run_once" ) global taskManager , deferredFns # reference the task manager ( a singleton ) taskManager = TaskManager ( ) try : delta = 0.0 while delta == 0.0 : # get the next task task , delta = taskManager . get_next_task ( ) if _debug : run_once ...
def updateColumnValues ( self , networkId , tableType , columnName , default , body , verbose = None ) : """Sets the values for cells in the table specified by the ` tableType ` and ` networkId ` parameters . If the ' default ` parameter is not specified , the message body should consist of key - value pairs with...
response = api ( url = self . ___url + 'networks/' + str ( networkId ) + '/tables/' + str ( tableType ) + '/columns/' + str ( columnName ) + '' , method = "PUT" , body = body , verbose = verbose ) return response
def _EntriesGenerator ( self ) : """Retrieves directory entries . Since a directory can contain a vast number of entries using a generator is more memory efficient . Yields : APFSContainerPathSpec : a path specification ."""
# Only the virtual root file has directory entries . volume_index = apfs_helper . APFSContainerPathSpecGetVolumeIndex ( self . path_spec ) if volume_index is not None : return location = getattr ( self . path_spec , 'location' , None ) if location is None or location != self . _file_system . LOCATION_ROOT : ret...
def _setup_argparse ( self ) : """Create ` argparse ` instance , and setup with appropriate parameters ."""
parser = argparse . ArgumentParser ( prog = 'catalog' , description = 'Parent Catalog class for astrocats.' ) subparsers = parser . add_subparsers ( description = 'valid subcommands' , dest = 'subcommand' ) # Data Import # Add the ' import ' command , and related arguments self . _add_parser_arguments_import ( subparse...
def container_move ( object_id , input_params = { } , always_retry = False , ** kwargs ) : """Invokes the / container - xxxx / move API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Folders - and - Deletion # API - method % 3A - % 2Fclass - xxxx % 2Fmove"""
return DXHTTPRequest ( '/%s/move' % object_id , input_params , always_retry = always_retry , ** kwargs )
def _set_disable ( self , v , load = False ) : """Setter method for disable , mapped from YANG variable / ntp / disable ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ disable is considered as a private method . Backends looking to populate this variable...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = disable . disable , is_container = 'container' , presence = False , yang_name = "disable" , rest_name = "disable" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True ,...
def _short_req_str ( package_request ) : """print shortened version of ' = = X | = = Y | = = Z ' ranged requests ."""
if not package_request . conflict : versions = package_request . range . to_versions ( ) if versions and len ( versions ) == len ( package_request . range ) and len ( versions ) > 1 : return "%s-%s(%d)" % ( package_request . name , str ( package_request . range . span ( ) ) , len ( versions ) ) return s...
def QA_user_sign_in ( username , password ) : """用户登陆 不使用 QAUSER库 只返回 TRUE / FALSE"""
# user = QA _ User ( name = name , password = password ) cursor = DATABASE . user . find_one ( { 'username' : username , 'password' : password } ) if cursor is None : QA_util_log_info ( 'SOMETHING WRONG' ) return False else : return True
def copy ( self ) : """Correctly copies the ` Record ` # Returns ` Record ` > A completely decoupled copy of the original"""
c = copy . copy ( self ) c . _fieldDict = c . _fieldDict . copy ( ) return c
def from_rgb ( cls , r : int , g : int , b : int ) -> 'ColorCode' : """Return a ColorCode from a RGB tuple ."""
c = cls ( ) c . _init_rgb ( r , g , b ) return c
def preprocess_source ( base_dir = os . curdir ) : """A special method for convert all source files to compatible with current python version during installation time . The source directory layout must like this : base _ dir - - + + - - src ( All sources are placed into this directory ) + - - preprocessed...
source_path = os . path . join ( base_dir , SOURCE_DIR ) destination_path = os . path . join ( base_dir , PREPROCESSED_DIR ) # The ' build ' and ' dist ' folder sometimes will not update ! So we need to # remove them all ! shutil . rmtree ( os . path . join ( base_dir , 'build' ) , ignore_errors = True ) shutil . rmtre...
def _bufferlist_overlay_visible ( editor ) : """True when the buffer list overlay should be displayed . ( This is when someone starts typing ' : b ' or ' : buffer ' in the command line . )"""
@ Condition def overlay_is_visible ( ) : app = get_app ( ) text = editor . command_buffer . text . lstrip ( ) return app . layout . has_focus ( editor . command_buffer ) and ( any ( text . startswith ( p ) for p in [ 'b ' , 'b! ' , 'buffer' , 'buffer!' ] ) ) return overlay_is_visible
def crypto_secretstream_xchacha20poly1305_init_push ( state , key ) : """Initialize a crypto _ secretstream _ xchacha20poly1305 encryption buffer . : param state : a secretstream state object : type state : crypto _ secretstream _ xchacha20poly1305 _ state : param key : must be : data : ` . crypto _ secrets...
ensure ( isinstance ( state , crypto_secretstream_xchacha20poly1305_state ) , 'State must be a crypto_secretstream_xchacha20poly1305_state object' , raising = exc . TypeError , ) ensure ( isinstance ( key , bytes ) , 'Key must be a bytes sequence' , raising = exc . TypeError , ) ensure ( len ( key ) == crypto_secretstr...
def matches ( self , other ) : '''A disjunctive list matches a phoneme if any of its members matches the phoneme . If other is also a disjunctive list , any match between this list and the other returns true .'''
if other is None : return False if isinstance ( other , PhonemeDisjunction ) : return any ( [ phoneme . matches ( other ) for phoneme in self ] ) if isinstance ( other , list ) or isinstance ( other , PhonologicalFeature ) : other = phoneme ( other ) return any ( [ phoneme <= other for phoneme in self ] )
def _cast_number ( value ) : # source : https : / / bitbucket . org / openpyxl / openpyxl / src / 93604327bce7aac5e8270674579af76d390e09c0 / openpyxl / cell / read _ only . py ? at = default & fileviewer = file - view - default "Convert numbers as string to an int or float"
m = FLOAT_REGEX . search ( value ) if m is not None : return float ( value ) return int ( value )
def transform_audio ( self , y ) : '''Compute the HCQT with unwrapped phase Parameters y : np . ndarray The audio buffer Returns data : dict data [ ' mag ' ] : np . ndarray , shape = ( n _ frames , n _ bins ) CQT magnitude data [ ' dphase ' ] : np . ndarray , shape = ( n _ frames , n _ bins ) Unwr...
data = super ( HCQTPhaseDiff , self ) . transform_audio ( y ) data [ 'dphase' ] = self . phase_diff ( data . pop ( 'phase' ) ) return data
def setedge ( delta , is_multigraph , graph , orig , dest , idx , exists ) : """Change a delta to say that an edge was created or deleted"""
if is_multigraph ( graph ) : delta . setdefault ( graph , { } ) . setdefault ( 'edges' , { } ) . setdefault ( orig , { } ) . setdefault ( dest , { } ) [ idx ] = bool ( exists ) else : delta . setdefault ( graph , { } ) . setdefault ( 'edges' , { } ) . setdefault ( orig , { } ) [ dest ] = bool ( exists )
def list_roots ( ) : '''Return all of the files names in all available environments'''
ret = { } for saltenv in __opts__ [ 'pillar_roots' ] : ret [ saltenv ] = [ ] ret [ saltenv ] . append ( list_env ( saltenv ) ) return ret
def cmd_requests_per_minute ( self ) : """Generates statistics on how many requests were made per minute . . . note : : Try to combine it with time constrains ( ` ` - s ` ` and ` ` - d ` ` ) as this command output can be huge otherwise ."""
if len ( self . _valid_lines ) == 0 : return current_minute = self . _valid_lines [ 0 ] . accept_date current_minute_counter = 0 requests = [ ] one_minute = timedelta ( minutes = 1 ) def format_and_append ( append_to , date , counter ) : seconds_and_micro = timedelta ( seconds = date . second , microseconds = d...
def maxlike ( self , nseeds = 50 ) : """Returns the best - fit parameters , choosing the best of multiple starting guesses : param nseeds : ( optional ) Number of starting guesses , uniformly distributed throughout allowed ranges . Default = 50. : return : list of best - fit parameters : ` ` [ mA , mB , a...
mA_0 , age0 , feh0 = self . ic . random_points ( nseeds ) mB_0 , foo1 , foo2 = self . ic . random_points ( nseeds ) mC_0 , foo3 , foo4 = self . ic . random_points ( nseeds ) m_all = np . sort ( np . array ( [ mA_0 , mB_0 , mC_0 ] ) , axis = 0 ) mA_0 , mB_0 , mC_0 = ( m_all [ 0 , : ] , m_all [ 1 , : ] , m_all [ 2 , : ] ...
def pdf ( self , mu ) : """PDF for Truncated Normal prior Parameters mu : float Latent variable for which the prior is being formed over Returns - p ( mu )"""
if self . transform is not None : mu = self . transform ( mu ) if mu < self . lower and self . lower is not None : return 0.0 elif mu > self . upper and self . upper is not None : return 0.0 else : return ( 1 / float ( self . sigma0 ) ) * np . exp ( - ( 0.5 * ( mu - self . mu0 ) ** 2 ) / float ( self . ...
def find_prf_cpu ( idxPrc , aryFuncChnk , aryPrfTc , aryMdlParams , strVersion , lgcXval , varNumXval , queOut , lgcRstr = None , lgcPrint = True ) : """Find best fitting pRF model for voxel time course , using the CPU . Parameters idxPrc : int Process ID of the process calling this function ( for CPU multi...
# Number of models in the visual space : varNumMdls = aryPrfTc . shape [ 0 ] # Number of feautures varNumFtr = aryPrfTc . shape [ 1 ] # Number of voxels to be fitted in this chunk : varNumVoxChnk = aryFuncChnk . shape [ 0 ] # Vectors for pRF finding results [ number - of - voxels times one ] : # make sure they have the...
def p_examples_add ( self , p ) : 'examples : examples example'
p [ 0 ] = p [ 1 ] if p [ 2 ] . label in p [ 0 ] : existing_ex = p [ 0 ] [ p [ 2 ] . label ] self . errors . append ( ( "Example with label '%s' already defined on line %d." % ( existing_ex . label , existing_ex . lineno ) , p [ 2 ] . lineno , p [ 2 ] . path ) ) p [ 0 ] [ p [ 2 ] . label ] = p [ 2 ]
def convertToAscii ( string , error = "?" ) : """Utility function that converts a unicode string to ASCII . This exists so the : class : ` Comic ` class can be compatible with Python 2 libraries that expect ASCII strings , such as Twisted ( as of this writing , anyway ) . It is unlikely something you will nee...
running = True asciiString = string while running : try : asciiString = asciiString . encode ( 'ascii' ) except UnicodeError as unicode : start = unicode . start end = unicode . end asciiString = asciiString [ : start ] + "?" + asciiString [ end : ] else : running = F...
def filter_by_meta ( data , df , join_meta = False , ** kwargs ) : """Filter by and join meta columns from an IamDataFrame to a pd . DataFrame Parameters data : pd . DataFrame instance DataFrame to which meta columns are to be joined , index or columns must include ` [ ' model ' , ' scenario ' ] ` df : Ia...
if not set ( META_IDX ) . issubset ( data . index . names + list ( data . columns ) ) : raise ValueError ( 'missing required index dimensions or columns!' ) meta = pd . DataFrame ( df . meta [ list ( set ( kwargs ) - set ( META_IDX ) ) ] . copy ( ) ) # filter meta by columns keep = np . array ( [ True ] * len ( met...
def get_chart ( self , id , ** kwargs ) : """" Retrieve a ( v2 ) chart by id ."""
resp = self . _get_object_by_name ( self . _CHART_ENDPOINT_SUFFIX , id , ** kwargs ) return resp
def awsReadInstanceTag ( ) : """Print key from a running instance ' s metadata"""
parser = argparse . ArgumentParser ( ) parser . add_argument ( "--tag" , dest = "tag" , required = True , help = "Which instance tag to read" ) cli = parser . parse_args ( ) print haze . ec2 . readMyEC2Tag ( tagName = cli . tag )
def delete ( self , id ) : """Delete a resource by bson id : raises : 404 Not Found : raises : 400 Bad request : raises : 500 Server Error"""
try : response = yield self . client . delete ( id ) if response . get ( "n" ) > 0 : self . write ( { "message" : "Deleted %s object: %s" % ( self . object_name , id ) } ) return self . raise_error ( 404 , "Resource not found" ) except InvalidId as ex : self . raise_error ( 400 , message...
def p_single_statement_delays ( self , p ) : 'single _ statement : DELAY expression SEMICOLON'
p [ 0 ] = SingleStatement ( DelayStatement ( p [ 2 ] , lineno = p . lineno ( 1 ) ) , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def request_io ( self , iocb ) : """Called by a client to start processing a request ."""
if _debug : IOQController . _debug ( "request_io %r" , iocb ) # bind the iocb to this controller iocb . ioController = self # if we ' re busy , queue it if ( self . state != CTRL_IDLE ) : if _debug : IOQController . _debug ( " - busy, request queued, active_iocb: %r" , self . active_iocb ) iocb ....
def add_sibling ( self , pos = None , ** kwargs ) : """Adds a new node as a sibling to the current node object ."""
pos = self . _prepare_pos_var_for_add_sibling ( pos ) if len ( kwargs ) == 1 and 'instance' in kwargs : # adding the passed ( unsaved ) instance to the tree newobj = kwargs [ 'instance' ] if newobj . pk : raise NodeAlreadySaved ( "Attempted to add a tree node that is " "already in the database" ) else :...
def analyze ( self , output_file = None ) : """Analyzes the parsed results from Flake8 or PEP 8 output and creates FileResult instances : param output _ file : If specified , output will be written to this file instead of stdout ."""
fr = None for path , code , line , char , desc in self . parser . parse ( ) : # Create a new FileResult and register it if we have changed to a new file if path not in self . files : # Update statistics if fr : self . update_stats ( fr ) fr = FileResult ( path ) self . files [ pa...
def parse_request ( self ) : """Parse a request ( internal ) . The request should be stored in self . raw _ requestline ; the results are in self . command , self . path , self . request _ version and self . headers . Return True for success , False for failure ; on failure , an error is sent back ."""
self . command = None # set in case of error on the first line self . request_version = version = self . default_request_version self . close_connection = 1 requestline = str ( self . raw_requestline , 'iso-8859-1' ) requestline = requestline . rstrip ( '\r\n' ) self . requestline = requestline words = requestline . sp...
def _step_envs ( self , action ) : """Perform step ( action ) on environments and update initial _ frame _ stack ."""
self . _frame_counter += 1 real_env_step_tuple = self . real_env . step ( action ) sim_env_step_tuple = self . sim_env . step ( action ) self . sim_env . add_to_initial_stack ( real_env_step_tuple [ 0 ] ) return self . _pack_step_tuples ( real_env_step_tuple , sim_env_step_tuple )
def create_image ( self , instance_id , name , description = None , no_reboot = False ) : """Will create an AMI from the instance in the running or stopped state . : type instance _ id : string : param instance _ id : the ID of the instance to image . : type name : string : param name : The name of the ne...
params = { 'InstanceId' : instance_id , 'Name' : name } if description : params [ 'Description' ] = description if no_reboot : params [ 'NoReboot' ] = 'true' img = self . get_object ( 'CreateImage' , params , Image , verb = 'POST' ) return img . id
def stop ( self , force = False ) : """Stop the instance : type force : bool : param force : Forces the instance to stop : rtype : list : return : A list of the instances stopped"""
rs = self . connection . stop_instances ( [ self . id ] , force ) if len ( rs ) > 0 : self . _update ( rs [ 0 ] )
def proceed ( self , * , action = adhoc_xso . ActionType . EXECUTE , payload = None ) : """Proceed command execution to the next stage . : param action : Action type for proceeding : type action : : class : ` ~ . ActionTyp ` : param payload : Payload for the request , or : data : ` None ` : return : The : a...
if self . _response is None : raise RuntimeError ( "command execution not started yet" ) if action not in self . allowed_actions : raise ValueError ( "action {} not allowed in this stage" . format ( action ) ) cmd = adhoc_xso . Command ( self . _command_name , action = action , payload = self . _response . payl...
def resolve_simulation ( self , fc , ct ) : """Resolve simulation specifications ."""
for run in ct . simulation . runs : try : run2 = Run ( fc . component_references [ run . component ] . referenced_component , run . variable , fc . parameters [ run . increment ] . numeric_value , fc . parameters [ run . total ] . numeric_value ) except : raise ModelError ( "Unable to resolve si...
def list_all_coupons ( cls , ** kwargs ) : """List Coupons Return a list of Coupons This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . list _ all _ coupons ( async = True ) > > > result = thread . get ( ) : param...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _list_all_coupons_with_http_info ( ** kwargs ) else : ( data ) = cls . _list_all_coupons_with_http_info ( ** kwargs ) return data
def join ( args ) : """% prog join fastafile [ phasefile ] Make AGP file for a bunch of sequences , and add gaps between , and then build the joined fastafile . This is useful by itself , but with - - oo option this can convert the . oo ( BAMBUS output ) into AGP and a joined fasta . Phasefile is optional ,...
from jcvi . formats . agp import OO , Phases , build from jcvi . formats . sizes import Sizes p = OptionParser ( join . __doc__ ) p . add_option ( "--newid" , default = None , help = "New sequence ID [default: `%default`]" ) p . add_option ( "--gapsize" , default = 100 , type = "int" , help = "Number of N's in between ...
def forward ( self , observations ) : """Calculate model outputs"""
input_data = self . input_block ( observations ) base_output = self . backbone ( input_data ) policy_params = self . action_head ( base_output ) q = self . q_head ( base_output ) return policy_params , q
def commit ( self ) : """Commits the batch . This is called automatically upon exiting a with statement , however it can be called explicitly if you don ' t want to use a context manager . : raises : : class : ` ~ exceptions . ValueError ` if the batch is not in progress ."""
if self . _status != self . _IN_PROGRESS : raise ValueError ( "Batch must be in progress to commit()" ) try : self . _commit ( ) finally : self . _status = self . _FINISHED
def _make_chunk_iter ( stream , limit , buffer_size ) : """Helper for the line and chunk iter functions ."""
if isinstance ( stream , ( bytes , bytearray , text_type ) ) : raise TypeError ( 'Passed a string or byte object instead of ' 'true iterator or stream.' ) if not hasattr ( stream , 'read' ) : for item in stream : if item : yield item return if not isinstance ( stream , LimitedStream ) an...
def containing_bins ( start , stop = None ) : """Given an interval ` start : stop ` , return bins for intervals completely * containing * ` start : stop ` . The order is according to the bin level ( starting with the smallest bins ) , and within a level according to the bin number ( ascending ) . : arg int ...
if stop is None : stop = start + 1 max_bin = assign_bin ( start , stop ) return [ bin for bin in overlapping_bins ( start , stop ) if bin <= max_bin ]
def get_pages_for_display ( self ) : """Return all pages needed for rendering all sub - levels for the current menu"""
# Start with an empty queryset , and expand as needed all_pages = Page . objects . none ( ) if self . max_levels == 1 : # If no additional sub - levels are needed , return empty queryset return all_pages for item in self . top_level_items : if item . link_page_id : # Fetch a ' branch ' of suitable descendants f...
def remover ( self , id_direito ) : """Remove os direitos de um grupo de usuário em um grupo de equipamento a partir do seu identificador . : param id _ direito : Identificador do direito grupo equipamento : return : None : raise DireitoGrupoEquipamentoNaoExisteError : Direito Grupo Equipamento não cadastra...
if not is_valid_int_param ( id_direito ) : raise InvalidParameterError ( u'O identificador do direito grupo equipamento é inválido ou não foi informado.' ) url = 'direitosgrupoequipamento/' + str ( id_direito ) + '/' code , xml = self . submit ( None , 'DELETE' , url ) return self . response ( code , xml )
def _set_rpc ( self , rpc_type : str ) -> None : """Sets rpc based on the type : param rpc _ type : The type of connection : like infura , ganache , localhost : return :"""
if rpc_type == "infura" : self . set_api_rpc_infura ( ) elif rpc_type == "localhost" : self . set_api_rpc_localhost ( ) else : self . set_api_rpc ( rpc_type )
def shift_peaks ( sig , peak_inds , search_radius , peak_up ) : """Helper function for correct _ peaks . Return the shifted peaks to local maxima or minima within a radius . peak _ up : bool Whether the expected peak direction is up"""
sig_len = sig . shape [ 0 ] n_peaks = len ( peak_inds ) # The indices to shift each peak ind by shift_inds = np . zeros ( n_peaks , dtype = 'int' ) # Iterate through peaks for i in range ( n_peaks ) : ind = peak_inds [ i ] local_sig = sig [ max ( 0 , ind - search_radius ) : min ( ind + search_radius , sig_len -...
def get_property_names ( self ) : '''Returns all property names in this collection of signatures'''
property_names = set ( ) for signature_value in self . values ( ) : for property_name in signature_value . keys ( ) : property_names . add ( property_name ) return property_names
def edit_config_input_edit_content_url_url ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) edit_config = ET . Element ( "edit_config" ) config = edit_config input = ET . SubElement ( edit_config , "input" ) edit_content = ET . SubElement ( input , "edit-content" ) url = ET . SubElement ( edit_content , "url" ) url = ET . SubElement ( url , "url" ) url . text = kwargs . pop ...
def set_value ( self , name , value , ignore_error = False , block_user_signals = False ) : """Sets the variable of the supplied name to the supplied value . Setting block _ user _ signals = True will temporarily block the widget from sending any signals when setting the value ."""
# first clean up the name name = self . _clean_up_name ( name ) # If we ' re supposed to , block the user signals for this parameter if block_user_signals : self . block_user_signals ( name , ignore_error ) # now get the parameter object x = self . _find_parameter ( name . split ( '/' ) , quiet = ignore_error ) # q...
def getVideoStreamTextureD3D11 ( self , hTrackedCamera , eFrameType , pD3D11DeviceOrResource , nFrameHeaderSize ) : """Access a shared D3D11 texture for the specified tracked camera stream . The camera frame type VRTrackedCameraFrameType _ Undistorted is not supported directly as a shared texture . It is an inter...
fn = self . function_table . getVideoStreamTextureD3D11 ppD3D11ShaderResourceView = c_void_p ( ) pFrameHeader = CameraVideoStreamFrameHeader_t ( ) result = fn ( hTrackedCamera , eFrameType , pD3D11DeviceOrResource , byref ( ppD3D11ShaderResourceView ) , byref ( pFrameHeader ) , nFrameHeaderSize ) return result , ppD3D1...
def read_string ( self , size ) : """Reads up to ' size ' bytes from the stream , stopping early only if we reach the end of the stream . Returns the bytes read as a string ."""
if size < 0 : raise errors . DecodeError ( 'Negative size %d' % size ) s = self . _input . read ( size ) if len ( s ) != size : raise errors . DecodeError ( 'String claims to have %d bytes, but read %d' % ( size , len ( s ) ) ) self . _pos += len ( s ) # Only advance by the number of bytes actually read . retur...
def get_content_object_url ( self ) : """Gets the absolute url for the content object ."""
if ( self . content_object and hasattr ( self . content_object , 'get_absolute_url' ) ) : return self . content_object . get_absolute_url ( ) return None
def run_generator ( product_category , obs_info ) : """This is the main calling subroutine . It decides which filename generation subroutine should be run based on the input product _ category , and then passes the information stored in input obs _ info to the subroutine so that the appropriate filenames can be...
category_generator_mapping = { 'single exposure product' : single_exposure_product_filename_generator , 'filter product' : filter_product_filename_generator , 'total detection product' : total_detection_product_filename_generator , 'multivisit mosaic product' : multivisit_mosaic_product_filename_generator } # Determine...
def format ( keys , value , _type , prefix = "" ) : """General format function . > > > StatsdClient . format ( " example . format " , 2 , " T " ) { ' example . format ' : ' 2 | T ' } > > > StatsdClient . format ( ( " example . format31 " , " example . format37 " ) , " 2 " , { ' example . format31 ' : ' 2 | ...
data = { } value = "{0}|{1}" . format ( value , _type ) # TODO : Allow any iterable except strings if not isinstance ( keys , ( list , tuple ) ) : keys = [ keys ] for key in keys : data [ prefix + key ] = value return data
def write_lockfile ( self , content ) : """Write out the lockfile ."""
s = self . _lockfile_encoder . encode ( content ) open_kwargs = { "newline" : self . _lockfile_newlines , "encoding" : "utf-8" } with vistir . contextmanagers . atomic_open_for_write ( self . lockfile_location , ** open_kwargs ) as f : f . write ( s ) # Write newline at end of document . GH - 319. # Only ne...
def validate ( self , request , data ) : """Validate response from OpenID server . Set identity in case of successfull validation ."""
client = consumer . Consumer ( request . session , None ) try : resp = client . complete ( data , request . session [ 'openid_return_to' ] ) except KeyError : messages . error ( request , lang . INVALID_RESPONSE_FROM_OPENID ) return redirect ( 'netauth-login' ) if resp . status == consumer . CANCEL : me...
def send ( ezo , name , method , data , target ) : '''runs a transaction on a contract method : param ezo : ezo instance : param name : name of the Contract : param method : name of the contract method : param data : formatted data to send to the contract method : return :'''
# load the contract by name c , err = Contract . get ( name , ezo ) if err : return None , err address , err = Contract . get_address ( name , c . hash , ezo . db , target ) if err : return None , err d = dict ( ) d [ "address" ] = address d [ "function" ] = method d [ "params" ] = c . paramsForMethod ( method ...
def active ( self ) : """Returns all outlets that are currently active and have sales ."""
qs = self . get_queryset ( ) return qs . filter ( models . Q ( models . Q ( start_date__isnull = True ) | models . Q ( start_date__lte = now ( ) . date ( ) ) ) & models . Q ( models . Q ( end_date__isnull = True ) | models . Q ( end_date__gte = now ( ) . date ( ) ) ) ) . distinct ( )
def main ( ) : """Example application that opens a serial device and prints messages to the terminal ."""
try : # Retrieve the specified serial device . device = AlarmDecoder ( SerialDevice ( interface = SERIAL_DEVICE ) ) # Set up an event handler and open the device device . on_message += handle_message # Override the default SerialDevice baudrate since we ' re using a USB device # over serial in this ...
def lon360to180 ( lon ) : """Convert longitude from ( 0 , 360 ) to ( - 180 , 180)"""
if np . any ( lon > 360.0 ) or np . any ( lon < 0.0 ) : print ( "Warning: lon outside expected range" ) lon = wraplon ( lon ) # lon [ lon > 180.0 ] - = 360.0 # lon180 = ( lon + 180 ) - np . floor ( ( lon + 180 ) / 360 ) * 360 - 180 lon = lon - ( lon . astype ( int ) / 180 ) * 360.0 return lon
def post ( url , var ) : """Post data to an url ."""
data = { b [ 0 ] : b [ 1 ] for b in [ a . split ( "=" ) for a in var ] } writeln ( "Sending data to url" , url ) response = requests . post ( url , data = data ) if response . status_code == 200 : writeln ( response . text ) else : writeln ( str ( response . status_code ) , response . reason )
def confirm_input ( user_input ) : """Check user input for yes , no , or an exit signal ."""
if isinstance ( user_input , list ) : user_input = '' . join ( user_input ) try : u_inp = user_input . lower ( ) . strip ( ) except AttributeError : u_inp = user_input # Check for exit signal if u_inp in ( 'q' , 'quit' , 'exit' ) : sys . exit ( ) if u_inp in ( 'y' , 'yes' ) : return True return Fals...
def addComponentEditor ( self ) : """Adds a new component to the model , and an editor for this component to this editor"""
row = self . _model . rowCount ( ) comp_stack_editor = ExploreComponentEditor ( ) self . ui . trackStack . addWidget ( comp_stack_editor ) idx_button = IndexButton ( row ) idx_button . pickMe . connect ( self . ui . trackStack . setCurrentIndex ) self . trackBtnGroup . addButton ( idx_button ) self . ui . trackBtnLayou...
def all_combinations_of_ensembl_genomes ( args ) : """Use all combinations of species and release versions specified by the commandline arguments to return a list of EnsemblRelease or Genome objects . The results will typically be of type EnsemblRelease unless the - - custom - mirror argument was given ."""
species_list = args . species if args . species else [ "human" ] release_list = args . release if args . release else [ MAX_ENSEMBL_RELEASE ] genomes = [ ] for species in species_list : # Otherwise , use Ensembl release information for version in release_list : ensembl_release = EnsemblRelease ( version , s...
def _assign_udf_desc_extents ( descs , start_extent ) : # type : ( PyCdlib . _ UDFDescriptors , int ) - > None '''An internal function to assign a consecutive sequence of extents for the given set of UDF Descriptors , starting at the given extent . Parameters : descs - The PyCdlib . _ UDFDescriptors object to...
current_extent = start_extent descs . pvd . set_extent_location ( current_extent ) current_extent += 1 descs . impl_use . set_extent_location ( current_extent ) current_extent += 1 descs . partition . set_extent_location ( current_extent ) current_extent += 1 descs . logical_volume . set_extent_location ( current_exten...
def parse_options ( cls , options ) : """Pass options through to this plugin ."""
cls . ignore_decorators = options . ignore_decorators cls . exclude_from_doctest = options . exclude_from_doctest if not isinstance ( cls . exclude_from_doctest , list ) : cls . exclude_from_doctest = [ cls . exclude_from_doctest ]
def run ( self , * args , ** kwargs ) : """Probe the input tree and print ."""
b_status = True d_probe = { } d_tree = { } d_stats = { } str_error = '' b_timerStart = False d_test = { } for k , v in kwargs . items ( ) : if k == 'timerStart' : b_timerStart = bool ( v ) if b_timerStart : other . tic ( ) if not os . path . exists ( self . str_inputDir ) : b_status = False self...
def is_empty ( self ) : """Return True if the table has no columns or the only column is the id"""
if len ( self . columns ) == 0 : return True if len ( self . columns ) == 1 and self . columns [ 0 ] . name == 'id' : return True return False
def _get_registry ( self , registry_path_or_url ) : '''Return a dict with objects mapped by their id from a CSV endpoint'''
if os . path . isfile ( registry_path_or_url ) : with open ( registry_path_or_url , 'r' ) as f : reader = compat . csv_dict_reader ( f . readlines ( ) ) else : res = requests . get ( registry_path_or_url ) res . raise_for_status ( ) reader = compat . csv_dict_reader ( StringIO ( res . text ) ) r...
def get_repo_url ( mead_tag , nexus_base_url , prefix = "hudson-" , suffix = "" ) : """Creates repository Nexus group URL composed of : < nexus _ base _ url > / content / groups / < prefix > < mead _ tag > < suffix > : param mead _ tag : name of the MEAD tag used to create the proxy URL in settings . xml : pa...
result = urlparse . urljoin ( nexus_base_url , "content/groups/" ) result = urlparse . urljoin ( result , "%s%s%s/" % ( prefix , mead_tag , suffix ) ) return result
def get_children ( self , ** kwargs ) : '''Recursively collects and returns all subtrees of given tree ( if no arguments are given ) , or , alternatively , collects and returns subtrees satisfying some specific criteria ( pre - specified in the arguments ) ; Parameters depth _ limit : int Specifies how de...
depth_limit = kwargs . get ( 'depth_limit' , 922337203685477580 ) # Just a nice big number to # assure that by default , # there is no depth limit . . . include_self = kwargs . get ( 'include_self' , False ) sorted_by_word_ids = kwargs . get ( 'sorted' , False ) subtrees = [ ] if include_self : if self . _satisfies...
def upsert ( self , doc , namespace , timestamp ) : """Adds a document to the doc dict ."""
# Allow exceptions to be triggered ( for testing purposes ) if doc . get ( "_upsert_exception" ) : raise Exception ( "upsert exception" ) doc_id = doc [ "_id" ] self . doc_dict [ doc_id ] = Entry ( doc = doc , ns = namespace , ts = timestamp )
def compile_pycos ( toc ) : """Given a TOC or equivalent list of tuples , generates all the required pyc / pyo files , writing in a local directory if required , and returns the list of tuples with the updated pathnames ."""
global BUILDPATH # For those modules that need to be rebuilt , use the build directory # PyInstaller creates during the build process . basepath = os . path . join ( BUILDPATH , "localpycos" ) new_toc = [ ] for ( nm , fnm , typ ) in toc : # Trim the terminal " c " or " o " source_fnm = fnm [ : - 1 ] # If the so...
def begin_run_group ( project ) : """Begin a run _ group in the database . A run _ group groups a set of runs for a given project . This models a series of runs that form a complete binary runtime test . Args : project : The project we begin a new run _ group for . Returns : ` ` ( group , session ) ` ` ...
from benchbuild . utils . db import create_run_group from datetime import datetime group , session = create_run_group ( project ) group . begin = datetime . now ( ) group . status = 'running' session . commit ( ) return group , session
def get_default ( self ) : """Get a string representation of a param ' s default value . Returns None if there is no default value for this param ."""
definfo = functionutils . DefinitionInfo . read ( self . _function ) for arg , default in definfo . args_with_defaults : if self . argname == arg : return default return None
def get_current_path ( index = 2 ) : # type : ( int ) - > str """Get the caller ' s path to sys . path If the caller is a CLI through stdin , the current working directory is used"""
try : path = _caller_path ( index ) except RuntimeError : path = os . getcwd ( ) return path
def start_logging ( gconfig , logpath ) : '''Turn on logging and set up the global config . This expects the : mod : ` yakonfig ` global configuration to be unset , and establishes it . It starts the log system via the : mod : ` dblogger ` setup . In addition to : mod : ` dblogger ` ' s defaults , if ` logpat...
yakonfig . set_default_config ( [ rejester , dblogger ] , config = gconfig ) if logpath : formatter = dblogger . FixedWidthFormatter ( ) # TODO : do we want byte - size RotatingFileHandler or TimedRotatingFileHandler ? handler = logging . handlers . RotatingFileHandler ( logpath , maxBytes = 10000000 , back...
def terminal_unreserve ( progress_obj , terminal_obj = None , verbose = 0 , identifier = None ) : """Unregisters the terminal ( stdout ) for printing . an instance ( progress _ obj ) can only unreserve the tty ( terminal _ obj ) when it also reserved it see terminal _ reserved for more information Returns N...
if terminal_obj is None : terminal_obj = sys . stdout if identifier is None : identifier = '' else : identifier = identifier + ': ' po = TERMINAL_RESERVATION . get ( terminal_obj ) if po is None : log . debug ( "terminal %s was not reserved, nothing happens" , terminal_obj ) else : if po is progress...
def send_http_request_with_json ( context , method ) : """Parameters : . . code - block : : json " param1 " : " value1 " , " param2 " : " value2 " , " param3 " : { " param31 " : " value31" """
safe_add_http_request_context_to_behave_context ( context ) context . http_request_context . body_params = json . loads ( context . text ) context . http_request_context . renderer = JSONRenderer ( ) send_http_request ( context , method )
def returnAllChips ( self , extname = None , exclude = None ) : """Returns a list containing all the chips which match the extname given minus those specified for exclusion ( if any ) ."""
extensions = self . _findExtnames ( extname = extname , exclude = exclude ) chiplist = [ ] for i in range ( 1 , self . _nextend + 1 , 1 ) : if 'extver' in self . _image [ i ] . header : extver = self . _image [ i ] . header [ 'extver' ] else : extver = 1 if hasattr ( self . _image [ i ] , '_...
def taxonomy_from_annotated_tree ( self , dendropy_tree ) : '''Given an annotated dendropy tree , return the taxonomy of each tip Parameters tree : dendropy . Tree Decorated tree to extract taxonomy from Returns dictionary of tip name to array of taxonomic affiliations'''
tip_to_taxonomy = { } for tip in dendropy_tree . leaf_node_iter ( ) : tax = [ ] n = tip . parent_node while n : node_taxonomy = self . taxonomy_from_node_name ( n . label ) if node_taxonomy and n . parent_node : tax = [ node_taxonomy ] + tax n = n . parent_node tip_na...
def save_fileAs ( self , file = None ) : """Saves the editor file content either using given file or user chosen file . : return : Method success . : rtype : bool : note : May require user interaction ."""
file = file or umbra . ui . common . store_last_browsed_path ( QFileDialog . getSaveFileName ( self , "Save As:" , self . __file ) ) if not file : return False return self . write_file ( foundations . strings . to_string ( file ) )
def wait_for_task ( task , instance_name , task_type , sleep_seconds = 1 , log_level = 'debug' ) : '''Waits for a task to be completed . task The task to wait for . instance _ name The name of the ESXi host , vCenter Server , or Virtual Machine that the task is being run on . task _ type The type of t...
time_counter = 0 start_time = time . time ( ) log . trace ( 'task = %s, task_type = %s' , task , task . __class__ . __name__ ) try : task_info = task . info except vim . fault . NoPermission as exc : log . exception ( exc ) raise salt . exceptions . VMwareApiError ( 'Not enough permissions. Required privile...
def get_session_value ( self , name , default = None ) : """Get value from session"""
session_name = 'list_{}_{}_{}' . format ( self . kwargs . get ( 'app' ) , self . kwargs . get ( 'model' ) , name ) return self . request . session . get ( session_name , default )
def normalize_path ( path_or_f ) : """Verifies that a file exists at a given path and that the file has a known extension type . : Parameters : path _ or _ f : ` str ` | ` file ` the path to a dump file or a file handle"""
if hasattr ( path_or_f , "read" ) : return path_or_f else : path = path_or_f path = os . path . expanduser ( path ) # Check if exists and is a file if os . path . isdir ( path ) : raise IsADirectoryError ( "Is a directory: {0}" . format ( path ) ) elif not os . path . isfile ( path ) : raise FileNotFoun...