signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def __run_blast_select_loop ( input_file , popens , fields ) : '''Run the select ( 2 ) loop to handle blast I / O to the given set of Popen objects . Yields records back that have been read from blast processes .'''
def make_nonblocking ( f ) : fl = fcntl . fcntl ( f . fileno ( ) , fcntl . F_GETFL ) fl |= os . O_NONBLOCK fcntl . fcntl ( f . fileno ( ) , fcntl . F_SETFL , fl ) rfds = set ( ) wfds = set ( ) fd_map = { } for p in popens : make_nonblocking ( p . stdout ) rfds . add ( p . stdout . fileno ( ) ) f...
def get ( self , ids , ** kwargs ) : """Method to get environments vip by their ids : param ids : List containing identifiers of environments vip : param include : Array containing fields to include on response . : param exclude : Array containing fields to exclude on response . : param fields : Array conta...
uri = build_uri_with_ids ( 'api/v3/environment-vip/%s/' , ids ) return super ( ApiEnvironmentVip , self ) . get ( self . prepare_url ( uri , kwargs ) )
def _stack_values_to_string ( self , stack_values ) : """Convert each stack value to a string : param stack _ values : A list of values : return : The converted string"""
strings = [ ] for stack_value in stack_values : if self . solver . symbolic ( stack_value ) : concretized_value = "SYMBOLIC - %s" % repr ( stack_value ) else : if len ( self . solver . eval_upto ( stack_value , 2 ) ) == 2 : concretized_value = repr ( stack_value ) else : ...
def has_abiext ( self , ext , single_file = True ) : """Returns the absolute path of the ABINIT file with extension ext . Support both Fortran files and netcdf files . In the later case , we check whether a file with extension ext + " . nc " is present in the directory . Returns empty string is file is not pr...
if ext != "abo" : ext = ext if ext . startswith ( '_' ) else '_' + ext files = [ ] for f in self . list_filepaths ( ) : # For the time being , we ignore DDB files in nc format . if ext == "_DDB" and f . endswith ( ".nc" ) : continue # Ignore BSE text files e . g . GW _ NLF _ MDF if ext == "_MDF"...
def to_file_object ( self , name , out_dir ) : """Dump to a pickle file and return an File object reference of this list Parameters name : str An identifier of this file . Needs to be unique . out _ dir : path path to place this file Returns file : AhopeFile"""
make_analysis_dir ( out_dir ) file_ref = File ( 'ALL' , name , self . get_times_covered_by_files ( ) , extension = '.pkl' , directory = out_dir ) self . dump ( file_ref . storage_path ) return file_ref
def convert_weights_and_inputs ( node , ** kwargs ) : """Helper function to convert weights and inputs ."""
name , _ , _ = get_inputs ( node , kwargs ) if kwargs [ "is_input" ] is False : weights = kwargs [ "weights" ] initializer = kwargs [ "initializer" ] np_arr = weights [ name ] data_type = onnx . mapping . NP_TYPE_TO_TENSOR_TYPE [ np_arr . dtype ] dims = np . shape ( np_arr ) tensor_node = onnx ....
def to_curve_spline ( obj ) : '''to _ curve _ spline ( obj ) obj if obj is a curve spline and otherwise attempts to coerce obj into a curve spline , raising an error if it cannot .'''
if is_curve_spline ( obj ) : return obj elif is_tuple ( obj ) and len ( obj ) == 2 : ( crds , opts ) = obj else : ( crds , opts ) = ( obj , { } ) if pimms . is_matrix ( crds ) or is_curve_spline ( crds ) : crds = [ crds ] spls = [ c for c in crds if is_curve_spline ( c ) ] opts = dict ( opts ) if 'weigh...
def maps_get_rules_output_rules_rulename ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) maps_get_rules = ET . Element ( "maps_get_rules" ) config = maps_get_rules output = ET . SubElement ( maps_get_rules , "output" ) rules = ET . SubElement ( output , "rules" ) rulename = ET . SubElement ( rules , "rulename" ) rulename . text = kwargs . pop ( 'rulename' ) callback = kwa...
def check_length_of_shape_or_intercept_names ( name_list , num_alts , constrained_param , list_title ) : """Ensures that the length of the parameter names matches the number of parameters that will be estimated . Will raise a ValueError otherwise . Parameters name _ list : list of strings . Each element sho...
if len ( name_list ) != ( num_alts - constrained_param ) : msg_1 = "{} is of the wrong length:" . format ( list_title ) msg_2 = "len({}) == {}" . format ( list_title , len ( name_list ) ) correct_length = num_alts - constrained_param msg_3 = "The correct length is: {}" . format ( correct_length ) to...
def remove_by ( keys , original ) : """Remove items in a list according to another list ."""
for i in [ original [ index ] for index , needed in enumerate ( keys ) if not needed ] : original . remove ( i )
def refund ( self , idempotency_key = None , ** params ) : """Return a deferred ."""
headers = populate_headers ( idempotency_key ) url = self . instance_url ( ) + '/refund' d = self . request ( 'post' , url , params , headers ) return d . addCallback ( self . refresh_from ) . addCallback ( lambda _ : self )
def sample ( problem , N , calc_second_order = True , seed = None ) : """Generates model inputs using Saltelli ' s extension of the Sobol sequence . Returns a NumPy matrix containing the model inputs using Saltelli ' s sampling scheme . Saltelli ' s scheme extends the Sobol sequence in a way to reduce the err...
if seed : np . random . seed ( seed ) D = problem [ 'num_vars' ] groups = problem . get ( 'groups' ) if not groups : Dg = problem [ 'num_vars' ] else : Dg = len ( set ( groups ) ) G , group_names = compute_groups_matrix ( groups ) # How many values of the Sobol sequence to skip skip_values = 1000 # Crea...
def parse_oxi_states ( self , data ) : """Parse oxidation states from data dictionary"""
try : oxi_states = { data [ "_atom_type_symbol" ] [ i ] : str2float ( data [ "_atom_type_oxidation_number" ] [ i ] ) for i in range ( len ( data [ "_atom_type_symbol" ] ) ) } # attempt to strip oxidation state from _ atom _ type _ symbol # in case the label does not contain an oxidation state for i , sy...
def rest_of_string ( self , offset = 0 ) : """A copy of the current position till the end of the source string ."""
if self . has_space ( offset = offset ) : return self . string [ self . pos + offset : ] else : return ''
def data_fetch ( self , url , task ) : '''A fake fetcher for dataurl'''
self . on_fetch ( 'data' , task ) result = { } result [ 'orig_url' ] = url result [ 'content' ] = dataurl . decode ( url ) result [ 'headers' ] = { } result [ 'status_code' ] = 200 result [ 'url' ] = url result [ 'cookies' ] = { } result [ 'time' ] = 0 result [ 'save' ] = task . get ( 'fetch' , { } ) . get ( 'save' ) i...
def output ( self , kind , line ) : "* line * should be bytes"
self . destination . write ( b'' . join ( [ self . _cyan , b't=%07d' % ( time . time ( ) - self . _t0 ) , self . _reset , self . _kind_prefixes [ kind ] , self . markers [ kind ] , line , self . _reset , ] ) ) self . destination . flush ( )
def fit ( self ) : """Do the fitting . Does least square fitting . If you want to use custom fitting , must override this ."""
# the objective function that will be minimized in the least square # fitting objective_func = lambda pars , x , y : y - self . _func ( x , pars ) self . _params = self . _initial_guess ( ) self . eos_params , ierr = leastsq ( objective_func , self . _params , args = ( self . volumes , self . energies ) ) # e0 , b0 , b...
def load ( filename = None , url = r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml" , loader_class = None ) : u"""load google ' s ` emoji4unicode ` project ' s xml file . must call this method first to use ` e4u ` library . this method never work twice if you want to reloa...
if not has_loaded ( ) : reload ( filename , url , loader_class )
def validate_input_source_config_source_candidate_candidate ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) validate = ET . Element ( "validate" ) config = validate input = ET . SubElement ( validate , "input" ) source = ET . SubElement ( input , "source" ) config_source = ET . SubElement ( source , "config-source" ) candidate = ET . SubElement ( config_source , "candidate" ) candidate = ET...
def cos_well ( f = Ellipsis , width = np . pi / 2 , offset = 0 , scale = 1 ) : '''cos _ well ( ) yields a potential function g ( x ) that calculates 0.5 * ( 1 - cos ( x ) ) for - pi / 2 < = x < = pi / 2 and is 1 outside of that range . The full formulat of the cosine well is , including optional arguments : s...
f = to_potential ( f ) freq = np . pi / width * 2 ( xmn , xmx ) = ( offset - width / 2 , offset + width / 2 ) F = piecewise ( scale , ( ( xmn , xmx ) , scale / 2 * ( 1 - cos ( freq * ( identity - offset ) ) ) ) ) if is_const_potential ( f ) : return const_potential ( F . value ( f . c ) ) elif is_identity_potential...
def get ( self , url , headers = None , kwargs = None ) : """Make a GET request . To make a GET request pass , ` ` url ` ` : param url : ` ` str ` ` : param headers : ` ` dict ` ` : param kwargs : ` ` dict ` `"""
return self . _request ( method = 'get' , url = url , headers = headers , kwargs = kwargs )
def extraSelections ( self , qpart , block , columnIndex ) : """List of QTextEdit . ExtraSelection ' s , which highlighte brackets"""
blockText = block . text ( ) if columnIndex < len ( blockText ) and blockText [ columnIndex ] in self . _ALL_BRACKETS and qpart . isCode ( block , columnIndex ) : return self . _highlightBracket ( blockText [ columnIndex ] , qpart , block , columnIndex ) elif columnIndex > 0 and blockText [ columnIndex - 1 ] in sel...
def call_graphviz_dot ( src , fmt ) : """Call dot command , and provide helpful error message if we cannot find it ."""
try : svg = dot ( src , T = fmt ) except OSError as e : # pragma : nocover if e . errno == 2 : cli . error ( """ cannot find 'dot' pydeps calls dot (from graphviz) to create svg diagrams, please make sure that the dot executable is available o...
def _set_xfp ( self , v , load = False ) : """Setter method for xfp , mapped from YANG variable / brocade _ interface _ ext _ rpc / get _ media _ detail / output / interface / xfp ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ xfp is considered as a priva...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = xfp . xfp , is_container = 'container' , presence = False , yang_name = "xfp" , rest_name = "xfp" , parent = self , choice = ( u'interface-identifier' , u'xfp' ) , path_helper = self . _path_helper , extmethods = self . _extm...
def _pystmark_call ( self , method , * args , ** kwargs ) : '''Wraps a call to the pystmark Simple API , adding configured settings'''
kwargs = self . _apply_config ( ** kwargs ) return method ( * args , ** kwargs )
def login ( self , username , password = None , email = None , registry = None , reauth = False , ** kwargs ) : """Login to a Docker registry server . : param username : User name for login . : type username : unicode | str : param password : Login password ; may be ` ` None ` ` if blank . : type password :...
response = super ( DockerClientWrapper , self ) . login ( username , password , email , registry , reauth = reauth , ** kwargs ) return response . get ( 'Status' ) == 'Login Succeeded' or response . get ( 'username' ) == username
def search ( self , initial_ids , initial_cache ) : """Beam search for sequences with highest scores ."""
state , state_shapes = self . _create_initial_state ( initial_ids , initial_cache ) finished_state = tf . while_loop ( self . _continue_search , self . _search_step , loop_vars = [ state ] , shape_invariants = [ state_shapes ] , parallel_iterations = 1 , back_prop = False ) finished_state = finished_state [ 0 ] alive_s...
def node ( self , nodeid ) : """Creates a new node with the specified name , with ` MockSocket ` instances as incoming and outgoing sockets . Returns the implementation object created for the node from the cls , args and address specified , and the sockets . ` cls ` must be a callable that takes the insock and ...
_assert_valid_nodeid ( nodeid ) # addr = ' tcp : / / ' + nodeid # insock = MockInSocket ( addEndpoints = lambda endpoints : self . bind ( addr , insock , endpoints ) ) # outsock = lambda : MockOutSocket ( addr , self ) return Node ( hub = Hub ( nodeid = nodeid ) )
def get_layer_names ( self ) : """: return : Names of all the layers kept by Keras"""
layer_names = [ x . name for x in self . model . layers ] return layer_names
def convert ( self , mode ) : """Convert the current image to the given * mode * . See : class : ` Image ` for a list of available modes ."""
if mode == self . mode : return if mode not in [ "L" , "LA" , "RGB" , "RGBA" , "YCbCr" , "YCbCrA" , "P" , "PA" ] : raise ValueError ( "Mode %s not recognized." % ( mode ) ) if self . is_empty ( ) : self . mode = mode return if mode == self . mode + "A" : self . channels . append ( np . ma . ones ( s...
def from_dict ( cls , d ) : """Returns a COHP object from a dict representation of the COHP ."""
if "ICOHP" in d : icohp = { Spin ( int ( key ) ) : np . array ( val ) for key , val in d [ "ICOHP" ] . items ( ) } else : icohp = None return Cohp ( d [ "efermi" ] , d [ "energies" ] , { Spin ( int ( key ) ) : np . array ( val ) for key , val in d [ "COHP" ] . items ( ) } , icohp = icohp , are_coops = d [ "are_...
def download_badge ( test_stats , # type : TestStats dest_folder = 'reports/junit' # type : str ) : """Downloads the badge corresponding to the provided success percentage , from https : / / img . shields . io . : param test _ stats : : param dest _ folder : : return :"""
if not path . exists ( dest_folder ) : makedirs ( dest_folder ) # , exist _ ok = True ) not python 2 compliant if test_stats . success_percentage < 50 : color = 'red' elif test_stats . success_percentage < 75 : color = 'orange' elif test_stats . success_percentage < 90 : color = 'green' else : color...
def enum_value ( self ) : """Return the value of an enum constant ."""
if not hasattr ( self , '_enum_value' ) : assert self . kind == CursorKind . ENUM_CONSTANT_DECL # Figure out the underlying type of the enum to know if it # is a signed or unsigned quantity . underlying_type = self . type if underlying_type . kind == TypeKind . ENUM : underlying_type = under...
def LoadFromXml ( self , node ) : """Method updates the object from the xml ."""
import os self . classId = node . localName metaClassId = UcsUtils . FindClassIdInMoMetaIgnoreCase ( self . classId ) if metaClassId : self . classId = metaClassId if node . hasAttribute ( NamingPropertyId . DN ) : self . dn = node . getAttribute ( NamingPropertyId . DN ) if self . dn : self . rn = os . pat...
def int2str ( self , num ) : """Converts an integer into a string . : param num : A numeric value to be converted to another base as a string . : rtype : string : raise TypeError : when * num * isn ' t an integer : raise ValueError : when * num * isn ' t positive"""
if int ( num ) != num : raise TypeError ( 'number must be an integer' ) if num < 0 : raise ValueError ( 'number must be positive' ) radix , alphabet = self . radix , self . alphabet if radix in ( 8 , 10 , 16 ) and alphabet [ : radix ] . lower ( ) == BASE85 [ : radix ] . lower ( ) : return ( { 8 : '%o' , 10 ...
def delete_object ( self , obj , post_delete = False ) : """Delete an object with Discipline Only argument is a Django object . Analogous to Editor . save _ object ."""
# Collect related objects that will be deleted by cascading links = [ rel . get_accessor_name ( ) for rel in obj . _meta . get_all_related_objects ( ) ] # Recursively delete each of them for link in links : objects = getattr ( obj , link ) . all ( ) for o in objects : self . delete_object ( o , post_del...
def format_cert_name ( env = '' , account = '' , region = '' , certificate = None ) : """Format the SSL certificate name into ARN for ELB . Args : env ( str ) : Account environment name account ( str ) : Account number for ARN region ( str ) : AWS Region . certificate ( str ) : Name of SSL certificate R...
cert_name = None if certificate : if certificate . startswith ( 'arn' ) : LOG . info ( "Full ARN provided...skipping lookup." ) cert_name = certificate else : generated_cert_name = generate_custom_cert_name ( env , region , account , certificate ) if generated_cert_name : ...
def total_num_violations ( self ) : """Returns the total number of lines in the diff that are in violation ."""
return sum ( len ( summary . lines ) for summary in self . _diff_violations ( ) . values ( ) )
def interpolateall ( table , fmt , ** kwargs ) : """Convenience function to interpolate all values in all fields using the ` fmt ` string . The ` ` where ` ` keyword argument can be given with a callable or expression which is evaluated on each row and which should return True if the conversion should be ap...
conv = lambda v : fmt % v return convertall ( table , conv , ** kwargs )
def cwd ( self ) : """Change to URL parent directory . Return filename of last path component ."""
path = self . urlparts [ 2 ] . encode ( self . filename_encoding , 'replace' ) dirname = path . strip ( '/' ) dirs = dirname . split ( '/' ) filename = dirs . pop ( ) self . url_connection . cwd ( '/' ) for d in dirs : self . url_connection . cwd ( d ) return filename
def is_subdomain_zonefile_hash ( fqn , zonefile_hash , db_path = None , zonefiles_dir = None ) : """Static method for getting all historic zone file hashes for a subdomain"""
opts = get_blockstack_opts ( ) if not is_subdomains_enabled ( opts ) : return [ ] if db_path is None : db_path = opts [ 'subdomaindb_path' ] if zonefiles_dir is None : zonefiles_dir = opts [ 'zonefiles' ] db = SubdomainDB ( db_path , zonefiles_dir ) zonefile_hashes = db . is_subdomain_zonefile_hash ( fqn , ...
def from_config ( cls , config , weights = None , weights_loader = None ) : """deserialize from a dict returned by get _ config ( ) . Parameters config : dict weights : list of array , optional Network weights to restore weights _ loader : callable , optional Function to call ( no arguments ) to load we...
config = dict ( config ) instance = cls ( ** config . pop ( 'hyperparameters' ) ) instance . __dict__ . update ( config ) instance . network_weights = weights instance . network_weights_loader = weights_loader instance . prediction_cache = weakref . WeakKeyDictionary ( ) return instance
def trigger_all_callbacks ( self , callbacks = None ) : """Trigger callbacks for all keys on all or a subset of subscribers . : param Iterable callbacks : list of callbacks or none for all subscribed : rtype : Iterable [ tornado . concurrent . Future ]"""
return [ ret for key in self for ret in self . trigger_callbacks ( key , callbacks = None ) ]
def log_benchmark ( fn , start , end ) : """Log a given function and how long the function takes in seconds : param str fn : Function name : param float start : Function start time : param float end : Function end time : return none :"""
elapsed = round ( end - start , 2 ) line = ( "Benchmark - Function: {} , Time: {} seconds" . format ( fn , elapsed ) ) return line
def _GetAttributes ( self ) : """Retrieves the attributes . Returns : list [ NTFSAttribute ] : attributes ."""
if self . _attributes is None : self . _attributes = [ ] for fsntfs_attribute in self . _fsntfs_file_entry . attributes : attribute_class = self . _ATTRIBUTE_TYPE_CLASS_MAPPINGS . get ( fsntfs_attribute . attribute_type , NTFSAttribute ) attribute_object = attribute_class ( fsntfs_attribute ) ...
def list_drafts ( self ) : """A filterable list views of layers , returning the draft version of each layer . If the most recent version of a layer or table has been published already , it won ’ t be returned here ."""
target_url = self . client . get_url ( 'LAYER' , 'GET' , 'multidraft' ) return base . Query ( self , target_url )
def deconv_rl ( data , h , Niter = 10 ) : """richardson lucy deconvolution of data with psf h using spatial convolutions ( h should be small then )"""
if isinstance ( data , np . ndarray ) : return _deconv_rl_np ( data , h , Niter ) elif isinstance ( data , OCLArray ) : return _deconv_rl_gpu_conv ( data , h , Niter ) else : raise TypeError ( "array argument (1) has bad type: %s" % type ( arr_obj ) )
def copy ( source_backend_names , bucket_names , static_bucket_name , s3_endpoint , s3_profile , s3_bucket_policy_file , rclone , output ) : """Copy files to S3. This command copies files to S3 and records the necessary database changes in a JSONL file . Multiple bucket names can be specified ; in that case t...
bucket_names = [ tuple ( x . split ( '/' , 1 ) ) if '/' in x else ( x , x . split ( ':' , 1 ) [ - 1 ] ) for x in bucket_names ] if ':' in bucket_names [ - 1 ] [ 0 ] : raise click . UsageError ( 'Last bucket name cannot contain criteria' ) if not all ( ':' in x [ 0 ] for x in bucket_names [ : - 1 ] ) : raise cli...
def handle_cmd ( self , command , application ) : """Handle running a given dot command from a user . : type command : str : param command : The full dot command string , e . g . ` ` . edit ` ` , of ` ` . profile prod ` ` . : type application : AWSShell : param application : The application object ."""
parts = command . split ( ) cmd_name = parts [ 0 ] [ 1 : ] if cmd_name not in self . HANDLER_CLASSES : self . _unknown_cmd ( parts , application ) else : # Note we expect the class to support no - arg # instantiation . return self . HANDLER_CLASSES [ cmd_name ] ( ) . run ( parts , application )
def solvemdbi_rsm ( ah , rho , b , axisK , dimN = 2 ) : r"""Solve a multiple diagonal block linear system with a scaled identity term by repeated application of the Sherman - Morrison equation . The computation is performed by explictly constructing the inverse operator , leading to an : math : ` O ( K ) ` ti...
axisM = dimN + 2 slcnc = ( slice ( None ) , ) * axisK M = ah . shape [ axisM ] K = ah . shape [ axisK ] a = np . conj ( ah ) Ainv = np . ones ( ah . shape [ 0 : dimN ] + ( 1 , ) * 4 ) * np . reshape ( np . eye ( M , M ) / rho , ( 1 , ) * ( dimN + 2 ) + ( M , M ) ) for k in range ( 0 , K ) : slck = slcnc + ( slice (...
def wallet_work_get ( self , wallet ) : """Returns a list of pairs of account and work from * * wallet * * . . enable _ control required . . version 8.0 required : param wallet : Wallet to return work for : type wallet : str : raises : : py : exc : ` nano . rpc . RPCException ` > > > rpc . wallet _ work...
wallet = self . _process_value ( wallet , 'wallet' ) payload = { "wallet" : wallet } resp = self . call ( 'wallet_work_get' , payload ) return resp . get ( 'works' ) or { }
def get_instance_type ( self , port ) : """Determine the port type based on device owner and vnic type"""
if port [ portbindings . VNIC_TYPE ] == portbindings . VNIC_BAREMETAL : return a_const . BAREMETAL_RESOURCE owner_to_type = { n_const . DEVICE_OWNER_DHCP : a_const . DHCP_RESOURCE , n_const . DEVICE_OWNER_DVR_INTERFACE : a_const . ROUTER_RESOURCE , trunk_consts . TRUNK_SUBPORT_OWNER : a_const . VM_RESOURCE } if por...
def angact_iso ( x , params ) : """Calculate angle and action variable in isochrone potential with parameters params = ( M , b )"""
GM = Grav * params [ 0 ] E = H_iso ( x , params ) r , p , t , vr , vphi , vt = cart2spol ( x ) st = np . sin ( t ) Lz = r * vphi * st L = np . sqrt ( r * r * vt * vt + Lz * Lz / st / st ) if ( E > 0. ) : # Unbound return ( np . nan , np . nan , np . nan , np . nan , np . nan , np . nan ) Jr = GM / np . sqrt ( - 2 *...
def _irc_upper ( self , in_string ) : """Convert us to our upper - case equivalent , given our std ."""
conv_string = self . _translate ( in_string ) if self . _upper_trans is not None : conv_string = in_string . translate ( self . _upper_trans ) return str . upper ( conv_string )
def _handle_exception ( self , row , exception ) : """Logs an exception occurred during transformation of a row . : param list | dict | ( ) row : The source row . : param Exception exception : The exception ."""
self . _log ( 'Error during processing of line {0:d}.' . format ( self . _source_reader . row_number ) ) self . _log ( row ) self . _log ( str ( exception ) ) self . _log ( traceback . format_exc ( ) )
def flexifunction_buffer_function_ack_send ( self , target_system , target_component , func_index , result , force_mavlink1 = False ) : '''Flexifunction type and parameters for component at function index from buffer target _ system : System ID ( uint8 _ t ) target _ component : Component ID ( uint8 _ t ) f...
return self . send ( self . flexifunction_buffer_function_ack_encode ( target_system , target_component , func_index , result ) , force_mavlink1 = force_mavlink1 )
def _classic_4d_to_nifti ( grouped_dicoms , output_file ) : """This function will convert siemens 4d series to a nifti Some inspiration on which fields can be used was taken from http : / / slicer . org / doc / html / DICOMDiffusionVolumePlugin _ 8py _ source . html"""
# Get the sorted mosaics all_dicoms = [ i for sl in grouped_dicoms for i in sl ] # combine into 1 list for validating common . validate_orientation ( all_dicoms ) # Create mosaic block logger . info ( 'Creating data block' ) full_block = _classic_get_full_block ( grouped_dicoms ) logger . info ( 'Creating affine' ) # C...
def directive_DCB ( self , label , params ) : """label DCB value [ , value . . . ] Allocate a byte space in read only memory for the value or list of values"""
# TODO make this read only # TODO check for byte size self . labels [ label ] = self . space_pointer if params in self . equates : params = self . equates [ params ] self . memory [ self . space_pointer ] = self . convert_to_integer ( params ) & 0xFF self . space_pointer += 1
def set_parent ( self , key_name , new_parent ) : """Sets the parent of the key ."""
self . unbake ( ) kf = self . dct [ key_name ] kf [ 'parent' ] = new_parent self . bake ( )
def inherit_type ( self , type_cls : Type [ TInherit ] ) -> Union [ TInherit , 'Publisher' ] : """enables the usage of method and attribute overloading for this publisher ."""
self . _inherited_type = type_cls return self
def format_t_into_dhms_format ( timestamp ) : """Convert an amount of second into day , hour , min and sec : param timestamp : seconds : type timestamp : int : return : ' Ad Bh Cm Ds ' : rtype : str > > > format _ t _ into _ dhms _ format ( 456189) '5d 6h 43m 9s ' > > > format _ t _ into _ dhms _ form...
mins , timestamp = divmod ( timestamp , 60 ) hour , mins = divmod ( mins , 60 ) day , hour = divmod ( hour , 24 ) return '%sd %sh %sm %ss' % ( day , hour , mins , timestamp )
def get_current_revision ( database_url : str , version_table : str = DEFAULT_ALEMBIC_VERSION_TABLE ) -> str : """Ask the database what its current revision is . Arguments : database _ url : SQLAlchemy URL for the database version _ table : table name for Alembic versions"""
engine = create_engine ( database_url ) conn = engine . connect ( ) opts = { 'version_table' : version_table } mig_context = MigrationContext . configure ( conn , opts = opts ) return mig_context . get_current_revision ( )
def getImage ( path , dockerfile , tag ) : '''Check if an image with a given tag exists . If not , build an image from using a given dockerfile in a given path , tagging it with a given tag . No extra side effects . Handles and reraises BuildError , TypeError , and APIError exceptions .'''
image = getImageByTag ( tag ) if not image : # Build an Image using the dockerfile in the path try : image = client . images . build ( path = path , dockerfile = dockerfile , tag = tag ) except BuildError as exc : eprint ( "Failed to build docker image" ) raise exc except TypeError a...
def start ( self ) : """The main method that starts the service . This is blocking ."""
self . _initial_setup ( ) self . on_service_start ( ) self . app = self . make_tornado_app ( ) enable_pretty_logging ( ) self . app . listen ( self . port , address = self . host ) self . _start_periodic_tasks ( ) # starts the event handlers self . _initialize_event_handlers ( ) self . _start_event_handlers ( ) try : ...
def fromJD ( jd , utcoffset ) : """Builds a Datetime object given a jd and utc offset ."""
if not isinstance ( utcoffset , Time ) : utcoffset = Time ( utcoffset ) localJD = jd + utcoffset . value / 24.0 date = Date ( round ( localJD ) ) time = Time ( ( localJD + 0.5 - date . jdn ) * 24 ) return Datetime ( date , time , utcoffset )
def _cast_types ( self , values , cast_type , column ) : """Cast values to specified type Parameters values : ndarray cast _ type : string or np . dtype dtype to cast values to column : string column name - used only for error reporting Returns converted : ndarray"""
if is_categorical_dtype ( cast_type ) : known_cats = ( isinstance ( cast_type , CategoricalDtype ) and cast_type . categories is not None ) if not is_object_dtype ( values ) and not known_cats : # XXX this is for consistency with # c - parser which parses all categories # as strings values = ast...
def _ExpandPath ( self , target , vals , paths ) : """Extract path information , interpolating current path values as needed ."""
if target not in self . _TARGETS : return expanded = [ ] for val in vals : # Null entries specify the current directory , so : a : : b : c : is equivalent # to . : a : . : b : c : . shellvar = self . _SHELLVAR_RE . match ( val ) if not val : expanded . append ( "." ) elif shellvar : # The value ...
def make_symlink ( src_path , lnk_path ) : """Safely create a symbolic link to an input field ."""
# Check for Lustre 60 - character symbolic link path bug if CHECK_LUSTRE_PATH_LEN : src_path = patch_lustre_path ( src_path ) lnk_path = patch_lustre_path ( lnk_path ) # os . symlink will happily make a symlink to a non - existent # file , but we don ' t want that behaviour # XXX : Do we want to be doing this ?...
def _get_tick_frac_labels ( self ) : """Get the major ticks , minor ticks , and major labels"""
minor_num = 4 # number of minor ticks per major division if ( self . axis . scale_type == 'linear' ) : domain = self . axis . domain if domain [ 1 ] < domain [ 0 ] : flip = True domain = domain [ : : - 1 ] else : flip = False offset = domain [ 0 ] scale = domain [ 1 ] - domai...
def recv_all ( self , timeout = 'default' ) : """Return all data recieved until connection closes . Aliases : read _ all , readall , recvall"""
self . _print_recv_header ( '======== Receiving until close{timeout_text} ========' , timeout ) return self . _recv_predicate ( lambda s : 0 , timeout , raise_eof = False )
def delay_off ( self ) : """The ` timer ` trigger will periodically change the LED brightness between 0 and the current brightness setting . The ` off ` time can be specified via ` delay _ off ` attribute in milliseconds ."""
# Workaround for ev3dev / ev3dev # 225. # ' delay _ on ' and ' delay _ off ' attributes are created when trigger is set # to ' timer ' , and destroyed when it is set to anything else . # This means the file cache may become outdated , and we may have to # reopen the file . for retry in ( True , False ) : try : ...
def ipi_name_number ( name = None ) : """IPI Name Number field . An IPI Name Number is composed of eleven digits . So , for example , an IPI Name Number code field can contain 00014107338. : param name : name for the field : return : a parser for the IPI Name Number field"""
if name is None : name = 'IPI Name Number Field' field = basic . numeric ( 11 ) field . setName ( name ) return field . setResultsName ( 'ipi_name_n' )
def submit_jobs ( job_specs ) : """Submit a job Args : job _ spec ( dict ) : The job specifiation ( see Grid ' 5000 API reference )"""
gk = get_api_client ( ) jobs = [ ] try : for site , job_spec in job_specs : logger . info ( "Submitting %s on %s" % ( job_spec , site ) ) jobs . append ( gk . sites [ site ] . jobs . create ( job_spec ) ) except Exception as e : logger . error ( "An error occured during the job submissions" ) ...
def get_if_raw_hwaddr ( ifname ) : """Returns the packed MAC address configured on ' ifname ' ."""
NULL_MAC_ADDRESS = b'\x00' * 6 # Handle the loopback interface separately if ifname == LOOPBACK_NAME : return ( ARPHDR_LOOPBACK , NULL_MAC_ADDRESS ) # Get ifconfig output try : fd = os . popen ( "%s %s" % ( conf . prog . ifconfig , ifname ) ) except OSError as msg : raise Scapy_Exception ( "Failed to execut...
def _verify ( leniency , numobj , candidate , matcher ) : """Returns True if number is a verified number according to the leniency ."""
if leniency == Leniency . POSSIBLE : return is_possible_number ( numobj ) elif leniency == Leniency . VALID : if ( not is_valid_number ( numobj ) or not _contains_only_valid_x_chars ( numobj , candidate ) ) : return False return _is_national_prefix_present_if_required ( numobj ) elif leniency == Len...
def crop ( im , r , c , sz ) : '''crop image into a square of size sz ,'''
return im [ r : r + sz , c : c + sz ]
def mnist_blackbox ( train_start = 0 , train_end = 60000 , test_start = 0 , test_end = 10000 , nb_classes = NB_CLASSES , batch_size = BATCH_SIZE , learning_rate = LEARNING_RATE , nb_epochs = NB_EPOCHS , holdout = HOLDOUT , data_aug = DATA_AUG , nb_epochs_s = NB_EPOCHS_S , lmbda = LMBDA , aug_batch_size = AUG_BATCH_SIZE...
# Set logging level to see debug information set_log_level ( logging . DEBUG ) # Dictionary used to keep track and return key accuracies accuracies = { } # Perform tutorial setup assert setup_tutorial ( ) # Create TF session sess = tf . Session ( ) # Get MNIST data mnist = MNIST ( train_start = train_start , train_end ...
def _cleanup_markers ( context_id , task_ids ) : """Delete the FuriousAsyncMarker entities corresponding to ids ."""
logging . debug ( "Cleanup %d markers for Context %s" , len ( task_ids ) , context_id ) # TODO : Handle exceptions and retries here . delete_entities = [ ndb . Key ( FuriousAsyncMarker , id ) for id in task_ids ] delete_entities . append ( ndb . Key ( FuriousCompletionMarker , context_id ) ) ndb . delete_multi ( delete...
def is_valid_index ( self , code ) : """returns : True | Flase , based on whether code is valid"""
index_list = self . get_index_list ( ) return True if code . upper ( ) in index_list else False
def delete_option_group ( name , region = None , key = None , keyid = None , profile = None ) : '''Delete an RDS option group . CLI example : : salt myminion boto _ rds . delete _ option _ group my - opt - group region = us - east - 1'''
try : conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) if not conn : return { 'deleted' : bool ( conn ) } res = conn . delete_option_group ( OptionGroupName = name ) if not res : return { 'deleted' : bool ( res ) , 'message' : 'Failed to delete RDS opt...
def _after_flush_handler ( session , _flush_context ) : """Archive all new / updated / deleted data"""
dialect = get_dialect ( session ) handlers = [ ( _versioned_delete , session . deleted ) , ( _versioned_insert , session . new ) , ( _versioned_update , session . dirty ) , ] for handler , rows in handlers : # TODO : Bulk archive insert statements for row in rows : if not isinstance ( row , SavageModelMixin...
def set_position ( self , decl_pos ) : """Set editor position from ENSIME declPos data ."""
if decl_pos [ "typehint" ] == "LineSourcePosition" : self . editor . set_cursor ( decl_pos [ 'line' ] , 0 ) else : # OffsetSourcePosition point = decl_pos [ "offset" ] row , col = self . editor . point2pos ( point + 1 ) self . editor . set_cursor ( row , col )
def output ( self ) : """Output the results to either STDOUT or : return :"""
if not self . path_output : self . output_to_fd ( sys . stdout ) else : with open ( self . path_output , "w" ) as out : self . output_to_fd ( out )
def _list_nodes ( full = False ) : '''Helper function for the list _ * query functions - Constructs the appropriate dictionaries to return from the API query . full If performing a full query , such as in list _ nodes _ full , change this parameter to ` ` True ` ` .'''
server , user , password = _get_xml_rpc ( ) auth = ':' . join ( [ user , password ] ) vm_pool = server . one . vmpool . info ( auth , - 2 , - 1 , - 1 , - 1 ) [ 1 ] vms = { } for vm in _get_xml ( vm_pool ) : name = vm . find ( 'NAME' ) . text vms [ name ] = { } cpu_size = vm . find ( 'TEMPLATE' ) . find ( 'C...
def query ( self , coords , order = 1 ) : """Returns E ( B - V ) at the specified location ( s ) on the sky . See Table 6 of Schlafly & Finkbeiner ( 2011 ) for instructions on how to convert this quantity to extinction in various passbands . Args : coords ( ` astropy . coordinates . SkyCoord ` ) : The coord...
return super ( SFDQuery , self ) . query ( coords , order = order )
def gradfunc ( self , p ) : """The gradient - computing function that gets passed to the optimizers , if needed ."""
self . _set_stochastics ( p ) for i in xrange ( self . len ) : self . grad [ i ] = self . diff ( i ) return - 1 * self . grad
def _get_norms_of_rows ( data_frame , method ) : """return a column vector containing the norm of each row"""
if method == 'vector' : norm_vector = np . linalg . norm ( data_frame . values , axis = 1 ) elif method == 'last' : norm_vector = data_frame . iloc [ : , - 1 ] . values elif method == 'mean' : norm_vector = np . mean ( data_frame . values , axis = 1 ) elif method == 'first' : norm_vector = data_frame . ...
def init_hidden ( self , batch_size ) : """Initiate the initial state . : param batch _ size : batch size . : type batch _ size : int : return : Initial state of LSTM : rtype : pair of torch . Tensors of shape ( num _ layers * num _ directions , batch _ size , hidden _ size )"""
b = 2 if self . bidirectional else 1 if self . use_cuda : return ( torch . zeros ( self . num_layers * b , batch_size , self . lstm_hidden ) . cuda ( ) , torch . zeros ( self . num_layers * b , batch_size , self . lstm_hidden ) . cuda ( ) , ) else : return ( torch . zeros ( self . num_layers * b , batch_size , ...
def patched_fax_v1_init ( self , domain ) : """Initialize the V1 version of Fax : returns : V1 version of Fax : rtype : twilio . rest . fax . v1 . V1 . V1"""
print ( domain . __class__ . __name__ ) super ( TwilioV1 , self ) . __init__ ( domain ) self . version = "2010-04-01/Accounts/" + domain . account_sid self . _faxes = None
def _representative_structure_setter ( self , structprop , keep_chain , clean = True , keep_chemicals = None , out_suffix = '_clean' , outdir = None , force_rerun = False ) : """Set the representative structure by 1 ) cleaning it and 2 ) copying over attributes of the original structure . The structure is copied ...
# Set output directory for cleaned PDB file if not outdir : outdir = self . structure_dir if not outdir : raise ValueError ( 'Output directory must be specified' ) # Create new ID for this representative structure , it cannot be the same as the original one new_id = 'REP-{}' . format ( structprop . id )...
def save_xml ( self , doc , element ) : '''Save this component group into an xml . dom . Element object .'''
element . setAttributeNS ( RTS_NS , RTS_NS_S + 'groupID' , self . group_id ) for m in self . members : new_element = doc . createElementNS ( RTS_NS , RTS_NS_S + 'Members' ) m . save_xml ( doc , new_element ) element . appendChild ( new_element )
def describe_hosted_zones ( zone_id = None , domain_name = None , region = None , key = None , keyid = None , profile = None ) : '''Return detailed info about one , or all , zones in the bound account . If neither zone _ id nor domain _ name is provided , return all zones . Note that the return format is slight...
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) if zone_id and domain_name : raise SaltInvocationError ( 'At most one of zone_id or domain_name may ' 'be provided' ) retries = 10 while retries : try : if zone_id : zone_id = zone_id . replace ( '/hostedzon...
def transform ( self , data ) : """: param data : DataFrame with column to encode : return : encoded Series"""
with timer ( 'transform %s' % self . name , logging . DEBUG ) : transformed = super ( NestedUnique , self ) . transform ( self . unnest ( data ) ) return transformed . reshape ( ( len ( data ) , self . sequence_length ) )
def shape_weights_hidden ( self ) -> Tuple [ int , int , int ] : """Shape of the array containing the activation of the hidden neurons . The first integer value is the number of connection between the hidden layers , the second integer value is maximum number of neurons of all hidden layers feeding informatio...
if self . nmb_layers > 1 : nmb_neurons = self . nmb_neurons return ( self . nmb_layers - 1 , max ( nmb_neurons [ : - 1 ] ) , max ( nmb_neurons [ 1 : ] ) ) return 0 , 0 , 0
def ranges ( self ) : """Returns a list of addresses with source data ."""
ranges = self . _target . getRanges ( ) return map ( SheetAddress . _from_uno , ranges )
def find_spelling ( n ) : """Finds d , r s . t . n - 1 = 2 ^ r * d"""
r = 0 d = n - 1 # divmod used for large numbers quotient , remainder = divmod ( d , 2 ) # while we can still divide 2 ' s into n - 1 . . . while remainder != 1 : r += 1 d = quotient # previous quotient before we overwrite it quotient , remainder = divmod ( d , 2 ) return r , d
def get_current_version_by_config_file ( ) -> str : """Get current version from the version variable defined in the configuration : return : A string with the current version number : raises ImproperConfigurationError : if version variable cannot be parsed"""
debug ( 'get_current_version_by_config_file' ) filename , variable = config . get ( 'semantic_release' , 'version_variable' ) . split ( ':' ) variable = variable . strip ( ) debug ( filename , variable ) with open ( filename , 'r' ) as fd : parts = re . search ( r'^{0}\s*=\s*[\'"]([^\'"]*)[\'"]' . format ( variable...
def validate ( self , signature , timestamp , nonce ) : """Validate request signature . : param signature : A string signature parameter sent by weixin . : param timestamp : A int timestamp parameter sent by weixin . : param nonce : A int nonce parameter sent by weixin ."""
if not self . token : raise RuntimeError ( 'WEIXIN_TOKEN is missing' ) if self . expires_in : try : timestamp = int ( timestamp ) except ( ValueError , TypeError ) : # fake timestamp return False delta = time . time ( ) - timestamp if delta < 0 : # this is a fake timestamp re...
def generate_id ( ) : """Generate a 64bit base 16 ID for use as a Span or Trace ID"""
global _current_pid pid = os . getpid ( ) if _current_pid != pid : _current_pid = pid _rnd . seed ( int ( 1000000 * time . time ( ) ) ^ pid ) id = format ( _rnd . randint ( 0 , 18446744073709551615 ) , '02x' ) if len ( id ) < 16 : id = id . zfill ( 16 ) return id
def apply_heuristic ( self , node_a , node_b , heuristic = None ) : """helper function to apply heuristic"""
if not heuristic : heuristic = self . heuristic return heuristic ( abs ( node_a . x - node_b . x ) , abs ( node_a . y - node_b . y ) )