signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def format_message ( self , message ) :
"""Formats a message with : class : Look""" | look = Look ( message )
return look . pretty ( display = False ) |
def _lookup_symbol_strict ( self , ownership_map , multi_country , symbol , as_of_date ) :
"""Resolve a symbol to an asset object without fuzzy matching .
Parameters
ownership _ map : dict [ ( str , str ) , list [ OwnershipPeriod ] ]
The mapping from split symbols to ownership periods .
multi _ country : bo... | # split the symbol into the components , if there are no
# company / share class parts then share _ class _ symbol will be empty
company_symbol , share_class_symbol = split_delimited_symbol ( symbol )
try :
owners = ownership_map [ company_symbol , share_class_symbol ]
assert owners , 'empty owners list for %r'... |
def set ( self , document_data , merge = False ) :
"""Replace the current document in the Firestore database .
A write ` ` option ` ` can be specified to indicate preconditions of
the " set " operation . If no ` ` option ` ` is specified and this document
doesn ' t exist yet , this method will create it .
O... | batch = self . _client . batch ( )
batch . set ( self , document_data , merge = merge )
write_results = batch . commit ( )
return _first_write_result ( write_results ) |
def MergeVcards ( vcard1 , vcard2 ) :
"""Create a new vCard and populate it .""" | new_vcard = vobject . vCard ( )
vcard1_fields = set ( vcard1 . contents . keys ( ) )
vcard2_fields = set ( vcard2 . contents . keys ( ) )
mutual_fields = vcard1_fields . intersection ( vcard2_fields )
logger . debug ( 'Potentially conflicting fields: {}' . format ( mutual_fields ) )
for field in mutual_fields :
val... |
def header_check ( self , content ) :
"""Special Python encoding check .""" | encode = None
m = RE_PY_ENCODE . match ( content )
if m :
if m . group ( 1 ) :
encode = m . group ( 1 ) . decode ( 'ascii' )
elif m . group ( 2 ) :
encode = m . group ( 2 ) . decode ( 'ascii' )
if encode is None :
encode = 'utf-8'
return encode |
def get_xlmhg_pval2 ( N , K , X , L , stat , tol = DEFAULT_TOL ) :
"""Calculate the XL - mHG p - value using " Algorithm 2 " .
Parameters
N : int
The length of the list .
K : int
The number of 1 ' s in the list .
X : int
The XL - mHG ` ` X ` ` parameter .
L : int
The XL - mHG ` ` L ` ` parameter .... | # type checking
assert isinstance ( N , int )
assert isinstance ( X , int )
assert isinstance ( L , int )
assert isinstance ( stat , float )
assert isinstance ( tol , float )
# raise exceptions for invalid parameters
if not ( N >= 1 ) :
raise ValueError ( 'Invalid value N=%d; must be >= 1.' % ( N ) )
if not ( 1 <= ... |
def get_variable ( self , variable_name , check_existence = False ) :
"""Get a variable from the tax and benefit system .
: param variable _ name : Name of the requested variable .
: param check _ existence : If True , raise an error if the requested variable does not exist .""" | variables = self . variables
found = variables . get ( variable_name )
if not found and check_existence :
raise VariableNotFound ( variable_name , self )
return found |
def discriminator2 ( ndf , no_bias = True , fix_gamma = True , eps = 1e-5 + 1e-12 ) :
'''Second part of the discriminator which takes a 256x8x8 feature map as input
and generates the loss based on whether the input image was a real one or fake one''' | BatchNorm = mx . sym . BatchNorm
data = mx . sym . Variable ( 'data' )
label = mx . sym . Variable ( 'label' )
d4 = mx . sym . Convolution ( data , name = 'd4' , kernel = ( 5 , 5 ) , stride = ( 2 , 2 ) , pad = ( 2 , 2 ) , num_filter = ndf * 8 , no_bias = no_bias )
dbn4 = BatchNorm ( d4 , name = 'dbn4' , fix_gamma = fix... |
def GetMessages ( self , formatter_mediator , event ) :
"""Determines the formatted message strings for an event object .
Args :
formatter _ mediator ( FormatterMediator ) : mediates the interactions
between formatters and other components , such as storage and Windows
EventLog resources .
event ( EventOb... | if self . DATA_TYPE != event . data_type :
raise errors . WrongFormatter ( 'Unsupported data type: {0:s}.' . format ( event . data_type ) )
event_values = event . CopyToDict ( )
attribute_type = event_values . get ( 'attribute_type' , 0 )
event_values [ 'attribute_name' ] = self . _ATTRIBUTE_NAMES . get ( attribute... |
def mask_image ( image , mask , level = 1 , binarize = False ) :
"""Mask an input image by a mask image . If the mask image has multiple labels ,
it is possible to specify which label ( s ) to mask at .
ANTsR function : ` maskImage `
Arguments
image : ANTsImage
Input image .
mask : ANTsImage
Mask or l... | leveluse = level
if type ( leveluse ) is np . ndarray :
leveluse = level . tolist ( )
image_out = image . clone ( ) * 0
for mylevel in leveluse :
temp = threshold_image ( mask , mylevel , mylevel )
if binarize :
image_out = image_out + temp
else :
image_out = image_out + temp * image
ret... |
def get_conflicts ( self ) :
"""Get conflicts in constraints , if any .
: return : Description of each conflict , empty if none .
: rtype : list ( str )""" | conflicts = [ ]
if self . _array and self . _range :
conflicts . append ( 'cannot use range expressions on arrays' )
return conflicts |
def parse_vasprun ( self ) :
"""Read in ` vasprun . xml ` as a pymatgen Vasprun object .
Args :
None
Returns :
None
None :
If the vasprun . xml is not well formed this method will catch the ParseError
and set self . vasprun = None .""" | self . vasprun_filename = match_filename ( 'vasprun.xml' )
if not self . vasprun_filename :
raise FileNotFoundError ( 'Could not find vasprun.xml or vasprun.xml.gz file' )
try :
self . vasprun = Vasprun ( self . vasprun_filename , parse_potcar_file = False )
except ET . ParseError :
self . vasprun = None
ex... |
def folderitem ( self , obj , item , index ) :
"""Service triggered each time an item is iterated in folderitems .
The use of this service prevents the extra - loops in child objects .
: obj : the instance of the class to be foldered
: item : dict containing the properties of the object to be used by
the te... | item [ "Description" ] = obj . Description ( )
item [ "replace" ] [ "Title" ] = get_link ( item [ "url" ] , item [ "Title" ] )
instrument = obj . getInstrument ( )
if instrument :
instrument_url = api . get_url ( instrument )
instrument_title = api . get_title ( instrument )
item [ "Instrument" ] = instrume... |
def calculate_incorrect_name_dict ( graph : BELGraph ) -> Mapping [ str , List [ str ] ] :
"""Get missing names grouped by namespace .""" | missing = defaultdict ( list )
for namespace , name in _iterate_namespace_name ( graph ) :
missing [ namespace ] . append ( name )
return dict ( missing ) |
def doPoolUpgrade ( self , upgrade : Upgrade ) :
"""Used to send a new code upgrade
: param upgrade : upgrade data
: return : number of pending txns""" | key = upgrade . key
self . _upgrades [ key ] = upgrade
req = upgrade . ledgerRequest ( )
if req :
self . pendRequest ( req , key )
return len ( self . _pending ) |
def _run_composer ( action , directory = None , composer = None , php = None , runas = None , prefer_source = None , prefer_dist = None , no_scripts = None , no_plugins = None , optimize = None , no_dev = None , quiet = False , composer_home = '/root' , extra_flags = None , env = None ) :
'''Run PHP ' s composer wi... | if composer is not None :
if php is None :
php = 'php'
else :
composer = 'composer'
# Validate Composer is there
if not _valid_composer ( composer ) :
raise CommandNotFoundError ( '\'composer.{0}\' is not available. Couldn\'t find \'{1}\'.' . format ( action , composer ) )
if action is None :
ra... |
def invariants ( mol ) :
"""Generate initial atom identifiers using atomic invariants""" | atom_ids = { }
for a in mol . atoms :
components = [ ]
components . append ( a . number )
components . append ( len ( a . oatoms ) )
components . append ( a . hcount )
components . append ( a . charge )
components . append ( a . mass )
if len ( a . rings ) > 0 :
components . append (... |
def url_for ( obj , ** kw ) :
"""Polymorphic variant of Flask ' s ` url _ for ` function .
Behaves like the original function when the first argument is a
string . When it ' s an object , it""" | if isinstance ( obj , str ) :
return flask_url_for ( obj , ** kw )
try :
return current_app . default_view . url_for ( obj , ** kw )
except KeyError :
if hasattr ( obj , "_url" ) :
return obj . _url
elif hasattr ( obj , "url" ) :
return obj . url
raise BuildError ( repr ( obj ) , kw , "G... |
def Perc ( poly , q , dist , sample = 10000 , ** kws ) :
"""Percentile function .
Note that this function is an empirical function that operates using Monte
Carlo sampling .
Args :
poly ( Poly ) :
Polynomial of interest .
q ( numpy . ndarray ) :
positions where percentiles are taken . Must be a number... | shape = poly . shape
poly = polynomials . flatten ( poly )
q = numpy . array ( q ) / 100.
dim = len ( dist )
# Interior
Z = dist . sample ( sample , ** kws )
if dim == 1 :
Z = ( Z , )
q = numpy . array ( [ q ] )
poly1 = poly ( * Z )
# Min / max
mi , ma = dist . range ( ) . reshape ( 2 , dim )
ext = numpy . mgri... |
def _get_powerinfo ( self , data ) :
'''Return battery voltage and tx power''' | power_info = ( data [ 13 ] & 0xFF ) << 8 | ( data [ 14 ] & 0xFF )
battery_voltage = rshift ( power_info , 5 ) + 1600
tx_power = ( power_info & 0b11111 ) * 2 - 40
if rshift ( power_info , 5 ) == 0b11111111111 :
battery_voltage = None
if ( power_info & 0b11111 ) == 0b11111 :
tx_power = None
return ( round ( batte... |
def register_class ( klass , alias = None ) :
"""Registers a class to be used in the data streaming . This is the equivalent
to the C { [ RemoteClass ( alias = " foobar " ) ] } AS3 metatag .
@ return : The registered L { ClassAlias } instance .
@ see : L { unregister _ class }""" | meta = util . get_class_meta ( klass )
if alias is not None :
meta [ 'alias' ] = alias
alias_klass = util . get_class_alias ( klass ) or ClassAlias
x = alias_klass ( klass , defer = True , ** meta )
if not x . anonymous :
CLASS_CACHE [ x . alias ] = x
CLASS_CACHE [ klass ] = x
return x |
def check_for_eni_source ( ) :
'''Juju removes the source line when setting up interfaces ,
replace if missing''' | with open ( '/etc/network/interfaces' , 'r' ) as eni :
for line in eni :
if line == 'source /etc/network/interfaces.d/*' :
return
with open ( '/etc/network/interfaces' , 'a' ) as eni :
eni . write ( '\nsource /etc/network/interfaces.d/*' ) |
def to_parmed ( self , box = None , title = '' , residues = None , show_ports = False ) :
"""Create a ParmEd Structure from a Compound .
Parameters
box : mb . Box , optional , default = self . boundingbox ( with buffer )
Box information to be used when converting to a ` Structure ` .
If ' None ' , a boundin... | structure = pmd . Structure ( )
structure . title = title if title else self . name
atom_mapping = { }
# For creating bonds below
guessed_elements = set ( )
if isinstance ( residues , string_types ) :
residues = [ residues ]
if isinstance ( residues , ( list , set ) ) :
residues = tuple ( residues )
default_res... |
def GET_load_conditionvalues ( self ) -> None :
"""Assign the | StateSequence | or | LogSequence | object values available
for the current simulation start point to the current | HydPy | instance .
When the simulation start point is identical with the initialisation
time point and you did not save conditions ... | try :
state . hp . conditions = state . conditions [ self . _id ] [ state . idx1 ]
except KeyError :
if state . idx1 :
self . _statuscode = 500
raise RuntimeError ( f'Conditions for ID `{self._id}` and time point ' f'`{hydpy.pub.timegrids.sim.firstdate}` are required, ' f'but have not been calcu... |
def highly_variable_genes ( adata_or_result , log = False , show = None , save = None , highly_variable_genes = True ) :
"""Plot dispersions versus means for genes .
Produces Supp . Fig . 5c of Zheng et al . ( 2017 ) and MeanVarPlot ( ) of Seurat .
Parameters
adata : : class : ` ~ anndata . AnnData ` , ` np .... | if isinstance ( adata_or_result , AnnData ) :
result = adata_or_result . var
else :
result = adata_or_result
if highly_variable_genes :
gene_subset = result . highly_variable
else :
gene_subset = result . gene_subset
means = result . means
dispersions = result . dispersions
dispersions_norm = result . d... |
def make_meetup_blueprint ( key = None , secret = None , scope = None , redirect_url = None , redirect_to = None , login_url = None , authorized_url = None , session_class = None , storage = None , ) :
"""Make a blueprint for authenticating with Meetup using OAuth 2 . This requires
an OAuth consumer from Meetup .... | scope = scope or [ "basic" ]
meetup_bp = OAuth2ConsumerBlueprint ( "meetup" , __name__ , client_id = key , client_secret = secret , scope = scope , base_url = "https://api.meetup.com/2/" , authorization_url = "https://secure.meetup.com/oauth2/authorize" , token_url = "https://secure.meetup.com/oauth2/access" , redirect... |
def view_history ( name , gitref ) :
"""Serve a page name from git repo ( an old version of a page ) .
. . note : : this is a bottle view
* this is a GET only method : you can not change a committed page
Keyword Arguments :
: name : ( str ) - - name of the rest file ( without the . rst extension )
: gitre... | response . set_header ( 'Cache-control' , 'no-cache' )
response . set_header ( 'Pragma' , 'no-cache' )
content = read_committed_file ( gitref , name + '.rst' )
if content :
html_body = publish_parts ( content , writer = AttowikiWriter ( ) , settings = None , settings_overrides = None ) [ 'html_body' ]
history =... |
def normalize_response ( response , request = None ) :
"""Given a response , normalize it to the internal Response class . This also
involves normalizing the associated request object .""" | if isinstance ( response , Response ) :
return response
if request is not None and not isinstance ( request , Request ) :
request = normalize_request ( request )
for normalizer in RESPONSE_NORMALIZERS :
try :
return normalizer ( response , request = request )
except TypeError :
continue
... |
def get_metadata ( data_dir = None ) :
'''Obtain the metadata for all basis sets
The metadata includes information such as the display name of the basis set ,
its versions , and what elements are included in the basis set
The data is read from the METADATA . json file in the ` data _ dir ` directory .
Param... | data_dir = fix_data_dir ( data_dir )
metadata_file = os . path . join ( data_dir , "METADATA.json" )
return fileio . read_metadata ( metadata_file ) |
def update_asset ( self , asset_form = None ) :
"""Updates an existing asset .
arg : asset _ form ( osid . repository . AssetForm ) : the form
containing the elements to be updated
raise : IllegalState - ` ` asset _ form ` ` already used in anupdate
transaction
raise : InvalidArgument - the form contains ... | return Asset ( self . _provider_session . update_asset ( asset_form ) , self . _config_map ) |
def setEffort ( self , edgeID , effort , begin = None , end = None ) :
"""setEffort ( string , double , int , int ) - > None
Adapt the effort value used for ( re - ) routing for the given edge .
When setting begin time and end time ( in seconds ) , the changes only
apply to that time range . Otherwise they ap... | if begin is None and end is None :
self . _connection . _beginMessage ( tc . CMD_SET_EDGE_VARIABLE , tc . VAR_EDGE_EFFORT , edgeID , 1 + 4 + 1 + 8 )
self . _connection . _string += struct . pack ( "!BiBd" , tc . TYPE_COMPOUND , 1 , tc . TYPE_DOUBLE , effort )
self . _connection . _sendExact ( )
elif begin i... |
def register_endpoint ( self , endpoint , handler ) :
"""Register a handler for a message received from the Pebble .
: param endpoint : The type of : class : ` . PebblePacket ` that is being listened for .
: type endpoint : . PacketType
: param handler : A callback to be called when a message is received .
... | return self . event_handler . register_handler ( ( _EventType . Watch , endpoint ) , handler ) |
def get_data ( self , request = None ) :
"""Get data from the dataset .""" | if request is None :
raise ValueError
data = [ [ ] for _ in self . sources ]
for i in range ( request ) :
try :
for source_data , example in zip ( data , next ( self . child_epoch_iterator ) ) :
source_data . append ( example )
except StopIteration : # If some data has been extracted and... |
def check_section ( node , section , keys = None ) :
"""Validate keys in a section""" | if keys :
for key in keys :
if key not in node :
raise ValueError ( 'Missing key %r inside %r node' % ( key , section ) ) |
def handleAllSync ( self , deq : deque , limit = None ) -> int :
"""Synchronously handle all items in a deque .
: param deq : a deque of items to be handled by this router
: param limit : the number of items in the deque to the handled
: return : the number of items handled successfully""" | count = 0
while deq and ( not limit or count < limit ) :
count += 1
msg = deq . popleft ( )
self . handleSync ( msg )
return count |
def safe_concurrent_rename ( src , dst ) :
"""Rename src to dst , ignoring errors due to dst already existing .
Useful when concurrent processes may attempt to create dst , and it doesn ' t matter who wins .""" | # Delete dst , in case it existed ( with old content ) even before any concurrent processes
# attempted this write . This ensures that at least one process writes the new content .
if os . path . isdir ( src ) : # Note that dst may not exist , so we test for the type of src .
safe_rmtree ( dst )
else :
safe_del... |
def _open ( self , mode = None ) :
"""Open the current base file with the ( original ) mode and encoding .
Return the resulting stream .
Note : Copied from stdlib . Added option to override ' mode '""" | if mode is None :
mode = self . mode
if self . encoding is None :
stream = open ( self . baseFilename , mode )
else :
stream = codecs . open ( self . baseFilename , mode , self . encoding )
return stream |
def travis_build_package ( ) :
"""Assumed called on Travis , to prepare a package to be deployed
This method prints on stdout for Travis .
Return is obj to pass to sys . exit ( ) directly""" | travis_tag = os . environ . get ( "TRAVIS_TAG" )
if not travis_tag :
print ( "TRAVIS_TAG environment variable is not present" )
return "TRAVIS_TAG environment variable is not present"
try :
version = Version ( travis_tag )
except InvalidVersion :
failure = "Version must be a valid PEP440 version (versio... |
def dp996 ( self , value = None ) :
"""Corresponds to IDD Field ` dp996 `
Dew - point temperature corresponding to 99.6 % annual cumulative
frequency of occurrence ( cold conditions )
Args :
value ( float ) : value for IDD Field ` dp996 `
Unit : C
if ` value ` is None it will not be checked against the ... | if value is not None :
try :
value = float ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type float ' 'for field `dp996`' . format ( value ) )
self . _dp996 = value |
def _depth_event ( self , msg ) :
"""Handle a depth event
: param msg :
: return :""" | if 'e' in msg and msg [ 'e' ] == 'error' : # close the socket
self . close ( )
# notify the user by returning a None value
if self . _callback :
self . _callback ( None )
if self . _last_update_id is None : # Initial depth snapshot fetch not yet performed , buffer messages
self . _depth_message_... |
def __get_xml_text ( root ) :
"""Return the text for the given root node ( xml . dom . minidom ) .""" | txt = ""
for e in root . childNodes :
if ( e . nodeType == e . TEXT_NODE ) :
txt += e . data
return txt |
def _data_zeroed ( self ) :
"""A 2D ` ~ numpy . nddarray ` cutout from the input ` ` data ` ` where any
masked pixels ( _ segment _ mask , _ input _ mask , or _ data _ mask ) are
set to zero . Invalid values ( e . g . NaNs or infs ) are set to
zero . Units are dropped on the input ` ` data ` ` .""" | # NOTE : using np . where is faster than
# _ data = np . copy ( self . data _ cutout )
# self . _ data [ self . _ total _ mask ] = 0.
return np . where ( self . _total_mask , 0 , self . data_cutout ) . astype ( np . float64 ) |
def muteThreadReactions ( self , mute = True , thread_id = None ) :
"""Mutes thread reactions
: param mute : Boolean . True to mute , False to unmute
: param thread _ id : User / Group ID to mute . See : ref : ` intro _ threads `""" | thread_id , thread_type = self . _getThread ( thread_id , None )
data = { "reactions_mute_mode" : int ( mute ) , "thread_fbid" : thread_id }
r = self . _post ( self . req_url . MUTE_REACTIONS , data , fix_request = True ) |
def _pre_create ( cls , atdepth , stackdepth , * argl , ** argd ) :
"""Checks whether the the logging should happen based on the specified
parameters . If it should , an initialized entry is returned .""" | from time import time
if not atdepth :
rstack = _reduced_stack ( )
reduced = len ( rstack )
if msg . will_print ( 3 ) : # pragma : no cover
sstack = [ ' | ' . join ( map ( str , r ) ) for r in rstack ]
msg . info ( "{} => stack ({}): {}" . format ( cls . __fqdn__ , len ( rstack ) , ', ' . jo... |
def to_XML ( self , xml_declaration = True , xmlns = True ) :
"""Dumps object fields to an XML - formatted string . The ' xml _ declaration '
switch enables printing of a leading standard XML line containing XML
version and encoding . The ' xmlns ' switch enables printing of qualified
XMLNS prefixes .
: par... | root_node = self . _to_DOM ( )
if xmlns :
xmlutils . annotate_with_XMLNS ( root_node , COINDEX_XMLNS_PREFIX , COINDEX_XMLNS_URL )
return xmlutils . DOM_node_to_XML ( root_node , xml_declaration ) |
def owner ( self ) :
"""Returns the owner of these capabilities , if any .
: return : the owner , can be None
: rtype : JavaObject""" | obj = javabridge . call ( self . jobject , "getOwner" , "()Lweka/core/CapabilitiesHandler;" )
if obj is None :
return None
else :
return JavaObject ( jobject = obj ) |
def _handle_error ( self , result , err_msg ) :
"""Check result for error
: type result : dict
: param result : response body
: type err _ msg : str
: param err _ msg : The message given to the : class : ` RequestError ` instance
raised
: returns : Actual result from result
: raises RequestError : If ... | if result . get ( u'error' ) :
raise RequestError ( "{}\nResponse: {}" . format ( err_msg , json . dumps ( result , indent = 2 ) ) )
else :
return result . get ( u'result' ) |
def _load_backend ( self , backend_uri , context ) :
"""Return the instantiated backend object identified by the given
` backend _ uri ` .
The entry point that is used to create the backend object is determined
by the protocol part of the given URI .""" | parsed = parse . urlparse ( backend_uri )
options = dict ( parse . parse_qsl ( parsed . query ) )
try :
backend = self . _entry_points [ self . BACKENDS_ENTRY_POINT ] [ parsed . scheme ] . load ( )
except KeyError :
raise BackendNotFoundError ( "The requested backend `%s` could not be found in the " "registered... |
def index ( self ) :
"""Display NIPAP version info""" | c . pynipap_version = pynipap . __version__
try :
c . nipapd_version = pynipap . nipapd_version ( )
except :
c . nipapd_version = 'unknown'
c . nipap_db_version = pynipap . nipap_db_version ( )
return render ( '/version.html' ) |
def call ( self , x ) :
"""Get token embeddings of x .
Args :
x : An int64 tensor with shape [ batch _ size , length ]
Returns :
embeddings : float32 tensor with shape [ batch _ size , length , embedding _ size ]
padding : float32 tensor with shape [ batch _ size , length ] indicating the
locations of t... | with tf . name_scope ( "embedding" ) :
embeddings = tf . gather ( self . shared_weights , x )
# Scale embedding by the sqrt of the hidden size
embeddings *= self . hidden_size ** 0.5
# Create binary array of size [ batch _ size , length ]
# where 1 = padding , 0 = not padding
padding = model_uti... |
def date ( objet ) :
"""abstractRender d ' une date datetime . date""" | if objet :
return "{}/{}/{}" . format ( objet . day , objet . month , objet . year )
return "" |
def add_widget ( self , wid , index = 0 , canvas = None ) :
"""Put the : class : ` Pawn ` at a point along my length proportionate to
how close it is to finishing its travel through me .
Only : class : ` Pawn ` should ever be added as a child of : class : ` Arrow ` .""" | super ( ) . add_widget ( wid , index , canvas )
if not hasattr ( wid , 'group' ) :
return
wid . _no_use_canvas = True
mycanvas = ( self . canvas . before if canvas == 'before' else self . canvas . after if canvas == 'after' else self . canvas )
mycanvas . remove ( wid . canvas )
pawncanvas = ( self . board . spotla... |
def contains_adaptor ( read , adaptor ) :
"""Check whether this sequence contains adaptor contamination . If it exists ,
we assume it ' s in the 3 ' end . This function requires 8 out of 10 of the
first bases in the adaptor sequence to match for an occurrence to be
reported .
: param adaptor : sequence to l... | origSeq = read . sequenceData
clip_adaptor ( read , adaptor )
res = False
if read . sequenceData != origSeq :
res = True
read . sequenceData = origSeq
return res |
def fit ( self , X , C ) :
"""Fit one regressor per class
Parameters
X : array ( n _ samples , n _ features )
The data on which to fit a cost - sensitive classifier .
C : array ( n _ samples , n _ classes )
The cost of predicting each label for each observation ( more means worse ) .""" | X , C = _check_fit_input ( X , C )
C = np . asfortranarray ( C )
self . nclasses = C . shape [ 1 ]
self . regressors = [ deepcopy ( self . base_regressor ) for i in range ( self . nclasses ) ]
Parallel ( n_jobs = self . njobs , verbose = 0 , require = "sharedmem" ) ( delayed ( self . _fit ) ( c , X , C ) for c in range... |
def do_get ( self , line ) :
"""get [ : tablename ] { haskkey } [ rangekey ]
or
get [ : tablename ] ( ( hkey , rkey ) , ( hkey , rkey ) . . . )""" | table , line = self . get_table_params ( line )
if line . startswith ( '(' ) or line . startswith ( '[' ) or "," in line :
print "batch: not yet implemented"
return
# list of IDs
list = self . get_list ( line )
from collections import OrderedDict
ordered = OrderedDict ( )
for id in list :
... |
def process_response ( self , request , response ) :
"""Set compact P3P policies and save signed request to cookie .
P3P is a WC3 standard ( see http : / / www . w3 . org / TR / P3P / ) , and although largely ignored by most
browsers it is considered by IE before accepting third - party cookies ( ie . cookies s... | response [ 'P3P' ] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"'
if FANDJANGO_CACHE_SIGNED_REQUEST :
if hasattr ( request , "facebook" ) and request . facebook and request . facebook . signed_request :
response . set_cookie ( 'signed_request' , request . facebook . signed_request . generate ( ) )
else ... |
def list_members_without_mfa ( profile = "github" , ignore_cache = False ) :
'''List all members ( in lower case ) without MFA turned on .
profile
The name of the profile configuration to use . Defaults to ` ` github ` ` .
ignore _ cache
Bypasses the use of cached team repos .
CLI Example :
. . code - b... | key = "github.{0}:non_mfa_users" . format ( _get_config_value ( profile , 'org_name' ) )
if key not in __context__ or ignore_cache :
client = _get_client ( profile )
organization = client . get_organization ( _get_config_value ( profile , 'org_name' ) )
filter_key = 'filter'
# Silly hack to see if we ' ... |
def convert_table ( table ) :
"""> > > print ( 1072 in convert _ table ( { " а " : " a " } ) )
True
> > > print ( 1073 in convert _ table ( { " а " : " a " } ) )
False
> > > print ( convert _ table ( { " а " : " a " } ) [ 1072 ] = = " a " )
True
> > > print ( len ( convert _ table ( { " а " : " a " } ) ... | return dict ( ( ord ( k ) , v ) for k , v in table . items ( ) ) |
def reload ( self , ** params ) :
"""Reloads the datatype from Riak .
. . warning : This clears any local modifications you might have
made .
: param r : the read quorum
: type r : integer , string , None
: param pr : the primary read quorum
: type pr : integer , string , None
: param basic _ quorum :... | if not self . bucket :
raise ValueError ( 'bucket property not assigned' )
if not self . key :
raise ValueError ( 'key property not assigned' )
dtype , value , context = self . bucket . _client . _fetch_datatype ( self . bucket , self . key , ** params )
if not dtype == self . type_name :
raise TypeError ( ... |
def read_structure ( self , cls = Structure ) :
"""Returns the crystalline structure .""" | if self . ngroups != 1 :
raise NotImplementedError ( "In file %s: ngroups != 1" % self . path )
return structure_from_ncdata ( self , cls = cls ) |
def get_login_redirect ( self , provider , account ) :
"""Return url to redirect authenticated users .""" | info = self . model . _meta . app_label , self . model . _meta . model_name
# inline import to prevent circular imports .
from . admin import PRESERVED_FILTERS_SESSION_KEY
preserved_filters = self . request . session . get ( PRESERVED_FILTERS_SESSION_KEY , None )
redirect_url = reverse ( 'admin:%s_%s_changelist' % info... |
def flaky ( max_runs = None , min_passes = None , rerun_filter = None ) :
"""Decorator used to mark a test as " flaky " . When used in conjuction with
the flaky nosetests plugin , will cause the decorated test to be retried
until min _ passes successes are achieved out of up to max _ runs test runs .
: param ... | # In case @ flaky is applied to a function or class without arguments
# ( and without parentheses ) , max _ runs will refer to the wrapped object .
# In this case , the default value can be used .
wrapped = None
if hasattr ( max_runs , '__call__' ) :
wrapped , max_runs = max_runs , None
attrib = default_flaky_attri... |
def _upstart_enable ( name ) :
'''Enable an Upstart service .''' | if _upstart_is_enabled ( name ) :
return _upstart_is_enabled ( name )
override = '/etc/init/{0}.override' . format ( name )
files = [ '/etc/init/{0}.conf' . format ( name ) , override ]
for file_name in filter ( os . path . isfile , files ) :
with salt . utils . files . fopen ( file_name , 'r+' ) as fp_ :
... |
def _packet_listener ( self ) :
"""Packet listener .""" | while True :
datastream , source = self . _sock . recvfrom ( BUFFERSIZE )
ipaddr , port = source
# mitigate against invalid packets
try :
sio = io . BytesIO ( datastream )
dummy1 , sec_part = struct . unpack ( "<HH" , sio . read ( 4 ) )
protocol = sec_part % 4096
if proto... |
def p_expr_include_once ( p ) :
'expr : INCLUDE _ ONCE expr' | p [ 0 ] = ast . Include ( p [ 2 ] , True , lineno = p . lineno ( 1 ) ) |
def evaluate ( self , x ) :
"""Performs the evaluation of the objective at x .""" | if self . n_procs == 1 :
f_evals , cost_evals = self . _eval_func ( x )
else :
try :
f_evals , cost_evals = self . _syncronous_batch_evaluation ( x )
except :
if not hasattr ( self , 'parallel_error' ) :
print ( 'Error in parallel computation. Fall back to single process!' )
... |
def unblock_pin ( ctx , puk , new_pin ) :
"""Unblock the PIN .
Reset the PIN using the PUK code .""" | controller = ctx . obj [ 'controller' ]
if not puk :
puk = click . prompt ( 'Enter PUK' , default = '' , show_default = False , hide_input = True , err = True )
if not new_pin :
new_pin = click . prompt ( 'Enter a new PIN' , default = '' , show_default = False , hide_input = True , err = True )
controller . unb... |
def trainHMM_fromDir ( dirPath , hmm_model_name , mt_win , mt_step ) :
'''This function trains a HMM model for segmentation - classification using
a where WAV files and . segment ( ground - truth files ) are stored
ARGUMENTS :
- dirPath : the path of the data diretory
- hmm _ model _ name : the name of the ... | flags_all = numpy . array ( [ ] )
classes_all = [ ]
for i , f in enumerate ( glob . glob ( dirPath + os . sep + '*.wav' ) ) : # for each WAV file
wav_file = f
gt_file = f . replace ( '.wav' , '.segments' )
if not os . path . isfile ( gt_file ) :
continue
[ seg_start , seg_end , seg_labs ] = read... |
def normalize_bit ( A , B , bit , id2desc ) :
"""normalize the bit score :
normalization factor = average max bit score for the two ORFs
normalized = bit score / normalization factor""" | Amax , Bmax = id2desc [ A ] [ - 1 ] , id2desc [ B ] [ - 1 ]
norm_factor = float ( numpy . average ( [ Amax , Bmax ] ) )
normalized = bit / norm_factor
return normalized |
def set_wake_on_network ( enabled ) :
'''Set whether or not the computer will wake from sleep when network activity
is detected .
: param bool enabled : True to enable , False to disable . " On " and " Off " are
also acceptable values . Additionally you can pass 1 and 0 to represent
True and False respectiv... | state = salt . utils . mac_utils . validate_enabled ( enabled )
cmd = 'systemsetup -setwakeonnetworkaccess {0}' . format ( state )
salt . utils . mac_utils . execute_return_success ( cmd )
return salt . utils . mac_utils . confirm_updated ( state , get_wake_on_network , ) |
def grouping_delta_stats ( old , new ) :
"""Returns statistics about grouping changes
Args :
old ( set of frozenset ) : old grouping
new ( set of frozenset ) : new grouping
Returns :
pd . DataFrame : df : data frame of size statistics
Example :
> > > # ENABLE _ DOCTEST
> > > from utool . util _ alg ... | import pandas as pd
import utool as ut
group_delta = ut . grouping_delta ( old , new )
stats = ut . odict ( )
unchanged = group_delta [ 'unchanged' ]
splits = group_delta [ 'splits' ]
merges = group_delta [ 'merges' ]
hybrid = group_delta [ 'hybrid' ]
statsmap = ut . partial ( lambda x : ut . stats_dict ( map ( len , x... |
def send ( self , command ) :
"""send function sends the command to the oxd server and recieves the
response .
Parameters :
* * * command ( dict ) : * * Dict representation of the JSON command string
Returns :
* * response ( dict ) : * * The JSON response from the oxd Server as a dict""" | cmd = json . dumps ( command )
cmd = "{:04d}" . format ( len ( cmd ) ) + cmd
msg_length = len ( cmd )
# make the first time connection
if not self . firstDone :
logger . info ( 'Initiating first time socket connection.' )
self . __connect ( )
self . firstDone = True
# Send the message the to the server
tota... |
def _subset ( self , subset ) :
"""Return a new pipeline with a subset of the sections""" | pl = Pipeline ( bundle = self . bundle )
for group_name , pl_segment in iteritems ( self ) :
if group_name not in subset :
continue
pl [ group_name ] = pl_segment
return pl |
def dispatch ( self , event ) :
"""Sends event notifications to the L { Debug } object and
the L { EventHandler } object provided by the user .
The L { Debug } object will forward the notifications to it ' s contained
snapshot objects ( L { System } , L { Process } , L { Thread } and L { Module } ) when
app... | returnValue = None
bCallHandler = True
pre_handler = None
post_handler = None
eventCode = event . get_event_code ( )
# Get the pre and post notification methods for exceptions .
# If not found , the following steps take care of that .
if eventCode == win32 . EXCEPTION_DEBUG_EVENT :
exceptionCode = event . get_excep... |
def checkIfRemoteIsNewer ( self , localfile , remote_size , remote_modify ) :
"""Overrides checkIfRemoteIsNewer in Source class
: param localfile : str file path
: param remote _ size : str bytes
: param remote _ modify : str last modify date in the form 20160705042714
: return : boolean True if remote file... | is_remote_newer = False
status = os . stat ( localfile )
LOG . info ( "\nLocal file size: %i" "\nLocal Timestamp: %s" , status [ ST_SIZE ] , datetime . fromtimestamp ( status . st_mtime ) )
remote_dt = Bgee . _convert_ftp_time_to_iso ( remote_modify )
if remote_dt != datetime . fromtimestamp ( status . st_mtime ) or st... |
def dial ( self , number , timeout = 5 , callStatusUpdateCallbackFunc = None ) :
"""Calls the specified phone number using a voice phone call
: param number : The phone number to dial
: param timeout : Maximum time to wait for the call to be established
: param callStatusUpdateCallbackFunc : Callback function... | if self . _waitForCallInitUpdate : # Wait for the " call originated " notification message
self . _dialEvent = threading . Event ( )
try :
self . write ( 'ATD{0};' . format ( number ) , timeout = timeout , waitForResponse = self . _waitForAtdResponse )
except Exception :
self . _dialEvent = ... |
def generate_client_callers ( spec , timeout , error_callback , local , app ) :
"""Return a dict mapping method names to anonymous functions that
will call the server ' s endpoint of the corresponding name as
described in the api defined by the swagger dict and bravado spec""" | callers_dict = { }
def mycallback ( endpoint ) :
if not endpoint . handler_client :
return
callers_dict [ endpoint . handler_client ] = _generate_client_caller ( spec , endpoint , timeout , error_callback , local , app )
spec . call_on_each_endpoint ( mycallback )
return callers_dict |
def add_put ( self , path : str , handler : _WebHandler , ** kwargs : Any ) -> AbstractRoute :
"""Shortcut for add _ route with method PUT""" | return self . add_route ( hdrs . METH_PUT , path , handler , ** kwargs ) |
def _expand_description ( desc ) :
"""Expand the description given the group names / patterns
e . g :
{ src : grp [ 1-3 ] , dst : grp [ 4-6 ] . . . } will generate 9 descriptions""" | srcs = expand_groups ( desc [ 'src' ] )
dsts = expand_groups ( desc [ 'dst' ] )
descs = [ ]
for src in srcs :
for dst in dsts :
local_desc = desc . copy ( )
local_desc [ 'src' ] = src
local_desc [ 'dst' ] = dst
descs . append ( local_desc )
return descs |
def connected_socket ( address , timeout = 3 ) :
"""yields a connected socket""" | sock = socket . create_connection ( address , timeout )
yield sock
sock . close ( ) |
def build_data ( self , plugin , attribute , stat ) :
"""Build and return the data line""" | line = ''
if attribute is not None :
line += '{}{}' . format ( str ( stat . get ( attribute , self . na ) ) , self . separator )
else :
if isinstance ( stat , dict ) :
for v in stat . values ( ) :
line += '{}{}' . format ( str ( v ) , self . separator )
elif isinstance ( stat , list ) :
... |
def close ( self ) :
"""Close the connection . Kills the send and receive threads , as
well as closing the underlying socket .""" | if self . _recv_thread :
self . _recv_thread . kill ( )
self . _recv_thread = None
if self . _send_thread :
self . _send_thread . kill ( )
self . _send_thread = None
if self . _sock :
self . _sock . close ( )
self . _sock = None
# Make sure to notify the manager we ' re closed
super ( TCPTendril... |
def tokenize ( self , expr ) :
"""Return an iterable of 3 - tuple describing each token given an expression
unicode string .
This 3 - tuple contains ( token , token string , position ) :
- token : either a Symbol instance or one of TOKEN _ * token types .
- token string : the original token unicode string .... | if not isinstance ( expr , basestring ) :
raise TypeError ( 'expr must be string but it is %s.' % type ( expr ) )
# mapping of lowercase token strings to a token type id for the standard
# operators , parens and common true or false symbols , as used in the
# default tokenizer implementation .
TOKENS = { '*' : TOKE... |
def handle_execution_engines ( args ) :
"""usage : { program } execution - engines
List the available execution - engine plugins .""" | assert args
print ( '\n' . join ( cosmic_ray . plugins . execution_engine_names ( ) ) )
return ExitCode . OK |
def normalizeToName ( val ) :
"""Converts tags or full names to full names , case sensitive
# Parameters
_ val _ : ` str `
> A two character string giving the tag or its full name
# Returns
` str `
> The full name of _ val _""" | if val not in tagsAndNameSet :
raise KeyError ( "{} is not a tag or name string" . format ( val ) )
else :
try :
return tagToFullDict [ val ]
except KeyError :
return val |
def from_json ( value , ** kwargs ) :
"""Convert a PNG Image from base64 - encoded JSON""" | if not value . startswith ( PNG_PREAMBLE ) :
raise ValueError ( 'Not a valid base64-encoded PNG image' )
infile = BytesIO ( )
rep = base64 . b64decode ( value [ len ( PNG_PREAMBLE ) : ] . encode ( 'utf-8' ) )
infile . write ( rep )
infile . seek ( 0 )
return infile |
def convert_JSON ( j ) :
"""Recursively convert CamelCase keys to snake _ case .
From : https : / / stackoverflow . com / questions / 17156078 / converting - identifier - naming - between - camelcase - and - underscores - during - json - seria""" | def camel_to_snake ( s ) :
a = re . compile ( '((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))' )
return a . sub ( r'_\1' , s ) . lower ( )
def convertArray ( a ) :
newArr = [ ]
for i in a :
if isinstance ( i , list ) :
newArr . append ( convertArray ( i ) )
elif isinstance ( i , di... |
def embed_seq ( X , Tau , D ) :
"""Build a set of embedding sequences from given time series X with lag Tau
and embedding dimension DE . Let X = [ x ( 1 ) , x ( 2 ) , . . . , x ( N ) ] , then for each
i such that 1 < i < N - ( D - 1 ) * Tau , we build an embedding sequence ,
Y ( i ) = [ x ( i ) , x ( i + Tau ... | shape = ( X . size - Tau * ( D - 1 ) , D )
strides = ( X . itemsize , Tau * X . itemsize )
return numpy . lib . stride_tricks . as_strided ( X , shape = shape , strides = strides ) |
def get_package_info ( self , name ) : # type : ( str ) - > dict
"""Return the package information given its name .
The information is returned from the cache if it exists
or retrieved from the remote server .""" | if self . _disable_cache :
return self . _get_package_info ( name )
return self . _cache . store ( "packages" ) . remember_forever ( name , lambda : self . _get_package_info ( name ) ) |
def get_watchers ( self , username , offset = 0 , limit = 10 ) :
"""Get the user ' s list of watchers
: param username : The username you want to get a list of watchers of
: param offset : the pagination offset
: param limit : the pagination limit""" | response = self . _req ( '/user/watchers/{}' . format ( username ) , { 'offset' : offset , 'limit' : limit } )
watchers = [ ]
for item in response [ 'results' ] :
w = { }
w [ 'user' ] = User ( )
w [ 'user' ] . from_dict ( item [ 'user' ] )
w [ 'is_watching' ] = item [ 'is_watching' ]
w [ 'lastvisit'... |
def stack_frames ( sig , sampling_frequency , frame_length = 0.020 , frame_stride = 0.020 , filter = lambda x : np . ones ( ( x , ) ) , zero_padding = True ) :
"""Frame a signal into overlapping frames .
Args :
sig ( array ) : The audio signal to frame of size ( N , ) .
sampling _ frequency ( int ) : The samp... | # Check dimension
s = "Signal dimention should be of the format of (N,) but it is %s instead"
assert sig . ndim == 1 , s % str ( sig . shape )
# Initial necessary values
length_signal = sig . shape [ 0 ]
frame_sample_length = int ( np . round ( sampling_frequency * frame_length ) )
# Defined by the number of samples
fr... |
def _init_glyph ( self , plot , mapping , properties ) :
"""Returns a Bokeh glyph object .""" | properties = mpl_to_bokeh ( properties )
properties = dict ( properties , ** mapping )
if 'xs' in mapping :
renderer = plot . patches ( ** properties )
else :
renderer = plot . quad ( ** properties )
if self . colorbar and 'color_mapper' in self . handles :
self . _draw_colorbar ( plot , self . handles [ 'c... |
def encode ( self , label ) :
"""Encodes a ` ` label ` ` .
Args :
label ( object ) : Label to encode .
Returns :
torch . Tensor : Encoding of the label .""" | label = super ( ) . encode ( label )
return torch . tensor ( self . stoi . get ( label , self . unknown_index ) ) |
def add ( name , connection_uri , id_file = "" , o = [ ] , config = None ) :
"""Adds a new entry to sshconfig .""" | storm_ = get_storm_instance ( config )
try : # validate name
if '@' in name :
raise ValueError ( 'invalid value: "@" cannot be used in name.' )
user , host , port = parse ( connection_uri , user = get_default ( "user" , storm_ . defaults ) , port = get_default ( "port" , storm_ . defaults ) )
storm_... |
def main ( ) :
"""NAME
quick _ hyst . py
DESCRIPTION
makes plots of hysteresis data
SYNTAX
quick _ hyst . py [ command line options ]
OPTIONS
- h prints help message and quits
- f : specify input file , default is measurements . txt
- spc SPEC : specify specimen name to plot and quit
- sav save ... | args = sys . argv
if "-h" in args :
print ( main . __doc__ )
sys . exit ( )
pltspec = ""
verbose = pmagplotlib . verbose
dir_path = pmag . get_named_arg ( '-WD' , '.' )
dir_path = os . path . realpath ( dir_path )
meas_file = pmag . get_named_arg ( '-f' , 'measurements.txt' )
fmt = pmag . get_named_arg ( '-fmt'... |
def split_title ( title , width , title_fs ) :
"""Split a string for a specified width and font size""" | titles = [ ]
if not title :
return titles
size = reverse_text_len ( width , title_fs * 1.1 )
title_lines = title . split ( "\n" )
for title_line in title_lines :
while len ( title_line ) > size :
title_part = title_line [ : size ]
i = title_part . rfind ( ' ' )
if i == - 1 :
... |
def _init_associations ( fin_anno , taxid = None , taxids = None ) :
"""Read annotation file and store a list of namedtuples .""" | return InitAssc ( taxid , taxids ) . init_associations ( fin_anno , taxids ) |
def is_all_field_none ( self ) :
""": rtype : bool""" | if self . _status is not None :
return False
if self . _balance_preferred is not None :
return False
if self . _balance_threshold_low is not None :
return False
if self . _method_fill is not None :
return False
if self . _issuer is not None :
return False
return True |
def writerow ( self , cells ) :
"""Write a row of cells into the default sheet of the spreadsheet .
: param cells : A list of cells ( most basic Python types supported ) .
: return : Nothing .""" | if self . default_sheet is None :
self . default_sheet = self . new_sheet ( )
self . default_sheet . writerow ( cells ) |
def _build_meta ( meta : str , pipelines : Iterable [ 'Pipeline' ] ) -> 'Pipeline' :
"""Build a pipeline with a given meta - argument .
: param meta : either union or intersection
: param pipelines :""" | return Pipeline ( protocol = [ { 'meta' : meta , 'pipelines' : [ pipeline . protocol for pipeline in pipelines ] } , ] ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.