signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def md ( cls , data , force_field , temperature , nsteps , other_settings = None ) : """Example for a simple MD run based on template md . txt . Args : data ( LammpsData or str ) : Data file as a LammpsData instance or path to an existing data file . force _ field ( str ) : Combined force field related cmds...
template_path = os . path . join ( cls . template_dir , "md.txt" ) with open ( template_path ) as f : script_template = f . read ( ) settings = other_settings . copy ( ) if other_settings is not None else { } settings . update ( { 'force_field' : force_field , "temperature" : temperature , "nsteps" : nsteps } ) scr...
def parse_path ( root_dir ) : """Split path into head and last component for the completer . Also return position where last component starts . : param root _ dir : str path : return : tuple of ( string , string , int )"""
base_dir , last_dir , position = '' , '' , 0 if root_dir : base_dir , last_dir = os . path . split ( root_dir ) position = - len ( last_dir ) if last_dir else 0 return base_dir , last_dir , position
def _loadTwoPartSource ( self , sourceFName , sourceLines ) : """is a helper for _ loadOneSource ."""
lineno = 1 enterInConfstems = 0 if sourceFName . find ( "conferences" ) != - 1 : enterInConfstems = 1 for ln in sourceLines : lineno += 1 try : stem , source = ln . split ( "\t" , 1 ) stem = stem . strip ( ) [ - 9 : ] if not source . strip ( ) : sys . stderr . write ( "so...
def execute ( filelocation , args , outdir , filters = None , executable = 'msConvert.exe' ) : """Execute the msConvert tool on Windows operating systems . : param filelocation : input file path : param args : str ( ) or list ( ) , msConvert arguments for details see the msConvert help below . : param outdi...
procArgs = [ executable , filelocation ] procArgs . extend ( aux . toList ( args ) ) if filters is not None : for arg in aux . toList ( filters ) : procArgs . extend ( [ '--filter' , arg ] ) procArgs . extend ( [ '-o' , outdir ] ) # # run it # # proc = subprocess . Popen ( procArgs , stderr = subprocess . P...
def validate_word_size ( word_size , BLAST_SETS ) : """Validate word size in blast / tblastn form ."""
blast_min_int_word_size = BLAST_SETS . min_word_size blast_max_int_word_size = BLAST_SETS . max_word_size blast_word_size_error = BLAST_SETS . get_word_size_error ( ) try : if len ( word_size ) <= 0 : raise forms . ValidationError ( blast_word_size_error ) int_word_size = int ( word_size ) if int_wo...
def wirevector_list ( names , bitwidth = None , wvtype = WireVector ) : """Allocate and return a list of WireVectors . : param names : Names for the WireVectors . Can be a list or single comma / space - separated string : param bitwidth : The desired bitwidth for the resulting WireVectors . : param WireVector...
if isinstance ( names , str ) : names = names . replace ( ',' , ' ' ) . split ( ) if any ( '/' in name for name in names ) and bitwidth is not None : raise PyrtlError ( 'only one of optional "/" or bitwidth parameter allowed' ) if bitwidth is None : bitwidth = 1 if isinstance ( bitwidth , numbers . Integral...
def request_frame ( self ) : """Construct initiating frame ."""
self . session_id = get_new_session_id ( ) return FrameActivateSceneRequest ( scene_id = self . scene_id , session_id = self . session_id )
def pay_dividends ( self , next_trading_day ) : """Returns a cash payment based on the dividends that should be paid out according to the accumulated bookkeeping of earned , unpaid , and stock dividends ."""
net_cash_payment = 0.0 try : payments = self . _unpaid_dividends [ next_trading_day ] # Mark these dividends as paid by dropping them from our unpaid del self . _unpaid_dividends [ next_trading_day ] except KeyError : payments = [ ] # representing the fact that we ' re required to reimburse the owner of...
def authenticate_http_request ( token = None ) : """Validate auth0 tokens passed in the request ' s header , hence ensuring that the user is authenticated . Code copied from : https : / / github . com / auth0 / auth0 - python / tree / master / examples / flask - api Return a PntCommonException if failed to va...
if token : auth = token else : auth = request . headers . get ( 'Authorization' , None ) if not auth : auth = request . cookies . get ( 'token' , None ) if auth : auth = unquote_plus ( auth ) log . debug ( "Validating Auth header [%s]" % auth ) if not auth : raise AuthMissingHeaderError ( 'T...
def parse ( text , showToc = True ) : """Returns HTML from MediaWiki markup"""
p = Parser ( show_toc = showToc ) return p . parse ( text )
def get_hash ( self , handle ) : """Get the associated hash for the given handle , the hash file must exist ( ` ` handle + ' . hash ' ` ` ) . Args : handle ( str ) : Path to the template to get the hash from Returns : str : Hash for the given handle"""
response = self . open_url ( url = handle , suffix = '.hash' ) try : return response . read ( ) finally : response . close ( )
def calcparams_pvsyst ( self , effective_irradiance , temp_cell ) : """Use the : py : func : ` calcparams _ pvsyst ` function , the input parameters and ` ` self . module _ parameters ` ` to calculate the module currents and resistances . Parameters effective _ irradiance : numeric The irradiance ( W / m2...
kwargs = _build_kwargs ( [ 'gamma_ref' , 'mu_gamma' , 'I_L_ref' , 'I_o_ref' , 'R_sh_ref' , 'R_sh_0' , 'R_sh_exp' , 'R_s' , 'alpha_sc' , 'EgRef' , 'irrad_ref' , 'temp_ref' , 'cells_in_series' ] , self . module_parameters ) return calcparams_pvsyst ( effective_irradiance , temp_cell , ** kwargs )
def register_name ( self , clsdict ) : """Add a member name to the class dict * clsdict * containing the value of this member object . Where the name of this object is None , do nothing ; this allows out - of - band values to be defined without adding a name to the class dict ."""
if self . name is None : return clsdict [ self . name ] = self . value
def workflow_set_visibility ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / workflow - xxxx / setVisibility API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Visibility # API - method % 3A - % 2Fclass - xxxx % 2FsetVisibil...
return DXHTTPRequest ( '/%s/setVisibility' % object_id , input_params , always_retry = always_retry , ** kwargs )
def history ( verbose , range ) : """List revision changesets chronologically"""
alembic_command . history ( config = get_config ( ) , rev_range = range , verbose = verbose )
def release ( self , conn ) : """Returns used connection back into pool . When returned connection has db index that differs from one in pool the connection will be closed and dropped . When queue of free connections is full the connection will be dropped ."""
assert conn in self . _used , ( "Invalid connection, maybe from other pool" , conn ) self . _used . remove ( conn ) if not conn . closed : if conn . in_transaction : logger . warning ( "Connection %r is in transaction, closing it." , conn ) conn . close ( ) elif conn . in_pubsub : logger...
def all_unambiguous ( sequence_str ) : """All unambiguous versions of sequence _ str"""
result = [ [ ] ] for c in sequence_str : result = [ i + [ a ] for i in result for a in _AMBIGUOUS_MAP . get ( c , c ) ] return [ '' . join ( i ) for i in result ]
def get_logview_address ( self , hours = None ) : """Get logview address of the instance object by hours . : param hours : : return : logview address : rtype : str"""
hours = hours or options . log_view_hours project = self . project url = '%s/authorization' % project . resource ( ) policy = { 'expires_in_hours' : hours , 'policy' : { 'Statement' : [ { 'Action' : [ 'odps:Read' ] , 'Effect' : 'Allow' , 'Resource' : 'acs:odps:*:projects/%s/instances/%s' % ( project . name , self . id ...
def p_expression_land ( self , p ) : 'expression : expression LAND expression'
p [ 0 ] = Land ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def _do_serialize ( struct , fmt , encoding ) : """Actually serialize input . Args : struct : structure to serialize to fmt : format to serialize to encoding : encoding to use while serializing Returns : encoded serialized structure Raises : various sorts of errors raised by libraries while serializ...
res = None _check_lib_installed ( fmt , 'serialize' ) if fmt == 'ini' : config = configobj . ConfigObj ( encoding = encoding ) for k , v in struct . items ( ) : config [ k ] = v res = b'\n' . join ( config . write ( ) ) elif fmt in [ 'json' , 'json5' ] : # specify separators to get rid of trailing w...
def get_one_parameter ( self , regex_exp , parameters ) : """Get three parameters from a given regex expression Raise an exception if more than three were found : param regex _ exp : : param parameters : : return :"""
Rx , other = self . get_parameters ( regex_exp , parameters ) if other is not None and other . strip ( ) : raise iarm . exceptions . ParsingError ( "Extra arguments found: {}" . format ( other ) ) return Rx . upper ( )
def _create_save_state ( self , link_item_dict : Dict [ str , LinkItem ] ) -> SaveState : """Create protobuf savestate of the module and the given data . : param link _ item _ dict : data : type link _ item _ dict : Dict [ str , ~ unidown . plugin . link _ item . LinkItem ] : return : the savestate : rtype ...
return SaveState ( dynamic_data . SAVE_STATE_VERSION , self . info , self . last_update , link_item_dict )
def _run_task_hook ( hooks , method , task , queue_name ) : """Invokes hooks . method ( task , queue _ name ) . Args : hooks : A hooks . Hooks instance or None . method : The name of the method to invoke on the hooks class e . g . " enqueue _ kickoff _ task " . task : The taskqueue . Task to pass to the h...
if hooks is not None : try : getattr ( hooks , method ) ( task , queue_name ) except NotImplementedError : # Use the default task addition implementation . return False return True return False
def create_user ( self , email , first_name , last_name , password , role = "user" , metadata = { } ) : """Create a new user : type email : str : param email : User ' s email : type first _ name : str : param first _ name : User ' s first name : type last _ name : str : param last _ name : User ' s last...
data = { 'firstName' : first_name , 'lastName' : last_name , 'email' : email , 'metadata' : metadata , 'role' : role . upper ( ) if role else role , 'newPassword' : password , } response = self . post ( 'createUser' , data ) return self . _handle_empty ( email , response )
def set_state ( self , state ) : """Activate and put this conversation into the given state . The relation name will be interpolated in the state name , and it is recommended that it be included to avoid conflicts with states from other relations . For example : : conversation . set _ state ( ' { relation _...
state = state . format ( relation_name = self . relation_name ) value = _get_flag_value ( state , { 'relation' : self . relation_name , 'conversations' : [ ] , } ) if self . key not in value [ 'conversations' ] : value [ 'conversations' ] . append ( self . key ) set_flag ( state , value )
def qget ( self , name , index ) : """Get the element of ` ` index ` ` within the queue ` ` name ` ` : param string name : the queue name : param int index : the specified index , can < 0 : return : the value at ` ` index ` ` within queue ` ` name ` ` , or ` ` None ` ` if the element doesn ' t exist : rty...
index = get_integer ( 'index' , index ) return self . execute_command ( 'qget' , name , index )
async def verify_scriptworker_task ( chain , obj ) : """Verify the signing trust object . Currently the only check is to make sure it was run on a scriptworker . Args : chain ( ChainOfTrust ) : the chain we ' re operating on obj ( ChainOfTrust or LinkOfTrust ) : the trust object for the signing task ."""
errors = [ ] if obj . worker_impl != "scriptworker" : errors . append ( "{} {} must be run from scriptworker!" . format ( obj . name , obj . task_id ) ) raise_on_errors ( errors )
def usable_id ( cls , id ) : """Retrieve id from input which can be ISO , name , country , dc _ code ."""
try : # id is maybe a dc _ code qry_id = cls . from_dc_code ( id ) if not qry_id : # id is maybe a ISO qry_id = cls . from_iso ( id ) if qry_id : cls . deprecated ( 'ISO code for datacenter filter use ' 'dc_code instead' ) if not qry_id : # id is maybe a country qry_id = ...
def allpathsX ( args ) : """% prog allpathsX folder tag Run assembly on a folder of paired reads and apply tag ( PE - 200 , PE - 500 ) . Allow multiple tags separated by comma , e . g . PE - 350 , TT - 1050"""
p = OptionParser ( allpathsX . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) folder , tag = args tag = tag . split ( "," ) for p , pf in iter_project ( folder ) : assemble_pairs ( p , pf , tag )
def _do_functions ( self , rule , p_selectors , p_parents , p_children , scope , media , c_lineno , c_property , c_codestr , code , name ) : """Implements @ mixin and @ function"""
if name : funct , params , _ = name . partition ( '(' ) funct = funct . strip ( ) params = split_params ( depar ( params + _ ) ) defaults = { } new_params = [ ] for param in params : param , _ , default = param . partition ( ':' ) param = param . strip ( ) default = defau...
def edit_scheme ( self ) : """Edit current scheme ."""
dlg = self . scheme_editor_dialog dlg . set_scheme ( self . current_scheme ) if dlg . exec_ ( ) : # Update temp scheme to reflect instant edits on the preview temporal_color_scheme = dlg . get_edited_color_scheme ( ) for key in temporal_color_scheme : option = "temp/{0}" . format ( key ) value =...
def validate_key_values ( config_handle , section , key , default = None ) : """Warn when * key * is missing from configuration * section * . Args : config _ handle ( configparser . ConfigParser ) : Instance of configurations . section ( str ) : Name of configuration section to retrieve . key ( str ) : Conf...
if section not in config_handle : LOG . info ( 'Section missing from configurations: [%s]' , section ) try : value = config_handle [ section ] [ key ] except KeyError : LOG . warning ( '[%s] missing key "%s", using %r.' , section , key , default ) value = default return value
def predict_from_mutation_effects ( self , effects , transcript_expression_dict = None , gene_expression_dict = None ) : """Given a Varcode . EffectCollection of predicted protein effects , return predicted epitopes around each mutation . Parameters effects : Varcode . EffectCollection transcript _ expressi...
# we only care about effects which impact the coding sequence of a # protein effects = filter_silent_and_noncoding_effects ( effects ) effects = apply_effect_expression_filters ( effects , transcript_expression_dict = transcript_expression_dict , transcript_expression_threshold = self . min_transcript_expression , gene...
def get_parameter ( self , name ) : """Get the parameter on this schema with the given C { name } ."""
for parameter in self . _parameters : if parameter . name == name : return parameter
def get_object ( self , queryset = None ) : """Return object with episode number attached to episode ."""
if settings . PODCAST_SINGULAR : show = get_object_or_404 ( Show , id = settings . PODCAST_ID ) else : show = get_object_or_404 ( Show , slug = self . kwargs [ 'show_slug' ] ) obj = get_object_or_404 ( Episode , show = show , slug = self . kwargs [ 'slug' ] ) index = Episode . objects . is_public_or_secret ( ) ...
def get_inputs_helper ( step , ignore , target ) : """Recursion helper used by get _ inputs ( )"""
outputs = set ( ) if not ignore and step . target == target : outputs . add ( step ) if ignore or not step . target : for i in step . inputs : outputs . update ( get_inputs_helper ( i , ignore = False , target = target ) ) return outputs
def get_knob_defaults_as_table ( cls ) : """Renders knobs in table : return :"""
knob_list = [ { 'Knob' : name , 'Description' : cls . get_registered_knob ( name ) . description , 'Default' : cls . get_registered_knob ( name ) . default } for name in sorted ( cls . _register . keys ( ) ) ] return tabulate . tabulate ( knob_list , headers = 'keys' , tablefmt = 'fancy_grid' )
def p_levelsigs ( self , p ) : 'levelsigs : levelsigs SENS _ OR levelsig'
p [ 0 ] = p [ 1 ] + ( p [ 3 ] , ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def blend_rect ( self , x0 , y0 , x1 , y1 , dx , dy , destination , alpha = 0xff ) : """Blend a rectangle onto the image"""
x0 , y0 , x1 , y1 = self . rect_helper ( x0 , y0 , x1 , y1 ) for x in range ( x0 , x1 + 1 ) : for y in range ( y0 , y1 + 1 ) : o = self . _offset ( x , y ) rgba = self . canvas [ o : o + 4 ] rgba [ 3 ] = alpha destination . point ( dx + x - x0 , dy + y - y0 , rgba )
def business_days ( start , stop ) : """Return business days between two inclusive dates - ignoring public holidays . Note that start must be less than stop or else 0 is returned . @ param start : Start date @ param stop : Stop date @ return int"""
dates = rrule . rruleset ( ) # Get dates between start / stop ( which are inclusive ) dates . rrule ( rrule . rrule ( rrule . DAILY , dtstart = start , until = stop ) ) # Exclude Sat / Sun dates . exrule ( rrule . rrule ( rrule . DAILY , byweekday = ( rrule . SA , rrule . SU ) , dtstart = start ) ) return dates . count...
def plot ( self , color = 'default' , ret = False , ax = None ) : """Generates a basic 3D visualization . : param color : Polygons color . : type color : matplotlib color , ' default ' or ' t ' ( transparent ) : param ret : If True , returns the figure . It can be used to add more elements to the plot or to...
import matplotlib . pylab as plt import mpl_toolkits . mplot3d as mplot3d # Bypass a plot if color == False : if ax is None : ax = mplot3d . Axes3D ( fig = plt . figure ( ) ) return ax # Clone and extract the information from the object obj = self . __class__ ( ** self . get_seed ( ) ) plotable3d = obj ...
def get ( self , remote_file , local_file ) : """下载文件 : param remote _ file : : param local _ file : : return :"""
sftp = self . get_sftp ( ) try : sftp . get ( remote_file , local_file ) except Exception as e : logger . error ( '下载文件失败' ) logger . error ( 'remote: %s, local: %s' % ( remote_file , local_file ) ) logger . error ( e )
def _addSpecfile ( self , specfile , path ) : """Adds a new specfile entry to SiiContainer . info . See also : class : ` SiiContainer . addSpecfile ( ) ` . : param specfile : the name of an ms - run file : param path : filedirectory for loading and saving the ` ` siic ` ` files"""
self . info [ specfile ] = { 'path' : path , 'qcAttr' : None , 'qcCutoff' : None , 'qcLargerBetter' : None , 'rankAttr' : None , 'rankLargerBetter' : None } self . container [ specfile ] = dict ( )
def readline ( self ) : """Readline wrapper to force readline ( ) to return str objects ."""
line = self . fd . __class__ . readline ( self . fd ) if isinstance ( line , bytes ) : line = line . decode ( ) return line
def set_value ( self , complete_name , value ) : """Set the value for the supplied parameter ."""
element = self . toc . get_element_by_complete_name ( complete_name ) if not element : logger . warning ( "Cannot set value for [%s], it's not in the TOC!" , complete_name ) raise KeyError ( '{} not in param TOC' . format ( complete_name ) ) elif element . access == ParamTocElement . RO_ACCESS : logger . de...
def get_assistants_from_file_hierarchy ( cls , file_hierarchy , superassistant , role = settings . DEFAULT_ASSISTANT_ROLE ) : """Accepts file _ hierarch as returned by cls . get _ assistant _ file _ hierarchy and returns instances of YamlAssistant for loaded files Args : file _ hierarchy : structure as descri...
result = [ ] warn_msg = 'Failed to load assistant {source}, skipping subassistants.' for name , attrs in file_hierarchy . items ( ) : loaded_yaml = yaml_loader . YamlLoader . load_yaml_by_path ( attrs [ 'source' ] ) if loaded_yaml is None : # there was an error parsing yaml logger . warning ( warn_msg ....
def getblock ( lines ) : """Extract the block of code at the top of the given list of lines ."""
try : tokenize . tokenize ( ListReader ( lines ) . readline , BlockFinder ( ) . tokeneater ) except EndOfBlock , eob : return lines [ : eob . args [ 0 ] ] # Fooling the indent / dedent logic implies a one - line definition return lines [ : 1 ]
async def end_takeout ( self , success ) : """Finishes a takeout , with specified result sent back to Telegram . Returns : ` ` True ` ` if the operation was successful , ` ` False ` ` otherwise ."""
try : async with _TakeoutClient ( True , self , None ) as takeout : takeout . success = success except ValueError : return False return True
def new ( cls , __name , __fields , ** defaults ) : '''Creates a new class that can represent a record with the specified * fields * . This is equal to a mutable namedtuple . The returned class also supports keyword arguments in its constructor . : param _ _ name : The name of the recordclass . : param _ ...
name = __name fields = __fields fieldset = set ( fields ) if isinstance ( fields , str ) : if ',' in fields : fields = fields . split ( ',' ) else : fields = fields . split ( ) else : fields = list ( fields ) for key in defaults . keys ( ) : if key not in fields : fields . append...
def _addRawResult ( self , resid , values = { } , override = False ) : """Structure of values dict ( dict entry for each analysis / field ) : { ' ALC ' : { ' ALC ' : ' 13.55 ' , ' DefaultResult ' : ' ALC ' , ' Remarks ' : ' ' } , ' CO2 ' : { ' CO2 ' : ' 0.66 ' , ' DefaultResult ' : ' CO2 ' , ' Remarks '...
if 'Date' in values and 'Time' in values : try : dtstr = '%s %s' % ( values . get ( 'Date' ) [ 'Date' ] , values . get ( 'Time' ) [ 'Time' ] ) # 2/11/2005 13:33 PM from datetime import datetime dtobj = datetime . strptime ( dtstr , '%d/%m/%Y %H:%M %p' ) dateTime = dtobj . str...
def compute ( self , data , fill_value = None , ** kwargs ) : """Resample the given data using bilinear interpolation"""
del kwargs if fill_value is None : fill_value = data . attrs . get ( '_FillValue' ) target_shape = self . target_geo_def . shape res = self . resampler . get_sample_from_bil_info ( data , fill_value = fill_value , output_shape = target_shape ) return res
def handle_xmlrpc ( self , request_text ) : """Handle a single XML - RPC request"""
response = self . _marshaled_dispatch ( request_text ) print ( 'Content-Type: text/xml' ) print ( 'Content-Length: %d' % len ( response ) ) print ( ) sys . stdout . flush ( ) sys . stdout . buffer . write ( response ) sys . stdout . buffer . flush ( )
def expectation ( p , obj1 , obj2 = None , nghp = None ) : """Compute the expectation < obj1 ( x ) obj2 ( x ) > _ p ( x ) Uses multiple - dispatch to select an analytical implementation , if one is available . If not , it falls back to quadrature . : type p : ( mu , cov ) tuple or a ` ProbabilityDistribution ...
if isinstance ( p , tuple ) : assert len ( p ) == 2 if p [ 1 ] . shape . ndims == 2 : p = DiagonalGaussian ( * p ) elif p [ 1 ] . shape . ndims == 3 : p = Gaussian ( * p ) elif p [ 1 ] . shape . ndims == 4 : p = MarkovGaussian ( * p ) if isinstance ( obj1 , tuple ) : obj1 , f...
def _paload8 ( ins ) : '''Loads an 8 bit value from a memory address If 2nd arg . start with ' * ' , it is always treated as an indirect value .'''
output = _paddr ( ins . quad [ 2 ] ) output . append ( 'ld a, (hl)' ) output . append ( 'push af' ) return output
def generate_gap_bed ( fname , outname ) : """Generate a BED file with gap locations . Parameters fname : str Filename of input FASTA file . outname : str Filename of output BED file ."""
f = Fasta ( fname ) with open ( outname , "w" ) as bed : for chrom in f . keys ( ) : for m in re . finditer ( r'N+' , f [ chrom ] [ : ] . seq ) : bed . write ( "{}\t{}\t{}\n" . format ( chrom , m . start ( 0 ) , m . end ( 0 ) ) )
def serialize ( self , value , ** kwargs ) : """Serialize every item of the list ."""
return [ self . item_type . serialize ( val , ** kwargs ) for val in value ]
def generate_payload ( self ) : """Generate a list of telemetry events as payload"""
events = [ ] transformation_task = self . _get_alias_transformation_properties ( ) transformation_task . update ( self . _get_based_properties ( ) ) events . append ( transformation_task ) for exception in self . exceptions : properties = { 'Reserved.DataModel.Fault.TypeString' : exception . __class__ . __name__ , ...
def generate_component_id_namespace_overview ( model , components ) : """Tabulate which MIRIAM databases the component ' s identifier matches . Parameters model : cobra . Model A cobrapy metabolic model . components : { " metabolites " , " reactions " , " genes " } A string denoting ` cobra . Model ` comp...
patterns = { "metabolites" : METABOLITE_ANNOTATIONS , "reactions" : REACTION_ANNOTATIONS , "genes" : GENE_PRODUCT_ANNOTATIONS } [ components ] databases = list ( patterns ) data = list ( ) index = list ( ) for elem in getattr ( model , components ) : index . append ( elem . id ) data . append ( tuple ( patterns...
def fft ( xi , yi , axis = 0 ) -> tuple : """Take the 1D FFT of an N - dimensional array and return " sensible " properly shifted arrays . Parameters xi : numpy . ndarray 1D array over which the points to be FFT ' ed are defined yi : numpy . ndarray ND array with values to FFT axis : int axis of yi to...
# xi must be 1D if xi . ndim != 1 : raise wt_exceptions . DimensionalityError ( 1 , xi . ndim ) # xi must be evenly spaced spacing = np . diff ( xi ) if not np . allclose ( spacing , spacing . mean ( ) ) : raise RuntimeError ( "WrightTools.kit.fft: argument xi must be evenly spaced" ) # fft yi = np . fft . fft ...
def provStacks ( self , offs , size ) : '''Returns a stream of provenance stacks at the given offset'''
for _ , iden in self . provseq . slice ( offs , size ) : stack = self . getProvStack ( iden ) if stack is None : continue yield ( iden , stack )
def rm_job ( name ) : '''Remove the specified job from the server . CLI Example : . . code - block : : bash salt chronos - minion - id chronos . rm _ job my - job'''
response = salt . utils . http . query ( "{0}/scheduler/job/{1}" . format ( _base_url ( ) , name ) , method = 'DELETE' , ) return True
def update ( self , role_sid = values . unset , attributes = values . unset , friendly_name = values . unset ) : """Update the UserInstance : param unicode role _ sid : The SID id of the Role assigned to this user : param unicode attributes : A valid JSON string that contains application - specific data : par...
data = values . of ( { 'RoleSid' : role_sid , 'Attributes' : attributes , 'FriendlyName' : friendly_name , } ) payload = self . _version . update ( 'POST' , self . _uri , data = data , ) return UserInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , sid = self . _solution [ 'sid' ]...
def funTransEdgeX ( theta , rho ) : """Fringe matrix in X : param theta : fringe angle , in [ rad ] : param rho : bend radius , in [ m ] : return : 2x2 numpy array"""
return np . matrix ( [ [ 1 , 0 ] , [ np . tan ( theta ) / rho , 1 ] ] , dtype = np . double )
def create_pod_security_policy ( self , body , ** kwargs ) : """create a PodSecurityPolicy This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . create _ pod _ security _ policy ( body , async _ req = True ) > > >...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . create_pod_security_policy_with_http_info ( body , ** kwargs ) else : ( data ) = self . create_pod_security_policy_with_http_info ( body , ** kwargs ) return data
def scan ( self , string ) : """Like findall , but also returning matching start and end string locations"""
return list ( self . _scanner_to_matches ( self . pattern . scanner ( string ) , self . run ) )
def direct_command_hub ( self , command ) : """Send direct hub command"""
self . logger . info ( "direct_command_hub: Command %s" , command ) command_url = ( self . hub_url + '/3?' + command + "=I=3" ) return self . post_direct_command ( command_url )
def accuracy ( self , mode : OsuMode ) : """Calculated accuracy . See Also < https : / / osu . ppy . sh / help / wiki / Accuracy >"""
if mode is OsuMode . osu : return ( ( 6 * self . count300 + 2 * self . count100 + self . count50 ) / ( 6 * ( self . count300 + self . count100 + self . count50 + self . countmiss ) ) ) if mode is OsuMode . taiko : return ( ( self . count300 + self . countgeki + ( 0.5 * ( self . count100 + self . countkatu ) ) )...
def _get_report_string ( time = 'hour' , threshold = 'significant' , online = False ) : """Like : func : ` get _ report ` except returns the raw data instead . : param str time : A string indicating the time range of earthquakes to report . Must be either " hour " ( only earthquakes in the past hour ) , " day " (...
key = _get_report_request ( time , threshold ) result = _get ( key ) if _CONNECTED else _lookup ( key ) if ( _CONNECTED or online ) and _EDITABLE : _add_to_cache ( key , result ) return result
def newNodeEatName ( self , name ) : """Creation of a new node element . @ ns is optional ( None ) ."""
ret = libxml2mod . xmlNewNodeEatName ( self . _o , name ) if ret is None : raise treeError ( 'xmlNewNodeEatName() failed' ) __tmp = xmlNode ( _obj = ret ) return __tmp
def clone ( srcpath , destpath , vcs = None ) : """Clone an existing repository . : param str srcpath : Path to an existing repository : param str destpath : Desired path of new repository : param str vcs : Either ` ` git ` ` , ` ` hg ` ` , or ` ` svn ` ` : returns VCSRepo : The newly cloned repository If...
vcs = vcs or probe ( srcpath ) cls = _get_repo_class ( vcs ) return cls . clone ( srcpath , destpath )
def add ( self , conn , key , value , exptime = 0 ) : """Store this data , but only if the server * doesn ' t * already hold data for this key . : param key : ` ` bytes ` ` , is the key of the item . : param value : ` ` bytes ` ` , data to store . : param exptime : ` ` int ` ` is expiration time . If it ' s...
flags = 0 # TODO : fix when exception removed return ( yield from self . _storage_command ( conn , b'add' , key , value , flags , exptime ) )
def normalizeKerningValue ( value ) : """Normalizes kerning value . * * * value * * must be an : ref : ` type - int - float ` . * Returned value is the same type as input value ."""
if not isinstance ( value , ( int , float ) ) : raise TypeError ( "Kerning value must be a int or a float, not %s." % type ( value ) . __name__ ) return value
def status ( self ) : """Return string indicating the error encountered on failure ."""
self . _check_valid ( ) if self . _ret_val == swiglpk . GLP_ENOPFS : return 'No primal feasible solution' elif self . _ret_val == swiglpk . GLP_ENODFS : return 'No dual feasible solution' return str ( swiglpk . glp_get_status ( self . _problem . _p ) )
def get_file_path ( dotted_path , extension = 'json' ) : """Reads a dotted file path and returns the file path ."""
# If the operating system ' s file path seperator character is in the string if os . sep in dotted_path or '/' in dotted_path : # Assume the path is a valid file path return dotted_path parts = dotted_path . split ( '.' ) if parts [ 0 ] == 'chatterbot' : parts . pop ( 0 ) parts [ 0 ] = DATA_DIRECTORY corpus...
def apply ( self , vpc ) : """returns a list of new security groups that will be added"""
assert vpc is not None # make sure we ' re up to date self . reload_remote_groups ( ) vpc_groups = self . vpc_groups ( vpc ) self . _apply_groups ( vpc ) # reloads groups from AWS , the authority self . reload_remote_groups ( ) vpc_groups = self . vpc_groups ( vpc ) groups = { k . name : k for k in vpc_groups } for x ,...
def setup_regex ( self ) : """Sets up compiled regex objects for parsing the executables from a module ."""
self . _RX_CONTAINS = r"^\s*contains[^\n]*?$" self . RE_CONTAINS = re . compile ( self . _RX_CONTAINS , re . M | re . I ) # Setup a regex that can extract information about both functions and subroutines self . _RX_EXEC = r"\n[ \t]*((?P<type>character|real|type|logical|integer|complex)?" + r"(?P<kind>\([a-z0-9_]+\))?)?...
def _get_seal_key_ntlm2 ( negotiate_flags , exported_session_key , magic_constant ) : """3.4.5.3 SEALKEY Calculates the seal _ key used to seal ( encrypt ) messages . This for authentication where NTLMSSP _ NEGOTIATE _ EXTENDED _ SESSIONSECURITY has been negotiated . Will weaken the keys if NTLMSSP _ NEGOTIAT...
if negotiate_flags & NegotiateFlags . NTLMSSP_NEGOTIATE_128 : seal_key = exported_session_key elif negotiate_flags & NegotiateFlags . NTLMSSP_NEGOTIATE_56 : seal_key = exported_session_key [ : 7 ] else : seal_key = exported_session_key [ : 5 ] seal_key = hashlib . md5 ( seal_key + magic_constant ) . digest ...
def show ( items , command = 'dmenu' , bottom = None , fast = None , case_insensitive = None , lines = None , monitor = None , prompt = None , font = None , background = None , foreground = None , background_selected = None , foreground_selected = None ) : '''Present a dmenu to the user . Args : items ( Iterabl...
# construct args args = [ command ] if bottom : args . append ( '-b' ) if fast : args . append ( '-f' ) if case_insensitive : args . append ( '-i' ) if lines is not None : args . extend ( ( '-l' , str ( lines ) ) ) if monitor is not None : args . extend ( ( '-m' , str ( monitor ) ) ) if prompt is no...
def get_enrollment_history_by_regid ( regid , verbose = 'true' , transcriptable_course = 'all' , changed_since_date = '' , include_unfinished_pce_course_reg = False ) : """: return : a complete chronological list of all the enrollemnts [ Enrollment ] , where the Enrollment object has a term element ."""
return _json_to_enrollment_list ( _enrollment_search ( regid , verbose , transcriptable_course , changed_since_date ) , include_unfinished_pce_course_reg )
async def sinter ( self , keys , * args ) : """Return the intersection of sets specified by ` ` keys ` ` Cluster impl : Querry all keys , intersection and return result"""
k = list_or_args ( keys , args ) res = await self . smembers ( k [ 0 ] ) for arg in k [ 1 : ] : res &= await self . smembers ( arg ) return res
def set_filter ( self , text ) : """Set regular expression for filter ."""
self . pattern = get_search_regex ( text ) if self . pattern : self . _parent . setSortingEnabled ( False ) else : self . _parent . setSortingEnabled ( True ) self . invalidateFilter ( )
def log ( self , cause = None , do_message = True , custom_msg = None ) : """Loads exception data from the current exception frame - should be called inside the except block : return :"""
message = error_message ( self , cause = cause ) exc_type , exc_value , exc_traceback = sys . exc_info ( ) traceback_formatted = traceback . format_exc ( ) traceback_val = traceback . extract_tb ( exc_traceback ) md5 = hashlib . md5 ( traceback_formatted . encode ( 'utf-8' ) ) . hexdigest ( ) if md5 in self . _db : # s...
def _decode ( self , obj , context ) : """Initialises a new Python class from a construct using the mapping passed to the adapter ."""
cls = self . _get_class ( obj . classID ) return cls . from_construct ( obj , context )
def basic_types ( self ) : """Returns non - postgres types referenced in user supplied model"""
if not self . foreign_key_definitions : return self . standard_types else : tmp = self . standard_types tmp . append ( 'ForeignKey' ) return tmp
def create_or_update ( cls , * props , ** kwargs ) : """Call to MERGE with parameters map . A new instance will be created and saved if does not already exists , this is an atomic operation . If an instance already exists all optional properties specified will be updated . Note that the post _ create hook isn '...
lazy = kwargs . get ( 'lazy' , False ) relationship = kwargs . get ( 'relationship' ) # build merge query , make sure to update only explicitly specified properties create_or_update_params = [ ] for specified , deflated in [ ( p , cls . deflate ( p , skip_empty = True ) ) for p in props ] : create_or_update_params ...
def noise_covariance ( fit , dof = 2 , ** kw ) : """Covariance taking into account the ' noise covariance ' of the data . This is technically more realistic for continuously sampled data . From Faber , 1993"""
ev = fit . eigenvalues measurement_noise = ev [ - 1 ] / ( fit . n - dof ) return 4 * ev * measurement_noise
def send_keys ( self , keyserver , * keyids ) : """Send keys to a keyserver ."""
result = self . _result_map [ 'list' ] ( self ) log . debug ( 'send_keys: %r' , keyids ) data = _util . _make_binary_stream ( "" , self . _encoding ) args = [ '--keyserver' , keyserver , '--send-keys' ] args . extend ( keyids ) self . _handle_io ( args , data , result , binary = True ) log . debug ( 'send_keys result: ...
def stage_tc_create_security_label ( self , label , resource ) : """Add a security label to a resource . Args : label ( str ) : The security label ( must exit in ThreatConnect ) . resource ( obj ) : An instance of tcex resource class ."""
sl_resource = resource . security_labels ( label ) sl_resource . http_method = 'POST' sl_response = sl_resource . request ( ) if sl_response . get ( 'status' ) != 'Success' : self . log . warning ( '[tcex] Failed adding security label "{}" ({}).' . format ( label , sl_response . get ( 'response' ) . text ) )
def _validate_filters_ndb ( cls , filters , model_class ) : """Validate ndb . Model filters ."""
if not filters : return properties = model_class . _properties for idx , f in enumerate ( filters ) : prop , ineq , val = f if prop not in properties : raise errors . BadReaderParamsError ( "Property %s is not defined for entity type %s" , prop , model_class . _get_kind ( ) ) # Attempt to cast t...
def color_check ( color ) : """Check input color format . : param color : input color : type color : tuple : return : color as list"""
if isinstance ( color , ( tuple , list ) ) : if all ( map ( lambda x : isinstance ( x , int ) , color ) ) : if all ( map ( lambda x : x < 256 , color ) ) : return list ( color ) if isinstance ( color , str ) : color_lower = color . lower ( ) if color_lower in TABLE_COLOR . keys ( ) : ...
def assert_ge ( left , right , message = None , extra = None ) : """Raises an AssertionError if left _ hand < right _ hand ."""
assert left >= right , _assert_fail_message ( message , left , right , "<" , extra )
def write_secret ( path , ** kwargs ) : '''Set secret at the path in vault . The vault policy used must allow this . CLI Example : . . code - block : : bash salt ' * ' vault . write _ secret " secret / my / secret " user = " foo " password = " bar "'''
log . debug ( 'Writing vault secrets for %s at %s' , __grains__ [ 'id' ] , path ) data = dict ( [ ( x , y ) for x , y in kwargs . items ( ) if not x . startswith ( '__' ) ] ) try : url = 'v1/{0}' . format ( path ) response = __utils__ [ 'vault.make_request' ] ( 'POST' , url , json = data ) if response . sta...
def _make_spec_file ( self ) : """Generates the text of an RPM spec file . Returns : A list of strings containing the lines of text ."""
# Note that bdist _ rpm can be an old style class . if issubclass ( BdistRPMCommand , object ) : spec_file = super ( BdistRPMCommand , self ) . _make_spec_file ( ) else : spec_file = bdist_rpm . _make_spec_file ( self ) if sys . version_info [ 0 ] < 3 : python_package = "python" else : python_package = ...
def _init_dict ( self , data , index = None , dtype = None ) : """Derive the " _ data " and " index " attributes of a new Series from a dictionary input . Parameters data : dict or dict - like Data used to populate the new Series index : Index or index - like , default None index for the new Series : if...
# Looking for NaN in dict doesn ' t work ( { np . nan : 1 } [ float ( ' nan ' ) ] # raises KeyError ) , so we iterate the entire dict , and align if data : keys , values = zip ( * data . items ( ) ) values = list ( values ) elif index is not None : # fastpath for Series ( data = None ) . Just use broadcasting a...
def list_nodes_select ( conn = None , call = None ) : '''Return a list of the VMs that are on the provider , with select fields'''
if not conn : conn = get_conn ( ) # pylint : disable = E0602 return salt . utils . cloud . list_nodes_select ( list_nodes_full ( conn , 'function' ) , __opts__ [ 'query.selection' ] , call , )
def make_serial ( self , data , days , rev = 0 ) : """make data in list if data enough , will return : [0 ] is the times of high , low or equal [1 ] is the serial of data . or return ' ? ' 資料數據 list 化 , days 移動平均值 [0 ] 回傳次數 [1 ] 回傳數據"""
raw = data [ : ] result = [ ] try : while len ( raw ) >= days : result . append ( float ( sum ( raw [ - days : ] ) / days ) ) raw . pop ( ) self . debug_print ( len ( result ) ) result . reverse ( ) re = [ self . cum_serial ( result , rev ) , result ] return re except : retur...
def example_path ( cls , project , dataset , annotated_dataset , example ) : """Return a fully - qualified example string ."""
return google . api_core . path_template . expand ( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}" , project = project , dataset = dataset , annotated_dataset = annotated_dataset , example = example , )
def send_video ( self , user_id , media_id , title = None , description = None , account = None ) : """发送视频消息 详情请参考 http : / / mp . weixin . qq . com / wiki / 7/12a5a320ae96fecdf0e15cb06123de9f . html : param user _ id : 用户 ID 。 就是你收到的 ` Message ` 的 source : param media _ id : 发送的视频的媒体ID 。 可以通过 : func : ` u...
video_data = { 'media_id' : media_id , } if title : video_data [ 'title' ] = title if description : video_data [ 'description' ] = description data = { 'touser' : user_id , 'msgtype' : 'video' , 'video' : video_data } return self . _send_custom_message ( data , account = account )
def install ( self , dependency ) : """Install a new dependency ."""
if not self . pip_installed : logger . info ( "Need to install a dependency with pip, but no builtin, " "doing it manually (just wait a little, all should go well)" ) self . _brute_force_install_pip ( ) # split to pass several tokens on multiword dependency ( this is very specific for ' - e ' on # external requ...
def create_object ( self , text ) : '''Allow creation of staff members using a full name string .'''
if self . create_field == 'fullName' : firstName = text . split ( ' ' ) [ 0 ] lastName = ' ' . join ( text . split ( ' ' ) [ 1 : ] ) return self . get_queryset ( ) . create ( ** { 'firstName' : firstName , 'lastName' : lastName } ) else : return super ( StaffMemberAutoComplete , self ) . create_object (...