signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def load ( self , file_parser , section_name ) : """The current element is loaded from the configuration file , all constraints and requirements are checked . Then element hooks are applied ."""
self . _load ( file_parser , section_name ) self . post_load ( )
def transform ( self , X , y = None , sample_weight = None ) : '''Transforms the time series data into fixed length segments using padding and or truncation If y is a time series and passed , it will be transformed as well Parameters X : array - like , shape [ n _ series , . . . ] Time series data and ( opt...
check_ts_data ( X , y ) Xt , Xc = get_ts_data_parts ( X ) yt = y swt = sample_weight Xt = self . _mv_resize ( Xt ) if Xc is not None : Xt = TS_Data ( Xt , Xc ) if yt is not None and len ( np . atleast_1d ( yt [ 0 ] ) ) > 1 : # y is a time series yt = self . _mv_resize ( yt ) swt = None elif yt is not None :...
def _request ( self , text , properties , retries = 0 ) : """Send a request to the CoreNLP server . : param ( str | unicode ) text : raw text for the CoreNLPServer to parse : param ( dict ) properties : properties that the server expects : return : request result"""
text = to_unicode ( text ) # ensures unicode try : r = requests . post ( self . server , params = { 'properties' : str ( properties ) } , data = text . encode ( 'utf-8' ) ) r . raise_for_status ( ) return r except requests . ConnectionError as e : if retries > 5 : logging . critical ( 'Max retri...
def reset ( self ) : """Resets the values to the current application information ."""
self . setValue ( 'colorSet' , XPaletteColorSet ( ) ) self . setValue ( 'font' , QApplication . font ( ) ) self . setValue ( 'fontSize' , QApplication . font ( ) . pointSize ( ) )
def rgb2hsv ( arr ) : """Converts an RGB image to HSV using scikit - image ' s algorithm ."""
arr = np . asanyarray ( arr ) if arr . ndim != 3 or arr . shape [ 2 ] != 3 : raise ValueError ( "the input array must have a shape == (.,.,3)" ) arr = as_float_image ( arr ) out = np . empty_like ( arr ) # - - V channel out_v = arr . max ( - 1 ) # - - S channel delta = arr . ptp ( - 1 ) # Ignore warning for zero di...
def generate ( env ) : """Add Builders and construction variables for jar to an Environment ."""
SCons . Tool . CreateJarBuilder ( env ) SCons . Tool . CreateJavaFileBuilder ( env ) SCons . Tool . CreateJavaClassFileBuilder ( env ) SCons . Tool . CreateJavaClassDirBuilder ( env ) env . AddMethod ( Jar ) env [ 'JAR' ] = 'jar' env [ 'JARFLAGS' ] = SCons . Util . CLVar ( 'cf' ) env [ '_JARFLAGS' ] = jarFlags env [ '_...
def K ( self , X , X2 , target ) : """Compute the covariance matrix between X and X2."""
AX = np . dot ( X , self . transform ) if X2 is None : X2 = X AX2 = AX else : AX2 = np . dot ( X2 , self . transform ) self . k . K ( X , X2 , target ) self . k . K ( AX , X2 , target ) self . k . K ( X , AX2 , target ) self . k . K ( AX , AX2 , target )
def run ( self , lines ) : """Filter method"""
ret = [ ] for line in lines : while True : match = re . search ( r'\[(.*?)\]\((.*?\.md)\)' , line ) if match != None : title = match . group ( 1 ) line = re . sub ( r'\[.*?\]\(.*?\.md\)' , title , line , count = 1 ) else : break ret . append ( line ) r...
def cmd_iter ( tgt , fun , arg = ( ) , timeout = None , tgt_type = 'glob' , ret = '' , kwarg = None , ssh = False , ** kwargs ) : '''. . versionchanged : : 2017.7.0 The ` ` expr _ form ` ` argument has been renamed to ` ` tgt _ type ` ` , earlier releases must use ` ` expr _ form ` ` . Assuming this minion is...
if ssh : client = salt . client . ssh . client . SSHClient ( __opts__ [ 'conf_file' ] ) else : client = salt . client . get_local_client ( __opts__ [ 'conf_file' ] ) for ret in client . cmd_iter ( tgt , fun , arg , timeout , tgt_type , ret , kwarg , ** kwargs ) : yield ret
def uninstall_all_integration_alerts ( self , id , ** kwargs ) : # noqa : E501 """Disable all alerts associated with this integration # 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...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . uninstall_all_integration_alerts_with_http_info ( id , ** kwargs ) # noqa : E501 else : ( data ) = self . uninstall_all_integration_alerts_with_http_info ( id , ** kwargs ) # noqa : E501 return data
def convenience_calc_log_likelihood ( self , params ) : """Calculates the log - likelihood for this model and dataset ."""
shapes , intercepts , betas = self . convenience_split_params ( params ) args = [ betas , self . design , self . alt_id_vector , self . rows_to_obs , self . rows_to_alts , self . choice_vector , self . utility_transform ] kwargs = { "intercept_params" : intercepts , "shape_params" : shapes , "ridge" : self . ridge , "w...
def srem ( self , key , * values ) : """Emulate srem ."""
redis_set = self . _get_set ( key , 'SREM' ) if not redis_set : return 0 before_count = len ( redis_set ) for value in values : redis_set . discard ( self . _encode ( value ) ) after_count = len ( redis_set ) if before_count > 0 and len ( redis_set ) == 0 : self . delete ( key ) return before_count - after_...
def decode ( self , s , _w = WHITESPACE . match , _PY3 = PY3 ) : """Return the Python representation of ` ` s ` ` ( a ` ` str ` ` or ` ` unicode ` ` instance containing a JSON document )"""
if _PY3 and isinstance ( s , binary_type ) : s = s . decode ( self . encoding ) obj , end = self . raw_decode ( s ) end = _w ( s , end ) . end ( ) if end != len ( s ) : raise JSONDecodeError ( "Extra data" , s , end , len ( s ) ) return obj
def convert ( document , canvas , items = None , tounicode = None ) : """Convert ' items ' stored in ' canvas ' to SVG ' document ' . If ' items ' is None , then all items are convered . tounicode is a function that get text and returns it ' s unicode representation . It should be used when national charact...
tk = canvas . tk global segment if items is None : # default : all items items = canvas . find_all ( ) supported_item_types = set ( [ "line" , "oval" , "polygon" , "rectangle" , "text" , "arc" ] ) if tounicode is None : try : # python3 bytes tounicode = lambda x : x except NameError : # pyth...
def _generic_action_parser ( self ) : """Generic parser for Actions ."""
actions = [ ] while True : action_code = unpack_ui8 ( self . _src ) if action_code == 0 : break action_name = ACTION_NAMES [ action_code ] if action_code > 128 : # have a payload ! action_len = unpack_ui16 ( self . _src ) try : action_meth = getattr ( self , "_handle_...
def build_responses ( self ) : """DNS measurement results are a little wacky . Sometimes you get a single response , other times you get a set of responses ( result set ) . In order to establish a unified interface , we conform all results to the same format : a list of response objects . Additionally , the...
responses = [ ] part_of_set = True # Account for single results if "result" in self . raw_data : if "qbuf" in self . raw_data : if "qbuf" not in self . raw_data [ "result" ] : self . raw_data [ "result" ] [ "qbuf" ] = self . raw_data . pop ( "qbuf" ) responses . append ( self . raw_data [ "r...
def protocol ( handler , cfg ) : """Run all the stages in protocol Parameters handler : SystemHandler Container of initial conditions of simulation cfg : dict Imported YAML file ."""
# Stages if 'stages' not in cfg : raise ValueError ( 'Protocol must include stages of simulation' ) pos , vel , box = handler . positions , handler . velocities , handler . box stages = cfg . pop ( 'stages' ) for stage_options in stages : options = DEFAULT_OPTIONS . copy ( ) options . update ( cfg ) sta...
def _build_parser ( ) : """Return a command - line arguments parser ."""
parser = argparse . ArgumentParser ( description = 'Search you Azure AD contacts from mutt or the command-line.' ) parser . add_argument ( '-c' , '--config' , help = 'Specify alternative configuration file.' , metavar = "FILE" ) parser . add_argument ( '-v' , '--verbose' , dest = "log_level" , action = 'store_const' , ...
def ok ( message ) : """prints an ok message : param message : the message < : return :"""
message = message or "" if Console . color : Console . cprint ( 'OKGREEN' , "" , message ) else : print ( Console . msg ( message ) )
def validate_steps ( self , request , workflow , start , end ) : """Validates the workflow steps from ` ` start ` ` to ` ` end ` ` , inclusive . Returns a dict describing the validation state of the workflow ."""
errors = { } for step in workflow . steps [ start : end + 1 ] : if not step . action . is_valid ( ) : errors [ step . slug ] = dict ( ( field , [ six . text_type ( error ) for error in errors ] ) for ( field , errors ) in step . action . errors . items ( ) ) return { 'has_errors' : bool ( errors ) , 'workfl...
def minimumLineInArray ( arr , relative = False , f = 0 , refinePosition = True , max_pos = 100 , return_pos_arr = False , # order = 2 ) : '''find closest minimum position next to middle line relative : return position relative to middle line f : relative decrease ( 0 . . . 1 ) - setting this value close to one...
s0 , s1 = arr . shape [ : 2 ] if max_pos >= s1 : x = np . arange ( s1 ) else : # take fewer positions within 0 - > ( s1-1) x = np . rint ( np . linspace ( 0 , s1 - 1 , min ( max_pos , s1 ) ) ) . astype ( int ) res = np . empty ( ( s0 , s0 ) , dtype = float ) _lineSumXY ( x , res , arr , f ) if return_pos_arr : ...
def expr ( s ) : """Construct a function operating on a table record . The expression string is converted into a lambda function by prepending the string with ` ` ' lambda rec : ' ` ` , then replacing anything enclosed in curly braces ( e . g . , ` ` " { foo } " ` ` ) with a lookup on the record ( e . g . , ...
prog = re . compile ( '\{([^}]+)\}' ) def repl ( matchobj ) : return "rec['%s']" % matchobj . group ( 1 ) return eval ( "lambda rec: " + prog . sub ( repl , s ) )
def _construct_register ( reg , default_reg ) : """Constructs a register dict ."""
if reg : x = dict ( ( k , reg . get ( k , d ) ) for k , d in default_reg . items ( ) ) else : x = dict ( default_reg ) return x
def is_possible ( self ) -> bool : """: return : True / False based on the existence of solution of constraints"""
if self . _is_possible is not None : return self . _is_possible solver = Solver ( ) solver . set_timeout ( self . _default_timeout ) for constraint in self [ : ] : constraint = ( symbol_factory . Bool ( constraint ) if isinstance ( constraint , bool ) else constraint ) solver . add ( constraint ) self . _is...
def _dump ( self ) : """For debugging , dump the entire data structure ."""
pp = pprint . PrettyPrinter ( indent = 4 ) print ( "=== Variables ===" ) print ( "-- Globals --" ) pp . pprint ( self . _global ) print ( "-- Bot vars --" ) pp . pprint ( self . _var ) print ( "-- Substitutions --" ) pp . pprint ( self . _sub ) print ( "-- Person Substitutions --" ) pp . pprint ( self . _person ) print...
def MultiResolve ( self , records ) : """Lookup multiple values by their record objects ."""
for value , timestamp in data_store . DB . CollectionReadItems ( records ) : rdf_value = self . RDF_TYPE . FromSerializedString ( value ) rdf_value . age = timestamp yield rdf_value
def checkAndCreate ( self , key , payload , domainId ) : """Function checkAndCreate Check if a subnet exists and create it if not @ param key : The targeted subnet @ param payload : The targeted subnet description @ param domainId : The domainId to be attached wiuth the subnet @ return RETURN : The id of ...
if key not in self : self [ key ] = payload oid = self [ key ] [ 'id' ] if not oid : return False # ~ Ensure subnet contains the domain subnetDomainIds = [ ] for domain in self [ key ] [ 'domains' ] : subnetDomainIds . append ( domain [ 'id' ] ) if domainId not in subnetDomainIds : subnetDomainIds . app...
def main ( ) : """standalone line script"""
print ( "Ontospy " + VERSION ) Shell ( ) . _clear_screen ( ) print ( Style . BRIGHT + "** Ontospy Interactive Ontology Browser " + VERSION + " **" + Style . RESET_ALL ) # manager . get _ or _ create _ home _ repo ( ) Shell ( ) . cmdloop ( ) raise SystemExit ( 1 )
def _get_code_w_scope ( data , position , obj_end , opts , element_name ) : """Decode a BSON code _ w _ scope to bson . code . Code ."""
code_end = position + _UNPACK_INT ( data [ position : position + 4 ] ) [ 0 ] code , position = _get_string ( data , position + 4 , code_end , opts , element_name ) scope , position = _get_object ( data , position , code_end , opts , element_name ) if position != code_end : raise InvalidBSON ( 'scope outside of java...
def _chown_workdir ( work_dir ) : """Ensure work directory files owned by original user . Docker runs can leave root owned files making cleanup difficult . Skips this if it fails , avoiding errors where we run remotely and don ' t have docker locally ."""
cmd = ( """docker run --rm -v %s:%s quay.io/bcbio/bcbio-base /bin/bash -c 'chown -R %s %s'""" % ( work_dir , work_dir , os . getuid ( ) , work_dir ) ) try : subprocess . check_call ( cmd , shell = True ) except subprocess . CalledProcessError : pass
def global_get ( self , key ) : """Return the value for the given key in the ` ` globals ` ` table ."""
key = self . pack ( key ) r = self . sql ( 'global_get' , key ) . fetchone ( ) if r is None : raise KeyError ( "Not set" ) return self . unpack ( r [ 0 ] )
def apps ( self ) : """List of : class : ` Application ` for this : class : ` MultiApp ` . The list is lazily loaded from the : meth : ` build ` method ."""
if self . _apps is None : # Add modified settings values to the list of cfg params self . cfg . params . update ( ( ( s . name , s . value ) for s in self . cfg . settings . values ( ) if s . modified ) ) self . cfg . settings = { } self . _apps = OrderedDict ( ) self . _apps . update ( self . _build ( ...
def send_dynamic_message ( sender , message ) : """Send a dynamic message to the listeners . Dynamic messages represents a progress . Usually it will be appended to the previous messages . . . versionadded : : 3.3 : param sender : The sender . : type sender : object : param message : An instance of our ...
dispatcher . send ( signal = DYNAMIC_MESSAGE_SIGNAL , sender = sender , message = message )
def main ( ) : """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send email messages ! : return : None"""
log = logging . getLogger ( mod_logger + '.main' ) parser = argparse . ArgumentParser ( description = 'This module allows sending email messages.' ) parser . add_argument ( '-f' , '--file' , help = 'Full path to a plain text file' , required = False ) parser . add_argument ( '-s' , '--sender' , help = 'Email address of...
def _set_mrouter ( self , v , load = False ) : """Setter method for mrouter , mapped from YANG variable / interface _ vlan / interface / vlan / ipv6 / mldVlan / snooping / mrouter ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ mrouter is considered as a p...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = mrouter . mrouter , is_container = 'container' , presence = False , yang_name = "mrouter" , rest_name = "mrouter" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True ,...
def _get_responses ( cls , requests , dispatcher ) : """Response to each single JSON - RPC Request . : return iterator ( JSONRPC20Response ) : . . versionadded : 1.9.0 TypeError inside the function is distinguished from Invalid Params ."""
for request in requests : def response ( ** kwargs ) : return cls . RESPONSE_CLASS_MAP [ request . JSONRPC_VERSION ] ( _id = request . _id , ** kwargs ) try : method = dispatcher [ request . method ] except KeyError : output = response ( error = JSONRPCMethodNotFound ( ) . _data ) ...
def reserve ( self , doc ) : """Reserve a DOI ( amounts to upload metadata , but not to mint ) . : param doc : Set metadata for DOI . : returns : ` True ` if is reserved successfully ."""
# Only registered PIDs can be updated . try : self . pid . reserve ( ) self . api . metadata_post ( doc ) except ( DataCiteError , HttpError ) : logger . exception ( "Failed to reserve in DataCite" , extra = dict ( pid = self . pid ) ) raise logger . info ( "Successfully reserved in DataCite" , extra = ...
def stem ( self , word ) : """Stem a Russian word and return the stemmed form . : param word : The word that is stemmed . : type word : str or unicode : return : The stemmed form . : rtype : unicode"""
chr_exceeded = False for i in range ( len ( word ) ) : if ord ( word [ i ] ) > 255 : chr_exceeded = True break if chr_exceeded : word = self . __cyrillic_to_roman ( word ) step1_success = False adjectival_removed = False verb_removed = False undouble_success = False superlative_removed = False r...
def _double_cross_over_cz ( op : ops . Operation , state : _OptimizerState ) -> None : """Crosses two W flips over a partial CZ . [ Where W ( a ) is shorthand for PhasedX ( phase _ exponent = a ) . ] Uses the following identity : ─ ─ ─ W ( a ) ─ ─ ─ @ ─ ─ ─ ─ ─ ─ ─ ─ W ( b ) ─ ─ ─ @ ^ t ─ ─ ─ ≡ ─ ─ ─ ─ ─ ...
t = cast ( float , _try_get_known_cz_half_turns ( op ) ) for q in op . qubits : state . held_w_phases [ q ] = cast ( float , state . held_w_phases [ q ] ) + t / 2
def maps_get_rules_output_rules_timebase ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) maps_get_rules = ET . Element ( "maps_get_rules" ) config = maps_get_rules output = ET . SubElement ( maps_get_rules , "output" ) rules = ET . SubElement ( output , "rules" ) timebase = ET . SubElement ( rules , "timebase" ) timebase . text = kwargs . pop ( 'timebase' ) callback = kwa...
def _validate_image_rank ( self , img_array ) : """Images must be either 2D or 3D ."""
if img_array . ndim == 1 or img_array . ndim > 3 : msg = "{0}D imagery is not allowed." . format ( img_array . ndim ) raise IOError ( msg )
def to_rawtx ( tx ) : """Take a tx object in the moneywagon format and convert it to the format that pybitcointools ' s ` serialize ` funcion takes , then return in raw hex format ."""
if tx . get ( 'hex' ) : return tx [ 'hex' ] new_tx = { } locktime = tx . get ( 'locktime' , 0 ) new_tx [ 'locktime' ] = locktime new_tx [ 'version' ] = tx . get ( 'version' , 1 ) new_tx [ 'ins' ] = [ { 'outpoint' : { 'hash' : str ( x [ 'txid' ] ) , 'index' : x [ 'n' ] } , 'script' : str ( x [ 'scriptSig' ] . replac...
def private_keys ( self ) : """A subset of the : attr : ` entries ` dictionary , filtered down to only those entries of type : class : ` PrivateKeyEntry ` ."""
return dict ( [ ( a , e ) for a , e in self . entries . items ( ) if isinstance ( e , PrivateKeyEntry ) ] )
def create_static_profile_path ( client_id ) : """Create a profile path folder if not exist @ param client _ id : ID of client user @ return string profile path"""
profile_path = os . path . join ( STATIC_FILES_PATH , str ( client_id ) ) if not os . path . exists ( profile_path ) : os . makedirs ( profile_path ) return profile_path
def _filter ( client , names = None , authors = None , include = None , exclude = None ) : """Filter dataset files by specified filters . : param names : Filter by specified dataset names . : param authors : Filter by authors . : param include : Include files matching file pattern . : param exclude : Exclud...
if isinstance ( authors , str ) : authors = set ( authors . split ( ',' ) ) if isinstance ( authors , list ) or isinstance ( authors , tuple ) : authors = set ( authors ) records = [ ] for path_ , dataset in client . datasets . items ( ) : if not names or dataset . name in names : for file_ in datas...
def find_index_of_smallest_triangular ( num_digits ) : """A Python function that locates the index of the smallest n - digit triangular number . Example usage : find _ index _ of _ smallest _ triangular ( 2 ) - > 4 find _ index _ of _ smallest _ triangular ( 3 ) - > 14 find _ index _ of _ smallest _ triangu...
import math triangular_index = math . sqrt ( ( 2 * math . pow ( 10 , ( num_digits - 1 ) ) ) ) return round ( triangular_index )
def _refine_merge ( merge , aliases , min_goodness ) : """Remove entries from a merge to generate a valid merge which may be applied to the routing table . Parameters merge : : py : class : ` ~ . Merge ` Initial merge to refine . aliases : { ( key , mask ) : { ( key , mask ) , . . . } , . . . } Map of k...
# Perform the down - check merge = _refine_downcheck ( merge , aliases , min_goodness ) # If the merge is still sufficiently good then continue to refine it . if merge . goodness > min_goodness : # Perform the up - check merge , changed = _refine_upcheck ( merge , min_goodness ) if changed and merge . goodness ...
def dissimilarity_metric ( self , a , b ) : """Return non - zero if references to this module are strange , and should be drawn extra - long . The value defines the length , in rank . This is also good for putting some vertical space between seperate subsystems . Returns an int between 1 ( default ) and 4 (...
# if self . _ is _ pylib ( a ) and self . _ is _ pylib ( b ) : # return 1 res = 4 for an , bn , n in zip_longest ( a . name_parts , b . name_parts , list ( range ( 4 ) ) ) : res -= an == bn if n >= 3 : break return res
def remove_collation ( coltype : TypeEngine ) -> TypeEngine : """Returns a copy of the specific column type with any ` ` COLLATION ` ` removed ."""
if not getattr ( coltype , 'collation' , None ) : return coltype newcoltype = copy . copy ( coltype ) newcoltype . collation = None return newcoltype
def _generate_random_leaf_count ( height ) : """Return a random leaf count for building binary trees . : param height : Height of the binary tree . : type height : int : return : Random leaf count . : rtype : int"""
max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random . randint ( 0 , half_leaf_count ) roll_2 = random . randint ( 0 , max_leaf_count - half_leaf_count ) return roll_1 + roll_2 or half_leaf_count
def deepcopy ( value ) : """The default copy . deepcopy seems to copy all objects and some are not ` copy - able ` . We only need to make sure the provided data is a copy per key , object does not need to be copied ."""
if not isinstance ( value , ( dict , list , tuple ) ) : return value if isinstance ( value , dict ) : copy = { } for k , v in value . items ( ) : copy [ k ] = deepcopy ( v ) if isinstance ( value , tuple ) : copy = list ( range ( len ( value ) ) ) for k in get_keys ( list ( value ) ) : ...
def validate ( bbllines : iter , * , profiling = False ) : """Yield lines of warnings and errors about input bbl lines . profiling - - yield also info lines about input bbl file . If bbllines is a valid file name , it will be read . Else , it should be an iterable of bubble file lines ."""
if isinstance ( bbllines , str ) : if os . path . exists ( bbllines ) : # filename containing bubble bbllines = utils . file_lines ( bbllines ) elif '\n' not in bbllines or '\t' not in bbllines : # probably a bad file name : let ' s rise the proper error bbllines = utils . file_lines ( bbllines ...
def prepare_w4 ( ) : """Prepare a 4 - qubit W state using sqrt ( iswaps ) and local gates"""
circ = qf . Circuit ( ) circ += qf . X ( 1 ) circ += qf . ISWAP ( 1 , 2 ) ** 0.5 circ += qf . S ( 2 ) circ += qf . Z ( 2 ) circ += qf . ISWAP ( 2 , 3 ) ** 0.5 circ += qf . S ( 3 ) circ += qf . Z ( 3 ) circ += qf . ISWAP ( 0 , 1 ) ** 0.5 circ += qf . S ( 0 ) circ += qf . Z ( 0 ) ket = circ . run ( ) return ket
def qos_map_cos_traffic_class_cos0 ( 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 _database_create ( self , engine , database ) : """Create a new database and return a new url representing a connection to the new database"""
logger . info ( 'Creating database "%s" in "%s"' , database , engine ) database_operation ( engine , 'create' , database ) url = copy ( engine . url ) url . database = database return str ( url )
def permute ( self , idx ) : """Permutes the columns of the factor matrices inplace"""
# Check that input is a true permutation if set ( idx ) != set ( range ( self . rank ) ) : raise ValueError ( 'Invalid permutation specified.' ) # Update factors self . factors = [ f [ : , idx ] for f in self . factors ] return self . factors
def execute ( command , abort = True , capture = False , verbose = False , echo = False , stream = None , ) : """Run a command locally . Arguments : command : a command to execute . abort : If True , a non - zero return code will trigger an exception . capture : If True , returns the output of the command ....
stream = stream or sys . stdout if echo : out = stream out . write ( u'$ %s' % command ) # Capture stdout and stderr in the same stream command = u'%s 2>&1' % command if verbose : out = stream err = stream else : out = subprocess . PIPE err = subprocess . PIPE process = subprocess . Popen ( comm...
def generate_xmltags ( fn , returntag , ignore_tags , ns = None ) : """Base generator for percolator xml psm , peptide , protein output , as well as for mzML , mzIdentML . ignore _ tags are the ones that are cleared when met by parser ."""
xmlns = create_namespace ( ns ) ns_ignore = [ '{0}{1}' . format ( xmlns , x ) for x in ignore_tags ] for ac , el in etree . iterparse ( fn ) : if el . tag == '{0}{1}' . format ( xmlns , returntag ) : yield el elif el . tag in ns_ignore : formatting . clear_el ( el )
def within_magnitude_range ( self , lower_mag = None , upper_mag = None ) : ''': param float lower _ mag : Lower magnitude for consideration : param float upper _ mag : Upper magnitude for consideration : returns : Instance of openquake . hmtk . seismicity . catalogue . Catalogue class containing only s...
if not lower_mag : if not upper_mag : # No limiting magnitudes defined - return entire catalogue ! return self . catalogue else : lower_mag = - np . inf if not upper_mag : upper_mag = np . inf is_valid = np . logical_and ( self . catalogue . data [ 'magnitude' ] >= lower_mag , self . catalog...
def search_update_index ( self ) : """Updates the search index for this instance . This happens automatically on put ."""
doc_id = self . search_get_document_id ( self . key ) fields = [ search . AtomField ( 'class_name' , name ) for name in self . search_get_class_names ( ) ] index = self . search_get_index ( ) if self . searchable_fields is None : searchable_fields = [ ] for field , prop in self . _properties . items ( ) : ...
def post_sea_resource ( url , body ) : """Get the requested resource using the Seattle account : returns : http response with content in json"""
response = None response = TrumbaSea_DAO ( ) . postURL ( url , { "Content-Type" : "application/json" } , body ) _log_json_resp ( "Seattle" , url , body , response ) return response
def do_ams_patch ( endpoint , path , body , access_token ) : '''Do a AMS PATCH request and return JSON . Args : endpoint ( str ) : Azure Media Services Initial Endpoint . path ( str ) : Azure Media Services Endpoint Path . body ( str ) : Azure Media Services Content Body . access _ token ( str ) : A valid...
headers = { "Content-Type" : json_acceptformat , "DataServiceVersion" : dsversion_min , "MaxDataServiceVersion" : dsversion_max , "Accept" : json_acceptformat , "Accept-Charset" : charset , "Authorization" : "Bearer " + access_token , "x-ms-version" : xmsversion } response = requests . patch ( endpoint , data = body , ...
def get_order ( self ) : """Returns the result order by clauses : rtype : str or None"""
# first get the filtered attributes in order as they must appear # in the order _ by first if not self . has_order : return None filter_order_clauses = OrderedDict ( [ ( filter_attr [ 0 ] , None ) for filter_attr in self . _filters if isinstance ( filter_attr , tuple ) ] ) # any order _ by attribute that appears in...
def _construct_form ( self , i , ** kwargs ) : """Override the method to change the form attribute empty _ permitted ."""
form = super ( MetadataFormset , self ) . _construct_form ( i , ** kwargs ) # Monkey patch the form to always force a save . # It ' s unfortunate , but necessary because we always want an instance # Affect on performance shouldn ' t be too great , because ther is only # ever one metadata attached form . empty_permitted...
def analysis_of_prot_lig_interactions ( self ) : """The classes and function that deal with protein - ligand interaction analysis ."""
self . hbonds = HBonds ( self . topol_data , self . trajectory , self . start , self . end , self . skip , self . analysis_cutoff , distance = 3 ) self . pistacking = PiStacking ( self . topol_data , self . trajectory , self . start , self . end , self . skip , self . analysis_cutoff ) self . sasa = SASA ( self . topol...
def get_data_metadata ( self ) : """Gets the metadata for the content data . return : ( osid . Metadata ) - metadata for the content data * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template metadata = dict ( self . _mdata [ 'data' ] ) metadata . update ( { 'existing_object_values' : self . _my_map [ 'data' ] } ) return Metadata ( ** metadata )
def stop ( self , msg = None ) : '''Stopping a run . Control for loops . Gentle stop / abort . This event should provide a more gentle abort . The run should stop ASAP but the run is still considered complete .'''
if not self . stop_run . is_set ( ) : if msg : logging . info ( '%s%s Stopping run...' , msg , ( '' if msg [ - 1 ] in punctuation else '.' ) ) else : logging . info ( 'Stopping run...' ) self . stop_run . set ( )
def removei ( self , begin , end , data = None ) : """Shortcut for remove ( Interval ( begin , end , data ) ) . Completes in O ( log n ) time ."""
return self . remove ( Interval ( begin , end , data ) )
def generate_zipfiles ( gallery_dir ) : """Collects all Python source files and Jupyter notebooks in gallery _ dir and makes zipfiles of them Parameters gallery _ dir : str path of the gallery to collect downloadable sources Return download _ rst : str RestructuredText to include download buttons to t...
listdir = list_downloadable_sources ( gallery_dir ) for directory in sorted ( os . listdir ( gallery_dir ) ) : if os . path . isdir ( os . path . join ( gallery_dir , directory ) ) : target_dir = os . path . join ( gallery_dir , directory ) listdir . extend ( list_downloadable_sources ( target_dir )...
def get_or_set_hash ( uri , length = 8 , chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' ) : '''Perform a one - time generation of a hash and write it to sdb . If that value has already been set return the value instead . This is useful for generating passwords or keys that are specific to multip...
return salt . utils . sdb . sdb_get_or_set_hash ( uri , __opts__ , length , chars , __utils__ )
def _load_streams ( self ) : """Reads , parses and creates streams specified in config . yaml ."""
common_err_msg = 'No valid {} stream configurations found. ' specific_err_msg = { 'inbound' : 'No data will be received (or displayed).' , 'outbound' : 'No data will be published.' } err_msgs = { } for stream_type in [ 'inbound' , 'outbound' ] : err_msgs [ stream_type ] = common_err_msg . format ( stream_type ) + s...
def validate ( self , data = None ) : """Validate the data Check also that no extra properties are present . : raises : ValidationError if the data is not valid ."""
errors = { } data = self . _getData ( data ) # validate each field , one by one for name , field in self . fields . items ( ) : try : field . clean ( data . get ( name ) ) except ValidationError , e : errors [ name ] = e . messages except AttributeError , e : raise ValidationError ( ...
def pileup_reads_at_position ( samfile , chromosome , base0_position ) : """Returns a pileup column at the specified position . Unclear if a function like this is hiding somewhere in pysam API ."""
# TODO : I want to pass truncate = True , stepper = " all " # but for some reason I get this error : # pileup ( ) got an unexpected keyword argument ' truncate ' # . . . even though these options are listed in the docs for pysam 0.9.0 for column in samfile . pileup ( chromosome , start = base0_position , end = base0_po...
def cli ( env , identifier , keys , permissions , hardware , virtual , logins , events ) : """User details ."""
mgr = SoftLayer . UserManager ( env . client ) user_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'username' ) object_mask = "userStatus[name], parent[id, username], apiAuthenticationKeys[authenticationKey], " "unsuccessfulLogins, successfulLogins" user = mgr . get_user ( user_id , object_mask ) env . fo...
def delFromTimeVary ( self , * params ) : '''Removes any number of parameters from time _ vary for this instance . Parameters params : string Any number of strings naming attributes to be removed from time _ vary Returns None'''
for param in params : if param in self . time_vary : self . time_vary . remove ( param )
def cmd_dot ( conf : Config ) : """Print out a neat targets dependency tree based on requested targets . Use graphviz to render the dot file , e . g . : > ybt dot : foo : bar | dot - Tpng - o graph . png"""
build_context = BuildContext ( conf ) populate_targets_graph ( build_context , conf ) if conf . output_dot_file is None : write_dot ( build_context , conf , sys . stdout ) else : with open ( conf . output_dot_file , 'w' ) as out_file : write_dot ( build_context , conf , out_file )
def _load_h5 ( file , devices , channels ) : """Function used for reading . h5 files generated by OpenSignals . Parameters file : file path . File Path . devices : list [ " mac _ address _ 1 " < str > , " mac _ address _ 2 " < str > . . . ] List of devices selected by the user . channels : list [ [ mac ...
# % % % % % Creation of h5py object % % % % % h5_object = h5py . File ( file ) # % % % % % Data of the selected channels % % % % % out_dict = { } for dev_nbr , device in enumerate ( devices ) : out_dict [ device ] = { } for chn in channels [ dev_nbr ] : data_temp = list ( h5_object . get ( device ) . ge...
def returns ( prices , method = 'simple' , periods = 1 , fill_method = 'pad' , limit = None , freq = None ) : """compute the returns for the specified prices . method : [ simple , compound , log ] , compound is log"""
if method not in ( 'simple' , 'compound' , 'log' ) : raise ValueError ( "Invalid method type. Valid values are ('simple', 'compound')" ) if method == 'simple' : return prices . pct_change ( periods = periods , fill_method = fill_method , limit = limit , freq = freq ) else : if freq is not None : rai...
def list_floatingips ( self , retrieve_all = True , ** _params ) : """Fetches a list of all floatingips for a project ."""
# Pass filters in " params " argument to do _ request return self . list ( 'floatingips' , self . floatingips_path , retrieve_all , ** _params )
def next ( self ) : """next ( self ) - > Annot"""
CheckParent ( self ) val = _fitz . Annot_next ( self ) if val : val . thisown = True val . parent = self . parent # copy owning page object from previous annot val . parent . _annot_refs [ id ( val ) ] = val return val
def find_types ( self , site = None , match = r'^(?!lastfile|spectro|\.).*' ) : """Return the list of known data types . This is just the basename of each FFL file found in the FFL directory ( minus the ` ` . ffl ` ` extension )"""
self . _find_paths ( ) types = [ tag for ( site_ , tag ) in self . paths if site in ( None , site_ ) ] if match is not None : match = re . compile ( match ) return list ( filter ( match . search , types ) ) return types
def braceexpand ( pattern , escape = True ) : """braceexpand ( pattern ) - > iterator over generated strings Returns an iterator over the strings resulting from brace expansion of pattern . This function implements Brace Expansion as described in bash ( 1 ) , with the following limitations : * A pattern con...
return ( _flatten ( t , escape ) for t in parse_pattern ( pattern , escape ) )
def encode_document ( obj ) : """Encode a single document ."""
warnings . warn ( "deprecated. Please use bioc.biocxml.encoder.encode_document" , DeprecationWarning ) return bioc . biocxml . encoder . encode_document ( obj )
def supported_fixes ( ) : """Yield pep8 error codes that autopep8 fixes . Each item we yield is a tuple of the code followed by its description ."""
yield ( 'E101' , docstring_summary ( reindent . __doc__ ) ) instance = FixPEP8 ( filename = None , options = None , contents = '' ) for attribute in dir ( instance ) : code = re . match ( 'fix_([ew][0-9][0-9][0-9])' , attribute ) if code : yield ( code . group ( 1 ) . upper ( ) , re . sub ( r'\s+' , ' '...
def main ( out_path , ud_dir , check_parse = False , langs = ALL_LANGUAGES , exclude_trained_models = False , exclude_multi = False , hide_freq = False , corpus = 'train' , best_per_language = False ) : """Assemble all treebanks and models to run evaluations with . When setting check _ parse to True , the default...
languages = [ lang . strip ( ) for lang in langs . split ( "," ) ] print_freq_tasks = [ ] if not hide_freq : print_freq_tasks = [ 'Tokens' ] # fetching all relevant treebank from the directory treebanks = fetch_all_treebanks ( ud_dir , languages , corpus , best_per_language ) print ( ) print ( "Loading all relevant...
def _run_checks ( self ) : '''basic sanity checks for the file name ( and others if needed ) before attempting parsing .'''
if self . recipe is not None : # Does the recipe provided exist ? if not os . path . exists ( self . recipe ) : bot . error ( "Cannot find %s, is the path correct?" % self . recipe ) sys . exit ( 1 ) # Ensure we carry fullpath self . recipe = os . path . abspath ( self . recipe )
def convert ( self , request , response , data ) : """Performs the desired Conversion . : param request : The webob Request object describing the request . : param response : The webob Response object describing the response . : param data : The data dictionary returned by the prepare ( ) method . : r...
# Determine which time to use fmtstr = self . modifier . param if fmtstr is None : log_time = data [ 'start' ] elif fmtstr == 'begin' or fmtstr . startswith ( 'begin:' ) : log_time = data [ 'start' ] if fmtstr == 'begin' : fmtstr = None else : fmtstr = fmtstr [ len ( 'begin:' ) : ] elif ...
def permanently_delete ( self , user ) : """Permanently delete user . User should be softly deleted first . Zendesk API ` Reference < https : / / developer . zendesk . com / rest _ api / docs / core / users # permanently - delete - user > ` _ _ . Note : This endpoint does not support multiple ids or list of ` U...
url = self . _build_url ( self . endpoint . deleted ( id = user ) ) deleted_user = self . _delete ( url ) self . cache . delete ( deleted_user ) return deleted_user
def add_net16string ( self , string ) : """> > > OutBuffer ( ) . add _ net16string ( b " x " ) . getvalue ( ) = = b ' \\ x00 \\ x01x ' True @ type string : bytes @ param string : maximum length must fit in a 16bit integer @ returns : self @ raises OmapiSizeLimitError :"""
if len ( string ) >= ( 1 << 16 ) : raise ValueError ( "string too long" ) return self . add_net16int ( len ( string ) ) . add ( string )
def get_asset_content_form_for_create ( self , asset_id , asset_content_record_types ) : """Gets an asset content form for creating new assets . arg : asset _ id ( osid . id . Id ) : the ` ` Id ` ` of an ` ` Asset ` ` arg : asset _ content _ record _ types ( osid . type . Type [ ] ) : array of asset content r...
# Implemented from template for # osid . learning . ActivityAdminSession . get _ activity _ form _ for _ create _ template if not isinstance ( asset_id , ABCId ) : raise errors . InvalidArgument ( 'argument is not a valid OSID Id' ) for arg in asset_content_record_types : if not isinstance ( arg , ABCType ) : ...
def parse_dimension ( text ) : """Parses the given text into one dimension and returns its equivalent size in points . The numbers provided can be integer or decimal , but exponents are not supported . The units may be inches ( " , in , ins , inch , inchs , inches ) , millimeters ( mm ) , points ( pt , pt...
size , unit = _split_dimension ( text ) factor = _unit_lookup [ unit ] return size * factor
def sg_conv1d ( tensor , opt ) : r"""Applies a 1 - D convolution . Args : tensor : A 3 - D ` Tensor ` ( automatically passed by decorator ) . opt : size : A positive ` integer ` representing ` [ kernel width ] ` . If not specified , 2 is set implicitly . stride : A positive ` integer ` . The number of e...
# default options opt += tf . sg_opt ( size = 2 , stride = 1 , pad = 'SAME' ) # parameter tf . sg _ initializer w = tf . sg_initializer . he_uniform ( 'W' , ( opt . size , opt . in_dim , opt . dim ) , regularizer = opt . regularizer , summary = opt . summary ) b = tf . sg_initializer . constant ( 'b' , opt . dim , summ...
def update_pull_request_properties ( self , patch_document , repository_id , pull_request_id , project = None ) : """UpdatePullRequestProperties . [ Preview API ] Create or update pull request external properties . The patch operation can be ` add ` , ` replace ` or ` remove ` . For ` add ` operation , the path c...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if repository_id is not None : route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' ) if pull_request_id is not None : route_values ...
def resolve ( self , correlation_id ) : """Resolves a single component connection . If connections are configured to be retrieved from Discovery service it finds a [ [ IDiscovery ] ] and resolves the connection there . : param correlation _ id : ( optional ) transaction id to trace execution through call chain ...
if len ( self . _connections ) == 0 : return None # Return connection that doesn ' t require discovery for connection in self . _connections : if not connection . use_discovery ( ) : return connection # Return connection that require discovery for connection in self . _connections : if connection . ...
def check ( self , targets , topological_order = False ) : """Checks whether each of the targets has changed and invalidates it if so . Returns a list of VersionedTargetSet objects ( either valid or invalid ) . The returned sets ' cover ' the input targets , with one caveat : if the FingerprintStrategy opted ...
all_vts = self . wrap_targets ( targets , topological_order = topological_order ) invalid_vts = [ vt for vt in all_vts if not vt . valid ] return InvalidationCheck ( all_vts , invalid_vts )
def _get_localzone ( _root = '/' ) : """Tries to find the local timezone configuration . This method prefers finding the timezone name and passing that to pytz , over passing in the localtime file , as in the later case the zoneinfo name is unknown . The parameter _ root makes the function look for files li...
tzenv = _try_tz_from_env ( ) if tzenv : return tzenv # Now look for distribution specific configuration files # that contain the timezone name . for configfile in ( 'etc/timezone' , 'var/db/zoneinfo' ) : tzpath = os . path . join ( _root , configfile ) try : with open ( tzpath , 'rb' ) as tzfile : ...
def update ( self , url , doc ) : """Update metadata associated with a DOI . This can be called before / after a DOI is registered . : param doc : Set metadata for DOI . : returns : ` True ` if is updated successfully ."""
if self . pid . is_deleted ( ) : logger . info ( "Reactivate in DataCite" , extra = dict ( pid = self . pid ) ) try : # Set metadata self . api . metadata_post ( doc ) self . api . doi_post ( self . pid . pid_value , url ) except ( DataCiteError , HttpError ) : logger . exception ( "Failed to update in ...
def release ( button = LEFT ) : """Sends an up event for the specified button , using the provided constants"""
location = get_position ( ) button_code , _ , button_up , _ = _button_mapping [ button ] e = Quartz . CGEventCreateMouseEvent ( None , button_up , location , button_code ) if _last_click [ "time" ] is not None and _last_click [ "time" ] > datetime . datetime . now ( ) - datetime . timedelta ( microseconds = 300000 ) an...
def get_installed_version ( self ) : """Return dependency status ( string )"""
if self . check ( ) : return '%s (%s)' % ( self . installed_version , self . OK ) else : return '%s (%s)' % ( self . installed_version , self . NOK )
def build_alexnet ( self , weights , output_layer = None ) : """Connects graph of alexnet from weights"""
if output_layer is None : output_layer = self . _output_layer # conv1 # conv ( 11 , 11 , 96 , 4 , 4 , padding = ' VALID ' , name = ' conv1 ' ) k_h = 11 ; k_w = 11 ; c_o = 96 ; s_h = 4 ; s_w = 4 conv1_in = conv ( self . _input_node , weights . conv1W , weights . conv1b , k_h , k_w , c_o , s_h , s_w , padding = "SAME...