signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def mini ( description , applicationName = 'PythonMini' , noteType = "Message" , title = "Mini Message" , applicationIcon = None , hostname = 'localhost' , password = None , port = 23053 , sticky = False , priority = None , callback = None , notificationIcon = None , identifier = None , notifierFactory = GrowlNotifier ... | try :
growl = notifierFactory ( applicationName = applicationName , notifications = [ noteType ] , defaultNotifications = [ noteType ] , applicationIcon = applicationIcon , hostname = hostname , password = password , port = port , )
result = growl . register ( )
if result is not True :
return result... |
def post ( self , result_id , project_id ) :
"""POST / api / v1 / results / < int : id > / commands .""" | result = db . session . query ( Result ) . filter_by ( id = result_id ) . first ( )
if result is None :
return jsonify ( { 'result' : None , 'message' : 'No interface defined for URL.' } ) , 404
job_status = CommandsState . job_status ( result . path_name )
if job_status != JobStatus . RUNNING :
if job_status =... |
def flattenPort ( port : LPort ) :
"""Flatten hierarchical ports""" | yield port
if port . children :
for ch in port . children :
yield from flattenPort ( ch )
port . children . clear ( ) |
def compute_diffusion_maps ( lapl_type , diffusion_map , lambdas , diffusion_time ) :
"""Credit to Satrajit Ghosh ( http : / / satra . cogitatum . org / ) for final steps""" | # Check that diffusion maps is using the correct laplacian , warn otherwise
if lapl_type not in [ 'geometric' , 'renormalized' ] :
warnings . warn ( "for correct diffusion maps embedding use laplacian type 'geometric' or 'renormalized'." )
# Step 5 of diffusion maps :
vectors = diffusion_map . copy ( )
psi = vector... |
def samse ( args , opts ) :
"""% prog samse database . fasta short _ read . fastq
Wrapper for ` bwa samse ` . Output will be short _ read . sam .""" | dbfile , readfile = args
dbfile = check_index ( dbfile )
saifile = check_aln ( dbfile , readfile , cpus = opts . cpus )
samfile , _ , unmapped = get_samfile ( readfile , dbfile , bam = opts . bam , unmapped = opts . unmapped )
if not need_update ( ( dbfile , saifile ) , samfile ) :
logging . error ( "`{0}` exists. ... |
def _invalid_implementation ( self , t , missing , mistyped , mismatched ) :
"""Make a TypeError explaining why ` ` t ` ` doesn ' t implement our interface .""" | assert missing or mistyped or mismatched , "Implementation wasn't invalid."
message = "\nclass {C} failed to implement interface {I}:" . format ( C = getname ( t ) , I = getname ( self ) , )
if missing :
message += dedent ( """
The following methods of {I} were not implemented:
{mis... |
def _add_non_batch ( self , TX_nodes , PmtInf_nodes ) :
"""Method to add a transaction as non batch , will fold the transaction
together with the payment info node and append to the main xml .""" | PmtInf_nodes [ 'PmtInfNode' ] . append ( PmtInf_nodes [ 'PmtInfIdNode' ] )
PmtInf_nodes [ 'PmtInfNode' ] . append ( PmtInf_nodes [ 'PmtMtdNode' ] )
PmtInf_nodes [ 'PmtInfNode' ] . append ( PmtInf_nodes [ 'BtchBookgNode' ] )
PmtInf_nodes [ 'PmtInfNode' ] . append ( PmtInf_nodes [ 'NbOfTxsNode' ] )
PmtInf_nodes [ 'PmtInf... |
def preview ( ident ) :
'''Preview an harvesting for a given source''' | source = get_source ( ident )
cls = backends . get ( current_app , source . backend )
max_items = current_app . config [ 'HARVEST_PREVIEW_MAX_ITEMS' ]
backend = cls ( source , dryrun = True , max_items = max_items )
return backend . harvest ( ) |
def _text_filter_input ( self , input_gen , scraper_config ) :
"""Filters out the text input line by line to avoid parsing and processing
metrics we know we don ' t want to process . This only works on ` text / plain `
payloads , and is an INTERNAL FEATURE implemented for the kubelet check
: param input _ get... | for line in input_gen :
for item in scraper_config [ '_text_filter_blacklist' ] :
if item in line :
break
else : # No blacklist matches , passing the line through
yield line |
def checkAndCreate ( self , key , payload ) :
"""Function checkAndCreate
Check if an object exists and create it if not
@ param key : The targeted object
@ param payload : The targeted object description
@ return RETURN : The id of the object""" | if key not in self :
self [ key ] = payload
return self [ key ] [ 'id' ] |
def handle_example ( self , text , continue_flag ) :
"""parses for the tutorial""" | cmd = text . partition ( SELECT_SYMBOL [ 'example' ] ) [ 0 ] . rstrip ( )
num = text . partition ( SELECT_SYMBOL [ 'example' ] ) [ 2 ] . strip ( )
example = ""
try :
num = int ( num ) - 1
except ValueError :
print ( "An Integer should follow the colon" , file = self . output )
return ""
if cmd in self . com... |
def poisson_equation ( image , gradient = 1 , max_iter = 100 , convergence = .01 , percentile = 90.0 ) :
'''Estimate the solution to the Poisson Equation
The Poisson Equation is the solution to gradient ( x ) = h ^ 2/4 and , in this
context , we use a boundary condition where x is zero for background
pixels .... | # Evaluate the poisson equation with zero - padded boundaries
pe = np . zeros ( ( image . shape [ 0 ] + 2 , image . shape [ 1 ] + 2 ) )
if image . shape [ 0 ] > 64 and image . shape [ 1 ] > 64 : # Sub - sample to get seed values
sub_image = image [ : : 2 , : : 2 ]
sub_pe = poisson_equation ( sub_image , gradien... |
def get_or_select_template ( self , template_name_or_list , parent = None , globals = None ) :
"""Does a typecheck and dispatches to : meth : ` select _ template `
if an iterable of template names is given , otherwise to
: meth : ` get _ template ` .
. . versionadded : : 2.3""" | if isinstance ( template_name_or_list , string_types ) :
return self . get_template ( template_name_or_list , parent , globals )
elif isinstance ( template_name_or_list , Template ) :
return template_name_or_list
return self . select_template ( template_name_or_list , parent , globals ) |
def cli ( wio ) :
'''Login with your Wio account .
DOES :
Login and save an access token for interacting with your account on the Wio .
USE :
wio login''' | mserver = wio . config . get ( "mserver" , None )
if mserver :
click . echo ( click . style ( '> ' , fg = 'green' ) + "Current server is: " + click . style ( mserver , fg = 'green' ) )
if click . confirm ( click . style ( 'Would you like login with a different server?' , bold = True ) , default = False ) :
... |
def editflags ( fd , add_flags = 0 , remove_flags = 0 ) :
"""Sets and unsets per - file filesystem flags .""" | if add_flags & remove_flags != 0 :
raise ValueError ( 'Added and removed flags shouldn\'t overlap' , add_flags , remove_flags )
# The ext2progs code uses int or unsigned long ,
# the kernel uses an implicit int ,
# let ' s be explicit here .
flags_ptr = ffi . new ( 'uint64_t*' )
flags_buf = ffi . buffer ( flags_ptr... |
def gw_run ( self ) :
"""Performs FIESTA ( gw ) run""" | if self . folder != os . getcwd ( ) :
init_folder = os . getcwd ( )
os . chdir ( self . folder )
with zopen ( self . log_file , 'w' ) as fout :
subprocess . call ( [ "mpirun" , "-n" , str ( self . mpi_procs ) , "fiesta" , str ( self . grid [ 0 ] ) , str ( self . grid [ 1 ] ) , str ( self . grid [ 2 ] ) ] , ... |
def prepend_to_list ( self , key , * value , pipeline = False ) :
"""Add new element to the start of the list stored at key .
Args :
key ( str ) : Key where the list is stored
value : Value to add to the list
pipeline ( bool ) : True , start a transaction block . Default false .""" | if pipeline :
self . _pipeline . lpush ( key , * value )
else :
self . _db . lpush ( key , * value ) |
def run ( self ) :
"""run : None - > None
This method overrides threading . Thread . run ( ) and is automatically
called when an instance is created with threading enabled .""" | while True :
try :
self . _callback ( self . wait_read_frame ( ) )
except ThreadQuitException : # Expected termintation of thread due to self . halt ( )
break
except Exception as e : # Unexpected thread quit .
if self . _error_callback :
self . _error_callback ( e ) |
def fit_offset_and_rotation ( coords0 , coords1 ) :
"""Fit a rotation and a traslation between two sets points .
Fit a rotation matrix and a traslation bewtween two matched sets
consisting of M N - dimensional points
Parameters
coords0 : ( M , N ) array _ like
coords1 : ( M , N ) array _ lke
Returns
o... | coords0 = numpy . asarray ( coords0 )
coords1 = numpy . asarray ( coords1 )
cp = coords0 . mean ( axis = 0 )
cq = coords1 . mean ( axis = 0 )
p0 = coords0 - cp
q0 = coords1 - cq
crossvar = numpy . dot ( numpy . transpose ( p0 ) , q0 )
u , _ , vt = linalg . svd ( crossvar )
d = linalg . det ( u ) * linalg . det ( vt )
i... |
def compute_merkletree_with ( merkletree : MerkleTreeState , lockhash : LockHash , ) -> Optional [ MerkleTreeState ] :
"""Register the given lockhash with the existing merkle tree .""" | # Use None to inform the caller the lockshash is already known
result = None
leaves = merkletree . layers [ LEAVES ]
if lockhash not in leaves :
leaves = list ( leaves )
leaves . append ( Keccak256 ( lockhash ) )
result = MerkleTreeState ( compute_layers ( leaves ) )
return result |
def remote_chassis_id_mac_uneq_store ( self , remote_chassis_id_mac ) :
"""This function saves the Chassis MAC , if different from stored .""" | if remote_chassis_id_mac != self . remote_chassis_id_mac :
self . remote_chassis_id_mac = remote_chassis_id_mac
return True
return False |
def topological_operator_iterator ( self ) :
'''This is an iterator of all operators in Topology object . Operators may be produced in a topological order .
If you want to simply go though all operators without considering their topological structure , please use
another function , unordered _ operator _ iterat... | self . _initialize_graph_status_for_traversing ( )
priorities = { 'tensorToProbabilityMap' : 2 , 'tensorToLabel' : 1 }
while not all ( operator . is_evaluated for scope in self . scopes for operator in scope . operators . values ( ) ) :
is_evaluation_happened = False
for operator in sorted ( self . unordered_op... |
def common ( self ) :
"""Return the set of parameters that are common to all types of keys .
: return : Dictionary""" | res = { "kty" : self . kty }
if self . use :
res [ "use" ] = self . use
if self . kid :
res [ "kid" ] = self . kid
if self . alg :
res [ "alg" ] = self . alg
return res |
def json_obj_to_cursor ( self , json ) :
"""( Deprecated ) Converts a JSON object to a mongo db cursor
: param str json : A json string
: returns : dictionary with ObjectId type
: rtype : dict""" | cursor = json_util . loads ( json )
if "id" in json :
cursor [ "_id" ] = ObjectId ( cursor [ "id" ] )
del cursor [ "id" ]
return cursor |
def serial_udb_extra_f15_send ( self , sue_ID_VEHICLE_MODEL_NAME , sue_ID_VEHICLE_REGISTRATION , force_mavlink1 = False ) :
'''Backwards compatible version of SERIAL _ UDB _ EXTRA F15 and F16 : format
sue _ ID _ VEHICLE _ MODEL _ NAME : Serial UDB Extra Model Name Of Vehicle ( uint8 _ t )
sue _ ID _ VEHICLE _ R... | return self . send ( self . serial_udb_extra_f15_encode ( sue_ID_VEHICLE_MODEL_NAME , sue_ID_VEHICLE_REGISTRATION ) , force_mavlink1 = force_mavlink1 ) |
def outputConnections ( self , cls = None ) :
"""Returns a list of output connections from the scene that match the
inputed class for this node .
: param cls | < subclass of XNodeConnection > | | None
: return [ < XNodeConnection > , . . ]""" | scene = self . scene ( )
if not scene :
return [ ]
if not cls :
cls = XNodeConnection
output = [ ]
for item in scene . items ( ) :
if not isinstance ( item , cls ) :
continue
if item . outputNode ( ) == self :
output . append ( item )
return output |
def helical_laminar_fd_White ( Re , Di , Dc ) :
r'''Calculates Darcy friction factor for a fluid flowing inside a curved
pipe such as a helical coil under laminar conditions , using the method of
White [ 1 ] _ as shown in [ 2 ] _ .
. . math : :
f _ { curved } = f _ { \ text { straight , laminar } } \ left [... | De = Dean ( Re = Re , Di = Di , D = Dc )
fd = friction_laminar ( Re )
if De < 11.6 :
return fd
return fd / ( 1. - ( 1. - ( 11.6 / De ) ** 0.45 ) ** ( 1. / 0.45 ) ) |
def MakeHistFromList ( t , name = '' ) :
"""Makes a histogram from an unsorted sequence of values .
Args :
t : sequence of numbers
name : string name for this histogram
Returns :
Hist object""" | hist = Hist ( name = name )
[ hist . Incr ( x ) for x in t ]
return hist |
async def BlockUntilLeadershipReleased ( self , name ) :
'''name : str
Returns - > Error''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'LeadershipService' , request = 'BlockUntilLeadershipReleased' , version = 2 , params = _params )
_params [ 'Name' ] = name
reply = await self . rpc ( msg )
return reply |
def make_ngram_corpus ( corpus_clean_visibles , num_tokens , filter_punctuation , zoning_rules = False ) :
'''takes a list of clean _ visible texts , such as from StreamItems or
FCs , tokenizes all the texts , and constructs n - grams using
` num _ tokens ` sized windows .
` ` corpus _ clean _ visibles ` ` - ... | # # TODO : generatlize this zoning code , so that it works on many
# # sites in the HT domain ; consider finishing streamcorpus - zoner
# # to do this .
if filter_punctuation : # # word tokenizer that removes punctuation
tokenize = RegexpTokenizer ( r'\w+' ) . tokenize
backpage_string = 'backpage'
end_strin... |
def round_to_sigfigs ( num , sigfigs ) :
"""Rounds a number rounded to a specific number of significant
figures instead of to a specific precision .""" | if type ( sigfigs ) != int :
raise TypeError ( "Number of significant figures must be integer." )
elif sigfigs < 1 :
raise ValueError ( "Number of significant figures " "must be larger than zero." )
elif num == 0 :
return num
else :
prec = int ( sigfigs - np . ceil ( np . log10 ( np . absolute ( num ) )... |
def user ( self , login = None ) :
'''Get user information .
: param login : ( optional ) the login name of the user or None . If login is None
this method will return the information of the authenticated user .''' | if login :
url = '%s/user/%s' % ( self . domain , login )
else :
url = '%s/user' % ( self . domain )
res = self . session . get ( url , verify = self . session . verify )
self . _check_response ( res )
return res . json ( ) |
def illumg ( method , target , ilusrc , et , fixref , abcorr , obsrvr , spoint ) :
"""Find the illumination angles ( phase , incidence , and
emission ) at a specified surface point of a target body .
The surface of the target body may be represented by a triaxial
ellipsoid or by topographic data provided by D... | method = stypes . stringToCharP ( method )
target = stypes . stringToCharP ( target )
ilusrc = stypes . stringToCharP ( ilusrc )
et = ctypes . c_double ( et )
fixref = stypes . stringToCharP ( fixref )
abcorr = stypes . stringToCharP ( abcorr )
obsrvr = stypes . stringToCharP ( obsrvr )
spoint = stypes . toDoubleVector... |
def check_initial_web_request ( self , item_session : ItemSession , request : HTTPRequest ) -> Tuple [ bool , str ] :
'''Check robots . txt , URL filters , and scripting hook .
Returns :
tuple : ( bool , str )
Coroutine .''' | verdict , reason , test_info = self . consult_filters ( item_session . request . url_info , item_session . url_record )
if verdict and self . _robots_txt_checker :
can_fetch = yield from self . consult_robots_txt ( request )
if not can_fetch :
verdict = False
reason = 'robotstxt'
verdict , reaso... |
def realtime ( widget , url_name = None , url_regex = None , time_interval = None ) :
"""Return a widget as real - time .
Args :
widget ( Widget ) : the widget to register and return as real - time .
url _ name ( str ) : the URL name to call to get updated content .
url _ regex ( regex ) : the URL regex to ... | if not hasattr ( widget , 'get_updated_content' ) :
raise AttributeError ( 'Widget %s must implement get_updated_content ' 'method.' % widget )
elif not callable ( widget . get_updated_content ) :
raise ValueError ( 'get_updated_content in widget %s is not callable' % widget )
if url_name is None :
if getat... |
def wait ( self , wait_time = 0 ) :
"""Blocking call to check if the worker returns the result . One can use
job . result after this call returns ` ` True ` ` .
: arg wait _ time : Time in seconds to wait , default is infinite .
: return : ` True ` or ` False ` .
. . note : :
This is a blocking call , you... | if self . __result :
return True
data = self . rdb . brpop ( self . urn , wait_time )
if data :
self . rdb . delete ( self . urn )
data = json . loads ( data [ 1 ] )
self . __result = data
return True
else :
return False |
def _parse_list_buckets ( self , ( response , xml_bytes ) ) :
"""Parse XML bucket list response .""" | root = XML ( xml_bytes )
buckets = [ ]
for bucket_data in root . find ( "Buckets" ) :
name = bucket_data . findtext ( "Name" )
date_text = bucket_data . findtext ( "CreationDate" )
date_time = parseTime ( date_text )
bucket = Bucket ( name , date_time )
buckets . append ( bucket )
return buckets |
def has_args ( ) :
'''returns true if the decorator invocation
had arguments passed to it before being
sent a function to decorate''' | no_args_syntax = '@overload'
args_syntax = no_args_syntax + '('
args , no_args = [ ( - 1 , - 1 ) ] , [ ( - 1 , - 1 ) ]
for i , line in enumerate ( Overload . traceback_lines ( ) ) :
if args_syntax in line :
args . append ( ( i , line . find ( args_syntax ) ) )
if no_args_syntax in line :
no_args... |
def addr ( self ) :
"""Get the concrete address of the instruction pointer , without triggering SimInspect breakpoints or generating
SimActions . An integer is returned , or an exception is raised if the instruction pointer is symbolic .
: return : an int""" | ip = self . regs . _ip
if isinstance ( ip , SootAddressDescriptor ) :
return ip
return self . solver . eval_one ( self . regs . _ip ) |
def prior_prior_model_dict ( self ) :
"""Returns
prior _ prior _ model _ dict : { Prior : PriorModel }
A dictionary mapping priors to associated prior models . Each prior will only have one prior model ; if a
prior is shared by two prior models then one of those prior models will be in this dictionary .""" | return { prior : prior_model [ 1 ] for prior_model in self . prior_model_tuples for _ , prior in prior_model [ 1 ] . prior_tuples } |
def data ( self , index , role = QtCore . Qt . DisplayRole ) :
"""Reimplemented from QtCore . QAbstractItemModel
The value gets validated and is red if validation fails
and green if it passes .""" | if not index . isValid ( ) :
return None
if role == QtCore . Qt . DisplayRole or role == QtCore . Qt . EditRole :
if index . column ( ) == 0 :
p = index . internalPointer ( )
k = self . get_key ( p , index . row ( ) )
return k
if index . column ( ) == 1 :
v = self . get_value... |
def update_topic ( self , topic_id , title , content ) :
"""更新话题
: param topic _ id : 话题ID
: param title : 标题
: param content : 内容
: return : bool""" | xml = self . api . req ( API_GROUP_UPDATE_TOPIC % topic_id , 'post' , data = { 'ck' : self . api . ck ( ) , 'rev_title' : title , 'rev_text' : content , 'rev_submit' : '好了,改吧' , } )
return not xml . url . startswith ( API_GROUP_UPDATE_TOPIC % topic_id ) |
def delete_image ( self , identifier ) :
"""DELETE / : login / images / : id
: param identifier : match on the listed image identifier
: type identifier : : py : class : ` basestring ` or : py : class : ` dict `
A string or a dictionary containing an ` ` id ` ` key may be
passed in . Will raise an error if ... | if isinstance ( identifier , dict ) :
identifier = identifier . get ( 'id' , '' )
j , r = self . request ( 'DELETE' , '/images/' + str ( identifier ) )
r . raise_for_status ( )
return j |
def subkey_for_path ( self , path ) :
"""path : a path of subkeys denoted by numbers and slashes . Use H or p
for private key derivation . End with . pub to force the key
public .
Examples : 1H / 5/2/1 would call subkey ( i = 1 , is _ hardened = True )
. subkey ( i = 5 ) . subkey ( i = 2 ) . subkey ( i = 1 ... | force_public = ( path [ - 4 : ] == '.pub' )
if force_public :
path = path [ : - 4 ]
key = self
if path :
invocations = path . split ( "/" )
for v in invocations :
is_hardened = v [ - 1 ] in ( "'pH" )
if is_hardened :
v = v [ : - 1 ]
v = int ( v )
key = key . subke... |
def update ( self , query_name , saved_query_attributes ) :
"""Given a dict of attributes to be updated , update only those attributes
in the Saved Query at the resource given by ' query _ name ' . This will
perform two HTTP requests - - one to fetch the query definition , and one
to set the new attributes . ... | query_name_attr_name = "query_name"
refresh_rate_attr_name = "refresh_rate"
query_attr_name = "query"
metadata_attr_name = "metadata"
old_saved_query = self . get ( query_name )
# Create a new query def to send back . We cannot send values for attributes like ' urls ' ,
# ' last _ modified _ date ' , ' run _ informatio... |
def _on_new_data_received ( self , data : bytes ) :
"""Gets called whenever we get a whole new XML element from kik ' s servers .
: param data : The data received ( bytes )""" | if data == b' ' : # Happens every half hour . Disconnect after 10th time . Some kind of keep - alive ? Let ' s send it back .
self . loop . call_soon_threadsafe ( self . connection . send_raw_data , b' ' )
return
xml_element = BeautifulSoup ( data . decode ( ) , features = 'xml' )
xml_element = next ( iter ( xm... |
def mac ( raw ) :
"""Converts a raw string to a standardised MAC Address EUI Format .
: param raw : the raw string containing the value of the MAC Address
: return : a string with the MAC Address in EUI format
Example :
. . code - block : : python
> > > mac ( ' 0123.4567.89ab ' )
u ' 01:23:45:67:89 : AB... | if raw . endswith ( ':' ) :
flat_raw = raw . replace ( ':' , '' )
raw = '{flat_raw}{zeros_stuffed}' . format ( flat_raw = flat_raw , zeros_stuffed = '0' * ( 12 - len ( flat_raw ) ) )
return py23_compat . text_type ( EUI ( raw , dialect = _MACFormat ) ) |
def swipe ( self ) :
"""Mirror current array value in reverse . Bits that had greater index will have lesser index , and
vice - versa . This method doesn ' t change this array . It creates a new one and return it as a result .
: return : WBinArray""" | result = WBinArray ( 0 , len ( self ) )
for i in range ( len ( self ) ) :
result [ len ( self ) - i - 1 ] = self [ i ]
return result |
def authenticate ( self , username = None , password = None , api_key = None , tenant_id = None , connect = False ) :
"""Using the supplied credentials , connects to the specified
authentication endpoint and attempts to log in .
Credentials can either be passed directly to this method , or
previously - stored... | self . username = username or self . username or pyrax . get_setting ( "username" )
# Different identity systems may pass these under inconsistent names .
self . password = password or self . password or api_key or self . api_key
self . api_key = api_key or self . api_key or self . password
self . tenant_id = tenant_id... |
def determine_action ( self , issue ) :
"""Determine the action we should take for the issue
Args :
issue : Issue to determine action for
Returns :
` dict `""" | resource_type = self . resource_types [ issue . resource . resource_type_id ]
issue_alert_schedule = self . alert_schedule [ resource_type ] if resource_type in self . alert_schedule else self . alert_schedule [ '*' ]
action_item = { 'action' : None , 'action_description' : None , 'last_alert' : issue . last_alert , 'i... |
def add_prefix ( self , ns_uri , prefix , set_as_preferred = False ) :
"""Adds prefix for the given namespace URI . The namespace must already
exist in this set . If set _ as _ preferred is True , also set this
namespace as the preferred one .
` ` prefix ` ` must be non - None ; a default preference can ' t b... | assert prefix
ni = self . __lookup_uri ( ns_uri )
self . __check_prefix_conflict ( ni , prefix )
ni . prefixes . add ( prefix )
self . __prefix_map [ prefix ] = ni
if set_as_preferred :
ni . preferred_prefix = prefix |
def get_tilting ( self , oplane ) :
'''Main procedure''' | surf_atom1 , surf_atom2 , surf_atom3 , surf_atom4 = oplane
# divide surface atoms into groups by distance between them
compare = [ surf_atom2 , surf_atom3 , surf_atom4 ]
distance_map = [ ]
for i in range ( 0 , 3 ) :
distance_map . append ( [ compare [ i ] , self . virtual_atoms . get_distance ( surf_atom1 , compare... |
def handle_error ( self ) :
"""Handles an error log record that should be shown
Returns :
None""" | if not self . tasks :
return
# All the parents inherit the failure
self . mark_parent_tasks_as_failed ( self . cur_task , flush_logs = True , )
# Show the start headers for all the parent tasks if they were not
# shown by the depth level limit
for index , task in enumerate ( self . tasks . values ( ) ) :
if sel... |
def _iterateToFindSCPDElements ( self , element , baseURIPath ) :
"""Internal method to iterate through device definition XML tree .
: param element : the XML root node of the device definitions
: type element : xml . etree . ElementTree . Element
: param str baseURIPath : the base URL""" | for child in element . getchildren ( ) :
tagName = child . tag . lower ( )
if tagName . endswith ( 'servicelist' ) :
self . _processServiceList ( child , baseURIPath )
elif tagName . endswith ( 'devicetype' ) :
if "deviceType" not in self . __deviceInformations . keys ( ) :
self ... |
def _eratosthenes ( ) :
"""Yields the sequence of prime numbers via the Sieve of Eratosthenes .""" | d = { }
# map each composite integer to its first - found prime factor
for q in count ( 2 ) : # q gets 2 , 3 , 4 , 5 , . . . ad infinitum
p = d . pop ( q , None )
if p is None : # q not a key in D , so q is prime , therefore , yield it
yield q
# mark q squared as not - prime ( with q as first - ... |
def deprecate ( warning , date = None , log = None ) :
"""Add a deprecation warning the first time the function is used .
The date , which is a string in semi - ISO8660 format indicate the year - month
that the function is officially going to be removed .
usage :
@ deprecate ( ' use core / fetch / add _ sou... | def wrap ( f ) :
@ functools . wraps ( f )
def wrapped_f ( * args , ** kwargs ) :
try :
module = inspect . getmodule ( f )
file = inspect . getsourcefile ( f )
lines = inspect . getsourcelines ( f )
f_name = "{}-{}-{}..{}-{}" . format ( module . __name__ ,... |
def wait_for_event ( self , event_name , predicate , timeout = DEFAULT_TIMEOUT , * args , ** kwargs ) :
"""Wait for an event that satisfies a predicate to appear .
Continuously pop events of a particular name and check against the
predicate until an event that satisfies the predicate is popped or
timed out . ... | deadline = time . time ( ) + timeout
while True :
event = None
try :
event = self . pop_event ( event_name , 1 )
except queue . Empty :
pass
if event and predicate ( event , * args , ** kwargs ) :
return event
if time . time ( ) > deadline :
raise queue . Empty ( 'Tim... |
def traverse ( self , strategy = "levelorder" , is_leaf_fn = None ) :
"""Returns an iterator to traverse tree under this node .
Parameters :
strategy :
set the way in which tree will be traversed . Possible
values are : " preorder " ( first parent and then children )
' postorder ' ( first children and the... | if strategy == "preorder" :
return self . _iter_descendants_preorder ( is_leaf_fn = is_leaf_fn )
elif strategy == "levelorder" :
return self . _iter_descendants_levelorder ( is_leaf_fn = is_leaf_fn )
elif strategy == "postorder" :
return self . _iter_descendants_postorder ( is_leaf_fn = is_leaf_fn ) |
def SendCommand ( self , command , arg = None ) :
"""Sends a command to the device .
Args :
command : The command to send .
arg : Optional argument to the command .""" | if arg is not None :
if not isinstance ( arg , bytes ) :
arg = arg . encode ( 'utf8' )
command = b'%s:%s' % ( command , arg )
self . _Write ( io . BytesIO ( command ) , len ( command ) ) |
def main ( ) :
"""% prog database . fa query . fa [ options ]
Run LASTZ similar to the BLAST interface , and generates - m8 tabular format""" | p = OptionParser ( main . __doc__ )
supported_formats = tuple ( x . strip ( ) for x in "lav, lav+text, axt, axt+, maf, maf+, maf-, sam, softsam, " "sam-, softsam-, cigar, BLASTN, BLASTN-, differences, rdotplot, text" . split ( ',' ) )
p . add_option ( "--format" , default = "BLASTN-" , choices = supported_formats , hel... |
def instances ( self ) :
"""Iterate over the defined Instancees .""" | definstance = lib . EnvGetNextInstance ( self . _env , ffi . NULL )
while definstance != ffi . NULL :
yield Instance ( self . _env , definstance )
definstance = lib . EnvGetNextInstance ( self . _env , definstance ) |
def get ( self , default = None ) :
"""Get the result of the Job , or return * default * if the job is not finished
or errored . This function will never explicitly raise an exception . Note
that the * default * value is also returned if the job was cancelled .
# Arguments
default ( any ) : The value to ret... | if not self . __cancelled and self . __state == Job . SUCCESS :
return self . __result
else :
return default |
def _complete_type_chain ( self , symbol , fullsymbol ) :
"""Suggests completion for the end of a type chain .""" | target , targmod = self . _get_chain_parent_symbol ( symbol , fullsymbol )
if target is None :
return { }
result = { }
# We might know what kind of symbol to limit the completion by depending on whether
# it was preceded by a " call " for example . Check the context ' s el _ call
if symbol != "" :
if self . con... |
def resubmit_workflow ( self , stage_name = None , description = None ) :
'''Resubmits the workflow .
Parameters
stage _ name : str , optional
name of the stage at which workflow should be resubmitted
( when omitted workflow will be restarted from the beginning )
description : dict , optional
workflow d... | logger . info ( 'resubmit workflow of experiment "%s"' , self . experiment_name )
content = dict ( )
if description is not None :
content [ 'description' ] = description
if stage_name is not None :
content [ 'stage_name' ] = stage_name
url = self . _build_api_url ( '/experiments/{experiment_id}/workflow/resubmi... |
def load_codebook ( self , filename ) :
"""Load the codebook from a file to the Somoclu object .
: param filename : The name of the file .
: type filename : str .""" | self . codebook = np . loadtxt ( filename , comments = '%' )
if self . n_dim == 0 :
self . n_dim = self . codebook . shape [ 1 ]
if self . codebook . shape != ( self . _n_rows * self . _n_columns , self . n_dim ) :
raise Exception ( "The dimensions of the codebook do not " "match that of the map" )
self . codeb... |
def _GetNormalizedTimestamp ( self ) :
"""Retrieves the normalized timestamp .
Returns :
decimal . Decimal : normalized timestamp , which contains the number of
seconds since January 1 , 1970 00:00:00 and a fraction of second used
for increased precision , or None if the normalized timestamp cannot be
det... | if self . _normalized_timestamp is None :
if self . _timestamp is not None :
self . _normalized_timestamp = ( decimal . Decimal ( self . _timestamp ) / definitions . NANOSECONDS_PER_SECOND )
return self . _normalized_timestamp |
def new ( self , min , max ) :
"""Create an empty index for intervals in the range min , max""" | # Ensure the range will fit given the shifting strategy
assert MIN <= min <= max <= MAX
self . min = min
self . max = max
# Determine offsets to use
self . offsets = offsets_for_max_size ( max )
# Determine the largest bin we will actually use
self . bin_count = bin_for_range ( max - 1 , max , offsets = self . offsets ... |
def _clean_record ( self , record ) :
"""Remove all fields with ` None ` values""" | for k , v in dict ( record ) . items ( ) :
if isinstance ( v , dict ) :
v = self . _clean_record ( v )
if v is None :
record . pop ( k )
return record |
def reconnect_account ( self ) :
"""Reconnect current account by refreshing OAuth access tokens
: return :""" | url = self . reconnect_url
result = self . get ( url )
return result |
def _load_neighbors_from_database ( self ) -> None :
"""Loads the neighbors of the node from the local database .""" | self . _are_neighbors_loaded = True
graph : Graph = self . _graph
neighbors : List [ DBNode ] = graph . database . Node . find_by_name ( self . name ) . neighbors
nodes : NodeList = graph . nodes
for db_node in neighbors :
graph . add_node ( db_node . name , db_node . external_id )
neighbor : Node = nodes . get... |
def query_param_string_from_option_args ( a2q_dict , args_dict ) :
"""From a dictionary of arguments to query string parameters , loops through ad arguments list and makes a query string .
: param a2q _ dict : a dictionary containing argument _ name > query string parameter name .
: param args _ dict : a dictio... | name_value_pairs = dict ( )
for ak in a2q_dict . keys ( ) :
value = args_dict [ ak ]
if value != None :
name_value_pairs [ a2q_dict [ ak ] ] = str ( value )
return urllib . urlencode ( name_value_pairs ) |
def chain ( self , wrapper , * args , ** kwargs ) :
"""Add a wrapper to the chain . Any extra positional or keyword
arguments will be passed to that wrapper through construction
of a ` ` TendrilPartial ` ` . For convenience , returns the
WrapperChain object , allowing ` ` chain ( ) ` ` to be called on the
r... | if args or kwargs :
wrapper = TendrilPartial ( wrapper , * args , ** kwargs )
self . _wrappers . append ( wrapper )
# For convenience . . .
return self |
def add_gemini_query ( self , name , query ) :
"""Add a user defined gemini query
Args :
name ( str )
query ( str )""" | logger . info ( "Adding query {0} with text {1}" . format ( name , query ) )
new_query = GeminiQuery ( name = name , query = query )
self . session . add ( new_query )
self . save ( )
return new_query |
def S ( self ) :
"English ordinal suffix for the day of the month , 2 characters ; i . e . ' st ' , ' nd ' , ' rd ' or ' th '" | if self . data . day in ( 11 , 12 , 13 ) : # Special case
return u'th'
last = self . data . day % 10
if last == 1 :
return u'st'
if last == 2 :
return u'nd'
if last == 3 :
return u'rd'
return u'th' |
def hmget ( self , name , keys , * args ) :
"Returns a list of values ordered identically to ` ` keys ` `" | args = list_or_args ( keys , args )
return self . execute_command ( 'HMGET' , name , * args ) |
def checkFiles ( filelist , ivmlist = None ) :
"""- Converts waiver fits sciece and data quality files to MEF format
- Converts GEIS science and data quality files to MEF format
- Checks for stis association tables and splits them into single imsets
- Removes files with EXPTIME = 0 and the corresponding ivm f... | toclose = False
if isinstance ( filelist [ 0 ] , str ) :
toclose = True
newfilelist , ivmlist = checkFITSFormat ( filelist , ivmlist )
# check for STIS association files . This must be done before
# the other checks in order to handle correctly stis
# assoc files
newfilelist , ivmlist = checkStisFiles ( newfilelist... |
def update ( self , new_keys : Index ) :
"""Adds the new keys to the mapping .
Parameters
new _ keys :
The new index to hash .""" | if not self . _map . index . intersection ( new_keys ) . empty :
raise KeyError ( "Non-unique keys in index." )
mapping_update = self . hash_ ( new_keys )
if self . _map . empty :
self . _map = mapping_update . drop_duplicates ( )
else :
self . _map = self . _map . append ( mapping_update ) . drop_duplicate... |
def doExperiment ( numColumns , l2Overrides , objectDescriptions , noiseMu , noiseSigma , numInitialTraversals , noiseEverywhere ) :
"""Touch every point on an object ' numInitialTraversals ' times , then evaluate
whether it has inferred the object by touching every point once more and
checking the number of co... | # For each column , keep a mapping from feature - location names to their SDRs
layer4sdr = lambda : np . array ( sorted ( random . sample ( xrange ( L4_CELL_COUNT ) , 40 ) ) , dtype = "uint32" )
featureLocationSDRs = [ defaultdict ( layer4sdr ) for _ in xrange ( numColumns ) ]
params = { "inputWidth" : L4_CELL_COUNT , ... |
def pop ( self ) :
"""Pops the data stack , returning the value .""" | try :
return self . data_stack . pop ( )
except errors . MachineError as e :
raise errors . MachineError ( "%s: At index %d in code: %s" % ( e , self . instruction_pointer , self . code_string ) ) |
def parse ( self , content ) :
"""Parse xml body sent by weixin .
: param content : A text of xml body .""" | raw = { }
try :
root = etree . fromstring ( content )
except SyntaxError as e :
raise ValueError ( * e . args )
for child in root :
raw [ child . tag ] = child . text
formatted = self . format ( raw )
msg_type = formatted [ 'type' ]
msg_parser = getattr ( self , 'parse_%s' % msg_type , None )
if callable ( ... |
def to_lookup ( self , key_selector = identity , value_selector = identity ) :
'''Returns a Lookup object , using the provided selector to generate a
key for each item .
Note : This method uses immediate execution .''' | if self . closed ( ) :
raise ValueError ( "Attempt to call to_lookup() on a closed Queryable." )
if not is_callable ( key_selector ) :
raise TypeError ( "to_lookup() parameter key_selector={key_selector} is not callable" . format ( key_selector = repr ( key_selector ) ) )
if not is_callable ( value_selector ) :... |
def get_authors_string ( self , own_accts = None , replace_own = None ) :
"""returns a string of comma - separated authors
Depending on settings , it will substitute " me " for author name if
address is user ' s own .
: param own _ accts : list of own accounts to replace
: type own _ accts : list of : class... | if replace_own is None :
replace_own = settings . get ( 'thread_authors_replace_me' )
if replace_own :
if own_accts is None :
own_accts = settings . get_accounts ( )
authorslist = [ ]
for aname , aaddress in self . get_authors ( ) :
for account in own_accts :
if account . mat... |
def try_import ( objname ) : # type : ( unicode ) - > Any
"""Import a object or module using * name * and * currentmodule * .
* name * should be a relative name from * currentmodule * or
a fully - qualified name .
Returns imported object or module . If failed , returns None value .""" | try :
__import__ ( objname )
return sys . modules . get ( objname )
# type : ignore
except ( ImportError , ValueError ) : # ValueError , py27 - > ImportError , py3
matched = module_sig_re . match ( objname )
# type : ignore
if not matched :
return None
modname , attrname = matched . ... |
def from_headers ( self , headers ) :
"""Generate a SpanContext object using the W3C Distributed Tracing headers .
: type headers : dict
: param headers : HTTP request headers .
: rtype : : class : ` ~ opencensus . trace . span _ context . SpanContext `
: returns : SpanContext generated from the trace conte... | if headers is None :
return SpanContext ( )
header = headers . get ( _TRACEPARENT_HEADER_NAME )
if header is None :
return SpanContext ( )
match = re . search ( _TRACEPARENT_HEADER_FORMAT_RE , header )
if not match :
return SpanContext ( )
version = match . group ( 1 )
trace_id = match . group ( 2 )
span_id... |
def failed_hosts ( self ) -> Dict [ str , "MultiResult" ] :
"""Hosts that failed to complete the task""" | return { k : v for k , v in self . result . items ( ) if v . failed } |
def get_spn ( unit ) :
"""获取文本行中非中文字符数的个数
Keyword arguments :
unit - - 文本行
Return :
spn - - 特殊字符数""" | spn = 0
match_re = re . findall ( no_chinese , unit )
if match_re :
string = '' . join ( match_re )
spn = len ( string )
return int ( spn ) |
def getOutputElementCount ( self , name ) :
"""Return the number of elements for the given output .""" | if name in [ "activeCells" , "predictedCells" , "predictedActiveCells" , "winnerCells" ] :
return self . cellsPerColumn * self . columnCount
else :
raise Exception ( "Invalid output name specified: %s" % name ) |
def avg ( self , func = lambda x : x ) :
"""Returns the average value of data elements
: param func : lambda expression to transform data
: return : average value as float object""" | count = self . count ( )
if count == 0 :
raise NoElementsError ( u"Iterable contains no elements" )
return float ( self . sum ( func ) ) / float ( count ) |
def tables ( self ) :
"""A lazy loaded reference to the table metadata for the DB .""" | if len ( self . _tables ) == 0 :
self . refresh_schema ( self . _exclude_system_tables , self . _use_cache )
return self . _tables |
def extended_cigar ( aligned_template , aligned_query ) :
'''Convert mutation annotations to extended cigar format
https : / / github . com / lh3 / minimap2 # the - cs - optional - tag
USAGE :
> > > template = ' CGATCGATAAATAGAGTAG - - - GAATAGCA '
> > > query = ' CGATCG - - - AATAGAGTAGGTCGAATtGCA '
> > ... | # - Go through each position in the alignment
insertion = [ ]
deletion = [ ]
matches = [ ]
cigar = [ ]
for r_aa , q_aa in zip ( aligned_template . lower ( ) , aligned_query . lower ( ) ) :
gap_ref = r_aa == '-'
gap_que = q_aa == '-'
match = r_aa == q_aa
if matches and not match : # End match block
... |
def delete_status ( app , user , status_id ) :
"""Deletes a status with given ID .
https : / / github . com / tootsuite / documentation / blob / master / Using - the - API / API . md # deleting - a - status""" | return http . delete ( app , user , '/api/v1/statuses/{}' . format ( status_id ) ) |
def add_column ( table_name , column_name , column , cache = False , cache_scope = _CS_FOREVER ) :
"""Add a new column to a table from a Series or callable .
Parameters
table _ name : str
Table with which the column will be associated .
column _ name : str
Name for the column .
column : pandas . Series ... | if isinstance ( column , Callable ) :
column = _ColumnFuncWrapper ( table_name , column_name , column , cache = cache , cache_scope = cache_scope )
else :
column = _SeriesWrapper ( table_name , column_name , column )
# clear any cached data from a previously registered column
column . clear_cached ( )
logger . ... |
def commit ( * args , ** kwargs ) :
"""Processes all jobs in the delayed queue .""" | delayed_queue = get_queue ( )
try :
while delayed_queue :
queue , args , kwargs = delayed_queue . pop ( 0 )
queue . original_enqueue_call ( * args , ** kwargs )
finally :
clear ( ) |
def _process_args_as_rows_or_columns ( self , arg , unpack = False ) :
"""We must be able to interpret the args as as either a column name or
row number , or sequences thereof . Numpy arrays and slices are also
fine .
Examples :
' field '
35
[35,55,86]
[ ' f1 ' , f2 ' , . . . ]
Can also be tuples or... | flags = set ( )
if isinstance ( arg , ( tuple , list , numpy . ndarray ) ) : # a sequence was entered
if isstring ( arg [ 0 ] ) :
result = arg
else :
result = arg
flags . add ( 'isrows' )
elif isstring ( arg ) : # a single string was entered
result = arg
elif isinstance ( arg , slice... |
def detectors ( regex = None , sep = '\t' , temporary = False ) :
"""Print the detectors table""" | db = DBManager ( temporary = temporary )
dt = db . detectors
if regex is not None :
try :
re . compile ( regex )
except re . error :
log . error ( "Invalid regex!" )
return
dt = dt [ dt [ 'OID' ] . str . contains ( regex ) | dt [ 'CITY' ] . str . contains ( regex ) ]
dt . to_csv ( sy... |
def make_ready ( self ) :
"""Make a task ready for execution""" | SCons . Taskmaster . OutOfDateTask . make_ready ( self )
if self . out_of_date and self . options . debug_explain :
explanation = self . out_of_date [ 0 ] . explain ( )
if explanation :
sys . stdout . write ( "scons: " + explanation ) |
def yesno ( prompt ) :
"""Returns True if user answers ' y '""" | prompt += " [y/n]"
a = ""
while a not in [ "y" , "n" ] :
a = input ( prompt ) . lower ( )
return a == "y" |
def get_slices ( self , extended = False ) :
"""Generator over all the slices selected , each time returning a cross - section .
Parameters
extended : bool
Flag to return just slice data ( default , extended = False ) , or
return a tuple of axis , slice _ num , slice _ data ( extended = True )
Returns
s... | for dim , slice_num in self . _slices :
yield self . _get_axis ( self . _image , dim , slice_num , extended = extended ) |
def id ( self ) -> typing . Union [ str , None ] :
"""Identifier for the project .""" | return self . _project . id if self . _project else None |
def float ( self , var , default = NOTSET ) :
""": rtype : float""" | return self . get_value ( var , cast = float , default = default ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.