signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_routing_tuples ( cls ) : '''A generator of ( rule , callback ) tuples .'''
for callback in cls . callbacks : ep_name = '{}.{}' . format ( cls . api . __name__ , callback . __name__ ) yield ( Rule ( cls . endpoint_path , endpoint = ep_name , methods = callback . swagger_ops ) , callback )
def read_block ( self , block ) : """Read complete PEB data from file . Argument : Obj : block - - Block data is desired for ."""
self . seek ( block . file_offset ) return self . _fhandle . read ( block . size )
def __to_plain_containers ( self , container : Union [ CommentedSeq , CommentedMap ] ) -> Union [ OrderedDict , list ] : """Converts any sequence or mapping to list or OrderedDict Stops at anything that isn ' t a sequence or a mapping . One day , we ' ll extract the comments and formatting and store them out - ...
if isinstance ( container , CommentedMap ) : new_container = OrderedDict ( ) # type : Union [ OrderedDict , list ] for key , value_obj in container . items ( ) : if ( isinstance ( value_obj , CommentedMap ) or isinstance ( value_obj , CommentedSeq ) ) : new_container [ key ] = self . __t...
def _copy_from ( self , rhs ) : """Copy all data from rhs into this instance , handles usage count"""
self . _manager = rhs . _manager self . _rlist = type ( rhs . _rlist ) ( rhs . _rlist ) self . _region = rhs . _region self . _ofs = rhs . _ofs self . _size = rhs . _size for region in self . _rlist : region . increment_client_count ( ) if self . _region is not None : self . _region . increment_client_count ( )
def update_observation ( observation_id : int , params : Dict [ str , Any ] , access_token : str ) -> List [ Dict [ str , Any ] ] : """Update a single observation . See https : / / www . inaturalist . org / pages / api + reference # put - observations - id : param observation _ id : the ID of the observation to u...
response = requests . put ( url = "{base_url}/observations/{id}.json" . format ( base_url = INAT_BASE_URL , id = observation_id ) , json = params , headers = _build_auth_header ( access_token ) ) response . raise_for_status ( ) return response . json ( )
def cumulative_value ( self , mag_val , moment_rate , beta , moment_mag ) : '''Calculates the cumulative rate of events with M > m0 using equation 11 of Youngs & Coppersmith ( 1985) : param float mag _ val : Magnitude : param float moment _ rate : Moment rate on fault ( in Nm ) from slip rate : param fl...
exponent = exp ( - beta * ( self . mmax - mag_val ) ) return ( moment_rate * ( D_VALUE - self . b_value ) * ( 1. - exponent ) ) / ( self . b_value * moment_mag * exponent )
def unalias_tool ( self , context_name , tool_name ) : """Deregister an alias for a specific tool . Args : context _ name ( str ) : Context containing the tool . tool _ name ( str ) : Name of tool to unalias ."""
data = self . _context ( context_name ) aliases = data [ "tool_aliases" ] if tool_name in aliases : del aliases [ tool_name ] self . _flush_tools ( )
def _lognl ( self ) : """Computes the log likelihood assuming the data is noise . Since this is a constant for Gaussian noise , this is only computed once then stored ."""
try : return self . __lognl except AttributeError : det_lognls = { } for ( det , d ) in self . _data . items ( ) : kmin = self . _kmin kmax = self . _kmax det_lognls [ det ] = - 0.5 * d [ kmin : kmax ] . inner ( d [ kmin : kmax ] ) . real self . __det_lognls = det_lognls self...
def path_iter ( path ) : """Returns an iterator over all the file & folder names in a path ."""
parts = [ ] while path : path , item = os . path . split ( path ) if item : parts . append ( item ) return reversed ( parts )
def reset ( self ) : """Clear all cell and segment activity ."""
super ( ApicalTiebreakSequenceMemory , self ) . reset ( ) self . prevApicalInput = np . empty ( 0 , dtype = "uint32" ) self . prevApicalGrowthCandidates = np . empty ( 0 , dtype = "uint32" ) self . prevPredictedCells = np . empty ( 0 , dtype = "uint32" )
def extend ( klass , name = None ) : '''A function decorator for extending an existing class . Use as a decorator for functions to add to an existing class . Args : klass : The class to be decorated . name : The name the new method is to be given in the klass class . Returns : A decorator function which...
def decorator ( f ) : return add_method ( f , klass , name ) return decorator
def list_deelgemeenten_by_gemeente ( self , gemeente ) : '''List all ` deelgemeenten ` in a ` gemeente ` . : param gemeente : The : class : ` Gemeente ` for which the ` deelgemeenten ` are wanted . Currently only Flanders is supported . : rtype : A : class : ` list ` of : class : ` Deelgemeente ` .'''
try : niscode = gemeente . niscode except AttributeError : niscode = gemeente def creator ( ) : return [ Deelgemeente ( dg [ 'id' ] , dg [ 'naam' ] , dg [ 'gemeente_niscode' ] ) for dg in self . deelgemeenten . values ( ) if dg [ 'gemeente_niscode' ] == niscode ] if self . caches [ 'permanent' ] . is_config...
def has_child_bins ( self , bin_id ) : """Tests if a bin has any children . arg : bin _ id ( osid . id . Id ) : the ` ` Id ` ` of a bin return : ( boolean ) - ` ` true ` ` if the ` ` bin _ id ` ` has children , ` ` false ` ` otherwise raise : NotFound - ` ` bin _ id ` ` not found raise : NullArgument - ` ...
# Implemented from template for # osid . resource . BinHierarchySession . has _ child _ bins if self . _catalog_session is not None : return self . _catalog_session . has_child_catalogs ( catalog_id = bin_id ) return self . _hierarchy_session . has_children ( id_ = bin_id )
def get_Fdot ( F , mc , e ) : """Compute frequency derivative from Taylor et al . ( 2015) : param F : Orbital frequency [ Hz ] : param mc : Chirp mass of binary [ Solar Mass ] : param e : Eccentricity of binary : returns : dF / dt"""
# chirp mass mc *= SOLAR2S dFdt = 48 / ( 5 * np . pi * mc ** 2 ) * ( 2 * np . pi * mc * F ) ** ( 11 / 3 ) * ( 1 + 73 / 24 * e ** 2 + 37 / 96 * e ** 4 ) / ( ( 1 - e ** 2 ) ** ( 7 / 2 ) ) return dFdt
def get_token ( opts , tok ) : '''Fetch the token data from the store . : param opts : Salt master config options : param tok : Token value to get : returns : Token data if successful . Empty dict if failed .'''
t_path = os . path . join ( opts [ 'token_dir' ] , tok ) if not os . path . isfile ( t_path ) : return { } serial = salt . payload . Serial ( opts ) try : with salt . utils . files . fopen ( t_path , 'rb' ) as fp_ : tdata = serial . loads ( fp_ . read ( ) ) return tdata except ( IOError , OSErro...
def closest_allzero_pixel ( self , pixel , direction , w = 13 , t = 0.5 ) : """Starting at pixel , moves pixel by direction * t until all zero pixels within a radius w of pixel . Then , returns pixel . Parameters pixel : : obj : ` numpy . ndarray ` of float The initial pixel location at which to start . d...
# create circular structure for checking clearance y , x = np . meshgrid ( np . arange ( w ) - w / 2 , np . arange ( w ) - w / 2 ) cur_px_y = np . ravel ( y + pixel [ 0 ] ) . astype ( np . uint16 ) cur_px_x = np . ravel ( x + pixel [ 1 ] ) . astype ( np . uint16 ) # Check if all pixels in radius are in bounds and zero ...
def newapp ( path ) : """Generates all files for a new vodka app at the specified location . Will generate to current directory if no path is specified"""
app_path = os . path . join ( VODKA_INSTALL_DIR , "resources" , "blank_app" ) if not os . path . exists ( path ) : os . makedirs ( path ) elif os . path . exists ( os . path . join ( path , "application.py" ) ) : click . error ( "There already exists a vodka app at %s, please specify a different path" % path ) ...
def build_model_columns ( ) : """Builds a set of wide and deep feature columns ."""
# Continuous variable columns age = tf . feature_column . numeric_column ( 'age' ) education_num = tf . feature_column . numeric_column ( 'education_num' ) capital_gain = tf . feature_column . numeric_column ( 'capital_gain' ) capital_loss = tf . feature_column . numeric_column ( 'capital_loss' ) hours_per_week = tf . ...
def objectproxy_realaddress ( obj ) : """Obtain a real address as an integer from an objectproxy ."""
voidp = QROOT . TPython . ObjectProxy_AsVoidPtr ( obj ) return C . addressof ( C . c_char . from_buffer ( voidp ) )
def formfields_for_xmlobject ( model , fields = None , exclude = None , widgets = None , options = None , declared_subforms = None , max_num = None , extra = None ) : """Returns three sorted dictionaries ( : class : ` django . utils . datastructures . SortedDict ` ) . * The first is a dictionary of form fields ba...
# first collect fields and excludes for the form and all subforms . base # these on the specified options object unless overridden in args . fieldlist = getattr ( options , 'parsed_fields' , None ) if isinstance ( fields , ParsedFieldList ) : fieldlist = fields elif fields is not None : fieldlist = _parse_field...
def __set ( self , key , real_value , coded_value ) : """Private method for setting a cookie ' s value"""
M = self . get ( key , Morsel ( ) ) M . set ( key , real_value , coded_value ) dict . __setitem__ ( self , key , M )
def coalign_waveforms ( h1 , h2 , psd = None , low_frequency_cutoff = None , high_frequency_cutoff = None , resize = True ) : """Return two time series which are aligned in time and phase . The alignment is only to the nearest sample point and all changes to the phase are made to the first input waveform . Wave...
from pycbc . filter import matched_filter mlen = ceilpow2 ( max ( len ( h1 ) , len ( h2 ) ) ) h1 = h1 . copy ( ) h2 = h2 . copy ( ) if resize : h1 . resize ( mlen ) h2 . resize ( mlen ) elif len ( h1 ) != len ( h2 ) or len ( h2 ) % 2 != 0 : raise ValueError ( "Time series must be the same size and even if y...
def commit_purchase ( self , purchaseid , transferid ) : """DECLARES a purchase defined with ` ` purchaseid ` ` ( bound to vingd transfer referenced by ` ` transferid ` ` ) as finished , with user being granted the access to the service or goods . If seller fails to commit the purchase , the user ( buyer ) sh...
return self . request ( 'put' , safeformat ( 'purchases/{:int}' , purchaseid ) , json . dumps ( { 'transferid' : transferid } ) )
def format_name ( net : str ) -> str : '''take care of specifics of cryptoid naming system'''
if net . startswith ( 't' ) or 'testnet' in net : net = net [ 1 : ] + '-test' else : net = net return net
def p_not_expression ( tok ) : """not _ expression : OP _ NOT ex _ expression | ex _ expression"""
if len ( tok ) == 3 : tok [ 0 ] = UnaryOperationRule ( tok [ 1 ] , tok [ 2 ] ) else : tok [ 0 ] = tok [ 1 ]
def remove ( self , statement_text ) : """Removes the statement that matches the input text . Removes any responses from statements where the response text matches the input text ."""
Statement = self . get_model ( 'statement' ) session = self . Session ( ) query = session . query ( Statement ) . filter_by ( text = statement_text ) record = query . first ( ) session . delete ( record ) self . _session_finish ( session )
def pdf ( self , x_test ) : """Computes the probability density function at all x _ test"""
N , D = self . data . shape x_test = np . asfortranarray ( x_test ) x_test = x_test . reshape ( [ - 1 , D ] ) pdfs = self . _individual_pdfs ( x_test ) # import pdb ; pdb . set _ trace ( ) # combine values based on fully _ dimensional ! if self . fully_dimensional : # first the product of the individual pdfs for each p...
def drop_udf ( self , name , input_types = None , database = None , force = False , aggregate = False , ) : """Drops a UDF If only name is given , this will search for the relevant UDF and drop it . To delete an overloaded UDF , give only a name and force = True Parameters name : string input _ types : ...
if not input_types : if not database : database = self . current_database result = self . list_udfs ( database = database , like = name ) if len ( result ) > 1 : if force : for func in result : self . _drop_single_function ( func . name , func . inputs , database ...
def from_array ( array ) : """Deserialize a new PassportData from a given dictionary . : return : new PassportData instance . : rtype : PassportData"""
if array is None or not array : return None # end if assert_type_or_raise ( array , dict , parameter_name = "array" ) from pytgbot . api_types . receivable . passport import EncryptedCredentials from pytgbot . api_types . receivable . passport import EncryptedPassportElement data = { } data [ 'data' ] = EncryptedPa...
def post_dns_record ( ** kwargs ) : '''Creates a DNS record for the given name if the domain is managed with DO .'''
if 'kwargs' in kwargs : # flatten kwargs if called via salt - cloud - f f_kwargs = kwargs [ 'kwargs' ] del kwargs [ 'kwargs' ] kwargs . update ( f_kwargs ) mandatory_kwargs = ( 'dns_domain' , 'name' , 'record_type' , 'record_data' ) for i in mandatory_kwargs : if kwargs [ i ] : pass else : ...
def do_GET ( self ) : """Dispatching logic . There are three paths defined : / - Display an empty form asking for an identity URL to verify / verify - Handle form submission , initiating OpenID verification / process - Handle a redirect from an OpenID server Any other path gets a 404 response . This funct...
try : self . parsed_uri = urlparse . urlparse ( self . path ) self . query = { } for k , v in cgi . parse_qsl ( self . parsed_uri [ 4 ] ) : self . query [ k ] = v . decode ( 'utf-8' ) path = self . parsed_uri [ 2 ] if path == '/' : self . render ( ) elif path == '/verify' : ...
def _eval_expectation ( command , response , future ) : """Evaluate the response from Redis to see if it matches the expected response . : param command : The command that is being evaluated : type command : tredis . client . Command : param bytes response : The response value to check : param future : Th...
if isinstance ( command . expectation , int ) and command . expectation > 1 : future . set_result ( response == command . expectation or response ) else : future . set_result ( response == command . expectation )
def send ( self , message , body_params = None ) : """. . versionchanged : : 0.8.4 Send a message to CM : param message : a message instance : type message : : class : ` . Msg ` , : class : ` . MsgProto ` : param body _ params : a dict with params to the body ( only : class : ` . MsgProto ` ) : type body ...
if not self . connected : self . _LOG . debug ( "Trying to send message when not connected. (discarded)" ) else : if body_params and isinstance ( message , MsgProto ) : proto_fill_from_dict ( message . body , body_params ) CMClient . send ( self , message )
def command ( self , regexp ) : """Register a new command : param str regexp : Regular expression matching the command to register : Example : > > > @ bot . command ( r " / echo ( . + ) " ) > > > def echo ( chat , match ) : > > > return chat . reply ( match . group ( 1 ) )"""
def decorator ( fn ) : self . add_command ( regexp , fn ) return fn return decorator
def writeMixedArray ( self , o ) : """Write mixed array to the data stream . @ type o : L { pyamf . MixedArray }"""
if self . writeReference ( o ) != - 1 : return self . context . addObject ( o ) self . writeType ( TYPE_MIXEDARRAY ) # TODO : optimise this # work out the highest integer index try : # list comprehensions to save the day max_index = max ( [ y [ 0 ] for y in o . items ( ) if isinstance ( y [ 0 ] , ( int , long )...
def detrended_price_oscillator ( data , period ) : """Detrended Price Oscillator . Formula : DPO = DATA [ i ] - Avg ( DATA [ period / 2 + 1 ] )"""
catch_errors . check_for_period_error ( data , period ) period = int ( period ) dop = [ data [ idx ] - np . mean ( data [ idx + 1 - ( int ( period / 2 ) + 1 ) : idx + 1 ] ) for idx in range ( period - 1 , len ( data ) ) ] dop = fill_for_noncomputable_vals ( data , dop ) return dop
def get_caller_module ( ) : """Returns the name of the caller ' s module as a string . > > > get _ caller _ module ( ) ' _ _ main _ _ '"""
stack = inspect . stack ( ) assert len ( stack ) > 1 caller = stack [ 2 ] [ 0 ] return caller . f_globals [ '__name__' ]
def typed_fields_with_attrnames ( cls ) : """Return a list of ( TypedField attribute name , TypedField object ) tuples for this Entity ."""
# Checking cls . _ typed _ fields could return a superclass _ typed _ fields # value . So we check our class _ _ dict _ _ which does not include # inherited attributes . klassdict = cls . __dict__ try : return klassdict [ "_typed_fields_with_attrnames" ] except KeyError : # No typed _ fields set on this Entity yet ...
def replace ( self , year = None , month = None , day = None ) : """Returns a new datetime . date or asn1crypto . util . extended _ date object with the specified components replaced : return : A datetime . date or asn1crypto . util . extended _ date object"""
if year is None : year = self . year if month is None : month = self . month if day is None : day = self . day if year > 0 : cls = date else : cls = extended_date return cls ( year , month , day )
def _create_bv_circuit ( self , bit_map : Dict [ str , str ] ) -> Program : """Implementation of the Bernstein - Vazirani Algorithm . Given a list of input qubits and an ancilla bit , all initially in the : math : ` \\ vert 0 \\ rangle ` state , create a program that can find : math : ` \\ vec { a } ` with one ...
unitary , _ = self . _compute_unitary_oracle_matrix ( bit_map ) full_bv_circuit = Program ( ) full_bv_circuit . defgate ( "BV-ORACLE" , unitary ) # Put ancilla bit into minus state full_bv_circuit . inst ( X ( self . ancilla ) , H ( self . ancilla ) ) full_bv_circuit . inst ( [ H ( i ) for i in self . computational_qub...
def wrap_rsem ( job , star_bams , univ_options , rsem_options ) : """A wrapper for run _ rsem using the results from run _ star as input . : param dict star _ bams : dict of results from star : param dict univ _ options : Dict of universal options used by almost all tools : param dict rsem _ options : Options...
rsem = job . addChildJobFn ( run_rsem , star_bams [ 'rna_transcriptome.bam' ] , univ_options , rsem_options , cores = rsem_options [ 'n' ] , disk = PromisedRequirement ( rsem_disk , star_bams , rsem_options [ 'index' ] ) ) return rsem . rv ( )
def selector_to_text ( sel , guess_punct_space = True , guess_layout = True ) : """Convert a cleaned parsel . Selector to text . See html _ text . extract _ text docstring for description of the approach and options ."""
import parsel if isinstance ( sel , parsel . SelectorList ) : # if selecting a specific xpath text = [ ] for s in sel : extracted = etree_to_text ( s . root , guess_punct_space = guess_punct_space , guess_layout = guess_layout ) if extracted : text . append ( extracted ) return '...
def block ( self , article ) : """Returns all block attachments associated with article _ id ( Such attachments has ` ` inline = False ` ` ) . Block attachments are displayed as separated files attached to Article . : param article : Numeric article id or : class : ` Article ` object . : return : Generator wi...
return self . _query_zendesk ( self . endpoint . block , 'article_attachment' , id = article )
def GoodResponse ( body , request , status_code = None , headers = None ) : """Construct a Good HTTP response ( defined in DEFAULT _ GOOD _ RESPONSE _ CODE ) : param body : The body of the response : type body : ` ` str ` ` : param request : The HTTP request : type request : : class : ` requests . Request `...
response = Response ( ) response . url = request . url response . raw = BytesIO ( body ) if status_code : response . status_code = status_code else : response . status_code = DEFAULT_GOOD_STATUS_CODE if headers : response . headers = headers else : response . headers = DEFAULT_RESPONSE_HEADERS response ...
def _filter_name ( name ) : """Filter words when adding to Dictionary . Return True if name should be added ."""
# Remove if length 3 or less if len ( name ) <= 3 : return False # Remove if starts with IL - if name . startswith ( 'IL-' ) : return False lowname = name . lower ( ) # Remove if contains certain sequences if any ( c in lowname for c in STOP_SUB ) : return False # Remove if ( case - insensitive ) exact matc...
def main ( ctx , connection ) : """Command line interface for PyBEL ."""
ctx . obj = Manager ( connection = connection ) ctx . obj . bind ( )
def MRSvoxelStats ( segfile , MRSfile = None , center = None , dim = None , subjID = None , gareas = GAREAS , wareas = WAREAS , csfareas = CSFAREAS ) : """returns grey / white / CSF content within MRS voxel Parameters segfile : nifti file path to segmentation file with grey / white matter labels ( freesurfer ...
# subject ID if subjID == None : m = re . search ( '(\w+?)_*_' , segfile ) subjID = m . group ( 0 ) [ : - 1 ] # get segmentation file aseg = nib . load ( segfile ) aseg_data = aseg . get_data ( ) . squeeze ( ) aseg_aff = aseg . get_affine ( ) segdir = os . path . dirname ( segfile ) segvoxdim = np . diagonal ( ...
def create_level ( self , depth ) : """Create and return a level for the given depth The model and root of the level will be automatically set by the browser . : param depth : the depth level that the level should handle : type depth : int : returns : a new level for the given depth : rtype : : class : ` ...
ll = ListLevel ( parent = self ) ll . setEditTriggers ( ll . DoubleClicked | ll . SelectedClicked | ll . CurrentChanged ) # ll . setSelectionBehavior ( ll . SelectRows ) ll . setResizeMode ( ll . Adjust ) self . delegate = CommentDelegate ( ll ) ll . setItemDelegate ( self . delegate ) ll . setVerticalScrollMode ( ll ....
def get_listeners ( self , name ) : """Return the callables related to name"""
return list ( map ( lambda listener : listener [ 0 ] , self . listeners [ name ] ) )
def run ( self , value , errors , request ) : """Return thing , but abort validation if request . user cannot edit ."""
thing = super ( EditableDBThing , self ) . run ( value , errors , request ) if errors : return None if not thing . can_edit ( request . user ) : message = 'Insufficient permissions for {0}' . format ( self . param ) raise HTTPForbidden ( message ) return thing
def request ( self , source = "candidate" ) : """Validate the contents of the specified configuration . * source * is the name of the configuration datastore being validated or ` config ` element containing the configuration subtree to be validated : seealso : : ref : ` srctarget _ params `"""
node = new_ele ( "validate" ) if type ( source ) is str : src = util . datastore_or_url ( "source" , source , self . _assert ) else : validated_element ( source , ( "config" , qualify ( "config" ) ) ) src = new_ele ( "source" ) src . append ( source ) node . append ( src ) return self . _request ( node ...
def _read_function ( schema ) : """Add a write method for named schema to a class ."""
def func ( filename , seq_label = 'sequence' , alphabet = None , use_uids = True , ** kwargs ) : # Use generic write class to write data . return _read ( filename = filename , schema = schema , seq_label = seq_label , alphabet = alphabet , use_uids = use_uids , ** kwargs ) # Update docs func . __doc__ = _read_doc_t...
def cross ( self , vec ) : """Cross product with another Vector3Array"""
if not isinstance ( vec , Vector3Array ) : raise TypeError ( 'Cross product operand must be a Vector3Array' ) if self . nV != 1 and vec . nV != 1 and self . nV != vec . nV : raise ValueError ( 'Cross product operands must have the same ' 'number of elements.' ) return Vector3Array ( np . cross ( self , vec ) )
def _resolve_workspace ( self ) : """Clone workspace from mets _ url unless workspace was provided ."""
if self . workspace is None : self . workspace = self . resolver . workspace_from_url ( self . mets_url , baseurl = self . src_dir , download = self . download ) self . mets = self . workspace . mets
def paste_from_clipboard ( self ) : """Pastes files from clipboard ."""
to = self . get_current_path ( ) if os . path . isfile ( to ) : to = os . path . abspath ( os . path . join ( to , os . pardir ) ) mime = QtWidgets . QApplication . clipboard ( ) . mimeData ( ) paste_operation = None if mime . hasFormat ( self . _UrlListMimeData . format ( copy = True ) ) : paste_operation = Tr...
def create ( self , obj , ref = None ) : """Convert * obj * to a new ShaderObject . If the output is a Variable with no name , then set its name using * ref * ."""
if isinstance ( ref , Variable ) : ref = ref . name elif isinstance ( ref , string_types ) and ref . startswith ( 'gl_' ) : # gl _ names not allowed for variables ref = ref [ 3 : ] . lower ( ) # Allow any type of object to be converted to ShaderObject if it # provides a magic method : if hasattr ( obj , '_shade...
def status ( self , external_id , ** params ) : """Retrieves the verification result for an App Verify transaction by external _ id . To ensure a secure verification flow you must check the status using TeleSign ' s servers on your backend . Do not rely on the SDK alone to indicate a successful verification . ...
return self . get ( APPVERIFY_STATUS_RESOURCE . format ( external_id = external_id ) , ** params )
def get_select_sql ( self ) : """Calculate the difference between this record ' s value and the lag / lead record ' s value"""
return '(({0}) - ({1}({2}){3}))' . format ( self . field . get_select_sql ( ) , self . name . upper ( ) , self . get_field_identifier ( ) , self . get_over ( ) , )
def complete_server ( self , text , line , begidx , endidx ) : '''Tab - complete server command'''
return [ i for i in PsiturkShell . server_commands if i . startswith ( text ) ]
def collect ( self ) : """Collector Passenger stats"""
if not os . access ( self . config [ "bin" ] , os . X_OK ) : self . log . error ( "Path %s does not exist or is not executable" , self . config [ "bin" ] ) return { } dict_stats = self . get_passenger_memory_stats ( ) if len ( dict_stats . keys ( ) ) == 0 : return { } queue_stats = self . get_passenger_queu...
def _get_all_slots ( self ) : """Returns all slots as set"""
all_slots = ( getattr ( cls , '__slots__' , [ ] ) for cls in self . __class__ . __mro__ ) return set ( slot for slots in all_slots for slot in slots )
def _series_shaped ( self ) : """Return image series in " shaped " file ."""
pages = self . pages pages . useframes = True lenpages = len ( pages ) def append_series ( series , pages , axes , shape , reshape , name , truncated ) : page = pages [ 0 ] if not axes : shape = page . shape axes = page . axes if len ( pages ) > 1 : shape = ( len ( pages ) , ...
def takes ( * type_list ) : """Decorates a function with type checks . Examples @ takes ( int ) : take an int as the first param @ takes ( int , str ) : take and int as first , string as 2nd @ takes ( int , ( int , None ) ) : take an int as first , and an int or None as second"""
def inner ( f ) : if enabled : # deal with the real function , not a wrapper f = getattr ( f , 'wrapped_fn' , f ) # need to check if ' self ' is the first arg , # since @ pre doesn ' t want the self param member_function = is_member_function ( f ) # need metadata for defaults...
def get ( key , default = - 1 ) : """Backport support for original codes ."""
if isinstance ( key , int ) : return Group ( key ) if key not in Group . _member_map_ : extend_enum ( Group , key , default ) return Group [ key ]
def delete ( self , force = False ) : """Deletes the current framework : param force : If True , stops the framework before deleting it : return : True if the framework has been delete , False if is couldn ' t"""
if not force and self . _state not in ( Bundle . INSTALLED , Bundle . RESOLVED , Bundle . STOPPING , ) : _logger . warning ( "Trying to delete an active framework" ) return False return FrameworkFactory . delete_framework ( self )
def _do_comment ( self , node ) : '''_ do _ comment ( self , node ) - > None Process a comment node . Render a leading or trailing # xA if the document order of the comment is greater or lesser ( respectively ) than the document element .'''
if not _in_subset ( self . subset , node ) : return if self . comments : W = self . write if self . documentOrder == _GreaterElement : W ( '\n' ) W ( '<!--' ) W ( node . data ) W ( '-->' ) if self . documentOrder == _LesserElement : W ( '\n' )
def flatten ( self , messages , parent_key = '' ) : """Flattens an nested array of translations . The scheme used is : ' key ' = > array ( ' key2 ' = > array ( ' key3 ' = > ' value ' ) ) Becomes : ' key . key2 . key3 ' = > ' value ' This function takes an array by reference and will modify it @ type mes...
items = [ ] sep = '.' for k , v in list ( messages . items ( ) ) : new_key = "{0}{1}{2}" . format ( parent_key , sep , k ) if parent_key else k if isinstance ( v , collections . MutableMapping ) : items . extend ( list ( self . flatten ( v , new_key ) . items ( ) ) ) else : items . append ( ...
def get_uids ( self ) : """Returns a uids list of the objects this action must be performed against to . If no values for uids param found in the request , returns the uid of the current context"""
uids = self . get_uids_from_request ( ) if not uids and api . is_object ( self . context ) : uids = [ api . get_uid ( self . context ) ] return uids
def close ( self , ** kwargs ) : """close websocket connection ."""
self . keep_running = False if self . sock : self . sock . close ( ** kwargs ) self . sock = None
def specbits ( self ) : """Returns the array of arguments that would be given to iptables for the current Rule ."""
def host_bits ( opt , optval ) : # handle the case where this is a negated value m = re . match ( r'^!\s*(.*)' , optval ) if m : return [ '!' , opt , m . group ( 1 ) ] else : return [ opt , optval ] bits = [ ] if self . protocol : bits . extend ( host_bits ( '-p' , self . protocol ) ) if...
def _compute_output_layer_expected ( self ) : """Compute output layers expected that the IF will produce . Be careful when you call this function . It ' s a private function , better to use the public function ` output _ layers _ expected ( ) ` . : return : List of expected layer keys . : rtype : list"""
# Actually , an IF can produce maximum 6 layers , by default . expected = [ layer_purpose_exposure_summary [ 'key' ] , layer_purpose_aggregate_hazard_impacted [ 'key' ] , layer_purpose_aggregation_summary [ 'key' ] , layer_purpose_analysis_impacted [ 'key' ] , layer_purpose_exposure_summary_table [ 'key' ] , layer_purp...
def haproxy ( line ) : # TODO Handle all message formats '''> > > import pprint > > > input _ line1 = ' Apr 24 00:00:02 node haproxy [ 12298 ] : 1.1.1.1:48660 [ 24 / Apr / 2019:00:00:02.358 ] pre - staging ~ pre - staging _ doc / pre - staging _ active 261/0/2/8/271 200 2406 - - - - - - 4/4/0/1/0 0/0 { AAAAA : AA...
_line = line . strip ( ) . split ( ) log = { } log [ 'client_server' ] = _line [ 5 ] . split ( ':' ) [ 0 ] . strip ( ) log [ 'client_port' ] = _line [ 5 ] . split ( ':' ) [ 1 ] . strip ( ) _timestamp = re . findall ( r'\[(.*?)\]' , _line [ 6 ] ) [ 0 ] log [ 'timestamp' ] = datetime . datetime . strptime ( _timestamp , ...
def psutil_phymem_usage ( ) : """Return physical memory usage ( float ) Requires the cross - platform psutil ( > = v0.3 ) library ( https : / / github . com / giampaolo / psutil )"""
import psutil # This is needed to avoid a deprecation warning error with # newer psutil versions try : percent = psutil . virtual_memory ( ) . percent except : percent = psutil . phymem_usage ( ) . percent return percent
def truncate ( s : str , length : int = DEFAULT_CURTAIL ) -> str : """Truncate a string and add an ellipsis ( three dots ) to the end if it was too long : param s : string to possibly truncate : param length : length to truncate the string to"""
if len ( s ) > length : s = s [ : length - 1 ] + '…' return s
def get_cfg_args ( ) : """Look for options in setup . cfg"""
if not os . path . exists ( 'setup.cfg' ) : return { } cfg = ConfigParser ( ) cfg . read ( 'setup.cfg' ) cfg = cfg2dict ( cfg ) g = cfg . setdefault ( 'global' , { } ) # boolean keys : for key in [ 'libzmq_extension' , 'bundle_libzmq_dylib' , 'no_libzmq_extension' , 'have_sys_un_h' , 'skip_check_zmq' , ] : if k...
def _validate_member ( self , member , classes , instanceof ) : """return error if ` member ` is not a member of any class in ` classes `"""
log . info ( "Validating member %s" % member ) stripped = self . _get_stripped_attributes ( member , classes ) if self . _field_name_from_uri ( member ) in stripped : all_class_members = sum ( [ self . schema_def . attributes_by_class [ cl ] for cl in classes ] , [ ] ) if member in all_class_members : r...
def slice_sequences ( sequences , start , end , apply_slice = None ) : """Performs a slice across multiple sequences . Useful when paginating across chained collections . : param sequences : an iterable of iterables , each nested iterable should contain a sequence and its size : param start : starting index...
if start < 0 or end < 0 or end <= start : raise ValueError ( 'Start and/or End out of range. Start: %s. End: %s' % ( start , end ) ) items_to_take = end - start items_passed = 0 collected_items = [ ] if apply_slice is None : apply_slice = _apply_slice for sequence , count in sequences : offset_start = start...
def _find_files ( directory ) : """Find XML files in the directory"""
pattern = "{directory}/*.xml" . format ( directory = directory , ) files = glob ( pattern ) return files
def on_step_end ( self , ** kwargs : Any ) -> None : "Update the params from master to model and zero grad ."
# Zeros the gradients of the model since the optimizer is disconnected . self . learn . model . zero_grad ( ) # Update the params from master to model . master2model ( self . model_params , self . master_params , self . flat_master )
def logliks ( self , x ) : """Calculate log - likelihood of a feature x for each model Converts all values that are exactly 1 or exactly 0 to 0.999 and 0.001 because they are out of range of the beta distribution . Parameters x : numpy . array - like A single vector to estimate the log - likelihood of the...
x = x . copy ( ) # Replace exactly 0 and exactly 1 values with a very small number # ( machine epsilon , the smallest number that this computer is capable # of storing ) because 0 and 1 are not in the Beta distribution . x [ x == 0 ] = VERY_SMALL_NUMBER x [ x == 1 ] = 1 - VERY_SMALL_NUMBER return np . array ( [ np . lo...
def matches ( cntxt : Context , T : RDFGraph , expr : ShExJ . tripleExpr ) -> bool : """* * matches * * : asserts that a triple expression is matched by a set of triples that come from the neighbourhood of a node in an RDF graph . The expression ` matches ( T , expr , m ) ` indicates that a set of triples ` T ` c...
if isinstance_ ( expr , ShExJ . tripleExprLabel ) : return matchesExpr ( cntxt , T , expr ) else : return matchesCardinality ( cntxt , T , expr ) and ( expr . semActs is None or semActsSatisfied ( expr . semActs , cntxt ) )
def filter_files_extensions ( files , extension_lists ) : """Put the files in buckets according to extension _ lists files = [ movie . avi , movie . srt ] , extension _ lists = [ [ avi ] , [ srt ] ] = = > [ [ movie . avi ] , [ movie . srt ] ] : param files : A list of files : param extension _ lists : A list ...
log . debug ( 'filter_files_extensions: files="{}"' . format ( files ) ) result = [ [ ] for _ in extension_lists ] for file in files : ext = file . suffix [ 1 : ] . lower ( ) for ext_i , ext_list in enumerate ( extension_lists ) : if ext in ext_list : result [ ext_i ] . append ( file ) log ....
def ghissue_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : """Link to a GitHub issue . Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages . Both are allowed to be empty . : param name : The role name used in the docume...
try : issue_num = int ( text ) if issue_num <= 0 : raise ValueError except ValueError : msg = inliner . reporter . error ( 'GitHub issue number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text , line = lineno ) prb = inliner . problematic ( rawtext , rawtext , msg ) r...
def surface ( self , param ) : """Return the detector surface point corresponding to ` ` param ` ` . For a parameter ` ` phi ` ` , the returned point is given by : : surf = R * radius * ( cos ( phi ) , - sin ( phi ) ) + t where ` ` R ` ` is a rotation matrix and ` ` t ` ` is a translation vector . Note that...
squeeze_out = ( np . shape ( param ) == ( ) ) param = np . array ( param , dtype = float , copy = False , ndmin = 1 ) if self . check_bounds and not is_inside_bounds ( param , self . params ) : raise ValueError ( '`param` {} not in the valid range ' '{}' . format ( param , self . params ) ) surf = np . empty ( para...
def wait_for_process_termination ( process , timeout = 10 ) : """Wait for a process terminate , and raise asyncio . TimeoutError in case of timeout . In theory this can be implemented by just : yield from asyncio . wait _ for ( self . _ iou _ process . wait ( ) , timeout = 100) But it ' s broken before Pyth...
if sys . version_info >= ( 3 , 5 ) : try : yield from asyncio . wait_for ( process . wait ( ) , timeout = timeout ) except ProcessLookupError : return else : while timeout > 0 : if process . returncode is not None : return yield from asyncio . sleep ( 0.1 ) ...
def do ( self , arg ) : ". exchain - Show the SEH chain"
thread = self . get_thread_from_prefix ( ) print "Exception handlers for thread %d" % thread . get_tid ( ) print table = Table ( ) table . addRow ( "Block" , "Function" ) bits = thread . get_bits ( ) for ( seh , seh_func ) in thread . get_seh_chain ( ) : if seh is not None : seh = HexDump . address ( seh , ...
def search_path ( self ) : """The relative image search path for this entry"""
return [ os . path . dirname ( self . _record . file_path ) ] + self . category . search_path
def flatatt ( attrs ) : """Pilfered from ` django . forms . utils ` : Convert a dictionary of attributes to a single string . The returned string will contain a leading space followed by key = " value " , XML - style pairs . In the case of a boolean value , the key will appear without a value . Otherwise , ...
key_value_attrs = [ ] boolean_attrs = [ ] for attr , value in attrs . items ( ) : if isinstance ( value , bool ) : if value : boolean_attrs . append ( ( attr , ) ) else : try : value = value . format ( ** attrs ) except KeyError : pass key_valu...
def compute_K ( dataframe , settings , keep_dir = False ) : """Parameters dataframe : pandas . DataFrame dataframe that contains the data settings : dict with required settings , see below keep _ dir : path if not None , copy modeling dir here settings = { ' rho ' : 100 , # resistivity to use for ho...
if settings is None : print ( 'using default settings' ) settings = get_default_settings ( ) if not os . path . isfile ( settings [ 'elem' ] ) : raise IOError ( 'elem file not found: {0}' . format ( settings [ 'elem' ] ) ) if not os . path . isfile ( settings [ 'elec' ] ) : raise IOError ( 'elec file no...
def from_name ( cls , name , vo = None , ro = None , zo = None , solarmotion = None ) : """NAME : from _ name PURPOSE : given the name of an object , retrieve coordinate information for that object from SIMBAD and return a corresponding orbit INPUT : name - the name of the object + standard Orbit initia...
if not _APY_LOADED : # pragma : no cover raise ImportError ( 'astropy needs to be installed to use ' 'Orbit.from_name' ) if not _ASTROQUERY_LOADED : # pragma : no cover raise ImportError ( 'astroquery needs to be installed to use ' 'Orbit.from_name' ) # setup a SIMBAD query with the appropriate fields simbad = ...
def create ( self ) : """Subscribes at the server ."""
self . logger . debug ( 'Create subscription on server...' ) if not self . connection . connected : self . state = 'connection_pending' return data = { 'command' : 'subscribe' , 'identifier' : self . _identifier_string ( ) } self . connection . send ( data ) self . state = 'pending'
def is_optional ( attr ) : """Helper method to find if an attribute is mandatory : param attr : : return :"""
return isinstance ( attr . validator , _OptionalValidator ) or ( attr . default is not None and attr . default is not NOTHING )
def create_stored_info_type ( self , parent , config = None , stored_info_type_id = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Creates a pre - built stored infoType to be used for inspection . See https : / ...
# Wrap the transport method to add retry and timeout logic . if "create_stored_info_type" not in self . _inner_api_calls : self . _inner_api_calls [ "create_stored_info_type" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . create_stored_info_type , default_retry = self . _method_configs...
def get_recommended_protein_name ( cls , entry ) : """get recommended full and short protein name as tuple from XML node : param entry : XML node entry : return : ( str , str ) = > ( full , short )"""
query_full = "./protein/recommendedName/fullName" full_name = entry . find ( query_full ) . text short_name = None query_short = "./protein/recommendedName/shortName" short_name_tag = entry . find ( query_short ) if short_name_tag is not None : short_name = short_name_tag . text return full_name , short_name
def progress_inc ( self , step = 1 , new_status = None ) : """: type step int : type new _ status str"""
self . _value += step self . progress ( self . _value , new_status = new_status )
def _get_aliases ( self ) : u"""Creates a dict with aliases . The key is a normalized tagname , value the original tagname ."""
if self . _aliases is None : self . _aliases = { } if self . _xml is not None : for child in self . _xml . iterchildren ( ) : self . _aliases [ helpers . normalize_tag ( child . tag ) ] = child . tag return self . _aliases
def weibo_url ( self ) : """获取用户微博链接 . : return : 微博链接地址 , 如没有则返回 ‘ unknown ’ : rtype : str"""
if self . url is None : return None else : tmp = self . soup . find ( 'a' , class_ = 'zm-profile-header-user-weibo' ) return tmp [ 'href' ] if tmp is not None else 'unknown'
def parse_names ( lstfile ) : """This is the alternative format ` lstfile ` . In this format , there are two sections , starting with [ Sequence ] and [ Manuscript ] , respectively , then followed by authors separated by comma ."""
from jcvi . formats . base import read_block fp = open ( lstfile ) all_authors = [ ] for header , seq in read_block ( fp , "[" ) : seq = " " . join ( seq ) authors = [ ] for au in seq . split ( "," ) : au = au . strip ( ) if not au : continue au = string . translate ( au ...
def packstr ( instr , textwidth = 160 , breakchars = ' ' , break_words = True , newline_prefix = '' , indentation = '' , nlprefix = None , wordsep = ' ' , remove_newlines = True ) : """alias for pack _ into . has more up to date kwargs"""
if not isinstance ( instr , six . string_types ) : instr = repr ( instr ) if nlprefix is not None : newline_prefix = nlprefix str_ = pack_into ( instr , textwidth , breakchars , break_words , newline_prefix , wordsep , remove_newlines ) if indentation != '' : str_ = indent ( str_ , indentation ) return str_
def create ( self , name , image , fetch_image = False , network = None , volumes = { } , ** kwargs ) : """Create a new container . : param name : The name for the container . This will be prefixed with the namespace . : param image : The image tag or image object to create the container from . : param ...
create_kwargs = { 'detach' : True , } # Convert network & volume models to IDs network = self . _network_for_container ( network , kwargs ) if network is not None : network_id , network = ( self . _network_helper . _get_id_and_model ( network ) ) create_kwargs [ 'network' ] = network_id if volumes : create_...