signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_metrics ( self ) : """Returns the Model metrics . : return : Nodes metrics . : rtype : dict"""
search_file_nodes_count = search_occurence_nodesCount = 0 for node in foundations . walkers . nodes_walker ( self . root_node ) : if node . family == "SearchFile" : search_file_nodes_count += 1 elif node . family == "SearchOccurence" : search_occurence_nodesCount += 1 return { "SearchFile" : sea...
def _x_tune_ok ( self , channel_max , frame_max , heartbeat ) : """Negotiate connection tuning parameters This method sends the client ' s connection tuning parameters to the server . Certain fields are negotiated , others provide capability information . PARAMETERS : channel _ max : short negotiated ma...
args = AMQPWriter ( ) args . write_short ( channel_max ) args . write_long ( frame_max ) args . write_short ( heartbeat or 0 ) self . _send_method ( ( 10 , 31 ) , args ) self . _wait_tune_ok = False
def physical_conversion ( quantity , pop = False ) : """Decorator to convert to physical coordinates : quantity = [ position , velocity , time ]"""
def wrapper ( method ) : @ wraps ( method ) def wrapped ( * args , ** kwargs ) : use_physical = kwargs . get ( 'use_physical' , True ) and not kwargs . get ( 'log' , False ) # Parse whether ro or vo should be considered to be set , because # the return value will have units anyway ...
def account_unpin ( self , id ) : """Unpin / un - endorse a user . Returns a ` relationship dict ` _ containing the updated relationship to the user ."""
id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}/unpin' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
def prepare_fcma_data ( images , conditions , mask1 , mask2 = None , random = RandomType . NORANDOM , comm = MPI . COMM_WORLD ) : """Prepare data for correlation - based computation and analysis . Generate epochs of interests , then broadcast to all workers . Parameters images : Iterable [ SpatialImage ] Da...
rank = comm . Get_rank ( ) labels = [ ] raw_data1 = [ ] raw_data2 = [ ] if rank == 0 : logger . info ( 'start to apply masks and separate epochs' ) if mask2 is not None : masks = ( mask1 , mask2 ) activity_data1 , activity_data2 = zip ( * multimask_images ( images , masks , np . float32 ) ) ...
def from_line ( cls , line , lineno = None ) : """Parses the given line of text to find the names for the host , the type of key , and the key data . The line is expected to be in the format used by the OpenSSH known _ hosts file . Lines are expected to not have leading or trailing whitespace . We don ' t b...
log = get_logger ( "paramiko.hostkeys" ) fields = line . split ( " " ) if len ( fields ) < 3 : # Bad number of fields msg = "Not enough fields found in known_hosts in line {} ({!r})" log . info ( msg . format ( lineno , line ) ) return None fields = fields [ : 3 ] names , keytype , key = fields names = name...
def auth_add ( user , auth ) : '''Add authorization to user user : string username auth : string authorization name CLI Example : . . code - block : : bash salt ' * ' rbac . auth _ add martine solaris . zone . manage salt ' * ' rbac . auth _ add martine solaris . zone . manage , solaris . mail . mai...
ret = { } # # validate auths auths = auth . split ( ',' ) known_auths = auth_list ( ) . keys ( ) valid_auths = [ r for r in auths if r in known_auths ] log . debug ( 'rbac.auth_add - auths=%s, known_auths=%s, valid_auths=%s' , auths , known_auths , valid_auths , ) # # update user auths if valid_auths : res = __salt...
def create ( self , _attributes = None , ** attributes ) : """Create a new instance of the related model . : param attributes : The attributes : type attributes : dict : rtype : Model"""
if _attributes is not None : attributes . update ( _attributes ) instance = self . _related . new_instance ( attributes ) instance . set_attribute ( self . get_plain_foreign_key ( ) , self . get_parent_key ( ) ) instance . save ( ) return instance
def notify_one ( correlation_id , component , args ) : """Notifies specific component . To be notiied components must implement [ [ INotifiable ] ] interface . If they don ' t the call to this method has no effect . : param correlation _ id : ( optional ) transaction id to trace execution through call chain ....
if component == None : return if isinstance ( component , INotifiable ) : component . notify ( correlation_id , args )
def y_offset ( self , container ) : """Vertical baseline offset ( up is positive ) ."""
offset = ( self . parent . y_offset ( container ) if hasattr ( self . parent , 'y_offset' ) else 0 ) if self . is_script ( container ) : style = self . _style ( container ) offset += ( self . parent . height ( container ) * self . position [ style . position ] ) # The Y offset should only change once for th...
def parse_status ( status_log , encoding = 'utf-8' ) : """Parses the status log of OpenVPN . : param status _ log : The content of status log . : type status _ log : : class : ` str ` : param encoding : Optional . The encoding of status log . : type encoding : : class : ` str ` : return : The instance of ...
if isinstance ( status_log , bytes ) : status_log = status_log . decode ( encoding ) parser = LogParser . fromstring ( status_log ) return parser . parse ( )
def fill ( duration , point ) : """fills the subsequence of the point with repetitions of its subsequence and sets the ` ` duration ` ` of each point ."""
point [ 'sequence' ] = point [ 'sequence' ] * ( point [ DURATION_64 ] / ( 8 * duration ) ) | add ( { DURATION_64 : duration } ) return point
def parse ( self , filepath , content ) : """Parse opened settings content using YAML parser . Args : filepath ( str ) : Settings object , depends from backend content ( str ) : Settings content from opened file , depends from backend . Raises : boussole . exceptions . SettingsBackendError : If parser c...
try : parsed = yaml . load ( content ) except yaml . YAMLError as exc : msg = "No YAML object could be decoded from file: {}\n{}" raise SettingsBackendError ( msg . format ( filepath , exc ) ) return parsed
def update ( self , currentTemp , targetTemp ) : """Calculate PID output value for given reference input and feedback ."""
# in this implementation , ki includes the dt multiplier term , # and kd includes the dt divisor term . This is typical practice in # industry . self . targetTemp = targetTemp self . error = targetTemp - currentTemp self . P_value = self . Kp * self . error # it is common practice to compute derivative term against PV ...
def from_path ( klass , path , tabix_path = None , record_checks = None , parsed_samples = None ) : """Create new : py : class : ` Reader ` from path . . note : : If you use the ` ` parsed _ samples ` ` feature and you write out records then you must not change the ` ` FORMAT ` ` of the record . : param pat...
record_checks = record_checks or [ ] path = str ( path ) if path . endswith ( ".gz" ) : f = gzip . open ( path , "rt" ) if not tabix_path : tabix_path = path + ".tbi" if not os . path . exists ( tabix_path ) : tabix_path = None # guessing path failed else : f = open (...
def json_description_metadata ( description ) : """Return metatata from JSON formated image description as dict . Raise ValuError if description is of unknown format . > > > description = ' { " shape " : [ 256 , 256 , 3 ] , " axes " : " YXS " } ' > > > json _ description _ metadata ( description ) # doctest :...
if description [ : 6 ] == 'shape=' : # old - style ' shaped ' description ; not JSON shape = tuple ( int ( i ) for i in description [ 7 : - 1 ] . split ( ',' ) ) return dict ( shape = shape ) if description [ : 1 ] == '{' and description [ - 1 : ] == '}' : # JSON description return json . loads ( descriptio...
def get_records_for_code ( self , meth_code , incl = True , use_slice = False , sli = None , strict_match = True ) : """Use regex to see if meth _ code is in the method _ codes " : " delimited list . If incl = = True , return all records WITH meth _ code . If incl = = False , return all records WITHOUT meth _ c...
# ( must use fillna to replace np . nan with False for indexing ) if use_slice : df = sli . copy ( ) else : df = self . df . copy ( ) # if meth _ code not provided , return unchanged dataframe if not meth_code : return df # get regex if not strict_match : # grab any record that contains any part of meth _ c...
def _setup_redis ( self ) : """Returns a Redis Client"""
if not self . closed : try : self . logger . debug ( "Creating redis connection to host " + str ( self . settings [ 'REDIS_HOST' ] ) ) self . redis_conn = redis . StrictRedis ( host = self . settings [ 'REDIS_HOST' ] , port = self . settings [ 'REDIS_PORT' ] , db = self . settings [ 'REDIS_DB' ] ) ...
def bezier_value_check ( coeffs , s_val , rhs_val = 0.0 ) : r"""Check if a polynomial in the Bernstein basis evaluates to a value . This is intended to be used for root checking , i . e . for a polynomial : math : ` f ( s ) ` and a particular value : math : ` s _ { \ ast } ` : Is it true that : math : ` f \ l...
if s_val == 1.0 : return coeffs [ - 1 ] == rhs_val shifted_coeffs = coeffs - rhs_val sigma_coeffs , _ , effective_degree = _get_sigma_coeffs ( shifted_coeffs ) if effective_degree == 0 : # This means that all coefficients except the ` ` ( 1 - s ) ^ n ` ` # term are zero , so we have ` ` f ( s ) = C ( 1 - s ) ^ n ` ...
def logpt ( self , t , xp , x ) : """Log - density of X _ t given X _ { t - 1 } ."""
raise NotImplementedError ( err_msg_missing_trans % self . __class__ . __name__ )
def __update_mouse ( self , milliseconds ) : """Use the mouse to control selection of the buttons ."""
for button in self . gui_buttons : was_hovering = button . is_mouse_hovering button . update ( milliseconds ) # Provides capibilities for the mouse to select a button if the mouse is the focus of input . if was_hovering == False and button . is_mouse_hovering : # The user has just moved the mouse over t...
def padded_variance_explained ( predictions , labels , weights_fn = common_layers . weights_all ) : """Explained variance , also known as R ^ 2."""
predictions , labels = common_layers . pad_with_zeros ( predictions , labels ) targets = labels weights = weights_fn ( targets ) y_bar = tf . reduce_mean ( weights * targets ) tot_ss = tf . reduce_sum ( weights * tf . pow ( targets - y_bar , 2 ) ) res_ss = tf . reduce_sum ( weights * tf . pow ( targets - predictions , ...
def _validate_dict ( self , input_dict , schema_dict , path_to_root , object_title = '' ) : '''a helper method for recursively validating keys in dictionaries : return input _ dict'''
# reconstruct key path to current dictionary in model rules_top_level_key = re . sub ( '\[\d+\]' , '[0]' , path_to_root ) map_rules = self . keyMap [ rules_top_level_key ] # construct list error report template map_error = { 'object_title' : object_title , 'model_schema' : self . schema , 'input_criteria' : map_rules ,...
def nlmsg_alloc ( len_ = default_msg_size ) : """Allocate a new Netlink message with maximum payload size specified . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / msg . c # L299 Allocates a new Netlink message without any further payload . The maximum payload size defaults to resour...
len_ = max ( libnl . linux_private . netlink . nlmsghdr . SIZEOF , len_ ) nm = nl_msg ( ) nm . nm_refcnt = 1 nm . nm_nlh = libnl . linux_private . netlink . nlmsghdr ( bytearray ( b'\0' ) * len_ ) nm . nm_protocol = - 1 nm . nm_size = len_ nm . nm_nlh . nlmsg_len = nlmsg_total_size ( 0 ) _LOGGER . debug ( 'msg 0x%x: Al...
def reorder ( self , dst_order , arr , src_order = None ) : """Reorder the output array to match that needed by the viewer ."""
if dst_order is None : dst_order = self . viewer . rgb_order if src_order is None : src_order = self . rgb_order if src_order != dst_order : arr = trcalc . reorder_image ( dst_order , arr , src_order ) return arr
def to_json_ ( self ) -> str : """Convert the main dataframe to json : return : json data : rtype : str : example : ` ` ds . to _ json _ ( ) ` `"""
try : renderer = pytablewriter . JsonTableWriter data = self . _build_export ( renderer ) return data except Exception as e : self . err ( e , "Can not convert data to json" )
def EnsureGdbPosition ( self , pid , tid , frame_depth ) : """Make sure our position matches the request . Args : pid : The process ID of the target process tid : The python thread ident of the target thread frame _ depth : The ' depth ' of the requested frame in the frame stack Raises : PositionUnavail...
position = [ pid , tid , frame_depth ] if not pid : return if not self . IsAttached ( ) : try : self . Attach ( position ) except gdb . error as exc : raise PositionUnavailableException ( exc . message ) if gdb . selected_inferior ( ) . pid != pid : self . Detach ( ) try : se...
def read_response ( self ) : "Read the response from a previously sent command"
try : response = self . _parser . read_response ( ) except socket . timeout : self . disconnect ( ) raise TimeoutError ( "Timeout reading from %s:%s" % ( self . host , self . port ) ) except socket . error : self . disconnect ( ) e = sys . exc_info ( ) [ 1 ] raise ConnectionError ( "Error while ...
def popup ( self , title , callfn , initialdir = None , filename = None ) : """Let user select and load file ."""
self . cb = callfn self . filew . set_title ( title ) if initialdir : self . filew . set_current_folder ( initialdir ) if filename : # self . filew . set _ filename ( filename ) self . filew . set_current_name ( filename ) self . filew . show ( )
def query ( cls , file , offset = None , limit = None , api = None ) : """Queries genome markers on a file . : param file : Genome file - Usually bam file . : param offset : Pagination offset . : param limit : Pagination limit . : param api : Api instance . : return : Collection object ."""
api = api if api else cls . _API file = Transform . to_file ( file ) return super ( Marker , cls ) . _query ( url = cls . _URL [ 'query' ] , offset = offset , limit = limit , file = file , fields = '_all' , api = api )
def connection_from_list ( data , args = None , ** kwargs ) : '''A simple function that accepts an array and connection arguments , and returns a connection object for use in GraphQL . It uses array offsets as pagination , so pagination will only work if the array is static .'''
_len = len ( data ) return connection_from_list_slice ( data , args , slice_start = 0 , list_length = _len , list_slice_length = _len , ** kwargs )
def get_all_roles ( self , view = None ) : """Get all roles in the service . @ param view : View to materialize ( ' full ' or ' summary ' ) @ return : A list of ApiRole objects ."""
return roles . get_all_roles ( self . _get_resource_root ( ) , self . name , self . _get_cluster_name ( ) , view )
def goto_definitions ( self ) : """Return the definition of a the symbol under the cursor via exact match . Goes to that definition with a buffer ."""
element = self . _evaluator . get_definition ( ) if element is not None : return BaseDefinition ( self . _user_context , element ) else : return None
def parse_name ( name ) : """Parse a gs : / / URL into the bucket and item names . Args : name : a GCS URL of the form gs : / / bucket or gs : / / bucket / item Returns : The bucket name ( with no gs : / / prefix ) , and the item name if present . If the name could not be parsed returns None for both ."""
bucket = None item = None m = re . match ( _STORAGE_NAME , name ) if m : # We want to return the last two groups as first group is the optional ' gs : / / ' bucket = m . group ( 1 ) item = m . group ( 2 ) if item is not None : item = item [ 1 : ] # Strip ' / ' else : m = re . match ( '('...
def fit_mle ( self , data , k_array = np . arange ( 0.1 , 100 , 0.1 ) ) : """% ( super ) s In addition to data , gives an optional keyword argument k _ array containing the values to search for k _ agg . A brute force search is then used to find the parameter k _ agg ."""
# todo : check and mention in docstring biases of mle for k _ agg data = np . array ( data ) mu = np . mean ( data ) return mu , _solve_k_from_mu ( data , k_array , nbinom_nll , mu )
def stdformD ( D , Cd , M , dimN = 2 ) : """Reshape dictionary array ( ` D ` in : mod : ` . admm . cbpdn ` module , ` X ` in : mod : ` . admm . ccmod ` module ) to internal standard form . Parameters D : array _ like Dictionary array Cd : int Size of dictionary channel index M : int Number of filter...
return D . reshape ( D . shape [ 0 : dimN ] + ( Cd , ) + ( 1 , ) + ( M , ) )
def connection ( self , connection ) : """Change the dynamo connection"""
if connection is not None : connection . subscribe ( "capacity" , self . _on_capacity_data ) connection . default_return_capacity = True if self . _connection is not None : connection . unsubscribe ( "capacity" , self . _on_capacity_data ) self . _connection = connection self . _cloudwatch_connection = None...
def symlink_to ( self , target , target_is_directory = False ) : """Make this path a symlink pointing to the given path . Note the order of arguments ( self , target ) is the reverse of os . symlink ' s ."""
self . _accessor . symlink ( target , self , target_is_directory )
def generate_key_pair ( secret = None ) : """Generates a cryptographic key pair . Args : secret ( : class : ` string ` ) : A secret that serves as a seed Returns : : class : ` ~ bigchaindb . common . crypto . CryptoKeypair ` : A : obj : ` collections . namedtuple ` with named fields : attr : ` ~ bigchai...
if secret : keypair_raw = ed25519_generate_key_pair_from_secret ( secret ) return CryptoKeypair ( * ( k . decode ( ) for k in keypair_raw ) ) else : return generate_keypair ( )
def corr_heatmap ( x , mask_half = True , cmap = "RdYlGn_r" , vmin = - 1 , vmax = 1 , linewidths = 0.5 , square = True , figsize = ( 10 , 10 ) , ** kwargs ) : """Wrapper around seaborn . heatmap for visualizing correlation matrix . Parameters x : DataFrame Underlying data ( not a correlation matrix ) mask _...
if mask_half : mask = np . zeros_like ( x . corr ( ) . values ) mask [ np . triu_indices_from ( mask ) ] = True else : mask = None with sns . axes_style ( "white" ) : return sns . heatmap ( x . corr ( ) , cmap = cmap , vmin = vmin , vmax = vmax , linewidths = linewidths , square = square , mask = mask ,...
def get_inventory ( self , keys = None ) : """Create an Ansible inventory based on python dicts and lists . The returned value is a dict in which every key represents a group and every value is a list of entries for that group . Args : keys ( list of str ) : Path to the keys that will be used to create gr...
inventory = defaultdict ( list ) keys = keys or [ 'vm-type' , 'groups' , 'vm-provider' ] vms = self . prefix . get_vms ( ) . values ( ) for vm in vms : entry = self . _generate_entry ( vm ) vm_spec = vm . spec for key in keys : value = self . get_key ( key , vm_spec ) if value is None : ...
def process_python ( self , path ) : """Process a python file ."""
( pylint_stdout , pylint_stderr ) = epylint . py_run ( ' ' . join ( [ str ( path ) ] + self . pylint_opts ) , return_std = True ) emap = { } print ( pylint_stderr . read ( ) ) for line in pylint_stdout : sys . stderr . write ( line ) key = line . split ( ':' ) [ - 1 ] . split ( '(' ) [ 0 ] . strip ( ) if ke...
def retention_policy_exists ( database , name , user = None , password = None , host = None , port = None ) : '''Check if a retention policy exists . database The database to operate on . name Name of the policy to modify . CLI Example : . . code - block : : bash salt ' * ' influxdb08 . retention _ po...
policy = retention_policy_get ( database , name , user , password , host , port ) return policy is not None
def preview_data ( self , flow_id , key = None , count = True , total = True ) : '''Get keys or number of series for a prospective dataset query allowing for keys with multiple values per dimension . It downloads the complete list of series keys for a dataflow rather than using constraints and DSD . This featur...
all_keys = self . series_keys ( flow_id ) # Handle the special case that no key is provided if not key : if count : return all_keys . shape [ 0 ] else : return all_keys # So there is a key specifying at least one dimension value . # Wrap single values in 1 - elem list for uniform treatment key_l...
def signal_handler ( sig , frame ) : """SIGINT handler . Disconnect all active clients and then invoke the original signal handler ."""
for client in connected_clients [ : ] : if client . is_asyncio_based ( ) : client . start_background_task ( client . disconnect , abort = True ) else : client . disconnect ( abort = True ) return original_signal_handler ( sig , frame )
def _get_device_id ( self , bus ) : """Find the device id"""
_dbus = bus . get ( SERVICE_BUS , PATH ) devices = _dbus . devices ( ) if self . device is None and self . device_id is None and len ( devices ) == 1 : return devices [ 0 ] for id in devices : self . _dev = bus . get ( SERVICE_BUS , DEVICE_PATH + "/%s" % id ) if self . device == self . _dev . name : ...
def _cond ( self , unused_x , unused_cumul_out , unused_prev_state , unused_cumul_state , cumul_halting , unused_iteration , unused_remainder ) : """The ` cond ` of the ` tf . while _ loop ` ."""
return tf . reduce_any ( cumul_halting < 1 )
def _compute_non_linear_term ( self , pga4nl , bnl ) : """Compute non - linear term , equation ( 8a ) to ( 8c ) , pag 108."""
fnl = np . zeros ( pga4nl . shape ) a1 = 0.03 a2 = 0.09 pga_low = 0.06 # equation ( 8a ) idx = pga4nl <= a1 fnl [ idx ] = bnl [ idx ] * np . log ( pga_low / 0.1 ) # equation ( 8b ) idx = np . where ( ( pga4nl > a1 ) & ( pga4nl <= a2 ) ) delta_x = np . log ( a2 / a1 ) delta_y = bnl [ idx ] * np . log ( a2 / pga_low ) c ...
def settrace_forked ( ) : '''When creating a fork from a process in the debugger , we need to reset the whole debugger environment !'''
from _pydevd_bundle . pydevd_constants import GlobalDebuggerHolder GlobalDebuggerHolder . global_dbg = None threading . current_thread ( ) . additional_info = None from _pydevd_frame_eval . pydevd_frame_eval_main import clear_thread_local_info host , port = dispatch ( ) import pydevd_tracing pydevd_tracing . restore_sy...
def collect_gallery_files ( examples_dirs ) : """Collect python files from the gallery example directories ."""
files = [ ] for example_dir in examples_dirs : for root , dirnames , filenames in os . walk ( example_dir ) : for filename in filenames : if filename . endswith ( '.py' ) : files . append ( os . path . join ( root , filename ) ) return files
def existence_check ( text , list , err , msg , ignore_case = True , str = False , max_errors = float ( "inf" ) , offset = 0 , require_padding = True , dotall = False , excluded_topics = None , join = False ) : """Build a checker that blacklists certain words ."""
flags = 0 msg = " " . join ( msg . split ( ) ) if ignore_case : flags = flags | re . IGNORECASE if str : flags = flags | re . UNICODE if dotall : flags = flags | re . DOTALL if require_padding : regex = u"(?:^|\W){}[\W$]" else : regex = u"{}" errors = [ ] # If the topic of the text is in the exclude...
def certify_set ( value , certifier = None , min_len = None , max_len = None , include_collections = False , required = True , ) : """Certifier for a set . : param set value : The set to be certified . : param func certifier : A function to be called on each value in the list to check that it is valid . :...
certify_bool ( include_collections , required = True ) certify_iterable ( value = value , types = tuple ( [ set , MutableSet , Set ] ) if include_collections else tuple ( [ set ] ) , certifier = certifier , min_len = min_len , max_len = max_len , schema = None , required = required , )
def connect ( self , pattern , presenter , ** kwargs ) : """Connect the given pattern with the given presenter : param pattern : URI pattern : param presenter : target presenter name : param kwargs : route arguments ( see : class : ` . WWebRoute ` ) : return : None"""
self . __routes . append ( WWebRoute ( pattern , presenter , ** kwargs ) )
def mark_best_classification ( text_log_error , classified_failure ) : """Wrapper for setting best _ classification on both TextLogError and FailureLine . Set the given ClassifiedFailure as best _ classification for the given TextLogError . Handles the duplication of best _ classification on FailureLine so yo...
text_log_error . metadata . best_classification = classified_failure text_log_error . metadata . save ( update_fields = [ 'best_classification' ] ) text_log_error . metadata . failure_line . elastic_search_insert ( )
def plot_phens_blits ( phen_grid , patches , ** kwargs ) : """A version of plot _ phens designed to be used in animations . Takes a 2D array of phenotypes and a list of matplotlib patch objects that have already been added to the current axes and recolors the patches based on the array ."""
denom , palette = get_kwargs ( phen_grid , kwargs ) grid = color_grid ( phen_grid , palette , denom ) for i in range ( len ( grid ) ) : for j in range ( len ( grid [ i ] ) ) : curr_patch = patches [ i * len ( grid [ i ] ) + j ] if grid [ i ] [ j ] == - 1 : curr_patch . set_visible ( Fals...
def list ( self , product , store_view = None , identifierType = None ) : """Retrieve product image list : param product : ID or SKU of product : param store _ view : Code or ID of store view : param identifierType : Defines whether the product or SKU value is passed in the " product " parameter . : retur...
return self . call ( 'catalog_product_attribute_media.list' , [ product , store_view , identifierType ] )
def stop_refresh ( self ) : """Stop redrawing the canvas at the previously set timed interval ."""
self . logger . debug ( "stopping timed refresh" ) self . rf_flags [ 'done' ] = True self . rf_timer . clear ( )
def set_scene_color ( self , scene_id , color ) : """reconfigure a scene by scene ID"""
if not scene_id in self . state . scenes : # does that scene _ id exist ? err_msg = "Requested to recolor scene {sceneNum}, which does not exist" . format ( sceneNum = scene_id ) logging . info ( err_msg ) return ( False , 0 , err_msg ) self . state . scenes [ scene_id ] = self . state . scenes [ scene_id ]...
def _get_ann ( dbs , features ) : """Gives format to annotation for html table output"""
value = "" for db , feature in zip ( dbs , features ) : value += db + ":" + feature return value
def add ( self , name , obj ) : '''Register a new feature serializer . The feature type should be one of the fixed set of feature representations , and ` name ` should be one of ` ` StringCounter ` ` , ` ` SparseVector ` ` , or ` ` DenseVector ` ` . ` obj ` is a describing object with three fields : ` const...
ro = obj . constructor ( ) if name not in cbor_names_to_tags : print ( name ) raise ValueError ( 'Unsupported feature type name: "%s". ' 'Allowed feature type names: %r' % ( name , cbor_names_to_tags . keys ( ) ) ) if not is_valid_feature_instance ( ro ) : raise ValueError ( 'Constructor for "%s" returned "...
def fastas ( self , download = False ) : """Dict of filepaths for all fasta files associated with code . Parameters download : bool If True , downloads the fasta file from the PDB . If False , uses the ampal Protein . fasta property Defaults to False - this is definitely the recommended behaviour . Note...
fastas_dict = { } fasta_dir = os . path . join ( self . parent_dir , 'fasta' ) if not os . path . exists ( fasta_dir ) : os . makedirs ( fasta_dir ) for i , mmol_file in self . mmols . items ( ) : mmol_name = os . path . basename ( mmol_file ) fasta_file_name = '{0}.fasta' . format ( mmol_name ) fasta_f...
def format_info_response ( value ) : """Format the response from redis : param str value : The return response from redis : rtype : dict"""
info = { } for line in value . decode ( 'utf-8' ) . splitlines ( ) : if not line or line [ 0 ] == '#' : continue if ':' in line : key , value = line . split ( ':' , 1 ) info [ key ] = parse_info_value ( value ) return info
def close ( self , connection , * , commit = True ) : """Close the connection using the closer method passed to the constructor ."""
if commit : connection . commit ( ) else : connection . rollback ( ) self . closer ( connection )
def _setup_ulimit_time_limit ( self , hardtimelimit , cgroups ) : """Setup time limit with ulimit for the current process ."""
if hardtimelimit is not None : # Also use ulimit for CPU time limit as a fallback if cgroups don ' t work . if CPUACCT in cgroups : # Use a slightly higher limit to ensure cgroups get used # ( otherwise we cannot detect the timeout properly ) . ulimit = hardtimelimit + _ULIMIT_DEFAULT_OVERHEAD else ...
def with_args ( self , * args , ** kwargs ) : """Declares that the double can only be called with the provided arguments . : param args : Any positional arguments required for invocation . : param kwargs : Any keyword arguments required for invocation ."""
self . args = args self . kwargs = kwargs self . verify_arguments ( ) return self
def from_file ( filename = None , io = 'auto' , prefix_dir = None , omit_facets = False ) : """Read a mesh from a file . Parameters filename : string or function or MeshIO instance or Mesh instance The name of file to read the mesh from . For convenience , a mesh creation function or a MeshIO instance or di...
if isinstance ( filename , Mesh ) : return filename if io == 'auto' : if filename is None : output ( 'filename or io must be specified!' ) raise ValueError else : io = MeshIO . any_from_filename ( filename , prefix_dir = prefix_dir ) output ( 'reading mesh (%s)...' % ( io . filename ...
def _run_progress_callbacks ( self , bytes_transferred ) : '''pass the number of bytes process to progress callbacks'''
if bytes_transferred : for callback in self . _progress_callbacks : try : callback ( bytes_transferred = bytes_transferred ) except Exception as ex : logger . error ( "Exception: %s" % str ( ex ) )
def to_resolvers ( sweepable : Sweepable ) -> List [ ParamResolver ] : """Convert a Sweepable to a list of ParamResolvers ."""
if isinstance ( sweepable , ParamResolver ) : return [ sweepable ] elif isinstance ( sweepable , Sweep ) : return list ( sweepable ) elif isinstance ( sweepable , collections . Iterable ) : iterable = cast ( collections . Iterable , sweepable ) return list ( iterable ) if isinstance ( next ( iter ( iter...
def unassign_activity_from_objective_bank ( self , activity_id , objective_bank_id ) : """Removes a ` ` Activity ` ` from a ` ` ObjectiveBank ` ` . arg : activity _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Activity ` ` arg : objective _ bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Objecti...
# Implemented from template for # osid . resource . ResourceBinAssignmentSession . unassign _ resource _ from _ bin mgr = self . _get_provider_manager ( 'LEARNING' , local = True ) lookup_session = mgr . get_objective_bank_lookup_session ( proxy = self . _proxy ) lookup_session . get_objective_bank ( objective_bank_id ...
def shell_call ( command , ** kwargs ) : """Calls shell command with argument substitution . Args : command : command represented as a list . Each element of the list is one token of the command . For example " cp a b " becomes [ ' cp ' , ' a ' , ' b ' ] If any element of the list looks like ' $ { NAME } ' ...
# Regular expression to find instances of ' $ { NAME } ' in a string CMD_VARIABLE_RE = re . compile ( '^\\$\\{(\\w+)\\}$' ) command = list ( command ) for i in range ( len ( command ) ) : m = CMD_VARIABLE_RE . match ( command [ i ] ) if m : var_id = m . group ( 1 ) if var_id in kwargs : ...
def guid ( valu = None ) : '''Get a 16 byte guid value . By default , this is a random guid value . Args : valu : Object used to construct the guid valu from . This must be able to be msgpack ' d . Returns : str : 32 character , lowercase ascii string .'''
if valu is None : return binascii . hexlify ( os . urandom ( 16 ) ) . decode ( 'utf8' ) # Generate a " stable " guid from the given item byts = s_msgpack . en ( valu ) return hashlib . md5 ( byts ) . hexdigest ( )
def read_sps ( path ) : """Read a LibSVM file line - by - line . Args : path ( str ) : A path to the LibSVM file to read . Yields : data ( list ) and target ( int ) ."""
for line in open ( path ) : # parse x xs = line . rstrip ( ) . split ( ' ' ) yield xs [ 1 : ] , int ( xs [ 0 ] )
def get_sound ( self , title , group ) : '''Retrieve sound @ title from group @ group .'''
return self . sounds [ group . lower ( ) ] [ title . lower ( ) ]
def main ( ) : """Main entry point for gunicorn _ console ."""
# Set up curses . stdscr = curses . initscr ( ) curses . start_color ( ) curses . init_pair ( 1 , foreground_colour , background_colour ) curses . noecho ( ) stdscr . keypad ( True ) stdscr . nodelay ( True ) try : curses . curs_set ( False ) except : pass try : # Run main event loop until quit . while True...
def axis_as_object ( arr , axis = - 1 ) : """cast the given axis of an array to a void object if the axis to be cast is contiguous , a view is returned , otherwise a copy is made this is useful for efficiently sorting by the content of an axis , for instance Parameters arr : ndarray array to view as void ...
shape = arr . shape # make axis to be viewed as a void object as contiguous items arr = np . ascontiguousarray ( np . rollaxis ( arr , axis , arr . ndim ) ) # number of bytes in each void object nbytes = arr . dtype . itemsize * shape [ axis ] # void type with the correct number of bytes voidtype = np . dtype ( ( np . ...
def mon_hosts ( mons ) : """Iterate through list of MON hosts , return tuples of ( name , host ) ."""
for m in mons : if m . count ( ':' ) : ( name , host ) = m . split ( ':' ) else : name = m host = m if name . count ( '.' ) > 0 : name = name . split ( '.' ) [ 0 ] yield ( name , host )
def enable ( identifier = None , * args , ** kwargs ) : '''Enables a specific cache for the current session . Remember that is has to be registered .'''
global cache if not identifier : for item in ( config [ 'default-caches' ] + [ 'NoCache' ] ) : if caches . has_key ( item ) : debug ( 'Enabling default cache %s...' % ( item , ) ) cache = caches [ item ] ( * args , ** kwargs ) if not cache . status ( ) : w...
def set_file_properties ( self , share_name , directory_name , file_name , content_settings , timeout = None ) : '''Sets system properties on the file . If one property is set for the content _ settings , all properties will be overriden . : param str share _ name : Name of existing share . : param str dire...
_validate_not_none ( 'share_name' , share_name ) _validate_not_none ( 'file_name' , file_name ) _validate_not_none ( 'content_settings' , content_settings ) request = HTTPRequest ( ) request . method = 'PUT' request . host = self . _get_host ( ) request . path = _get_path ( share_name , directory_name , file_name ) req...
def hsl2rgb ( hsl ) : """Convert HSL representation towards RGB : param h : Hue , position around the chromatic circle ( h = 1 equiv h = 0) : param s : Saturation , color saturation ( 0 = full gray , 1 = full color ) : param l : Ligthness , Overhaul lightness ( 0 = full black , 1 = full white ) : rtype : 3 ...
h , s , l = [ float ( v ) for v in hsl ] if not ( 0.0 - FLOAT_ERROR <= s <= 1.0 + FLOAT_ERROR ) : raise ValueError ( "Saturation must be between 0 and 1." ) if not ( 0.0 - FLOAT_ERROR <= l <= 1.0 + FLOAT_ERROR ) : raise ValueError ( "Lightness must be between 0 and 1." ) if s == 0 : return l , l , l if l < ...
def list_subnetpools ( self , retrieve_all = True , ** _params ) : """Fetches a list of all subnetpools for a project ."""
return self . list ( 'subnetpools' , self . subnetpools_path , retrieve_all , ** _params )
def extractSNPs ( prefixes , snpToExtractFileNames , outPrefixes , runSGE ) : """Extract a list of SNPs using Plink ."""
s = None jobIDs = [ ] jobTemplates = [ ] if runSGE : # Add the environment variable for DRMAA package if "DRMAA_LIBRARY_PATH" not in os . environ : t = "/shares/data/sge/lib/lx24-amd64/libdrmaa.so.1.0" os . environ [ "DRMAA_LIBRARY_PATH" ] = t # Import the python drmaa library try : ...
def seekend ( self ) : """Set the current record position past the last vdata record . Subsequent write ( ) calls will append records to the vdata . Args : : no argument Returns : : index of the last record plus 1 C library equivalent : no equivalent"""
try : # Seek to the next - to - last record position n = self . seek ( self . _nrecs - 1 ) # updates _ offset # Read last record , ignoring values self . read ( 1 ) # updates _ offset return self . _nrecs except HDF4Error : raise HDF4Error ( "seekend: cannot execute" )
def main_restore ( directory , conn_name ) : """Restore your database dumped with the dump command just a wrapper around ` dump restore ` https : / / github . com / Jaymon / dump"""
inter = get_interface ( conn_name ) conn = inter . connection_config cmd = get_base_cmd ( "restore" , inter , directory ) run_cmd ( cmd )
def build_permutation_matrix ( permutation ) : """Build a permutation matrix for a permutation ."""
matrix = lil_matrix ( ( len ( permutation ) , len ( permutation ) ) ) column = 0 for row in permutation : matrix [ row , column ] = 1 column += 1 return matrix
def find_show_premium_by_ids ( self , show_ids , page = 1 , count = 20 ) : """doc : http : / / open . youku . com / docs / doc ? id = 61"""
url = 'https://openapi.youku.com/v2/shows/show_premium.json' params = { 'client_id' : self . client_id , 'show_ids' : show_ids , 'page' : page , 'count' : count } r = requests . get ( url , params = params ) check_error ( r ) return r . json ( )
def connect_container_to_network ( container , net_id , ** kwargs ) : '''. . versionadded : : 2015.8.3 . . versionchanged : : 2017.7.0 Support for ` ` ipv4 _ address ` ` argument added . . versionchanged : : 2018.3.0 All arguments are now passed through to ` connect _ container _ to _ network ( ) ` _ , al...
kwargs = __utils__ [ 'args.clean_kwargs' ] ( ** kwargs ) log . debug ( 'Connecting container \'%s\' to network \'%s\' with the following ' 'configuration: %s' , container , net_id , kwargs ) response = _client_wrapper ( 'connect_container_to_network' , container , net_id , ** kwargs ) log . debug ( 'Successfully connec...
def dump ( self , force = False ) : """Encodes the value using DER : param force : If the encoded contents already exist , clear them and regenerate to ensure they are in DER format instead of BER format : return : A byte string of the DER - encoded value"""
if self . _parsed is None : self . parse ( ) return self . _parsed [ 0 ] . dump ( force = force )
def _upd_unused ( self , what ) : """Make sure to have exactly one copy of every valid function in the " unused " pile on the right . Doesn ' t read from the database . : param what : a string , ' trigger ' , ' prereq ' , or ' action '"""
builder = getattr ( self , '_{}_builder' . format ( what ) ) updtrig = getattr ( self , '_trigger_upd_unused_{}s' . format ( what ) ) builder . unbind ( decks = updtrig ) funcs = OrderedDict ( ) cards = list ( self . _action_builder . decks [ 1 ] ) cards . reverse ( ) for card in cards : funcs [ card . ud [ 'funcna...
def get_country_name_from_iso3 ( cls , iso3 , use_live = True , exception = None ) : # type : ( str , bool , Optional [ ExceptionUpperBound ] ) - > Optional [ str ] """Get country name from ISO3 code Args : iso3 ( str ) : ISO3 code for which to get country name use _ live ( bool ) : Try to get use latest data...
countryinfo = cls . get_country_info_from_iso3 ( iso3 , use_live = use_live , exception = exception ) if countryinfo is not None : return countryinfo . get ( '#country+name+preferred' ) return None
def _cleanAndRebuildIfNeeded ( portal , cleanrebuild ) : """Rebuild the given catalogs . : portal : the Plone portal object : cleanrebuild : a list with catalog ids"""
for cat in cleanrebuild : catalog = getToolByName ( portal , cat ) if catalog : if hasattr ( catalog , "softClearFindAndRebuild" ) : catalog . softClearFindAndRebuild ( ) else : catalog . clearFindAndRebuild ( ) else : logger . warning ( '%s do not found' % ca...
def add_cache_entry ( self , key , entry ) : """Add the given ` entry ` ( which must be a : class : ` ~ . disco . xso . InfoQuery ` instance ) to the user - level database keyed with the hash function type ` hash _ ` and the ` node ` URL . The ` entry ` is * * not * * validated to actually map to ` node ` wit...
copied_entry = copy . copy ( entry ) self . _memory_overlay [ key ] = copied_entry if self . _user_db_path is not None : asyncio . ensure_future ( asyncio . get_event_loop ( ) . run_in_executor ( None , writeback , self . _user_db_path / key . path , entry . captured_events ) )
def merge_duplicates ( self ) : """Merge and remove duplicate entries . Compares each entry ( ' name ' ) in ` stubs ` to all later entries to check for duplicates in name or alias . If a duplicate is found , they are merged and written to file ."""
if len ( self . entries ) == 0 : self . log . error ( "WARNING: `entries` is empty, loading stubs" ) if self . args . update : self . log . warning ( "No sources changed, entry files unchanged in update." " Skipping merge." ) return self . entries = self . load_stubs ( ) task_str = self . g...
def get_keypair_dict ( ) : """Returns dictionary of { keypairname : keypair }"""
client = get_ec2_client ( ) response = client . describe_key_pairs ( ) assert is_good_response ( response ) result = { } ec2 = get_ec2_resource ( ) for keypair in response [ 'KeyPairs' ] : keypair_name = keypair . get ( 'KeyName' , '' ) if keypair_name in result : util . log ( f"Warning: Duplicate key {...
def touch ( name , atime = None , mtime = None ) : '''. . versionadded : : 0.9.5 Just like the ` ` touch ` ` command , create a file if it doesn ' t exist or simply update the atime and mtime if it already does . atime : Access time in Unix epoch time . Set it to 0 to set atime of the file with Unix date ...
name = os . path . expanduser ( name ) if atime and atime . isdigit ( ) : atime = int ( atime ) if mtime and mtime . isdigit ( ) : mtime = int ( mtime ) try : if not os . path . exists ( name ) : with salt . utils . files . fopen ( name , 'a' ) : pass if atime is None and mtime is No...
def save ( self , filename = None , * , gzipped = None , byteorder = None ) : """Write the file at the specified location . The ` gzipped ` keyword only argument indicates if the file should be gzipped . The ` byteorder ` keyword only argument lets you specify whether the file should be big - endian or little...
if gzipped is None : gzipped = self . gzipped if filename is None : filename = self . filename if filename is None : raise ValueError ( 'No filename specified' ) open_file = gzip . open if gzipped else open with open_file ( filename , 'wb' ) as buff : self . write ( buff , byteorder or self . byteorder ...
def commit_hash ( self ) : """Return the current commit hash if available . This is not a required task so best effort is fine . In other words this is not guaranteed to work 100 % of the time ."""
commit_hash = None branch = None branch_file = '.git/HEAD' # ref : refs / heads / develop # get current branch if os . path . isfile ( branch_file ) : with open ( branch_file , 'r' ) as f : try : branch = f . read ( ) . strip ( ) . split ( '/' ) [ 2 ] except IndexError : pass...
def _adjust_object_lists ( obj ) : '''For creation or update of object that have attribute which contains a list Zabbix awaits plain list of IDs while querying Zabbix for same object returns list of dicts : param obj : Zabbix object parameters'''
for subcomp in TEMPLATE_COMPONENT_DEF : if subcomp in obj and TEMPLATE_COMPONENT_DEF [ subcomp ] [ 'adjust' ] : obj [ subcomp ] = [ item [ TEMPLATE_COMPONENT_DEF [ subcomp ] [ 'qidname' ] ] for item in obj [ subcomp ] ]
def md5 ( self ) : """An MD5 hash of the current vertices and entities . Returns md5 : str , two appended MD5 hashes"""
# first MD5 the points in every entity target = '{}{}' . format ( util . md5_object ( bytes ( ) . join ( e . _bytes ( ) for e in self . entities ) ) , self . vertices . md5 ( ) ) return target
def verify_calling_thread ( self , should_be_emulation , message = None ) : """Verify if the calling thread is or is not the emulation thread . This method can be called to make sure that an action is being taken in the appropriate context such as not blocking the event loop thread or modifying an emulate sta...
if should_be_emulation == self . _on_emulation_thread ( ) : return if message is None : message = "Operation performed on invalid thread" raise InternalError ( message )
def cancelall ( self ) : """Cancel all orders of this bot"""
if self . orders : return self . bitshares . cancel ( [ o [ "id" ] for o in self . orders ] , account = self . account )