signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def add_module ( self , module ) : '''Adds configuration parameters from a Python module .'''
for key , value in module . __dict__ . iteritems ( ) : if key [ 0 : 2 ] != '__' : self . __setattr__ ( attr = key , value = value )
def containerIsRunning ( container_name ) : """Checks whether the container is running or not . : param container _ name : Name of the container being checked . : returns : True if status is ' running ' , False if status is anything else , and None if the container does not exist ."""
client = docker . from_env ( version = 'auto' ) try : this_container = client . containers . get ( container_name ) if this_container . status == 'running' : return True else : # this _ container . status = = ' exited ' , ' restarting ' , or ' paused ' return False except NotFound : retu...
def recv ( self , blocking = True ) : """Receive the next object from the socket"""
length = struct . unpack ( "<I" , self . sock . recv ( 4 ) ) [ 0 ] return self . _get_next_obj ( length )
def make_summary_funcs ( rows , ids ) : """Functions available for listing summary fields ."""
return { 'len' : len , 'list' : lambda * x : filter ( None , list ( x ) ) , 'max' : max , 'min' : min , 'rows' : partial ( summary_rows , rows , ids ) , 'sum' : sum , 'trace' : print_trace }
def read_file ( self , fasta_path ) : """Read the contents of a FASTA file into a dictionary"""
fasta_dictionary = { } for ( identifier , sequence ) in self . iterate_over_file ( fasta_path ) : fasta_dictionary [ identifier ] = sequence return fasta_dictionary
def positive_float ( string ) : """Convert string to positive float ."""
error_msg = 'Positive float required, {string} given.' . format ( string = string ) try : value = float ( string ) except ValueError : raise ArgumentTypeError ( error_msg ) if value < 0 : raise ArgumentTypeError ( error_msg ) return value
def _text_filter_input ( self , input_gen ) : """Filters out the text input line by line to avoid parsing and processing metrics we know we don ' t want to process . This only works on ` text / plain ` payloads , and is an INTERNAL FEATURE implemented for the kubelet check : param input _ get : line generator...
for line in input_gen : for item in self . _text_filter_blacklist : if item in line : break else : # No blacklist matches , passing the line through yield line
def create_tar ( self ) : """Create a tar file with all the files ."""
def add_file_to_tar ( tar , orig_fn , new_fn , func = None ) : tf = tarfile . TarInfo ( name = new_fn ) with open ( orig_fn ) as f : tfs = f . read ( ) if func is not None : tfs = func ( tfs ) tf . size = len ( tfs ) tfs = io . BytesIO ( tfs . encode ( 'utf8' ) ) tar . addfile ( ...
def get_results ( self , params = None , result_id = None ) : """Return all the results available from the database that fulfill some parameter combinations . If params is None ( or not specified ) , return all results . If params is specified , it must be a dictionary specifying the result values we are in...
# In this case , return all results # A cast to dict is necessary , since self . db . table ( ) contains TinyDB ' s # Document object ( which is simply a wrapper for a dictionary , thus the # simple cast ) . if result_id is not None : return [ dict ( i ) for i in self . db . table ( 'results' ) . all ( ) if i [ 'me...
def time_window ( self , window_width_ms ) : """Applies a system time window to the stream . Attributes : window _ width _ ms ( int ) : The length of the window in ms ."""
op = Operator ( _generate_uuid ( ) , OpType . TimeWindow , "TimeWindow" , num_instances = self . env . config . parallelism , other = window_width_ms ) return self . __register ( op )
def send_close ( self , status = STATUS_NORMAL , reason = six . b ( "" ) ) : """send close data to the server . status : status code to send . see STATUS _ XXX . reason : the reason to close . This must be string or bytes ."""
if status < 0 or status >= ABNF . LENGTH_16 : raise ValueError ( "code is invalid range" ) self . connected = False self . send ( struct . pack ( '!H' , status ) + reason , ABNF . OPCODE_CLOSE )
def day ( self , value = None ) : """Corresponds to IDD Field ` day ` Args : value ( int ) : value for IDD Field ` day ` value > = 1 value < = 31 if ` value ` is None it will not be checked against the specification and is assumed to be a missing value Raises : ValueError : if ` value ` is not a val...
if value is not None : try : value = int ( value ) except ValueError : raise ValueError ( 'value {} need to be of type int ' 'for field `day`' . format ( value ) ) if value < 1 : raise ValueError ( 'value need to be greater or equal 1 ' 'for field `day`' ) if value > 31 : ...
def add_state ( self , state , storage_load = False ) : """Overwrite the parent class add _ state method Add automatic transition generation for the decider _ state . : param state : The state to be added : return :"""
state_id = super ( BarrierConcurrencyState , self ) . add_state ( state ) if not storage_load and not self . __init_running and not state . state_id == UNIQUE_DECIDER_STATE_ID : # the transitions must only be created for the initial add _ state call and not during each load procedure for o_id , o in list ( state . ...
def genre ( self ) : """Cette routine convertit les indications morphologiques , données dans le fichier lemmes . la , pour exprimer le genre du mot dans la langue courante . : return : Genre : rtype : str"""
_genre = "" if " m." in self . _indMorph : _genre += "m" if " f." in self . _indMorph : _genre += "f" if " n." in self . _indMorph : _genre += "n" _genre = _genre . strip ( ) if self . _renvoi and not _genre : lr = self . _lemmatiseur . lemme ( self . _renvoi ) if lr : return lr . genre ( ) ...
def _map_response ( response , decode = False ) : """Maps a urllib3 response to a httplib / httplib2 Response ."""
# This causes weird deepcopy errors , so it ' s commented out for now . # item . _ urllib3 _ response = response item = httplib2 . Response ( response . getheaders ( ) ) item . status = response . status item [ 'status' ] = str ( item . status ) item . reason = response . reason item . version = response . version # ht...
def dictionary ( value ) : """: param value : input string corresponding to a literal Python object : returns : the Python object > > > dictionary ( ' ' ) > > > dictionary ( ' { } ' ) > > > dictionary ( ' { " a " : 1 } ' ) { ' a ' : 1} > > > dictionary ( ' " vs30 _ clustering : true " ' ) # an error...
if not value : return { } value = value . replace ( 'logscale(' , '("logscale", ' ) # dirty but quick try : dic = dict ( ast . literal_eval ( value ) ) except Exception : raise ValueError ( '%r is not a valid Python dictionary' % value ) for key , val in dic . items ( ) : try : has_logscale = ( ...
def build_nodes ( width , height , matrix = None , inverse = False ) : """create nodes according to grid size . If a matrix is given it will be used to determine what nodes are walkable . : rtype : list"""
nodes = [ ] use_matrix = ( isinstance ( matrix , ( tuple , list ) ) ) or ( USE_NUMPY and isinstance ( matrix , np . ndarray ) and matrix . size > 0 ) for y in range ( height ) : nodes . append ( [ ] ) for x in range ( width ) : # 1 , ' 1 ' , True will be walkable # while others will be obstacles # if in...
def _get_config ( filename ) : """Parse the provided YAML file and return a dict . : parse filename : A string containing the path to YAML file . : return : dict"""
i = interpolation . Interpolator ( interpolation . TemplateWithDefaults , os . environ ) with open ( filename , 'r' ) as stream : try : interpolated_config = i . interpolate ( stream . read ( ) ) return yaml . safe_load ( interpolated_config ) except yaml . parser . ParserError as e : ms...
def save ( self , commit = True ) : """Saves this ` ` form ` ` ' s cleaned _ data into model instance ` ` self . instance ` ` and related EAV attributes . Returns ` ` instance ` ` ."""
if self . errors : raise ValueError ( "The %s could not be saved because the data didn't" " validate." % self . instance . _meta . object_name ) # create entity instance , don ' t save yet instance = super ( BaseDynamicEntityForm , self ) . save ( commit = False ) # assign attributes for name in instance . get_sche...
def run_suite ( case , config , summary ) : """Run the full suite of numerics tests"""
m = importlib . import_module ( config [ 'module' ] ) m . set_up ( ) config [ "name" ] = case analysis_data = { } bundle = livvkit . numerics_model_module model_dir = os . path . join ( livvkit . model_dir , config [ 'data_dir' ] , case ) bench_dir = os . path . join ( livvkit . bench_dir , config [ 'data_dir' ] , case...
def crack1 ( self , rnum , snum , message , signsecret ) : """find privkey , given signsecret k , message m , signature ( r , s ) x = ( s * k - m ) / r"""
m = self . GFn . value ( message ) r = self . GFn . value ( rnum ) s = self . GFn . value ( snum ) k = self . GFn . value ( signsecret ) return ( s * k - m ) / r
def from_regular_array ( self , A ) : """Converts from an array of type ` int ` where the last index is assumed to have length ` self . n _ elements ` to an array of type ` self . d _ type ` with one fewer index . : param np . ndarray A : An ` np . array ` of type ` int ` . : rtype : ` np . ndarray `"""
dims = A . shape [ : - 1 ] return A . reshape ( ( np . prod ( dims ) , - 1 ) ) . view ( dtype = self . dtype ) . squeeze ( - 1 ) . reshape ( dims )
def get_variant_by_name ( self , name ) : """Get the genotype of a marker using it ' s name . Args : name ( str ) : The name of the marker . Returns : list : A list of Genotypes ."""
results = [ ] try : for info , dosage in self . _bgen . get_variant ( name ) : results . append ( Genotypes ( Variant ( info . name , CHROM_STR_ENCODE . get ( info . chrom , info . chrom ) , info . pos , [ info . a1 , info . a2 ] , ) , dosage , reference = info . a1 , coded = info . a2 , multiallelic = Fals...
def get_model ( self , ids ) : """Gets the model for the specified motors ."""
to_get_ids = [ i for i in ids if i not in self . _known_models ] models = [ dxl_to_model ( m ) for m in self . _get_model ( to_get_ids , convert = False ) ] self . _known_models . update ( zip ( to_get_ids , models ) ) return tuple ( self . _known_models [ id ] for id in ids )
def _bind_exit_key ( self , key ) : u"""setup the mapping from key to call the function ."""
keyinfo = make_KeyPress_from_keydescr ( key . lower ( ) ) . tuple ( ) self . exit_dispatch [ keyinfo ] = None
def setup_common_actions ( self ) : """Setup context menu common actions"""
actions = FilteredDirView . setup_common_actions ( self ) # Toggle horizontal scrollbar hscrollbar_action = create_action ( self , _ ( "Show horizontal scrollbar" ) , toggled = self . toggle_hscrollbar ) hscrollbar_action . setChecked ( self . show_hscrollbar ) self . toggle_hscrollbar ( self . show_hscrollbar ) return...
def modes ( self ) : """Returns a list of the available modes of the port ."""
( self . _modes , value ) = self . get_cached_attr_set ( self . _modes , 'modes' ) return value
def manage_job ( self , job_record ) : """method main duty - is to _ avoid _ publishing another unit _ of _ work , if previous was not yet processed In case the State Machine sees that the unit _ of _ work already exist it could either : - update boundaries of the processing ; republish - wait another tick ; ...
assert isinstance ( job_record , Job ) try : if self . _is_noop_timeperiod ( job_record . process_name , job_record . timeperiod ) : self . _process_noop_timeperiod ( job_record ) return if job_record . is_embryo : self . _process_state_embryo ( job_record ) elif job_record . is_in_p...
def sky_bbox_ll ( self ) : """The sky coordinates of the lower - left vertex of the minimal bounding box of the source segment , returned as a ` ~ astropy . coordinates . SkyCoord ` object . The bounding box encloses all of the source segment pixels in their entirety , thus the vertices are at the pixel * c...
if self . _wcs is not None : return pixel_to_skycoord ( self . xmin . value - 0.5 , self . ymin . value - 0.5 , self . _wcs , origin = 0 ) else : return None
def wrap_create_channel ( create_channel_func , tracer = None ) : """Wrap the google . api _ core . grpc _ helpers . create _ channel ."""
def call ( * args , ** kwargs ) : channel = create_channel_func ( * args , ** kwargs ) try : target = kwargs . get ( 'target' ) tracer_interceptor = OpenCensusClientInterceptor ( tracer , target ) intercepted_channel = grpc . intercept_channel ( channel , tracer_interceptor ) ret...
def _days ( cls , start , end ) : """Scrape a MLBAM Data : param start : Start Day ( YYYYMMDD ) : param end : End Day ( YYYYMMDD )"""
days = [ ] # datetime start_day , end_day = dt . strptime ( start , cls . DATE_FORMAT ) , dt . strptime ( end , cls . DATE_FORMAT ) delta = end_day - start_day for day in range ( delta . days + 1 ) : days . append ( start_day + timedelta ( days = day ) ) return days
def write_outxy ( self , filename ) : """Write out the output ( transformed ) XY catalog for this image to a file ."""
f = open ( filename , 'w' ) f . write ( "#Pixel positions for: " + self . name + '\n' ) f . write ( "#X Y\n" ) f . write ( "#(pix) (pix)\n" ) for i in range ( self . all_radec [ 0 ] . shape [ 0 ] ) : f . write ( '%f %f\n' % ( self . outxy [ i , 0 ] , self . outxy [ i , 1 ] ) ) f . close ( )
def does_match_exist ( self , inst ) : """Returns True if inst does match one of specified criteria . : param inst : declaration instance : type inst : : class : ` declaration _ t ` : rtype : bool"""
answer = True if self . _decl_type is not None : answer &= isinstance ( inst , self . _decl_type ) if self . name is not None : answer &= inst . name == self . name if self . parent is not None : answer &= self . parent is inst . parent if self . fullname is not None : if inst . name : answer &=...
def _create_filter ( self , condition ) : """Create a filter object from a textual condition ."""
# " Normal " comparison operators ? comparison = re . match ( r"^(%s)(<[>=]?|>=?|!=|~)(.*)$" % self . ident_re , condition ) if comparison : name , comparison , values = comparison . groups ( ) if values and values [ 0 ] in "+-" : raise FilterError ( "Comparison operator cannot be followed by '%s' in '%...
def parse ( self , key , value ) : """Parse the environment value for a given key against the schema . Args : key : The name of the environment variable . value : The value to be parsed ."""
if value is not None : try : return self . _parser ( value ) except Exception : raise ParsingError ( "Error parsing {}" . format ( key ) ) elif self . _default is not SENTINAL : return self . _default else : raise KeyError ( key )
def transQuad ( length = 0.0 , k1 = 0.0 , gamma = None ) : """Transport matrix of quadrupole : param length : quad width in [ m ] : param k1 : quad k1 strength in [ T / m ] : param gamma : electron energy , gamma value : return : 6x6 numpy array"""
m = np . eye ( 6 , 6 , dtype = np . float64 ) if length == 0.0 : print ( "warning: 'length' should be a positive float number." ) elif gamma is not None and gamma != 0.0 : if k1 == 0 : print ( "warning: 'k1' should be a positive float number." ) m [ 0 , 1 ] = m [ 2 , 3 ] = 1.0 m [ 4 , 5 ...
def get_fill_value ( dataset ) : """Get the fill value of the * dataset * , defaulting to np . nan ."""
if np . issubdtype ( dataset . dtype , np . integer ) : return dataset . attrs . get ( '_FillValue' , np . nan ) return np . nan
def from_custom_template ( cls , searchpath , name ) : """Factory function for creating a subclass of ` ` Styler ` ` with a custom template and Jinja environment . Parameters searchpath : str or list Path or paths of directories containing the templates name : str Name of your custom template to use for...
loader = ChoiceLoader ( [ FileSystemLoader ( searchpath ) , cls . loader , ] ) class MyStyler ( cls ) : env = Environment ( loader = loader ) template = env . get_template ( name ) return MyStyler
def get_all_cloud_integration ( self , ** kwargs ) : # noqa : E501 """Get all cloud integrations for a customer # noqa : E501 # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . get _ all _ cloud _...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . get_all_cloud_integration_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . get_all_cloud_integration_with_http_info ( ** kwargs ) # noqa : E501 return data
def __extractSkosConcepts ( self ) : """2015-08-19 : first draft"""
self . skosConcepts = [ ] # @ todo : keep adding ? qres = self . queryHelper . getSKOSInstances ( ) for candidate in qres : test_existing_cl = self . getSkosConcept ( uri = candidate [ 0 ] ) if not test_existing_cl : # create it self . skosConcepts += [ OntoSKOSConcept ( candidate [ 0 ] , None , self . ...
def update_learning_rate ( lr , trainer , epoch , ratio , steps ) : """Set the learning rate to the initial value decayed by ratio every N epochs ."""
new_lr = lr * ( ratio ** int ( np . sum ( np . array ( steps ) < epoch ) ) ) trainer . set_learning_rate ( new_lr ) return trainer
def body ( self ) -> Union [ bytes , str , List [ Any ] , Dict [ Any , Any ] , RawIOBase , None ] : """获取body"""
return self . _body
def check_duplicate_axis ( self , ds ) : '''Checks that no variable contains two coordinates defining the same axis . Chapter 5 paragraph 6 If an axis attribute is attached to an auxiliary coordinate variable , it can be used by applications in the same way the ` axis ` attribute attached to a coordinate ...
ret_val = [ ] geophysical_variables = self . _find_geophysical_vars ( ds ) for name in geophysical_variables : no_duplicates = TestCtx ( BaseCheck . HIGH , self . section_titles [ '5' ] ) axis_map = cfutil . get_axis_map ( ds , name ) axes = [ ] # For every coordinate associated with this variable , kee...
def set_cmap ( cmap ) : '''Set the color map of the current ' color ' scale .'''
scale = _context [ 'scales' ] [ 'color' ] for k , v in _process_cmap ( cmap ) . items ( ) : setattr ( scale , k , v ) return scale
def member_add ( self , cluster_id , params ) : """add new member into configuration"""
cluster = self . _storage [ cluster_id ] result = cluster . member_add ( params . get ( 'id' , None ) , params . get ( 'shardParams' , { } ) ) self . _storage [ cluster_id ] = cluster return result
def ecef_to_geocentric ( x , y , z , ref_height = None ) : """Convert ECEF into geocentric coordinates Parameters x : float or array _ like ECEF - X in km y : float or array _ like ECEF - Y in km z : float or array _ like ECEF - Z in km ref _ height : float or array _ like Reference radius used fo...
if ref_height is None : ref_height = earth_geo_radius r = np . sqrt ( x ** 2 + y ** 2 + z ** 2 ) colatitude = np . rad2deg ( np . arccos ( z / r ) ) longitude = np . rad2deg ( np . arctan2 ( y , x ) ) latitude = 90. - colatitude return latitude , longitude , r - ref_height
def login ( ) : """Logs a user in by parsing a POST request containing user credentials and issuing a JWT token . . . example : : $ curl http : / / localhost : 5000 / login - X POST - d ' { " username " : " Walter " , " password " : " calmerthanyouare " } '"""
req = flask . request . get_json ( force = True ) username = req . pop ( 'username' , None ) password = req . pop ( 'password' , None ) user = guard . authenticate ( username , password ) ret = { 'access_token' : guard . encode_jwt_token ( user , firstname = user . firstname , nickname = user . nickname , surname = use...
def check_updates ( self , startup = False ) : """Check for spyder updates on github releases using a QThread ."""
from spyder . workers . updates import WorkerUpdates # Disable check _ updates _ action while the thread is working self . check_updates_action . setDisabled ( True ) if self . thread_updates is not None : self . thread_updates . terminate ( ) self . thread_updates = QThread ( self ) self . worker_updates = WorkerU...
def update ( collection_name , upsert , multi , spec , doc , safe , last_error_args ) : """Get an * * update * * message ."""
options = 0 if upsert : options += 1 if multi : options += 2 data = __ZERO data += bson . _make_c_string ( collection_name ) data += struct . pack ( "<i" , options ) data += bson . BSON . encode ( spec ) data += bson . BSON . encode ( doc ) if safe : ( _ , update_message ) = __pack_message ( 2001 , data ) ...
def adjoint ( self ) : r"""Return the ( right ) adjoint . Notes Due to technicalities of operators from a real space into a complex space , this does not satisfy the usual adjoint equation : . . math : : \ langle Ax , y \ rangle = \ langle x , A ^ * y \ rangle Instead it is an adjoint in a weaker sense ...
if self . domain . is_real : # Real domain # Optimizations for simple cases . if self . scalar . real == self . scalar : return self . scalar . real * RealPart ( self . range ) elif 1j * self . scalar . imag == self . scalar : return self . scalar . imag * ImagPart ( self . range ) else : # ...
def set_destination ( source , suffix , filename = False , ext = None ) : """Create new pdf filename for temp files"""
source_dirname = os . path . dirname ( source ) # Do not create nested temp folders ( / temp / temp ) if not source_dirname . endswith ( 'temp' ) : directory = os . path . join ( source_dirname , 'temp' ) # directory else : directory = source_dirname # Create temp dir if it does not exist if not os . path ....
def delete_document ( self , name , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None ) : """Deletes the specified document . Operation < response : ` ` google . protobuf . Empty ` ` , metadata : [ KnowledgeOperationMetadata ] [...
# Wrap the transport method to add retry and timeout logic . if 'delete_document' not in self . _inner_api_calls : self . _inner_api_calls [ 'delete_document' ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . delete_document , default_retry = self . _method_configs [ 'DeleteDocument' ] . ...
def getscale ( self ) : """Obtain the scale values along a dimension . Args : : no argument Returns : : list with the scale values ; the list length is equal to the dimension length ; the element type is equal to the dimension data type , as set when the ' setdimscale ( ) ' method was called . C libra...
# Get dimension info . If data _ type is 0 , no scale have been set # on the dimension . status , dim_name , dim_size , data_type , n_attrs = _C . SDdiminfo ( self . _id ) _checkErr ( 'getscale' , status , 'cannot execute' ) if data_type == 0 : raise HDF4Error ( "no scale set on that dimension" ) # dim _ size is 0 ...
def load ( cls , directory ) : """Load a Digest from a ` . digest ` file adjacent to the given directory . : return : A Digest , or None if the Digest did not exist ."""
read_file = maybe_read_file ( cls . _path ( directory ) ) if read_file : fingerprint , length = read_file . split ( ':' ) return Digest ( fingerprint , int ( length ) ) else : return None
def override_familly ( self , args ) : """Look in the current wrapped object to find a cache configuration to override the current default configuration ."""
resourceapi = args [ 0 ] cache_cfg = resourceapi . cache if cache_cfg . has_key ( 'familly' ) : self . familly = cache_cfg [ 'familly' ] if cache_cfg . has_key ( 'whole_familly' ) : self . whole_familly = cache_cfg [ 'whole_familly' ] if self . familly is None : raise Exception ( "Invalid familly value for ...
def parity_get_pending_transaction_hash_by_nonce ( self , address : AddressHex , nonce : Nonce , ) -> Optional [ TransactionHash ] : """Queries the local parity transaction pool and searches for a transaction . Checks the local tx pool for a transaction from a particular address and for a given nonce . If it ex...
assert self . eth_node is constants . EthClient . PARITY # https : / / wiki . parity . io / JSONRPC - parity - module . html ? q = traceTransaction # parity _ alltransactions transactions = self . web3 . manager . request_blocking ( 'parity_allTransactions' , [ ] ) log . debug ( 'RETURNED TRANSACTIONS' , transactions =...
def cli ( env , sortby , cpu , domain , datacenter , hostname , memory , network , tag , columns , limit ) : """List hardware servers ."""
manager = SoftLayer . HardwareManager ( env . client ) servers = manager . list_hardware ( hostname = hostname , domain = domain , cpus = cpu , memory = memory , datacenter = datacenter , nic_speed = network , tags = tag , mask = "mask(SoftLayer_Hardware_Server)[%s]" % columns . mask ( ) , limit = limit ) table = forma...
def data_vectors ( self ) : """The per - sample data in a vector . Returns : dict : A dict where the keys are the fields in the record and the values are the corresponding arrays . Examples : > > > sampleset = dimod . SampleSet . from _ samples ( [ [ - 1 , 1 ] , [ 1 , 1 ] ] , dimod . SPIN , energy = [ -...
return { field : self . record [ field ] for field in self . record . dtype . names if field != 'sample' }
def about_axis ( cls , center , angle , axis , invert = False ) : """Create transformation that represents a rotation about an axis Arguments : | ` ` center ` ` - - Point on the axis | ` ` angle ` ` - - Rotation angle | ` ` axis ` ` - - Rotation axis | ` ` invert ` ` - - When True , an inversion rotation ...
return Translation ( center ) * Rotation . from_properties ( angle , axis , invert ) * Translation ( - center )
def hyperparameters ( self ) : """Return hyperparameters used by your custom TensorFlow code during model training ."""
hyperparameters = super ( TensorFlow , self ) . hyperparameters ( ) self . checkpoint_path = self . checkpoint_path or self . _default_s3_path ( 'checkpoints' ) mpi_enabled = False if self . _script_mode_enabled ( ) : additional_hyperparameters = { } if 'parameter_server' in self . distributions : ps_en...
def get_args ( job ) : """This function gets the arguments from a job : param job : job dictionary : return : input tuple , optional tuple"""
return tuple ( _get_args_loop ( job , INPUT_FIELD ) ) , tuple ( _get_args_loop ( job , OPTIONAL_FIELD ) )
def gather_callbacks ( self , optimizer ) -> list : """Gather all the callbacks to be used in this training run"""
callbacks = [ FrameTracker ( self . total_frames ) , TimeTracker ( ) ] if self . scheduler_factory is not None : callbacks . append ( self . scheduler_factory . instantiate ( optimizer ) ) callbacks . extend ( self . callbacks ) callbacks . extend ( self . storage . streaming_callbacks ( ) ) return callbacks
def free_size ( self , units = "MiB" ) : """Returns the volume group free size in the given units . Default units are MiB . * Args : * * units ( str ) : Unit label ( ' MiB ' , ' GiB ' , etc . . . ) . Default is MiB ."""
self . open ( ) size = lvm_vg_get_free_size ( self . handle ) self . close ( ) return size_convert ( size , units )
def get_result_as_array ( self ) : """Returns the float values converted into strings using the parameters given at initialisation , as a numpy array"""
if self . formatter is not None : return np . array ( [ self . formatter ( x ) for x in self . values ] ) if self . fixed_width : threshold = get_option ( "display.chop_threshold" ) else : threshold = None # if we have a fixed _ width , we ' ll need to try different float _ format def format_values_with ( f...
def _determine_selected_stencil ( stencil_set , stencil_definition ) : """Determine appropriate stencil name for stencil definition . Given a fastfood . json stencil definition with a stencil set , figure out what the name of the stencil within the set should be , or use the default"""
if 'stencil' not in stencil_definition : selected_stencil_name = stencil_set . manifest . get ( 'default_stencil' ) else : selected_stencil_name = stencil_definition . get ( 'stencil' ) if not selected_stencil_name : raise ValueError ( "No stencil name, within stencil set %s, specified." % stencil_definitio...
def get_type_data ( name ) : """Return dictionary representation of type . Can be used to initialize primordium . type . primitives . Type"""
name = name . upper ( ) if name in ISO_CURRENCY_TYPES : article = 'the ' type_name = ISO_CURRENCY_TYPES [ name ] elif name in ISO_CURRENCY_ELEMENT_TYPES : article = '' type_name = ISO_CURRENCY_ELEMENT_TYPES [ name ] else : raise NotFound ( 'Currency Type: ' + name ) return { 'authority' : 'ISO' , 'n...
def copy_template ( template_name , copy_to , tag_library_name ) : """Copy the specified template directory to the copy _ to location"""
import django_extensions import shutil template_dir = os . path . join ( django_extensions . __path__ [ 0 ] , 'conf' , template_name ) # walk the template structure and copies it for d , subdirs , files in os . walk ( template_dir ) : relative_dir = d [ len ( template_dir ) + 1 : ] if relative_dir and not os . ...
def init_db ( ) : """Drops and re - creates the SQL schema"""
db . drop_all ( ) db . configure_mappers ( ) db . create_all ( ) db . session . commit ( )
def is_module_on_std_lib_path ( cls , module ) : """Sometimes . py files are symlinked to the real python files , such as the case of virtual env . However the . pyc files are created under the virtual env directory rather than the path in cls . STANDARD _ LIB _ PATH . Hence this function checks for both . : ...
module_file_real_path = os . path . realpath ( module . __file__ ) if module_file_real_path . startswith ( cls . STANDARD_LIB_PATH ) : return True elif os . path . splitext ( module_file_real_path ) [ 1 ] == '.pyc' : py_file_real_path = os . path . realpath ( os . path . splitext ( module_file_real_path ) [ 0 ]...
def _z2deriv ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ z2deriv PURPOSE : evaluate the second vertical derivative for this potential INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : the second vertical derivative HISTORY : 2018-08-04 -...
Raz2 = ( R + self . a ) ** 2 + z ** 2 m = 4. * R * self . a / Raz2 # Explicitly swapped in zforce here , so the z / z can be cancelled # and z = 0 is handled properly return - 4. * ( 3. * z ** 2 / Raz2 - 1. + 4. * ( ( 1. + m ) / ( 1. - m ) - special . ellipk ( m ) / special . ellipe ( m ) ) * self . a * R * z ** 2 / Ra...
def _ctypes_dtype ( parameter ) : """Determines the ISO _ C data type to use for describing the specified parameter ."""
ctype = parameter . ctype if ctype is None : if parameter . kind is not None : return "{}({})" . format ( parameter . dtype , parameter . kind ) else : return parameter . dtype else : return "{}({})" . format ( parameter . dtype , ctype )
def predict_image ( img , model_func ) : """Run detection on one image , using the TF callable . This function should handle the preprocessing internally . Args : img : an image model _ func : a callable from the TF model . It takes image and returns ( boxes , probs , labels , [ masks ] ) Returns : [ ...
orig_shape = img . shape [ : 2 ] resizer = CustomResize ( cfg . PREPROC . TEST_SHORT_EDGE_SIZE , cfg . PREPROC . MAX_SIZE ) resized_img = resizer . augment ( img ) scale = np . sqrt ( resized_img . shape [ 0 ] * 1.0 / img . shape [ 0 ] * resized_img . shape [ 1 ] / img . shape [ 1 ] ) boxes , probs , labels , * masks =...
def run_actions ( self , actions ) : """Runs the given lists of attached actions and instance actions on the client . : param actions : Actions to apply . : type actions : list [ dockermap . map . action . ItemAction ] : return : Where the result is not ` ` None ` ` , returns the output from the client . Note...
policy = self . _policy for action in actions : config_id = action . config_id config_type = config_id . config_type client_config = policy . clients [ action . client_name ] client = client_config . get_client ( ) c_map = policy . container_maps [ config_id . map_name ] if config_type == ItemTy...
def fire_master ( self , data , tag , timeout = 1000 ) : '''Send a single event to the master , with the payload " data " and the event identifier " tag " . Default timeout is 1000ms'''
msg = { 'tag' : tag , 'data' : data , 'events' : None , 'pretag' : None } return self . fire_event ( msg , "fire_master" , timeout )
def _add_hookimpl ( self , hookimpl ) : """Add an implementation to the callback chain ."""
if hookimpl . hookwrapper : methods = self . _wrappers else : methods = self . _nonwrappers if hookimpl . trylast : methods . insert ( 0 , hookimpl ) elif hookimpl . tryfirst : methods . append ( hookimpl ) else : # find last non - tryfirst method i = len ( methods ) - 1 while i >= 0 and methods...
def add_user ( name , password = None , read_only = None , db = None , ** kwargs ) : """Adds a user that can be used for authentication . @ param name : the name of the user to create @ param passowrd : the password of the user to create . Can not be used with the userSource argument . @ param read _ only :...
return CONNECTION . add_user ( name , password = password , read_only = read_only , db = db , ** kwargs )
def rename ( self , old_host , new_host ) : """Renames a host configuration . Parameters old _ host : the host to rename . new _ host : the new host value"""
if new_host in self . hosts_ : raise ValueError ( "Host %s: already exists." % new_host ) for line in self . lines_ : # update lines if line . host == old_host : line . host = new_host if line . key . lower ( ) == "host" : line . value = new_host line . line = "Host %s" %...
def kernels_status ( self , kernel ) : """call to the api to get the status of a kernel . Parameters kernel : the kernel to get the status for"""
if kernel is None : raise ValueError ( 'A kernel must be specified' ) if '/' in kernel : self . validate_kernel_string ( kernel ) kernel_url_list = kernel . split ( '/' ) owner_slug = kernel_url_list [ 0 ] kernel_slug = kernel_url_list [ 1 ] else : owner_slug = self . get_config_value ( self . C...
def get_param ( self , keyword , param = None , default = None ) : """Get all the parameters for a given keyword , or default if keyword or parameter are not present in the configuration . This finds every declaration of the given parameter ( which is the one which takes effect ) . If no parameter is given , ...
if not keyword or keyword not in self . data : return [ default ] # keyword in data - if no value , we store None , so return that in a list if self . data [ keyword ] is None : return [ None ] # If we ' re not searching for a particular parameter , just return all # the values for this keyword . if not param :...
def get_image_info_by_image_name ( self , image , exact_tag = True ) : """using ` docker images ` , provide information about an image : param image : ImageName , name of image : param exact _ tag : bool , if false then return info for all images of the given name regardless what their tag is : return : lis...
logger . info ( "getting info about provided image specified by name '%s'" , image ) logger . debug ( "image_name = '%s'" , image ) # returns list of # { u ' Created ' : 1414577076, # u ' Id ' : u ' 3ab9a7ed8a169ab89b09fb3e12a14a390d3c662703b65b4541c0c7bde0ee97eb ' , # u ' ParentId ' : u ' a79ad4dac406fcf85b9c7315fe08d...
def _parse_forward ( mapping ) : '''Parses a port forwarding statement in the form used by this state : from _ port : to _ port : protocol [ : destination ] and returns a ForwardingMapping object'''
if len ( mapping . split ( ':' ) ) > 3 : ( srcport , destport , protocol , destaddr ) = mapping . split ( ':' ) else : ( srcport , destport , protocol ) = mapping . split ( ':' ) destaddr = '' return ForwardingMapping ( srcport , destport , protocol , destaddr )
def get_es_object_ids ( self , objects ) : """Return IDs of : objects : if they are not IDs already ."""
id_field = self . clean_id_name ids = [ getattr ( obj , id_field , obj ) for obj in objects ] return list ( set ( str ( id_ ) for id_ in ids ) )
def _GetFirefoxConfig ( self , file_object , display_name ) : """Determine cache file block size . Args : file _ object ( dfvfs . FileIO ) : a file - like object . display _ name ( str ) : display name . Returns : firefox _ cache _ config : namedtuple containing the block size and first record offset . ...
# There ought to be a valid record within the first 4 MiB . We use this # limit to prevent reading large invalid files . to_read = min ( file_object . get_size ( ) , self . _INITIAL_CACHE_FILE_SIZE ) while file_object . get_offset ( ) < to_read : offset = file_object . get_offset ( ) try : cache_entry ,...
def qos_map_cos_traffic_class_cos6 ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) qos = ET . SubElement ( config , "qos" , xmlns = "urn:brocade.com:mgmt:brocade-qos" ) map = ET . SubElement ( qos , "map" ) cos_traffic_class = ET . SubElement ( map , "cos-traffic-class" ) name_key = ET . SubElement ( cos_traffic_class , "name" ) name_key . text = kwargs . pop ( 'nam...
def check_engine ( handle ) : """Check availability of requested template engine ."""
if handle == 'help' : dump_engines ( ) sys . exit ( 0 ) if handle not in engines . engines : print ( 'Engine "%s" is not available.' % ( handle , ) , file = sys . stderr ) sys . exit ( 1 )
def known_formats ( use : Union [ Serializer , Parser ] = Serializer , include_mime_types : bool = False ) -> List [ str ] : """Return a list of available formats in rdflib for the required task : param use : task ( typically Serializer or Parser ) : param include _ mime _ types : whether mime types are include...
return sorted ( [ name for name , kind in plugin . _plugins . keys ( ) if kind == use and ( include_mime_types or '/' not in name ) ] )
def check_postconditions ( f , return_value ) : """Runs all of the postconditions ."""
f = getattr ( f , 'wrapped_fn' , f ) if f and hasattr ( f , 'postconditions' ) : for cond in f . postconditions : cond ( return_value )
def clear_buffer ( self ) : """Clear the hub buffer"""
command_url = self . hub_url + '/1?XB=M=1' response = self . post_direct_command ( command_url ) self . logger . info ( "clear_buffer: %s" , response ) return response
def lobstrindex ( args ) : """% prog lobstrindex hg38 . trf . bed hg38 . upper . fa Make lobSTR index . Make sure the FASTA contain only upper case ( so use fasta . format - - upper to convert from UCSC fasta ) . The bed file is generated by str ( ) ."""
p = OptionParser ( lobstrindex . __doc__ ) p . add_option ( "--notreds" , default = False , action = "store_true" , help = "Remove TREDs from the bed file" ) p . set_home ( "lobstr" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) trfbed , fastafile = args pf = fa...
def add_element ( self , element ) : """Add an element to this ComplexType and also append it to element dict of parent type graph ."""
self . elements . append ( element ) self . type_graph . add_element ( element )
def note ( self , note ) : """Sets the note of this OrderFulfillmentPickupDetails . A general note about the pickup fulfillment . Notes are useful for providing additional instructions and are displayed in Square apps . : param note : The note of this OrderFulfillmentPickupDetails . : type : str"""
if note is None : raise ValueError ( "Invalid value for `note`, must not be `None`" ) if len ( note ) > 500 : raise ValueError ( "Invalid value for `note`, length must be less than `500`" ) self . _note = note
def rollback ( name , database = None , directory = None , verbose = None ) : """Rollback a migration with given name ."""
router = get_router ( directory , database , verbose ) router . rollback ( name )
def humanTime ( seconds ) : '''Convert seconds to something more human - friendly'''
intervals = [ 'days' , 'hours' , 'minutes' , 'seconds' ] x = deltaTime ( seconds = seconds ) return ' ' . join ( '{} {}' . format ( getattr ( x , k ) , k ) for k in intervals if getattr ( x , k ) )
def letras ( song ) : """Returns the lyrics found in letras . com for the specified mp3 file or an empty string if not found ."""
translate = { '&' : 'a' , URLESCAPE : '' , ' ' : '-' } artist = song . artist . lower ( ) artist = normalize ( artist , translate ) title = song . title . lower ( ) title = normalize ( title , translate ) url = 'https://www.letras.com/{}/{}/' . format ( artist , title ) soup = get_url ( url ) if not soup : return '...
def pred_to_prob ( Y_h , k ) : """Converts a 1D tensor of predicted labels into a 2D tensor of probabilistic labels Args : Y _ h : an [ n ] , or [ n , 1 ] tensor of predicted ( int ) labels in { 1 , . . . , k } k : the largest possible label in Y _ h Returns : Y _ s : a torch . FloatTensor of shape [ n , ...
Y_h = Y_h . clone ( ) if Y_h . dim ( ) > 1 : Y_h = Y_h . squeeze ( ) assert Y_h . dim ( ) == 1 assert ( Y_h >= 1 ) . all ( ) assert ( Y_h <= k ) . all ( ) n = Y_h . shape [ 0 ] Y_s = torch . zeros ( ( n , k ) , dtype = Y_h . dtype , device = Y_h . device ) for i , j in enumerate ( Y_h ) : Y_s [ i , j - 1 ] = 1....
def validate ( self ) : """Validate this model recursively and return a list of ValidationError . : returns : A list of validation error : rtype : list"""
validation_result = [ ] for attr_name , value in [ ( attr , getattr ( self , attr ) ) for attr in self . _attribute_map ] : attr_desc = self . _attribute_map [ attr_name ] if attr_name == "additional_properties" and attr_desc [ "key" ] == '' : # Do NOT validate additional _ properties continue attr_...
def server_session ( model = None , session_id = None , url = "default" , relative_urls = False , resources = "default" ) : '''Return a script tag that embeds content from a specific existing session on a Bokeh server . This function is typically only useful for serving from a a specific session that was prev...
if session_id is None : raise ValueError ( "Must supply a session_id" ) url = _clean_url ( url ) app_path = _get_app_path ( url ) elementid = make_id ( ) modelid = "" if model is None else model . id src_path = _src_path ( url , elementid ) src_path += _process_app_path ( app_path ) src_path += _process_relative_ur...
def get_name_history ( name , hostport = None , proxy = None , history_page = None ) : """Get the full history of a name Returns { ' status ' : True , ' history ' : . . . } on success , where history is grouped by block Returns { ' error ' : . . . } on error"""
assert hostport or proxy , 'Need hostport or proxy' if proxy is None : proxy = connect_hostport ( hostport ) hist = { } indexing = None lastblock = None if history_page != None : resp = get_name_history_page ( name , history_page , proxy = proxy ) if 'error' in resp : return resp indexing = resp...
def function_nodes ( self ) : """Returns all function nodes of the dispatcher . : return : All data function of the dispatcher . : rtype : dict [ str , dict ]"""
return { k : v for k , v in self . nodes . items ( ) if v [ 'type' ] == 'function' }
def from_etree ( cls , etree_element ) : """create a ` ` TextualRelation ` ` instance from an etree element representing an < edges > element with xsi : type ' sDocumentStructure : STextualRelation ' ."""
ins = SaltEdge . from_etree ( etree_element ) # TODO : this looks dangerous , ask Stackoverflow about it ! # convert SaltEdge into TextualRelation ins . __class__ = TextualRelation . mro ( ) [ 0 ] ins . onset = get_string_onset ( etree_element ) ins . offset = get_string_offset ( etree_element ) return ins