signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def tier ( self , * args , append = True , source = None , ** kwargs ) : """Function decorator for a tier coroutine . If the function being decorated is not already a coroutine function it will be wrapped ."""
if len ( args ) == 1 and not kwargs and callable ( args [ 0 ] ) : raise TypeError ( 'Uncalled decorator syntax is invalid' ) def decorator ( coro ) : if not asyncio . iscoroutinefunction ( coro ) : coro = asyncio . coroutine ( coro ) if append and source is None : self . append_tier ( coro ,...
def run_migrations_online ( ) : """Run migrations in ' online ' mode . In this scenario we need to create an Engine and associate a connection with the context ."""
connectable = context . config . attributes . get ( "connection" , None ) if connectable is None : options = context . config . get_section ( context . config . config_ini_section ) url = options . pop ( "url" ) connectable = create_engine ( url , poolclass = pool . NullPool ) with connectable . connect ( )...
def square ( self , n_coeffs , do_overlap_add = False ) : """Compute a " square " view of the frequency adaptive transform , by resampling each frequency band such that they all contain the same number of samples , and performing an overlap - add procedure in the case where the sample frequency and duration d...
resampled_bands = [ self . _resample ( band , n_coeffs ) for band in self . iter_bands ( ) ] stacked = np . vstack ( resampled_bands ) . T fdim = FrequencyDimension ( self . scale ) # TODO : This feels like it could be wrapped up nicely elsewhere chunk_frequency = Picoseconds ( int ( np . round ( self . time_dimension ...
def get_favicon ( self , article ) : """Extract the favicon from a website http : / / en . wikipedia . org / wiki / Favicon < link rel = " shortcut icon " type = " image / png " href = " favicon . png " / > < link rel = " icon " type = " image / png " href = " favicon . png " / >"""
kwargs = { 'tag' : 'link' , 'attr' : 'rel' , 'value' : 'icon' } meta = self . parser . getElementsByTag ( article . doc , ** kwargs ) if meta : favicon = self . parser . getAttribute ( meta [ 0 ] , 'href' ) return favicon return ''
def safe_mkdir ( path , uid = - 1 , gid = - 1 ) : """create path if it doesn ' t exist"""
try : os . mkdir ( path ) except OSError as e : if e . errno == errno . EEXIST : pass else : raise else : os . chown ( path , uid , gid )
def to_string ( type ) : """Converts a TypeCode into its string name . : param type : the TypeCode to convert into a string . : return : the name of the TypeCode passed as a string value ."""
if type == None : return "unknown" elif type == TypeCode . Unknown : return "unknown" elif type == TypeCode . String : return "string" elif type == TypeCode . Integer : return "integer" elif type == TypeCode . Long : return "long" elif type == TypeCode . Float : return "float" elif type == TypeC...
def observe ( self , ob ) : """Add the Observe option . : param ob : observe count"""
option = Option ( ) option . number = defines . OptionRegistry . OBSERVE . number option . value = ob self . del_option_by_number ( defines . OptionRegistry . OBSERVE . number ) self . add_option ( option )
def add_record ( self , orcid_id , token , request_type , data , content_type = 'application/orcid+json' ) : """Add a record to a profile . Parameters : param orcid _ id : string Id of the author . : param token : string Token received from OAuth 2 3 - legged authorization . : param request _ type : str...
return self . _update_activities ( orcid_id , token , requests . post , request_type , data , content_type = content_type )
def _make_intersection ( edge_info , all_edge_nodes ) : """Convert a description of edges into a curved polygon . . . note : : This is a helper used only by : meth : ` . Surface . intersect ` . Args : edge _ info ( Tuple [ Tuple [ int , float , float ] , . . . ] ) : Information describing each edge in the...
edges = [ ] for index , start , end in edge_info : nodes = all_edge_nodes [ index ] new_nodes = _curve_helpers . specialize_curve ( nodes , start , end ) degree = new_nodes . shape [ 1 ] - 1 edge = _curve_mod . Curve ( new_nodes , degree , _copy = False ) edges . append ( edge ) return curved_polygo...
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : ExportContext for this ExportInstance : rtype : twilio . rest . preview . bulk _ exports . export . ExportContext"""
if self . _context is None : self . _context = ExportContext ( self . _version , resource_type = self . _solution [ 'resource_type' ] , ) return self . _context
def subscribe ( self , subscription ) : """Create the given ` Subscription ` for this existing account ."""
url = urljoin ( self . _url , '/subscriptions' ) return subscription . post ( url )
def customize ( self , customize ) : """Special handling for opcodes , such as those that take a variable number of arguments - - we add a new entry for each in TABLE _ R ."""
for k , v in list ( customize . items ( ) ) : if k in TABLE_R : continue op = k [ : k . rfind ( '_' ) ] if k . startswith ( 'CALL_METHOD' ) : # This happens in PyPy only TABLE_R [ k ] = ( '%c(%P)' , 0 , ( 1 , - 1 , ', ' , 100 ) ) elif self . version >= 3.6 and k . startswith ( 'CALL_FUNC...
def current_ioloop ( io_loop ) : '''A context manager that will set the current ioloop to io _ loop for the context'''
orig_loop = tornado . ioloop . IOLoop . current ( ) io_loop . make_current ( ) try : yield finally : orig_loop . make_current ( )
def write ( self , len , buf ) : """Write the content of the array in the output I / O buffer This routine handle the I18N transcoding from internal UTF - 8 The buffer is lossless , i . e . will store in case of partial or delayed writes ."""
ret = libxml2mod . xmlOutputBufferWrite ( self . _o , len , buf ) return ret
async def send_async ( self , message , callback , timeout = 0 ) : """Add a single message to the internal pending queue to be processed by the Connection without waiting for it to be sent . : param message : The message to send . : type message : ~ uamqp . message . Message : param callback : The callback ...
# pylint : disable = protected - access try : raise self . _error except TypeError : pass except Exception as e : _logger . warning ( "%r" , e ) raise c_message = message . get_message ( ) message . _on_message_sent = callback try : await self . _session . _connection . lock_async ( timeout = None )...
def float_range ( string , minimum , maximum , inf , sup ) : """Requires values to be a number and range in a certain range . : param string : Value to validate : param minimum : Minimum value to accept : param maximum : Maximum value to accept : param inf : Infimum value to accept : param sup : Supremum ...
return _inrange ( float ( string ) , minimum , maximum , inf , sup )
def _assign_to_field ( obj , name , val ) : 'Helper to assign an arbitrary value to a protobuf field'
target = getattr ( obj , name ) if isinstance ( target , containers . RepeatedScalarFieldContainer ) : target . append ( val ) elif isinstance ( target , containers . RepeatedCompositeFieldContainer ) : target = target . add ( ) target . CopyFrom ( val ) elif isinstance ( target , ( int , float , bool , str...
def q_gram ( self , qrange = qtransform . DEFAULT_QRANGE , frange = qtransform . DEFAULT_FRANGE , mismatch = qtransform . DEFAULT_MISMATCH , snrthresh = 5.5 , ** kwargs ) : """Scan a ` TimeSeries ` using the multi - Q transform and return an ` EventTable ` of the most significant tiles Parameters qrange : ` t...
qscan , _ = qtransform . q_scan ( self , mismatch = mismatch , qrange = qrange , frange = frange , ** kwargs ) qgram = qscan . table ( snrthresh = snrthresh ) return qgram
def find ( self , upload_id , ** kwargs ) : """Finds an upload by ID ."""
return super ( UploadsProxy , self ) . find ( upload_id , file_upload = True )
def _copy ( self , other , copy_func ) : """Copies the contents of another Any object to itself : param object : Another instance of the same class : param copy _ func : An reference of copy . copy ( ) or copy . deepcopy ( ) to use when copying lists , dicts and objects"""
super ( Any , self ) . _copy ( other , copy_func ) self . _parsed = copy_func ( other . _parsed )
def delete_all_pipelines ( self ) : '''Deletes all pipelines Args : returnsOK for overall success or last error code , resp data .'''
code , data = self . get_pipeline ( ) if code == requests . codes . ok : for pl_data in data : c , d = self . delete_pipeline ( pl_data [ 'pipelineKey' ] ) if c != requests . codes . ok : code = c data = d return code , data
def align_generation ( self , file_nm , padding = 75 ) : """Description : Align to lip position"""
align = Align ( self . _align_root + '/' + file_nm + '.align' ) return nd . array ( align . sentence ( padding ) )
def reset_state ( self ) : """All forked dataflows should only be reset * * once and only once * * in spawned processes . Subclasses should call this method with super ."""
assert not self . _reset_done , "reset_state() was called twice! This violates the API of DataFlow!" self . _reset_done = True # _ _ del _ _ not guaranteed to get called at exit atexit . register ( del_weakref , weakref . ref ( self ) )
def evalRanges ( self , datetimeString , sourceTime = None ) : """Evaluate the C { datetimeString } text and determine if it represents a date or time range . @ type datetimeString : string @ param datetimeString : datetime text to evaluate @ type sourceTime : struct _ time @ param sourceTime : C { struct...
startTime = '' endTime = '' startDate = '' endDate = '' rangeFlag = 0 s = datetimeString . strip ( ) . lower ( ) if self . ptc . rangeSep in s : s = s . replace ( self . ptc . rangeSep , ' %s ' % self . ptc . rangeSep ) s = s . replace ( ' ' , ' ' ) m = self . ptc . CRE_TIMERNG1 . search ( s ) if m is not None...
def construct_meta ( need_data , env ) : """Constructs the node - structure for the status container : param need _ data : need _ info container : return : node"""
hide_options = env . config . needs_hide_options if not isinstance ( hide_options , list ) : raise SphinxError ( 'Config parameter needs_hide_options must be of type list' ) node_meta = nodes . line_block ( classes = [ 'needs_meta' ] ) # need parameters param_status = "status: " param_tags = "tags: " if need_data [...
def verify_all ( num ) : """Verifies all problem files in the current directory and prints an overview of the status of each problem ."""
# Define various problem statuses keys = ( 'correct' , 'incorrect' , 'error' , 'skipped' , 'missing' ) symbols = ( 'C' , 'I' , 'E' , 'S' , '.' ) colours = ( 'green' , 'red' , 'yellow' , 'cyan' , 'white' ) status = OrderedDict ( ( key , click . style ( symbol , fg = colour , bold = True ) ) for key , symbol , colour in ...
def encode ( cls , line ) : """Backslash escape line . value ."""
if not line . encoded : encoding = getattr ( line , 'encoding_param' , None ) if encoding and encoding . upper ( ) == cls . base64string : line . value = b64encode ( line . value ) . decode ( 'utf-8' ) else : line . value = backslashEscape ( str_ ( line . value ) ) line . encoded = True
def visitObjectMacro ( self , ctx : jsgParser . ObjectExprContext ) : """objectMacro : ID EQUALS membersDef SEMI"""
name = as_token ( ctx ) self . _context . grammarelts [ name ] = JSGObjectExpr ( self . _context , ctx . membersDef ( ) , name )
def Max ( a , axis , keep_dims ) : """Max reduction op ."""
return np . amax ( a , axis = axis if not isinstance ( axis , np . ndarray ) else tuple ( axis ) , keepdims = keep_dims ) ,
def fft_convolve ( in1 , in2 , conv_device = "cpu" , conv_mode = "linear" , store_on_gpu = False ) : """This function determines the convolution of two inputs using the FFT . Contains an implementation for both CPU and GPU . INPUTS : in1 ( no default ) : Array containing one set of data , possibly an image . ...
# NOTE : Circular convolution assumes a periodic repetition of the input . This can cause edge effects . Linear # convolution pads the input with zeros to avoid this problem but is consequently heavier on computation and # memory . if conv_device == 'gpu' : if conv_mode == "linear" : fft_in1 = pad_array ( i...
def unlink_parameter ( self , param ) : """: param param : param object to remove from being a parameter of this parameterized object ."""
if not param in self . parameters : try : raise HierarchyError ( "{} does not belong to this object {}, remove parameters directly from their respective parents" . format ( param . _short ( ) , self . name ) ) except AttributeError : raise HierarchyError ( "{} does not seem to be a parameter, re...
def trim_data ( x ) : """Trim leading and trailing NaNs from dataset This is done by browsing the array from each end and store the index of the first non - NaN in each case , the return the appropriate slice of the array"""
# Find indices for first and last valid data first = 0 while np . isnan ( x [ first ] ) : first += 1 last = len ( x ) while np . isnan ( x [ last - 1 ] ) : last -= 1 return x [ first : last ]
def plot_coupling_matrix ( self , lmax , nwin = None , weights = None , mode = 'full' , axes_labelsize = None , tick_labelsize = None , show = True , ax = None , fname = None ) : """Plot the multitaper coupling matrix . This matrix relates the global power spectrum to the expectation of the localized multitaper...
figsize = ( _mpl . rcParams [ 'figure.figsize' ] [ 0 ] , _mpl . rcParams [ 'figure.figsize' ] [ 0 ] ) if axes_labelsize is None : axes_labelsize = _mpl . rcParams [ 'axes.labelsize' ] if tick_labelsize is None : tick_labelsize = _mpl . rcParams [ 'xtick.labelsize' ] if ax is None : fig = _plt . figure ( fig...
def execute_closing_transaction ( statements : Iterable ) : """Open a connection , commit a transaction , and close it ."""
with closing ( connect ( ) ) as conn : with conn . cursor ( ) as cursor : for statement in statements : cursor . execute ( statement )
def cheby_rect ( G , bounds , signal , ** kwargs ) : r"""Fast filtering using Chebyshev polynomial for a perfect rectangle filter . Parameters G : Graph bounds : array _ like The bounds of the pass - band filter signal : array _ like Signal to filter order : int ( optional ) Order of the Chebyshev p...
if not ( isinstance ( bounds , ( list , np . ndarray ) ) and len ( bounds ) == 2 ) : raise ValueError ( 'Bounds of wrong shape.' ) bounds = np . array ( bounds ) m = int ( kwargs . pop ( 'order' , 30 ) + 1 ) try : Nv = np . shape ( signal ) [ 1 ] r = np . zeros ( ( G . N , Nv ) ) except IndexError : r =...
def marvcli_query ( ctx , list_tags , collections , discarded , outdated , path , tags , null ) : """Query datasets . Use - - collection = * to list all datasets across all collections ."""
if not any ( [ collections , discarded , list_tags , outdated , path , tags ] ) : click . echo ( ctx . get_help ( ) ) ctx . exit ( 1 ) sep = '\x00' if null else '\n' site = create_app ( ) . site if '*' in collections : collections = None else : for col in collections : if col not in site . colle...
def readline_check_physical ( self ) : """Check and return the next physical line . This method can be used to feed tokenize . generate _ tokens ."""
line = self . readline ( ) if line : self . check_physical ( line ) return line
def _read_file ( self , filename ) : """Return the lines from the given file , ignoring lines that start with comments"""
result = [ ] with open ( filename , 'r' ) as f : lines = f . read ( ) . split ( '\n' ) for line in lines : nocomment = line . strip ( ) . split ( '#' ) [ 0 ] . strip ( ) if nocomment : result . append ( nocomment ) return result
def generate_acl ( config , model_cls , raml_resource , es_based = True ) : """Generate an ACL . Generated ACL class has a ` item _ model ` attribute set to : model _ cls : . ACLs used for collection and item access control are generated from a first security scheme with type ` x - ACL ` . If : raml _ res...
schemes = raml_resource . security_schemes or [ ] schemes = [ sch for sch in schemes if sch . type == 'x-ACL' ] if not schemes : collection_acl = item_acl = [ ] log . debug ( 'No ACL scheme applied. Using ACL: {}' . format ( item_acl ) ) else : sec_scheme = schemes [ 0 ] log . debug ( '{} ACL scheme app...
def add_effect ( effect_id , * args , ** kwargs ) : '''If inside a side - effect , adds an effect to it .'''
effect = fiber . get_stack_var ( SIDE_EFFECT_TAG ) if effect is None : return False effect . add_effect ( effect_id , * args , ** kwargs ) return True
def getHeader ( self ) : """Returns the file header as dict Parameters None"""
return { "technician" : self . getTechnician ( ) , "recording_additional" : self . getRecordingAdditional ( ) , "patientname" : self . getPatientName ( ) , "patient_additional" : self . getPatientAdditional ( ) , "patientcode" : self . getPatientCode ( ) , "equipment" : self . getEquipment ( ) , "admincode" : self . ge...
def plot_script ( self , script ) : """Calls the plot function of the script , and redraws both plots Args : script : script to be plotted"""
script . plot ( [ self . matplotlibwidget_1 . figure , self . matplotlibwidget_2 . figure ] ) self . matplotlibwidget_1 . draw ( ) self . matplotlibwidget_2 . draw ( )
def locale_check ( ) : """Checks if this application runs with a correct locale ( i . e . supports UTF - 8 encoding ) and attempt to fix if this is not the case . This is to prevent UnicodeEncodeError with unicode paths when using standard library I / O operation methods ( e . g . os . stat ( ) or os . path ....
# no need to check on Windows or when this application is frozen if sys . platform . startswith ( "win" ) or hasattr ( sys , "frozen" ) : return language = encoding = None try : language , encoding = locale . getlocale ( ) except ValueError as e : log . error ( "Could not determine the current locale: {}" ....
def object_table ( self , object_id = None ) : """Fetch and parse the object table info for one or more object IDs . Args : object _ id : An object ID to fetch information about . If this is None , then the entire object table is fetched . Returns : Information from the object table ."""
self . _check_connected ( ) if object_id is not None : # Return information about a single object ID . return self . _object_table ( object_id ) else : # Return the entire object table . object_keys = self . _keys ( ray . gcs_utils . TablePrefix_OBJECT_string + "*" ) object_ids_binary = { key [ len ( ray . ...
def get_negative_log_likelihood ( self , y_true , X , mask ) : """Compute the loss , i . e . , negative log likelihood ( normalize by number of time steps ) likelihood = 1 / Z * exp ( - E ) - > neg _ log _ like = - log ( 1 / Z * exp ( - E ) ) = logZ + E"""
input_energy = self . activation ( K . dot ( X , self . kernel ) + self . bias ) if self . use_boundary : input_energy = self . add_boundary_energy ( input_energy , mask , self . left_boundary , self . right_boundary ) energy = self . get_energy ( y_true , input_energy , mask ) logZ = self . get_log_normalization_c...
def _close_connections ( self , connection = None , timeout = 5 ) : """Close ` ` connection ` ` if specified , otherwise close all connections . Return a list of : class : ` . Future ` called back once the connection / s are closed ."""
all = [ ] if connection : waiter = connection . event ( 'connection_lost' ) . waiter ( ) if waiter : all . append ( waiter ) connection . close ( ) else : connections = list ( self . _concurrent_connections ) self . _concurrent_connections = set ( ) for connection in connections : ...
def _init_glyph ( self , plot , mapping , properties ) : """Returns a Bokeh glyph object and optionally creates a colorbar ."""
ret = super ( ColorbarPlot , self ) . _init_glyph ( plot , mapping , properties ) if self . colorbar : for k , v in list ( self . handles . items ( ) ) : if not k . endswith ( 'color_mapper' ) : continue self . _draw_colorbar ( plot , v , k [ : - 12 ] ) return ret
def _get_chart_info ( df , vtype , cat , prep , callers ) : """Retrieve values for a specific variant type , category and prep method ."""
maxval_raw = max ( list ( df [ "value.floor" ] ) ) curdf = df [ ( df [ "variant.type" ] == vtype ) & ( df [ "category" ] == cat ) & ( df [ "bamprep" ] == prep ) ] vals = [ ] labels = [ ] for c in callers : row = curdf [ df [ "caller" ] == c ] if len ( row ) > 0 : vals . append ( list ( row [ "value.floo...
def solve_ng ( self , structure , wavelength_step = 0.01 , filename = "ng.dat" ) : r"""Solve for the group index , : math : ` n _ g ` , of a structure at a particular wavelength . Args : structure ( Structure ) : The target structure to solve for modes . wavelength _ step ( float ) : The step to take belo...
wl_nom = structure . _wl self . solve ( structure ) n_ctrs = self . n_effs structure . change_wavelength ( wl_nom - wavelength_step ) self . solve ( structure ) n_bcks = self . n_effs structure . change_wavelength ( wl_nom + wavelength_step ) self . solve ( structure ) n_frws = self . n_effs n_gs = [ ] for n_ctr , n_bc...
def validate_username_for_new_account ( person , username ) : """Validate the new username for a new account . If the username is invalid or in use , raises : py : exc : ` UsernameInvalid ` or : py : exc : ` UsernameTaken ` . : param person : Owner of new account . : param username : Username to validate ."""
# This is much the same as validate _ username _ for _ new _ person , except # we don ' t care if the username is used by the person owning the account # is the username valid ? validate_username ( username ) # Check for existing people query = Person . objects . filter ( username__exact = username ) count = query . ex...
def __update ( self , breakpoint_graph , merge_edges = False ) : """Updates a current : class ` BreakpointGraph ` object with information from a supplied : class ` BreakpointGraph ` instance . Depending of a ` ` merge _ edges ` ` flag , while updating of a current : class ` BreakpointGraph ` object is occuring , ...
for bgedge in breakpoint_graph . edges ( ) : self . __add_bgedge ( bgedge = deepcopy ( bgedge ) , merge = merge_edges )
def create_attributes ( klass , attributes , previous_object = None ) : """Attributes for resource creation ."""
result = { } if previous_object is not None : result = { k : v for k , v in previous_object . to_json ( ) . items ( ) if k != 'sys' } result . update ( attributes ) return result
def get_protein_coding_genes ( path_or_buffer , include_polymorphic_pseudogenes = True , remove_duplicates = True , ** kwargs ) : r"""Get list of all protein - coding genes based on Ensembl GTF file . Parameters See : func : ` get _ genes ` function . Returns ` pandas . DataFrame ` Table with rows corresp...
valid_biotypes = set ( [ 'protein_coding' ] ) if include_polymorphic_pseudogenes : valid_biotypes . add ( 'polymorphic_pseudogene' ) df = get_genes ( path_or_buffer , valid_biotypes , remove_duplicates = remove_duplicates , ** kwargs ) return df
def get_showcases ( self ) : # type : ( ) - > List [ hdx . data . showcase . Showcase ] """Get any showcases the dataset is in Returns : List [ Showcase ] : list of showcases"""
assoc_result , showcases_dicts = self . _read_from_hdx ( 'showcase' , self . data [ 'id' ] , fieldname = 'package_id' , action = hdx . data . showcase . Showcase . actions ( ) [ 'list_showcases' ] ) showcases = list ( ) if assoc_result : for showcase_dict in showcases_dicts : showcase = hdx . data . showcas...
def protocol_names ( self ) : """Returns all registered protocol names"""
l = self . protocols ( ) retval = [ str ( k . name ) for k in l ] return retval
def __update_rating ( uid , rating ) : '''Update rating .'''
entry = TabRating . update ( rating = rating ) . where ( TabRating . uid == uid ) entry . execute ( )
def make_multi_lagger ( lags , groupby_kwargs = None ) : """Return a union of transformers that apply different lags Args : lags ( Collection [ int ] ) : collection of lags to apply groupby _ kwargs ( dict ) : keyword arguments to pd . DataFrame . groupby"""
laggers = [ SingleLagger ( l , groupby_kwargs = groupby_kwargs ) for l in lags ] feature_union = FeatureUnion ( [ ( repr ( lagger ) , lagger ) for lagger in laggers ] ) return feature_union
def verify_ws2p_head ( self , head : Any ) -> bool : """Check specified document : param Any head : : return :"""
signature = base64 . b64decode ( head . signature ) inline = head . inline ( ) prepended = signature + bytes ( inline , 'ascii' ) try : self . verify ( prepended ) return True except ValueError : return False
def list_builds ( page_size = 200 , page_index = 0 , sort = "" , q = "" ) : """List all builds : param page _ size : number of builds returned per query : param sort : RSQL sorting query : param q : RSQL query : return :"""
response = utils . checked_api_call ( pnc_api . builds_running , 'get_all' , page_size = page_size , page_index = page_index , sort = sort , q = q ) if response : return response . content
def apply_bparams ( fn ) : """apply fn to each line of bparams , returning the result"""
cmd = [ "bparams" , "-a" ] try : output = subprocess . check_output ( cmd ) . decode ( 'utf-8' ) except : return None return fn ( output . split ( "\n" ) )
def getHook ( self , repo_user , repo_name , hook_id ) : """GET / repos / : owner / : repo / hooks / : id Returns the Hook ."""
return self . api . makeRequest ( [ 'repos' , repo_user , repo_name , 'hooks' , str ( hook_id ) ] , method = 'GET' , )
def get_tac_resource ( url ) : """Get the requested resource or update resource using Tacoma account : returns : http response with content in xml"""
response = None response = TrumbaTac_DAO ( ) . getURL ( url , { "Accept" : "application/xml" } ) _log_xml_resp ( "Tacoma" , url , response ) return response
def imagetransformer_b12l_4h_b128_h512_uncond_dr01_im ( ) : """TPU related imagenet model ."""
hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu ( ) update_hparams_for_tpu ( hparams ) hparams . batch_size = 4 hparams . optimizer = "Adafactor" hparams . learning_rate_schedule = "rsqrt_decay" hparams . learning_rate_warmup_steps = 6000 hparams . layer_prepostprocess_dropout = 0.1 return hparams
def set_position ( self , resource_id , to_position , db_session = None , * args , ** kwargs ) : """Sets node position for new node in the tree : param resource _ id : resource to move : param to _ position : new position : param db _ session : : return : def count _ children ( cls , resource _ id , db _ se...
return self . service . set_position ( resource_id = resource_id , to_position = to_position , db_session = db_session , * args , ** kwargs )
def get_user ( self , sAMAccountName ) : """Fetches one user object from the AD , based on the sAMAccountName attribute ( read : username )"""
logger . debug ( 'Polling AD for user %s' % sAMAccountName ) ldap_filter = r'(&(objectClass=user)(sAMAccountName=%s)' % sAMAccountName attributes = MSADUser . ATTRS for entry in self . pagedsearch ( ldap_filter , attributes ) : # TODO : return ldapuser object yield MSADUser . from_ldap ( entry , self . _ldapinfo ) ...
def compatible_firmware_version ( self ) : """Returns the DLL ' s compatible J - Link firmware version . Args : self ( JLink ) : the ` ` JLink ` ` instance Returns : The firmware version of the J - Link that the DLL is compatible with . Raises : JLinkException : on error ."""
identifier = self . firmware_version . split ( 'compiled' ) [ 0 ] buf_size = self . MAX_BUF_SIZE buf = ( ctypes . c_char * buf_size ) ( ) res = self . _dll . JLINKARM_GetEmbeddedFWString ( identifier . encode ( ) , buf , buf_size ) if res < 0 : raise errors . JLinkException ( res ) return ctypes . string_at ( buf )...
def flag_based_complete ( self , text : str , line : str , begidx : int , endidx : int , flag_dict : Dict [ str , Union [ Iterable , Callable ] ] , all_else : Union [ None , Iterable , Callable ] = None ) -> List [ str ] : """Tab completes based on a particular flag preceding the token being completed : param tex...
# Get all tokens through the one being completed tokens , _ = self . tokens_for_completion ( line , begidx , endidx ) if not tokens : return [ ] completions_matches = [ ] match_against = all_else # Must have at least 2 args for a flag to precede the token being completed if len ( tokens ) > 1 : flag = tokens [ ...
def class_space ( classlevel = 3 ) : "returns the calling class ' name and dictionary"
frame = sys . _getframe ( classlevel ) classname = frame . f_code . co_name classdict = frame . f_locals return classname , classdict
def with_matching_args ( self , * args , ** kwargs ) : """Set the last call to expect specific argument values if those arguments exist . Unlike : func : ` fudge . Fake . with _ args ` use this if you want to only declare expectations about matching arguments . Any unknown keyword arguments used by the app un...
exp = self . _get_current_call ( ) if args : exp . expected_matching_args = args if kwargs : exp . expected_matching_kwargs = kwargs return self
def has_conflicting_update ( self , update ) : """Checks if there are conflicting updates . Conflicting updates are updates that have the same requirement but different target versions to update to . : param update : Update to check : return : bool - True if conflict found"""
# we explicitly want a flat list of updates here , that ' s why we call iter _ updates # with both ` initial ` and ` scheduled ` = = False for _ , _ , _ , updates in self . iter_updates ( initial = False , scheduled = False ) : for _update in updates : if ( update . requirement . key == _update . requiremen...
def load ( fh , model ) : """Deserialize PENMAN graphs from a file ( handle or filename ) Args : fh : filename or file object model : Xmrs subclass instantiated from decoded triples Returns : a list of objects ( of class * model * )"""
graphs = penman . load ( fh , cls = XMRSCodec ) xs = [ model . from_triples ( g . triples ( ) ) for g in graphs ] return xs
def get_release_notes ( osa_repo_dir , osa_old_commit , osa_new_commit ) : """Get release notes between the two revisions ."""
repo = Repo ( osa_repo_dir ) # Get a list of tags , sorted tags = repo . git . tag ( ) . split ( '\n' ) tags = sorted ( tags , key = LooseVersion ) # Currently major tags are being printed after rc and # b tags . We need to fix the list so that major # tags are printed before rc and b releases tags = _fix_tags_list ( t...
def row_content_length ( row ) : '''Returns the length of non - empty content in a given row .'''
if not row : return 0 try : return ( index + 1 for index , cell in reversed ( list ( enumerate ( row ) ) ) if not is_empty_cell ( cell ) ) . next ( ) except StopIteration : return len ( row )
def flush ( self ) : """Append the latest updates to file , or optionally to stdout instead . See the constructor for logging options ."""
latest = self . _latest ( ) self . _chars_flushed += len ( latest ) if self . _use_stdout : file = sys . stdout else : file = open ( self . logpath ( ) , 'a' ) print ( latest , file = file , flush = True , end = '' ) if not self . _use_stdout : file . close ( )
def save ( filename , n_frames = 1 , axis = np . array ( [ 0. , 0. , 1. ] ) , clf = True , ** kwargs ) : """Save frames from the viewer out to a file . Parameters filename : str The filename in which to save the output image . If more than one frame , should have extension . gif . n _ frames : int Numbe...
if n_frames > 1 and os . path . splitext ( filename ) [ 1 ] != '.gif' : raise ValueError ( 'Expected .gif file for multiple-frame save.' ) v = SceneViewer ( Visualizer3D . _scene , size = Visualizer3D . _init_size , animate = ( n_frames > 1 ) , animate_axis = axis , max_frames = n_frames , ** kwargs ) data = [ m . ...
def big_bounding_box ( paths_n_stuff ) : """Finds a BB containing a collection of paths , Bezier path segments , and points ( given as complex numbers ) ."""
bbs = [ ] for thing in paths_n_stuff : if is_path_segment ( thing ) or isinstance ( thing , Path ) : bbs . append ( thing . bbox ( ) ) elif isinstance ( thing , complex ) : bbs . append ( ( thing . real , thing . real , thing . imag , thing . imag ) ) else : try : complex...
def cipher ( self ) : """Retrieve information about the current cipher Return a triple consisting of cipher name , SSL protocol version defining its use , and the number of secret bits . Return None if handshaking has not been completed ."""
if not self . _handshake_done : return current_cipher = SSL_get_current_cipher ( self . _ssl . value ) cipher_name = SSL_CIPHER_get_name ( current_cipher ) cipher_version = SSL_CIPHER_get_version ( current_cipher ) cipher_bits = SSL_CIPHER_get_bits ( current_cipher ) return cipher_name , cipher_version , cipher_bit...
def from_pickle ( cls , filename ) : """Loads and Returns a Camera from a pickle file , given a filename ."""
with open ( filename , 'rb' ) as f : cam = pickle . load ( f ) projection = cam . projection . copy ( ) return cls ( projection = projection , position = cam . position . xyz , rotation = cam . rotation . __class__ ( * cam . rotation [ : ] ) )
def to_key_val_list ( value , sort = False , insensitive = False ) : """Take an object and test to see if it can be represented as a dictionary . If it can be , return a list of tuples , e . g . , > > > to _ key _ val _ list ( [ ( ' key ' , ' val ' ) ] ) [ ( ' key ' , ' val ' ) ] > > > to _ key _ val _ list...
if value is None : return None if isinstance ( value , ( str , bytes , bool , int ) ) : raise ValueError ( 'cannot encode objects that are not 2-tuples' ) if isinstance ( value , collections . Mapping ) : value = value . items ( ) if sort and not insensitive : values = sorted ( value ) elif sort : v...
def mangle_volume ( citation_elements ) : """Make sure the volume letter is before the volume number e . g . transforms 100B to B100"""
volume_re = re . compile ( ur"(\d+)([A-Z])" , re . U | re . I ) for el in citation_elements : if el [ 'type' ] == 'JOURNAL' : matches = volume_re . match ( el [ 'volume' ] ) if matches : el [ 'volume' ] = matches . group ( 2 ) + matches . group ( 1 ) return citation_elements
def get_names_and_paths ( compiler_output : Dict [ str , Any ] ) -> Dict [ str , str ] : """Return a mapping of contract name to relative path as defined in compiler output ."""
return { contract_name : make_path_relative ( path ) for path in compiler_output for contract_name in compiler_output [ path ] . keys ( ) }
def check_version_info ( redis_client ) : """Check if various version info of this process is correct . This will be used to detect if workers or drivers are started using different versions of Python , pyarrow , or Ray . If the version information is not present in Redis , then no check is done . Args : ...
redis_reply = redis_client . get ( "VERSION_INFO" ) # Don ' t do the check if there is no version information in Redis . This # is to make it easier to do things like start the processes by hand . if redis_reply is None : return true_version_info = tuple ( json . loads ( ray . utils . decode ( redis_reply ) ) ) ver...
def create_dev_vlan ( vlanid , vlan_name , auth , url , devid = None , devip = None ) : """function takes devid and vlanid vlan _ name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device . VLAN Name MUST be valid on target device . : param vlanid :...
if devip is not None : devid = get_dev_details ( devip , auth , url ) [ 'id' ] create_dev_vlan_url = "/imcrs/vlan?devId=" + str ( devid ) f_url = url + create_dev_vlan_url payload = '''{"vlanId":"%s", "vlanName":"%s"}''' % ( str ( vlanid ) , vlan_name ) response = requests . post ( f_url , data = payload , auth = a...
def dump_stats ( myStats ) : """Show stats when pings are done"""
print ( "\n----%s PYTHON PING Statistics----" % ( myStats . thisIP ) ) if myStats . pktsSent > 0 : myStats . fracLoss = ( myStats . pktsSent - myStats . pktsRcvd ) / myStats . pktsSent print ( ( "%d packets transmitted, %d packets received, " "%0.1f%% packet loss" ) % ( myStats . pktsSent , myStats . pktsRcvd , 100...
def register_actions ( self , shortcut_manager ) : """Register callback methods for triggered actions in all child controllers . : param rafcon . gui . shortcut _ manager . ShortcutManager shortcut _ manager : Shortcut Manager Object holding mappings between shortcuts and actions ."""
assert isinstance ( shortcut_manager , ShortcutManager ) self . __shortcut_manager = shortcut_manager for controller in list ( self . __child_controllers . values ( ) ) : if controller not in self . __action_registered_controllers : try : controller . register_actions ( shortcut_manager ) ...
def find_module ( self , fullname , path = None ) : """Looks up the table based on the module path ."""
if not fullname . startswith ( self . _module_name + '.' ) : # Not a quilt submodule . return None submodule = fullname [ len ( self . _module_name ) + 1 : ] parts = submodule . split ( '.' ) # Pop the team prefix if this is a team import . if self . _teams : team = parts . pop ( 0 ) else : team = None # Ha...
def muc_set_affiliation ( self , jid , affiliation , * , reason = None ) : """Convenience wrapper around : meth : ` . MUCClient . set _ affiliation ` . See there for details , and consider its ` mucjid ` argument to be set to : attr : ` mucjid ` ."""
return ( yield from self . service . set_affiliation ( self . _mucjid , jid , affiliation , reason = reason ) )
def printmp ( msg ) : """Print temporarily , until next print overrides it ."""
filler = ( 80 - len ( msg ) ) * ' ' print ( msg + filler , end = '\r' ) sys . stdout . flush ( )
def do_loop_turn ( self ) : # pylint : disable = too - many - branches , too - many - statements , too - many - locals """Loop turn for Arbiter If not a master daemon , wait for my master death . . . Else , run : * Check satellites are alive * Check and dispatch ( if needed ) the configuration * Get broks...
# If I am a spare , I only wait for the master arbiter to die . . . if not self . is_master : logger . debug ( "Waiting for my master death..." ) self . wait_for_master_death ( ) return if self . loop_count % self . alignak_monitor_period == 1 : self . get_alignak_status ( details = True ) # Maybe an ex...
def send ( self , data ) : """Sends data to the ` AlarmDecoder ` _ device . : param data : data to send : type data : string"""
if self . _device : if isinstance ( data , str ) : data = str . encode ( data ) # Hack to support unicode under Python 2 . x if sys . version_info < ( 3 , ) : if isinstance ( data , unicode ) : data = bytes ( data ) self . _device . write ( data )
def generate_start_command ( server , options_override = None , standalone = False ) : """Check if we need to use numactl if we are running on a NUMA box . 10gen recommends using numactl on NUMA . For more info , see http : / / www . mongodb . org / display / DOCS / NUMA"""
command = [ ] if mongod_needs_numactl ( ) : log_info ( "Running on a NUMA machine..." ) command = apply_numactl ( command ) # append the mongod executable command . append ( get_server_executable ( server ) ) # create the command args cmd_options = server . export_cmd_options ( options_override = options_overri...
def status_messages ( self ) : """Returns status messages if any"""
messages = IStatusMessage ( self . request ) m = messages . show ( ) for item in m : item . id = idnormalizer . normalize ( item . message ) return m
def arg_parser ( * args , ** kwargs ) : """Return a parser with common options used in the prawtools commands ."""
msg = { 'site' : 'The site to connect to defined in your praw.ini file.' , 'update' : 'Prevent the checking for prawtools package updates.' } kwargs [ 'version' ] = 'BBoe\'s PRAWtools {}' . format ( __version__ ) parser = OptionParser ( * args , ** kwargs ) parser . add_option ( '-v' , '--verbose' , action = 'count' , ...
def get_parent ( self , context ) : """Load the parent template using our own ` ` find _ template ` ` , which will cause its absolute path to not be used again . Then peek at the first node , and if its parent arg is the same as the current parent arg , we know circular inheritance is going to occur , in wh...
parent = self . parent_name . resolve ( context ) # If parent is a template object , just return it . if hasattr ( parent , "render" ) : return parent template = self . find_template ( parent , context ) for node in template . nodelist : if ( isinstance ( node , ExtendsNode ) and node . parent_name . resolve ( ...
def validate ( cls , mapper_spec ) : """Validate mapper specification . Args : mapper _ spec : an instance of model . MapperSpec Raises : BadReaderParamsError : if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name ."""
reader_spec = cls . get_params ( mapper_spec , allow_old = False ) # Bucket Name is required if cls . BUCKET_NAME_PARAM not in reader_spec : raise errors . BadReaderParamsError ( "%s is required for Google Cloud Storage" % cls . BUCKET_NAME_PARAM ) try : cloudstorage . validate_bucket_name ( reader_spec [ cls ....
def serialize_quantity ( o ) : """Serializes an : obj : ` astropy . units . Quantity ` , for JSONification . Args : o ( : obj : ` astropy . units . Quantity ` ) : : obj : ` Quantity ` to be serialized . Returns : A dictionary that can be passed to : obj : ` json . dumps ` ."""
return dict ( _type = 'astropy.units.Quantity' , value = o . value , unit = o . unit . to_string ( ) )
def heating_remaining ( self ) : """Return seconds of heat time remaining ."""
try : if self . side == 'left' : timerem = self . device . device_data [ 'leftHeatingDuration' ] elif self . side == 'right' : timerem = self . device . device_data [ 'rightHeatingDuration' ] return timerem except TypeError : return None
def authorized ( self ) : """This is the route / function that the user will be redirected to by the provider ( e . g . Twitter ) after the user has logged into the provider ' s website and authorized your app to access their account ."""
if self . redirect_url : next_url = self . redirect_url elif self . redirect_to : next_url = url_for ( self . redirect_to ) else : next_url = "/" try : self . session . parse_authorization_response ( request . url ) except TokenMissing as err : message = err . args [ 0 ] response = getattr ( err...
def NoExclusions ( self ) : """Determine that there are no exclusion criterion in play : return : True if there is no real boundary specification of any kind . Simple method allowing parsers to short circuit the determination of missingness , which can be moderately compute intensive ."""
if len ( self . start_bounds ) + len ( self . target_rs ) + len ( self . ignored_rs ) == 0 : return BoundaryCheck . chrom == - 1 return False
def get_phrases ( self , ns = None , layer = 'syntax' , cat_key = 'cat' , cat_val = 'NP' ) : """yield all node IDs that dominate the given phrase type , e . g . all NPs"""
if not ns : ns = self . ns for node_id in select_nodes_by_layer ( self , '{0}:{1}' . format ( ns , layer ) ) : if self . node [ node_id ] [ self . ns + ':' + cat_key ] == cat_val : yield node_id