signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def match_similar ( base , items ) : """Get the most similar matching item from a list of items . @ param base : base item to locate best match @ param items : list of items for comparison @ return : most similar matching item or None"""
finds = list ( find_similar ( base , items ) ) if finds : return max ( finds , key = base . similarity ) # TODO : make O ( n ) return None
def _valid_table_name ( self , table_name ) : """Check if the table name is obviously invalid ."""
if table_name is None or not len ( table_name . strip ( ) ) : raise ValueError ( "Invalid table name: %r" % table_name ) return table_name . strip ( )
def add_all ( application , project_id , control_client , loader = service . Loaders . FROM_SERVICE_MANAGEMENT ) : """Adds all endpoints middleware to a wsgi application . Sets up application to use all default endpoints middleware . Example : > > > application = MyWsgiApp ( ) # an existing WSGI application ...
return ConfigFetchWrapper ( application , project_id , control_client , loader )
def split ( expr , frac , seed = None ) : """Split the current column into two column objects with certain ratio . : param float frac : Split ratio : return : two split DataFrame objects"""
if hasattr ( expr , '_xflow_split' ) : return expr . _xflow_split ( frac , seed = seed ) else : return _split ( expr , frac , seed = seed )
def make_fcn ( filename ) : """Return the fit - test function corresponding to file ` ` filename ` ` ."""
# collect lines and parse first several lines for fit info with open ( filename , 'r' ) as ifile : lines = ifile . readlines ( ) name = filename . split ( '.' ) [ 0 ] _certified_values = re . compile ( '.*Certified Values\s*\(lines\s*([0-9]*)\s*to\s*([0-9]*)\)' ) _data = re . compile ( '.*Data\s*\(lines\s*([0-9]*)\...
def book_hotel ( intent_request ) : """Performs dialog management and fulfillment for booking a hotel . Beyond fulfillment , the implementation for this intent demonstrates the following : 1 ) Use of elicitSlot in slot validation and re - prompting 2 ) Use of sessionAttributes to pass information that can be ...
location = try_ex ( lambda : intent_request [ 'currentIntent' ] [ 'slots' ] [ 'Location' ] ) checkin_date = try_ex ( lambda : intent_request [ 'currentIntent' ] [ 'slots' ] [ 'CheckInDate' ] ) nights = safe_int ( try_ex ( lambda : intent_request [ 'currentIntent' ] [ 'slots' ] [ 'Nights' ] ) ) room_type = try_ex ( lamb...
def bam_to_bigwig ( self , input_bam , output_bigwig , genome_sizes , genome , tagmented = False , normalize = False , norm_factor = 1000 ) : """Convert a BAM file to a bigWig file . : param str input _ bam : path to BAM file to convert : param str output _ bigwig : path to which to write file in bigwig format ...
# TODO : # addjust fragment length dependent on read size and real fragment size # ( right now it asssumes 50bp reads with 180bp fragments ) cmds = list ( ) transient_file = os . path . abspath ( re . sub ( "\.bigWig" , "" , output_bigwig ) ) cmd1 = self . tools . bedtools + " bamtobed -i {0} |" . format ( input_bam ) ...
def delete_item ( self , item , expected_value = None , return_values = None ) : """Delete the item from Amazon DynamoDB . : type item : : class : ` boto . dynamodb . item . Item ` : param item : The Item to delete from Amazon DynamoDB . : type expected _ value : dict : param expected _ value : A dictionary...
expected_value = self . dynamize_expected_value ( expected_value ) key = self . build_key_from_values ( item . table . schema , item . hash_key , item . range_key ) return self . layer1 . delete_item ( item . table . name , key , expected = expected_value , return_values = return_values , object_hook = item_object_hook...
def diff_packages ( pkg1 , pkg2 = None ) : """Invoke a diff editor to show the difference between the source of two packages . Args : pkg1 ( ` Package ` ) : Package to diff . pkg2 ( ` Package ` ) : Package to diff against . If None , the next most recent package version is used ."""
if pkg2 is None : it = iter_packages ( pkg1 . name ) pkgs = [ x for x in it if x . version < pkg1 . version ] if not pkgs : raise RezError ( "No package to diff with - %s is the earliest " "package version" % pkg1 . qualified_name ) pkgs = sorted ( pkgs , key = lambda x : x . version ) pkg2 ...
def get_obj_subcmds ( obj ) : """Fetch action in callable attributes which and commands Callable must have their attribute ' command ' set to True to be recognised by this lookup . Please consider using the decorator ` ` @ cmd ` ` to declare your subcommands in classes for instance ."""
subcmds = [ ] for label in dir ( obj . __class__ ) : if label . startswith ( "_" ) : continue if isinstance ( getattr ( obj . __class__ , label , False ) , property ) : continue rvalue = getattr ( obj , label ) if not callable ( rvalue ) or not is_cmd ( rvalue ) : continue if...
def set_name_with_model ( self , model ) : """Sets an unique generated name for the index . PartialIndex would like to only override " hash _ data = . . . " , but the entire method must be duplicated for that ."""
table_name = model . _meta . db_table column_names = [ model . _meta . get_field ( field_name ) . column for field_name , order in self . fields_orders ] column_names_with_order = [ ( ( '-%s' if order else '%s' ) % column_name ) for column_name , ( field_name , order ) in zip ( column_names , self . fields_orders ) ] #...
def is_by_step ( raw ) : """If the password is alphabet step by step ."""
# make sure it is unicode delta = ord ( raw [ 1 ] ) - ord ( raw [ 0 ] ) for i in range ( 2 , len ( raw ) ) : if ord ( raw [ i ] ) - ord ( raw [ i - 1 ] ) != delta : return False return True
def fit_transform ( self , X , y = None ) : """Fits the imputer on X and return the transformed X . Parameters X : array - like , shape ( n _ samples , n _ features ) Input data , where " n _ samples " is the number of samples and " n _ features " is the number of features . y : ignored . Returns Xt :...
self . random_state_ = getattr ( self , "random_state_" , check_random_state ( self . random_state ) ) if self . n_iter < 0 : raise ValueError ( "'n_iter' should be a positive integer. Got {} instead." . format ( self . n_iter ) ) if self . predictor is None : if self . sample_posterior : from sklearn ....
def create_folder_manage_actions ( self , fnames ) : """Return folder management actions"""
actions = [ ] if os . name == 'nt' : _title = _ ( "Open command prompt here" ) else : _title = _ ( "Open terminal here" ) _title = _ ( "Open IPython console here" ) action = create_action ( self , _title , triggered = lambda : self . open_interpreter ( fnames ) ) actions . append ( action ) return actions
def parse_iterable ( self , stream , start , end ) : """Sequence : : = SequenceStart WSC SequenceValue ? WSC SequenceEnd Set : = SetStart WSC SequenceValue ? WSC SetEnd SequenceValue : : = Value ( WSC SeparatorSymbol WSC Value ) *"""
values = [ ] self . expect ( stream , start ) self . skip_whitespace_or_comment ( stream ) if self . has_next ( end , stream ) : self . expect ( stream , end ) return values while 1 : self . skip_whitespace_or_comment ( stream ) values . append ( self . parse_value ( stream ) ) self . skip_whitespac...
def select_fds ( read_fds , timeout , selector = AutoSelector ) : """Wait for a list of file descriptors ( ` read _ fds ` ) to become ready for reading . This chooses the most appropriate select - tool for use in prompt - toolkit ."""
# Map to ensure that we return the objects that were passed in originally . # Whether they are a fd integer or an object that has a fileno ( ) . # ( The ' poll ' implementation for instance , returns always integers . ) fd_map = dict ( ( fd_to_int ( fd ) , fd ) for fd in read_fds ) # Wait , using selector . sel = selec...
def __parse_tostr ( self , text , ** kwargs ) : '''Builds and returns the MeCab function for parsing Unicode text . Args : fn _ name : MeCab function name that determines the function behavior , either ' mecab _ sparse _ tostr ' or ' mecab _ nbest _ sparse _ tostr ' . Returns : A function definition , t...
n = self . options . get ( 'nbest' , 1 ) if self . _KW_BOUNDARY in kwargs : patt = kwargs . get ( self . _KW_BOUNDARY , '.' ) tokens = list ( self . __split_pattern ( text , patt ) ) text = '' . join ( [ t [ 0 ] for t in tokens ] ) btext = self . __str2bytes ( text ) self . __mecab . mecab_lattice_s...
def get_last_response_xml ( self , pretty_print_if_possible = False ) : """Retrieves the raw XML ( decrypted ) of the last SAML response , or the last Logout Response generated or processed : returns : SAML response XML : rtype : string | None"""
response = None if self . __last_response is not None : if isinstance ( self . __last_response , compat . str_type ) : response = self . __last_response else : response = tostring ( self . __last_response , encoding = 'unicode' , pretty_print = pretty_print_if_possible ) return response
def translate ( dnaseq , host = 'human' , fmtout = str , tax_id = None ) : """Translates a DNA seqeunce : param dnaseq : DNA sequence : param host : host organism : param fmtout : format of output sequence"""
if isinstance ( dnaseq , str ) : dnaseq = Seq . Seq ( dnaseq , Alphabet . generic_dna ) if tax_id is None : tax_id = 1 # stanndard codon table . ref http : / / biopython . org / DIST / docs / tutorial / Tutorial . html # htoc25 prtseq = dnaseq . translate ( table = tax_id ) if fmtout is str : return str...
def setCenterLineColor ( self , color ) : """Sets the color for the center line . : return < QColor >"""
palette = self . palette ( ) palette . setColor ( palette . GridCenterline , QColor ( color ) )
def iterator ( self ) : """Returns an iterator over all entity states held by this Unit Of Work ."""
# FIXME : There is no dependency tracking ; objects are iterated in # random order . for ent_cls in list ( self . __entity_set_map . keys ( ) ) : for ent in self . __entity_set_map [ ent_cls ] : yield EntityState . get_state ( ent )
def _find_no_duplicates ( self , name , domain = None , path = None ) : """Both ` ` _ _ get _ item _ _ ` ` and ` ` get ` ` call this function : it ' s never used elsewhere in Requests . : param name : a string containing name of cookie : param domain : ( optional ) string containing domain of cookie : param...
toReturn = None for cookie in iter ( self ) : if cookie . name == name : if domain is None or cookie . domain == domain : if path is None or cookie . path == path : if toReturn is not None : # if there are multiple cookies that meet passed in criteria raise Co...
def _exec_loop_moving_window ( self , a_all , bd_all , mask , bd_idx ) : """Solves the kriging system by looping over all specified points . Uses only a certain number of closest points . Not very memory intensive , but the loop is done in pure Python ."""
import scipy . linalg . lapack npt = bd_all . shape [ 0 ] n = bd_idx . shape [ 1 ] kvalues = np . zeros ( npt ) sigmasq = np . zeros ( npt ) for i in np . nonzero ( ~ mask ) [ 0 ] : b_selector = bd_idx [ i ] bd = bd_all [ i ] a_selector = np . concatenate ( ( b_selector , np . array ( [ a_all . shape [ 0 ] ...
async def addMachines ( self , params = None ) : """: param params dict : Dictionary specifying the machine to add . All keys are optional . Keys include : series : string specifying the machine OS series . constraints : string holding machine constraints , if any . We ' ll parse this into the json friend...
params = params or { } # Normalize keys params = { normalize_key ( k ) : params [ k ] for k in params . keys ( ) } # Fix up values , as necessary . if 'parent_id' in params : if params [ 'parent_id' ] . startswith ( '$addUnit' ) : unit = self . resolve ( params [ 'parent_id' ] ) [ 0 ] params [ 'pare...
def load ( path ) : """Load pickled object from the specified file path . Parameters path : string File path Returns unpickled : type of object stored in file"""
f = open ( path , 'rb' ) try : return pickle . load ( f ) finally : f . close ( )
def get_api_url ( self , api_resource , auth_token_ticket , authenticator , private_key , service_url = None , ** kwargs ) : '''Build an auth - token - protected CAS API url .'''
auth_token , auth_token_signature = self . _build_auth_token_data ( auth_token_ticket , authenticator , private_key , ** kwargs ) params = { 'at' : auth_token , 'ats' : auth_token_signature , } if service_url is not None : params [ 'service' ] = service_url url = '{}?{}' . format ( self . _get_api_url ( api_resourc...
def wait_socks ( sock_events , inmask = 1 , outmask = 2 , timeout = None ) : """wait on a combination of zeromq sockets , normal sockets , and fds . . note : : this method can block it will return once there is relevant activity on any of the descriptors or sockets , or the timeout expires : param sock _ ev...
results = [ ] for sock , mask in sock_events : if isinstance ( sock , zmq . backend . Socket ) : mask = _check_events ( sock , mask , inmask , outmask ) if mask : results . append ( ( sock , mask ) ) if results : return results fd_map = { } fd_events = [ ] for sock , mask in sock_eve...
def get_config ( self ) : """Returns pickle - serializable configuration struct for storage ."""
# Fill this dict with config data return { 'hash_name' : self . hash_name , 'dim' : self . dim , 'bin_width' : self . bin_width , 'projection_count' : self . projection_count , 'components' : self . components }
def draw_normal ( self ) : """Draw parameters from a mean - field normal family"""
means , scale = self . get_means_and_scales ( ) return np . random . normal ( means , scale , size = [ self . sims , means . shape [ 0 ] ] ) . T
def get_review_history_for ( brain_or_object ) : """Returns the review history list for the given object . If there is no review history for the object , it returns a default review history"""
workflow_history = api . get_object ( brain_or_object ) . workflow_history if not workflow_history : # No review _ history for this object ! . This object was probably # migrated to 1.3.0 before review _ history was handled in this # upgrade step . # https : / / github . com / senaite / senaite . core / issues / 1270 ...
def _handle_eio_disconnect ( self ) : """Handle the Engine . IO disconnection event ."""
self . logger . info ( 'Engine.IO connection dropped' ) for n in self . namespaces : self . _trigger_event ( 'disconnect' , namespace = n ) self . _trigger_event ( 'disconnect' , namespace = '/' ) self . callbacks = { } self . _binary_packet = None if self . eio . state == 'connected' and self . reconnection : ...
def _file_prefix ( self ) : """* Generate a file prefix based on the type of search for saving files to disk * * * Return : * * - ` ` prefix ` ` - - the file prefix"""
self . log . info ( 'starting the ``_file_prefix`` method' ) if self . ra : now = datetime . now ( ) prefix = now . strftime ( "%Y%m%dt%H%M%S%f_tns_conesearch_" ) elif self . name : prefix = self . name + "_tns_conesearch_" elif self . internal_name : prefix = self . internal_name + "_tns_conesearch_" e...
def _encode_buffer ( string , f ) : """Writes the bencoded form of the input string or bytes"""
if isinstance ( string , str ) : string = string . encode ( ) f . write ( str ( len ( string ) ) . encode ( ) ) f . write ( _TYPE_SEP ) f . write ( string )
def netconf_state_sessions_session_source_host ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) netconf_state = ET . SubElement ( config , "netconf-state" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring" ) sessions = ET . SubElement ( netconf_state , "sessions" ) session = ET . SubElement ( sessions , "session" ) session_id_key = ET . SubElement ( session , "sessi...
def vmstats ( ) : '''Return information about the virtual memory on the machine Returns : dict : A dictionary of virtual memory stats CLI Example : . . code - block : : bash salt * status . vmstats'''
# Setup the SPI Structure spi = SYSTEM_PERFORMANCE_INFORMATION ( ) retlen = ctypes . c_ulong ( ) # 2 means to query System Performance Information and return it in a # SYSTEM _ PERFORMANCE _ INFORMATION Structure ctypes . windll . ntdll . NtQuerySystemInformation ( 2 , ctypes . byref ( spi ) , ctypes . sizeof ( spi ) ,...
def def_attrs ( cls , ** kw ) : '''set attributes for class . @ param cls [ any class ] : the class to update the given attributes in . @ param kw [ dictionary ] : dictionary of attributes names and values . if the given class hasn ' t one ( or more ) of these attributes , add the attribute with its value to ...
for k , v in kw . iteritems ( ) : if not hasattr ( cls , k ) : setattr ( cls , k , v )
def from_rdata_list ( ttl , rdatas ) : """Create an rdataset with the specified TTL , and with the specified list of rdata objects . @ rtype : dns . rdataset . Rdataset object"""
if len ( rdatas ) == 0 : raise ValueError ( "rdata list must not be empty" ) r = None for rd in rdatas : if r is None : r = Rdataset ( rd . rdclass , rd . rdtype ) r . update_ttl ( ttl ) first_time = False r . add ( rd ) return r
def _set_ldp_gr ( self , v , load = False ) : """Setter method for ldp _ gr , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / ldp / ldp _ holder / ldp _ gr ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ldp _ gr is consi...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = ldp_gr . ldp_gr , is_container = 'container' , presence = True , yang_name = "ldp-gr" , rest_name = "graceful-restart" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = T...
def ls_dir ( base_dir ) : """List files recursively ."""
return [ os . path . join ( dirpath . replace ( base_dir , '' , 1 ) , f ) for ( dirpath , dirnames , files ) in os . walk ( base_dir ) for f in files ]
def find_callback ( args , kw = None ) : 'Return callback whether passed as a last argument or as a keyword'
if args and callable ( args [ - 1 ] ) : return args [ - 1 ] , args [ : - 1 ] try : return kw [ 'callback' ] , args except ( KeyError , TypeError ) : return None , args
def get_var_properties ( self ) : """Get some properties of the variables in the current namespace"""
from spyder_kernels . utils . nsview import get_remote_data settings = self . namespace_view_settings if settings : ns = self . _get_current_namespace ( ) data = get_remote_data ( ns , settings , mode = 'editable' , more_excluded_names = EXCLUDED_NAMES ) properties = { } for name , value in list ( data ...
def make_step_lcont ( transition ) : """Return a ufunc - like step function that is left - continuous . Returns 1 if x > transition , 0 otherwise ."""
if not np . isfinite ( transition ) : raise ValueError ( '"transition" argument must be finite number; got %r' % transition ) def step_lcont ( x ) : x = np . asarray ( x ) x1 = np . atleast_1d ( x ) r = ( x1 > transition ) . astype ( x . dtype ) if x . ndim == 0 : return np . asscalar ( r ) ...
def _encrypt_queue_message ( message , key_encryption_key ) : '''Encrypts the given plain text message using AES256 in CBC mode with 128 bit padding . Wraps the generated content - encryption - key using the user - provided key - encryption - key ( kek ) . Returns a json - formatted string containing the encryp...
_validate_not_none ( 'message' , message ) _validate_not_none ( 'key_encryption_key' , key_encryption_key ) _validate_key_encryption_key_wrap ( key_encryption_key ) # AES256 uses 256 bit ( 32 byte ) keys and always with 16 byte blocks content_encryption_key = os . urandom ( 32 ) initialization_vector = os . urandom ( 1...
def authenticate_admin ( self , transport , account_name , password ) : """Authenticates administrator using username and password ."""
Authenticator . authenticate_admin ( self , transport , account_name , password ) auth_token = AuthToken ( ) auth_token . account_name = account_name params = { sconstant . E_NAME : account_name , sconstant . E_PASSWORD : password } self . log . debug ( 'Authenticating admin %s' % account_name ) try : res = transpo...
def _normalize_field_name ( value ) : """Normalizing value string used as key and field name . : param value : String to normalize : type value : str : return : normalized string : rtype : str"""
# Replace non word / letter character return_value = re . sub ( r'[^\w\s-]+' , '' , value ) # Replaces whitespace with underscores return_value = re . sub ( r'\s+' , '_' , return_value ) return return_value . lower ( )
def get_plat_operator ( auth , url ) : """Funtion takes no inputs and returns a list of dictionaties of all of the operators currently configured on the HPE IMC system : param auth : requests auth object # usually auth . creds from auth pyhpeimc . auth . class : param url : base url of IMC RS interface # usua...
f_url = url + '/imcrs/plat/operator?start=0&size=1000&orderBy=id&desc=false&total=false' try : response = requests . get ( f_url , auth = auth , headers = HEADERS ) plat_oper_list = json . loads ( response . text ) [ 'operator' ] if isinstance ( plat_oper_list , dict ) : oper_list = [ plat_oper_list...
def _pys2col_widths ( self , line ) : """Updates col _ widths in code _ array"""
# Split with maxsplit 3 split_line = self . _split_tidy ( line ) key = col , tab = self . _get_key ( * split_line [ : 2 ] ) width = float ( split_line [ 2 ] ) shape = self . code_array . shape try : if col < shape [ 1 ] and tab < shape [ 2 ] : self . code_array . col_widths [ key ] = width except ValueError...
def lookup_ips ( ips ) : """Return set of host names that resolve to given ips ."""
hosts = set ( ) for ip in ips : try : hosts . add ( socket . gethostbyaddr ( ip ) [ 0 ] ) except socket . error : hosts . add ( ip ) return hosts
def bulkImport_json ( self , filename , onDuplicate = "error" , formatType = "auto" , ** params ) : """bulk import from a file repecting arango ' s key / value format"""
url = "%s/import" % self . database . URL params [ "onDuplicate" ] = onDuplicate params [ "collection" ] = self . name params [ "type" ] = formatType with open ( filename ) as f : data = f . read ( ) r = self . connection . session . post ( URL , params = params , data = data ) try : errorMessage = ...
def add_osm_layer ( self ) : """Add OSM tile layer to the map . This uses a gdal wrapper around the OSM tile service - see the WorldOSM . gdal file for how it is constructed ."""
path = resources_path ( 'osm' , 'WorldOSM.gdal' ) layer = QgsRasterLayer ( path , self . tr ( 'OpenStreetMap' ) ) project = QgsProject . instance ( ) # Try to add it as the last layer in the list # False flag prevents layer being added to legend project . addMapLayer ( layer , False ) root = QgsProject . instance ( ) ....
def dpt_timeseries ( adata , color_map = None , show = None , save = None , as_heatmap = True ) : """Heatmap of pseudotime series . Parameters as _ heatmap : bool ( default : False ) Plot the timeseries as heatmap ."""
if adata . n_vars > 100 : logg . warn ( 'Plotting more than 100 genes might take some while,' 'consider selecting only highly variable genes, for example.' ) # only if number of genes is not too high if as_heatmap : # plot time series as heatmap , as in Haghverdi et al . ( 2016 ) , Fig . 1d timeseries_as_heatma...
def createEditor ( self , parent , column , op , value ) : """Creates a new editor for the parent based on the plugin parameters . : param parent | < QWidget > : return < QWidget > | | None"""
try : cls = self . _operatorMap [ nativestring ( op ) ] . cls except KeyError , AttributeError : return None # create the new editor if cls : widget = cls ( parent ) widget . setAttribute ( Qt . WA_DeleteOnClose ) projexui . setWidgetValue ( widget , value ) return widget return None
def covariance_matrix ( nums_with_uncert ) : """Calculate the covariance matrix of uncertain variables , oriented by the order of the inputs Parameters nums _ with _ uncert : array - like A list of variables that have an associated uncertainty Returns cov _ matrix : 2d - array - like A nested list con...
ufuncs = list ( map ( to_uncertain_func , nums_with_uncert ) ) cov_matrix = [ ] for ( i1 , expr1 ) in enumerate ( ufuncs ) : coefs_expr1 = [ ] mean1 = expr1 . mean for ( i2 , expr2 ) in enumerate ( ufuncs [ : i1 + 1 ] ) : mean2 = expr2 . mean coef = np . mean ( ( expr1 . _mcpts - mean1 ) * (...
def side_chain ( self ) : """List of the side - chain atoms ( R - group ) . Notes Returns empty list for glycine . Returns side _ chain _ atoms : list ( ` Atoms ` )"""
side_chain_atoms = [ ] if self . mol_code != 'GLY' : covalent_bond_graph = generate_covalent_bond_graph ( find_covalent_bonds ( self ) ) try : subgraphs = generate_bond_subgraphs_from_break ( covalent_bond_graph , self [ 'CA' ] , self [ 'CB' ] ) if len ( subgraphs ) == 1 : subgraphs ...
def _check_error_response ( self , response , context ) : """Check if the response is an OAuth error response . : param response : the OIDC response : type response : oic . oic . message : raise SATOSAAuthenticationError : if the response is an OAuth error response"""
if "error" in response : satosa_logging ( logger , logging . DEBUG , "%s error: %s %s" % ( type ( response ) . __name__ , response [ "error" ] , response . get ( "error_description" , "" ) ) , context . state ) raise SATOSAAuthenticationError ( context . state , "Access denied" )
def __get_lowpoints ( node , dfs_data ) : """Calculates the lowpoints for a single node in a graph ."""
ordering_lookup = dfs_data [ 'ordering_lookup' ] t_u = T ( node , dfs_data ) sorted_t_u = sorted ( t_u , key = lambda a : ordering_lookup [ a ] ) lowpoint_1 = sorted_t_u [ 0 ] lowpoint_2 = sorted_t_u [ 1 ] return lowpoint_1 , lowpoint_2
def _load_training_state ( self , train_iter : data_io . BaseParallelSampleIter ) : """Loads the full training state from disk . : param train _ iter : training data iterator ."""
# (1 ) Parameters params_fname = os . path . join ( self . training_state_dirname , C . TRAINING_STATE_PARAMS_NAME ) self . model . load_params_from_file ( params_fname ) # (2 ) Optimizer states opt_state_fname = os . path . join ( self . training_state_dirname , C . OPT_STATES_LAST ) self . model . load_optimizer_stat...
def quantile ( self , q = 0.5 , axis = 0 , numeric_only = True , interpolation = "linear" ) : """Return values at the given quantile over requested axis , a la numpy . percentile . Args : q ( float ) : 0 < = q < = 1 , the quantile ( s ) to compute axis ( int ) : 0 or ' index ' for row - wise , 1 or ' colu...
axis = self . _get_axis_number ( axis ) if axis is not None else 0 def check_dtype ( t ) : return is_numeric_dtype ( t ) or is_datetime_or_timedelta_dtype ( t ) if not numeric_only : # If not numeric _ only and columns , then check all columns are either # numeric , timestamp , or timedelta if not axis and not ...
def validate_uses_tls_for_glance ( audit_options ) : """Verify that TLS is used to communicate with Glance ."""
section = _config_section ( audit_options , 'glance' ) assert section is not None , "Missing section 'glance'" assert not section . get ( 'insecure' ) and "https://" in section . get ( "api_servers" ) , "TLS is not used for Glance"
def connection_made ( self , transport ) : """Used to signal ` asyncio . Protocol ` of a successful connection ."""
self . _transport = transport self . _raw_transport = transport if isinstance ( transport , asyncio . SubprocessTransport ) : self . _transport = transport . get_pipe_transport ( 0 )
def environment_run ( up , down , sleep = None , endpoints = None , conditions = None , env_vars = None , wrapper = None ) : """This utility provides a convenient way to safely set up and tear down arbitrary types of environments . : param up : A custom setup callable . : type up : ` ` callable ` ` : param do...
if not callable ( up ) : raise TypeError ( 'The custom setup `{}` is not callable.' . format ( repr ( up ) ) ) elif not callable ( down ) : raise TypeError ( 'The custom tear down `{}` is not callable.' . format ( repr ( down ) ) ) conditions = list ( conditions ) if conditions is not None else [ ] if endpoints...
def django_object_from_row ( row , model , field_names = None , ignore_fields = ( 'id' , 'pk' ) , ignore_related = True , strip = True , ignore_errors = True , verbosity = 0 ) : """Construct Django model instance from values provided in a python dict or Mapping Args : row ( list or dict ) : Data ( values of any...
field_dict , errors = field_dict_from_row ( row , model , field_names = field_names , ignore_fields = ignore_fields , strip = strip , ignore_errors = ignore_errors , ignore_related = ignore_related , verbosity = verbosity ) if verbosity >= 3 : print 'field_dict = %r' % field_dict try : obj = model ( ** field_di...
def run_sweep ( self , program : Union [ circuits . Circuit , schedules . Schedule ] , params : study . Sweepable , repetitions : int = 1 , ) -> List [ study . TrialResult ] : """Samples from the given Circuit or Schedule . In contrast to run , this allows for sweeping over different parameter values . Args :...
def clear ( self ) : """calls clear on any report format instances created during setup and drops the cache"""
if self . _formats : for fmt in self . _formats : fmt . clear ( ) self . _formats = None
def mouseMoveEvent ( self , event ) : """Handle mouse over file link ."""
c = self . cursorForPosition ( event . pos ( ) ) block = c . block ( ) self . _link_match = None self . viewport ( ) . setCursor ( QtCore . Qt . IBeamCursor ) for match in self . link_regex . finditer ( block . text ( ) ) : if not match : continue start , end = match . span ( ) if start <= c . posit...
def _is_text_file ( filename ) : '''Checks if a file is a text file'''
type_of_file = os . popen ( 'file -bi {0}' . format ( filename ) , 'r' ) . read ( ) return type_of_file . startswith ( 'text' )
def label_saves ( name ) : """Labels plots and saves file"""
plt . legend ( loc = 0 ) plt . ylim ( [ 0 , 1.025 ] ) plt . xlabel ( '$U/D$' , fontsize = 20 ) plt . ylabel ( '$Z$' , fontsize = 20 ) plt . savefig ( name , dpi = 300 , format = 'png' , transparent = False , bbox_inches = 'tight' , pad_inches = 0.05 )
def tail ( filepath = "log.txt" , lines = 50 ) : """Return a specified number of last lines of a specified file . If there is an error or the file does not exist , return False ."""
try : filepath = os . path . expanduser ( os . path . expandvars ( filepath ) ) if os . path . isfile ( filepath ) : text = subprocess . check_output ( [ "tail" , "-" + str ( lines ) , filepath ] ) if text : return text else : return False else : retur...
def set ( self , subname , value ) : '''Set the data ignoring the sign , ie set ( " test " , - 1 ) will set " test " exactly to - 1 ( not decrement it by 1) See https : / / github . com / etsy / statsd / blob / master / docs / metric _ types . md " Adding a sign to the gauge value will change the value , rath...
assert isinstance ( value , compat . NUM_TYPES ) if value < 0 : self . _send ( subname , 0 ) return self . _send ( subname , value )
def create_hipersocket ( self , properties ) : """Create and configure a HiperSockets Adapter in this CPC . Authorization requirements : * Object - access permission to the scoping CPC . * Task permission to the " Create HiperSockets Adapter " task . Parameters : properties ( dict ) : Initial property val...
result = self . session . post ( self . cpc . uri + '/adapters' , body = properties ) # There should not be overlaps , but just in case there are , the # returned props should overwrite the input props : props = copy . deepcopy ( properties ) props . update ( result ) name = props . get ( self . _name_prop , None ) uri...
def get_order_history ( self , market = None ) : """Used to retrieve order trade history of account Endpoint : 1.1 / account / getorderhistory 2.0 / key / orders / getorderhistory or / key / market / GetOrderHistory : param market : optional a string literal for the market ( ie . BTC - LTC ) . If omitted ...
if market : return self . _api_query ( path_dict = { API_V1_1 : '/account/getorderhistory' , API_V2_0 : '/key/market/GetOrderHistory' } , options = { 'market' : market , 'marketname' : market } , protection = PROTECTION_PRV ) else : return self . _api_query ( path_dict = { API_V1_1 : '/account/getorderhistory' ...
def get_case_lists ( study_id ) : """Return a list of the case set ids for a particular study . TAKE NOTE the " case _ list _ id " are the same thing as " case _ set _ id " Within the data , this string is referred to as a " case _ list _ id " . Within API calls it is referred to as a ' case _ set _ id ' . ...
data = { 'cmd' : 'getCaseLists' , 'cancer_study_id' : study_id } df = send_request ( ** data ) case_set_ids = df [ 'case_list_id' ] . tolist ( ) return case_set_ids
def _recursive_work_resolver ( self , worker_name , md5 ) : """Internal : Input dependencies are recursively backtracked , invoked and then passed down the pipeline until getting to the requested worker ."""
# Looking for the sample ? if worker_name == 'sample' : return self . get_sample ( md5 ) # Looking for info ? if worker_name == 'info' : return self . _get_work_results ( 'info' , md5 ) # Looking for tags ? if worker_name == 'tags' : return self . _get_work_results ( 'tags' , md5 ) # Do I actually have this...
def add_hyperedge ( self , hyperedge ) : """Add given hyperedge to the hypergraph . @ attention : While hyperedge - nodes can be of any type , it ' s strongly recommended to use only numbers and single - line strings as node identifiers if you intend to use write ( ) . @ type hyperedge : hyperedge @ param h...
if ( not hyperedge in self . edge_links ) : self . edge_links [ hyperedge ] = [ ] self . graph . add_node ( ( hyperedge , 'h' ) )
def buttons ( self , master ) : '''Add a standard button box . Override if you do not want the standard buttons'''
box = tk . Frame ( master ) ttk . Button ( box , text = "Next" , width = 10 , command = self . next_day ) . pack ( side = tk . LEFT , padx = 5 , pady = 5 ) ttk . Button ( box , text = "OK" , width = 10 , command = self . ok , default = tk . ACTIVE ) . pack ( side = tk . LEFT , padx = 5 , pady = 5 ) ttk . Button ( box ,...
def efficient_risk ( self , target_risk , risk_free_rate = 0.02 , market_neutral = False ) : """Calculate the Sharpe - maximising portfolio for a given volatility ( i . e max return for a target risk ) . : param target _ risk : the desired volatility of the resulting portfolio . : type target _ risk : float ...
if not isinstance ( target_risk , float ) or target_risk < 0 : raise ValueError ( "target_risk should be a positive float" ) if not isinstance ( risk_free_rate , ( int , float ) ) : raise ValueError ( "risk_free_rate should be numeric" ) args = ( self . expected_returns , self . cov_matrix , self . gamma , risk...
def _filter_rows ( self , rows ) : """Filter ` rows ` based on the visible columns ."""
filtered_rows = [ ] for row in rows : filtered_row = [ ] for idx , name in enumerate ( self . columns . keys ( ) ) : if name in self . visible_columns : filtered_row . append ( row [ idx ] ) filtered_rows . append ( filtered_row ) return filtered_rows
def form_valid ( self , form , formsets ) : """Response for valid form . In one transaction this will save the current form and formsets , log the action and message the user . Returns the results of calling the ` success _ response ` method ."""
# check if it ' s a new object before it save the form new_object = False if not self . object : new_object = True instance = getattr ( form , 'instance' , None ) auto_tags , changed_tags , old_tags = tag_handler . get_tags_from_data ( form . data , self . get_tags ( instance ) ) tag_handler . set_auto_tags_for_for...
def get_vip_settings ( vip ) : """Calculate which nic is on the correct network for the given vip . If nic or netmask discovery fail then fallback to using charm supplied config . If fallback is used this is indicated via the fallback variable . @ param vip : VIP to lookup nic and cidr for . @ returns ( str...
iface = get_iface_for_address ( vip ) netmask = get_netmask_for_address ( vip ) fallback = False if iface is None : iface = config ( 'vip_iface' ) fallback = True if netmask is None : netmask = config ( 'vip_cidr' ) fallback = True return iface , netmask , fallback
def describe ( cwd , rev = 'tip' , user = None ) : '''Mimic git describe and return an identifier for the given revision cwd The path to the Mercurial repository rev : tip The path to the archive tarball user : None Run hg as a user other than what the minion runs as CLI Example : . . code - block :...
cmd = [ 'hg' , 'log' , '-r' , '{0}' . format ( rev ) , '--template' , "'{{latesttag}}-{{latesttagdistance}}-{{node|short}}'" ] desc = __salt__ [ 'cmd.run_stdout' ] ( cmd , cwd = cwd , runas = user , python_shell = False ) return desc or revision ( cwd , rev , short = True )
def on_get ( resc , req , resp ) : """Get the models identified by query parameters We return an empty list if no models are found ."""
signals . pre_req . send ( resc . model ) signals . pre_req_search . send ( resc . model ) models = goldman . sess . store . search ( resc . rtype , ** { 'filters' : req . filters , 'pages' : req . pages , 'sorts' : req . sorts , } ) props = to_rest_models ( models , includes = req . includes ) resp . serialize ( props...
def query_total_cat_recent_no_label ( cat_id_arr , num = 8 , kind = '1' ) : ''': param cat _ id _ arr : list of categories . [ ' 0101 ' , ' 0102 ' ]'''
return TabPost . select ( ) . join ( TabPost2Tag , on = ( TabPost . uid == TabPost2Tag . post_id ) ) . where ( ( TabPost . kind == kind ) & ( TabPost2Tag . tag_id << cat_id_arr ) # the " < < " operator signifies an " IN " query ) . order_by ( TabPost . time_create . desc ( ) ) . limit ( num )
def add_to_object ( self , target : object , override : bool = False ) -> int : """Add the bindings to the target object : param target : target to add to : param override : override existing bindings if they are of type Namespace : return : number of items actually added"""
nret = 0 for k , v in self : key = k . upper ( ) exists = hasattr ( target , key ) if not exists or ( override and isinstance ( getattr ( target , k ) , ( Namespace , _RDFNamespace ) ) ) : setattr ( target , k , v ) nret += 1 else : print ( f"Warning: {key} is already defined in ...
def get_assessment_part_item_session ( self , proxy ) : """Gets the ` ` OsidSession ` ` associated with the assessment part item service . return : ( osid . assessment . authoring . AssessmentPartItemSession ) - an ` ` AssessmentPartItemSession ` ` raise : OperationFailed - unable to complete request raise ...
if not self . supports_assessment_part_lookup ( ) : # This is kludgy , but only until Tom fixes spec raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . AssessmentPartItemSession ( proxy = proxy , runtime = self . _runtime )
def arc_center ( points ) : """Given three points on an arc find : center , radius , normal , and angle . This uses the fact that the intersection of the perp bisectors of the segments between the control points is the center of the arc . Parameters points : ( 3 , dimension ) float Points in space , w...
# it ' s a lot easier to treat 2D as 3D with a zero Z value points , is_2D = util . stack_3D ( points , return_2D = True ) # find the two edge vectors of the triangle edge_direction = np . diff ( points , axis = 0 ) edge_midpoints = ( edge_direction * 0.5 ) + points [ : 2 ] # three points define a plane , so we find it...
def hpsplit ( self , data : [ 'SASdata' , str ] = None , cls : [ str , list ] = None , code : str = None , grow : str = None , id : str = None , input : [ str , list , dict ] = None , model : str = None , out : [ str , bool , 'SASdata' ] = None , partition : str = None , performance : str = None , prune : str = None , ...
def lt ( self , v , limit = None , offset = None ) : """Returns the list of the members of the set that have scores less than v ."""
if limit is not None and offset is None : offset = 0 return self . zrangebyscore ( self . _min_score , "(%f" % v , start = offset , num = limit )
def sh ( cmd , ignore_error = False , cwd = None , shell = False , ** kwargs ) : """Execute a command with subprocess . Popen and block until output Args : cmd ( tuple or str ) : same as subprocess . Popen args Keyword Arguments : ignore _ error ( bool ) : if False , raise an Exception if p . returncode is ...
kwargs . update ( { 'shell' : shell , 'cwd' : cwd , 'stderr' : subprocess . STDOUT , 'stdout' : subprocess . PIPE , } ) log . debug ( ( ( 'cmd' , cmd ) , ( 'kwargs' , kwargs ) ) ) p = subprocess . Popen ( cmd , universal_newlines = True , ** kwargs ) p_stdout = p . communicate ( ) [ 0 ] if p . returncode and not ignore...
def simToReg ( self , sim ) : """Convert simplified domain expression to regular expression"""
# remove initial slash if present res = re . sub ( '^/' , '' , sim ) res = re . sub ( '/$' , '' , res ) return '^/?' + re . sub ( '\*' , '[^/]+' , res ) + '/?$'
def parse ( self ) : """parse the data"""
wb = load_workbook ( self . getInputFile ( ) ) sheet = wb . worksheets [ 0 ] sample_id = None cnt = 0 for row in sheet . rows : # sampleid is only present in first row of each sample . # any rows above the first sample id are ignored . if row [ 1 ] . value : sample_id = row [ 1 ] . value if not sample_i...
def response ( code , body = '' , etag = None , last_modified = None , expires = None , ** kw ) : """Helper to build an HTTP response . Parameters : code : An integer status code . body : The response body . See ` Response . _ _ init _ _ ` for details . etag : A value for the ETag header . Double quot...
if etag is not None : if not ( etag [ 0 ] == '"' and etag [ - 1 ] == '"' ) : etag = '"%s"' % etag kw [ 'etag' ] = etag if last_modified is not None : kw [ 'last_modified' ] = datetime_to_httpdate ( last_modified ) if expires is not None : if isinstance ( expires , datetime ) : kw [ 'expi...
def clear_droppables ( self ) : """stub"""
if self . get_droppables_metadata ( ) . is_read_only ( ) : raise NoAccess ( ) self . my_osid_object_form . _my_map [ 'droppables' ] = self . _droppables_metadata [ 'default_object_values' ] [ 0 ]
def __parameter_default ( self , field ) : """Returns default value of field if it has one . Args : field : A simple field . Returns : The default value of the field , if any exists , with the exception of an enum field , which will have its value cast to a string ."""
if field . default : if isinstance ( field , messages . EnumField ) : return field . default . name elif isinstance ( field , messages . BooleanField ) : # The Python standard representation of a boolean value causes problems # when generating client code . return 'true' if field . default e...
def extract_profiles ( self , pipeline_name , expose_data = True ) : """Extract all the profiles of a specific pipeline and exposes the data in the namespace"""
compas_pipe = self . __profile_definition ( pipeline_name ) get_variable = compas_pipe . GEtUserVariable if os . path . isdir ( self . path + 'profiles' ) is not True : os . mkdir ( self . path + 'profiles' ) target_dir = self . path + 'profiles' if expose_data is True : self . profiles [ pipeline_name ] = { } ...
def filter_events ( cls , client , event_data ) : """Filter registered events and yield them ."""
for event in cls . events : # try event filters if event . matches ( client , event_data ) : yield event
def mulmod ( computation : BaseComputation ) -> None : """Modulo Multiplication"""
left , right , mod = computation . stack_pop ( num_items = 3 , type_hint = constants . UINT256 ) if mod == 0 : result = 0 else : result = ( left * right ) % mod computation . stack_push ( result )
def CreateHttpHeader ( self ) : """Creates an OAuth2 HTTP header . The OAuth2 credentials will be refreshed as necessary . In the event that the credentials fail to refresh , a message is logged but no exception is raised . Returns : A dictionary containing one entry : the OAuth2 Bearer header under the ...
oauth2_header = { } if self . creds . expiry is None or self . creds . expired : self . Refresh ( ) self . creds . apply ( oauth2_header ) return oauth2_header
def read_jsonld ( ) : """Find jsonld file in the cwd ( or within a 2 levels below cwd ) , and load it in . : return dict : Jsonld data"""
_d = { } try : # Find a jsonld file in cwd . If none , fallback for a json file . If neither found , return empty . _filename = [ file for file in os . listdir ( ) if file . endswith ( ".jsonld" ) ] [ 0 ] if not _filename : _filename = [ file for file in os . listdir ( ) if file . endswith ( ".json" ) ]...
def parseStr ( self , html ) : '''parseStr - Parses a string and creates the DOM tree and indexes . @ param html < str > - valid HTML'''
self . reset ( ) if isinstance ( html , bytes ) : self . feed ( html . decode ( self . encoding ) ) else : self . feed ( html )
def sync_druid_source ( self ) : """Syncs the druid datasource in main db with the provided config . The endpoint takes 3 arguments : user - user name to perform the operation as cluster - name of the druid cluster config - configuration stored in json that contains : name : druid datasource name dimens...
payload = request . get_json ( force = True ) druid_config = payload [ 'config' ] user_name = payload [ 'user' ] cluster_name = payload [ 'cluster' ] user = security_manager . find_user ( username = user_name ) DruidDatasource = ConnectorRegistry . sources [ 'druid' ] DruidCluster = DruidDatasource . cluster_class if n...