signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def evaluate_generative_model ( A , Atgt , D , eta , gamma = None , model_type = 'matching' , model_var = 'powerlaw' , epsilon = 1e-6 , seed = None ) :
'''Generates synthetic networks with parameters provided and evaluates their
energy function . The energy function is defined as in Betzel et al . 2016.
Basical... | m = np . size ( np . where ( Atgt . flat ) ) // 2
n = len ( Atgt )
xk = np . sum ( Atgt , axis = 1 )
xc = clustering_coef_bu ( Atgt )
xb = betweenness_bin ( Atgt )
xe = D [ np . triu ( Atgt , 1 ) > 0 ]
B = generative_model ( A , D , m , eta , gamma , model_type = model_type , model_var = model_var , epsilon = epsilon ,... |
def load ( self , filename ) :
"""Read a file of known SSH host keys , in the format used by OpenSSH .
This type of file unfortunately doesn ' t exist on Windows , but on
posix , it will usually be stored in
` ` os . path . expanduser ( " ~ / . ssh / known _ hosts " ) ` ` .
If this method is called multiple... | with open ( filename , "r" ) as f :
for lineno , line in enumerate ( f , 1 ) :
line = line . strip ( )
if ( len ( line ) == 0 ) or ( line [ 0 ] == "#" ) :
continue
try :
e = HostKeyEntry . from_line ( line , lineno )
except SSHException :
continue
... |
def view ( cls , database , viewname , ** options ) :
"""Execute a CouchDB named view and map the result values back to
objects of this mapping .
Note that by default , any properties of the document that are not
included in the values of the view will be treated as if they were
missing from the document . ... | return database . view ( viewname , wrapper = cls . _wrap_row , ** options ) |
def on_change_checkout ( self ) :
'''When you change checkout or checkin update dummy field
@ param self : object pointer
@ return : raise warning depending on the validation''' | checkout_date = time . strftime ( dt )
checkin_date = time . strftime ( dt )
if not ( checkout_date and checkin_date ) :
return { 'value' : { } }
delta = timedelta ( days = 1 )
dat_a = time . strptime ( checkout_date , dt ) [ : 5 ]
addDays = datetime ( * dat_a ) + delta
self . dummy = addDays . strftime ( dt ) |
def cublasDsyr2k ( handle , uplo , trans , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) :
"""Rank - 2k operation on real symmetric matrix .""" | status = _libcublas . cublasDsyr2k_v2 ( handle , _CUBLAS_FILL_MODE [ uplo ] , _CUBLAS_OP [ trans ] , n , k , ctypes . byref ( ctypes . c_double ( alpha ) ) , int ( A ) , lda , int ( B ) , ldb , ctypes . byref ( ctypes . c_double ( beta ) ) , int ( C ) , ldc )
cublasCheckStatus ( status ) |
def calculate_all_information_content ( self ) -> pd . Series :
"""Calculate the Information Content ( IC ) value of every class
Sets the internal icmap cache and returns an array
Return
Series
a pandas Series indexed by class id and with IC as value""" | logging . info ( "Calculating all class ICs" )
df = self . assoc_df
freqs = df . sum ( axis = 0 )
n_subjects , _ = df . shape
ics = freqs . apply ( lambda x : - math . log ( x / n_subjects ) / math . log ( 2 ) )
self . ics = ics
logging . info ( "DONE calculating all class ICs" )
return ics |
def complexity_fd_petrosian ( signal ) :
"""Computes the Petrosian Fractal Dimension of a signal . Based on the ` pyrem < https : / / github . com / gilestrolab / pyrem > ` _ repo by Quentin Geissmann .
Parameters
signal : list or array
List or array of values .
Returns
fd _ petrosian : float
The Petros... | diff = np . diff ( signal )
# x [ i ] * x [ i - 1 ] for i in t0 - > tmax
prod = diff [ 1 : - 1 ] * diff [ 0 : - 2 ]
# Number of sign changes in derivative of the signal
N_delta = np . sum ( prod < 0 )
n = len ( signal )
fd_petrosian = np . log ( n ) / ( np . log ( n ) + np . log ( n / ( n + 0.4 * N_delta ) ) )
return (... |
def resize_image ( image_str_tensor ) :
"""Decodes jpeg string , resizes it and re - encode it to jpeg .""" | image = decode_and_resize ( image_str_tensor )
image = tf . image . encode_jpeg ( image , quality = 100 )
return image |
def wrap_exception ( exc , new_exc ) :
"""Catches exceptions ` exc ` and raises ` new _ exc ( exc ) ` instead .
E . g . : :
> > > class MyValueError ( Exception ) :
. . . ' ' ' Custom ValueError . ' ' '
. . . @ wrap _ exception ( exc = ValueError , new _ exc = MyValueError )
. . . def test ( ) :
. . . r... | def make_wrapper ( fn ) :
@ functools . wraps ( fn )
def wrapper ( * args , ** kw ) :
try :
return fn ( * args , ** kw )
except exc as e :
future . utils . raise_with_traceback ( new_exc ( e ) )
return wrapper
return make_wrapper |
def is_image ( file ) :
"""Returns ` ` True ` ` if the file extension looks like an image file to Telegram .""" | match = re . match ( r'\.(png|jpe?g)' , _get_extension ( file ) , re . IGNORECASE )
if match :
return True
else :
return isinstance ( resolve_bot_file_id ( file ) , types . Photo ) |
def attach ( self , app , engineio_path = 'engine.io' ) :
"""Attach the Engine . IO server to an application .""" | engineio_path = engineio_path . strip ( '/' )
self . _async [ 'create_route' ] ( app , self , '/{}/' . format ( engineio_path ) ) |
def deploy_static ( ) :
"""Deploy static ( application ) versioned media""" | if not env . STATIC_URL or 'http://' in env . STATIC_URL :
return
from django . core . servers . basehttp import AdminMediaHandler
remote_dir = '/' . join ( [ deployment_root ( ) , 'env' , env . project_fullname , 'static' ] )
m_prefix = len ( env . MEDIA_URL )
# if app media is not handled by django - staticfiles ... |
def visit_importfrom ( self , node , parent ) :
"""visit an ImportFrom node by returning a fresh instance of it""" | names = [ ( alias . name , alias . asname ) for alias in node . names ]
newnode = nodes . ImportFrom ( node . module or "" , names , node . level or None , getattr ( node , "lineno" , None ) , getattr ( node , "col_offset" , None ) , parent , )
# store From names to add them to locals after building
self . _import_from... |
def _preprocess ( text , tab = 4 ) :
"""Normalize a text .""" | text = re . sub ( r'\r\n|\r' , '\n' , text )
text = text . replace ( '\t' , ' ' * tab )
text = text . replace ( '\u00a0' , ' ' )
text = text . replace ( '\u2424' , '\n' )
pattern = re . compile ( r'^ +$' , re . M )
text = pattern . sub ( '' , text )
text = _rstrip_lines ( text )
return text |
def setZoomAmount ( self , amount ) :
"""Sets the zoom level for the current scene , updating all the views that it is connected to .
: param amount < int > ( 100 based % )""" | amount = max ( self . _minZoomAmount , amount )
amount = min ( self . _maxZoomAmount , amount )
# only update when necessary
if amount == self . zoomAmount ( ) :
return
# calculate the scalar value
scale = ( amount / 100.0 )
# assign the new transform to all of the views
view = self . mainView ( )
view . setTransfo... |
def jsonify ( obj , trimmable = False ) :
"""Serialize an object to a JSON formatted string .
@ param obj : an instance to convert to a JSON formatted string .
@ param trimmable : indicate whether null attributes of this object
need to be stripped out the JSON formatted string .
@ return : a JSON formatted ... | # def jsonify _ ex ( obj , trimmable = False ) :
# if obj is None :
# return None
# elif isinstance ( obj , ( basestring , bool , int , long , float , complex ) ) :
# return obj
# elif isinstance ( obj , ( list , set , tuple ) ) :
# return [ jsonify _ ex ( item , trimmable = trimmable ) for item in obj ] # MUST NOT rem... |
def calc_freefree_eta ( ne , t , hz ) :
"""Dulk ( 1985 ) equations 7 and 20 , assuming pure hydrogen .""" | kappa = calc_freefree_kappa ( ne , t , hz )
return kappa * cgs . k * t * hz ** 2 / cgs . c ** 2 |
def body_json ( soup , base_url = None ) :
"""Get body json and then alter it with section wrapping and removing boxed - text""" | body_content = body ( soup , remove_key_info_box = True , base_url = base_url )
# Wrap in a section if the first block is not a section
if ( body_content and len ( body_content ) > 0 and "type" in body_content [ 0 ] and body_content [ 0 ] [ "type" ] != "section" ) : # Wrap this one
new_body_section = OrderedDict ( ... |
def document_examples ( p ) :
"""Document example programs with purpose ( and intent )""" | p . comment ( 'maths_ml_algorithms.py' , 'machine learning algorithms for toolbox in AIKIF' )
p . comment ( 'algebra.py' , 'toolbox module for based evaluation of maths problems' )
p . comment ( 'crypt_utils.py' , 'scripts to encode / decode data' )
p . comment ( 'game_board_utils.py' , 'board game rules' )
p . comment... |
def kendallTau ( self , orderVector , wmgMap ) :
"""Given a ranking for a single vote and a wmg for the entire election , calculate the kendall - tau
distance . a . k . a the number of discordant pairs between the wmg for the vote and the wmg for the
election . Currently , we expect the vote to be a strict comp... | discordantPairs = 0.0
for i in itertools . combinations ( orderVector , 2 ) :
discordantPairs = discordantPairs + max ( 0 , wmgMap [ i [ 1 ] ] [ i [ 0 ] ] )
return discordantPairs |
def to_frequencies ( self , fill = np . nan ) :
"""Compute allele frequencies .
Parameters
fill : float , optional
Value to use when number of allele calls is 0.
Returns
af : ndarray , float , shape ( n _ variants , n _ alleles )
Examples
> > > import allel
> > > g = allel . GenotypeArray ( [ [ [ 0 ... | an = np . sum ( self , axis = 1 ) [ : , None ]
with ignore_invalid ( ) :
af = np . where ( an > 0 , self / an , fill )
return af |
def _get_view_details ( self , urlpatterns , parent = '' ) :
"""Recursive function to extract all url details""" | for pattern in urlpatterns :
if isinstance ( pattern , ( URLPattern , RegexURLPattern ) ) :
try :
d = describe_pattern ( pattern )
docstr = pattern . callback . __doc__
method = None
expected_json_response = ''
expected_url = ''
if docs... |
def print_spans ( spans , max_idx : int ) -> None :
"""Quick test to show how character spans match original BEL String
Mostly for debugging purposes""" | bel_spans = [ " " ] * ( max_idx + 3 )
for val , span in spans :
if val in [ "Nested" , "NSArg" ] :
continue
for i in range ( span [ 0 ] , span [ 1 ] + 1 ) :
bel_spans [ i ] = val [ 0 ]
# print ( ' ' . join ( bel _ spans ) )
# Add second layer for Nested Objects if available
bel_spans = [ " " ] *... |
def process_document ( self , doc ) :
"""Add your code for processing the document""" | descriptions = doc . select_segments ( "projects[*].description" )
projects = doc . select_segments ( "projects[*]" )
for d , p in zip ( descriptions , projects ) :
names = doc . extract ( self . rule_extractor , d )
p . store ( names , "members" )
return list ( ) |
def toarray ( self ) :
"""Convert blocks to local ndarray""" | if self . mode == 'spark' :
return self . values . unchunk ( ) . toarray ( )
if self . mode == 'local' :
return self . values . unchunk ( ) |
def _set_loopback ( self , v , load = False ) :
"""Setter method for loopback , mapped from YANG variable / overlay _ gateway / ip / interface / loopback ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ loopback is considered as a private
method . Backend... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = loopback . loopback , is_container = 'container' , presence = False , yang_name = "loopback" , rest_name = "Loopback" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def sortino_ratio ( self , threshold = 0.0 , ddof = 0 , freq = None ) :
"""Return over a threshold per unit of downside deviation .
A performance appraisal ratio that replaces standard deviation
in the Sharpe ratio with downside deviation .
[ Source : CFA Institute ]
Parameters
threshold : { float , TSeri... | stdev = self . semi_stdev ( threshold = threshold , ddof = ddof , freq = freq )
return ( self . anlzd_ret ( ) - threshold ) / stdev |
def update_r ( self , fs = None , qinv = None , fc = None , kappa_c = 1.0 , kappa_tst_re = 1.0 , kappa_tst_im = 0.0 , kappa_pu_re = 1.0 , kappa_pu_im = 0.0 ) :
"""Calculate the response function R ( f , t ) given the new parameters
kappa _ c ( t ) , kappa _ a ( t ) , f _ c ( t ) , fs , and qinv .
Parameters
f... | c = self . update_c ( fs = fs , qinv = qinv , fc = fc , kappa_c = kappa_c )
g = self . update_g ( fs = fs , qinv = qinv , fc = fc , kappa_c = kappa_c , kappa_tst_re = kappa_tst_re , kappa_tst_im = kappa_tst_im , kappa_pu_re = kappa_pu_re , kappa_pu_im = kappa_pu_im )
return ( 1.0 + g ) / c |
def present ( name , listeners , availability_zones = None , subnets = None , subnet_names = None , security_groups = None , scheme = 'internet-facing' , health_check = None , attributes = None , attributes_from_pillar = "boto_elb_attributes" , cnames = None , alarms = None , alarms_from_pillar = "boto_elb_alarms" , po... | # load data from attributes _ from _ pillar and merge with attributes
tmp = __salt__ [ 'config.option' ] ( attributes_from_pillar , { } )
attributes = salt . utils . dictupdate . update ( tmp , attributes ) if attributes else tmp
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
if not isinst... |
def GetMountpoints ( ) :
"""List all the filesystems mounted on the system .""" | devices = { }
for filesys in GetFileSystems ( ) :
devices [ filesys . f_mntonname ] = ( filesys . f_mntfromname , filesys . f_fstypename )
return devices |
def merge ( self , datasets = None , separate_datasets = False ) :
"""This function merges datasets into one set .""" | self . logger . info ( "merging" )
if separate_datasets :
warnings . warn ( "The option seperate_datasets=True is" "not implemented yet. Performing merging, but" "neglecting the option." )
else :
if datasets is None :
datasets = list ( range ( len ( self . datasets ) ) )
first = True
for dataset... |
def replaceMaskedValueWithFloat ( data , mask , replacementValue , copyOnReplace = True ) :
"""Replaces values where the mask is True with the replacement value .
Will change the data type to float if the data is an integer .
If the data is not a float ( or int ) the function does nothing . Otherwise it will ca... | kind = data . dtype . kind
if kind == 'i' or kind == 'u' : # signed / unsigned int
data = data . astype ( np . float , casting = 'safe' )
if data . dtype . kind != 'f' :
return
# only replace for floats
else :
return replaceMaskedValue ( data , mask , replacementValue , copyOnReplace = copyOnReplace ) |
def request ( self , method , url , ** kwargs ) :
"Build remote url request . Constructs necessary auth ." | user_token = kwargs . pop ( 'token' , self . token )
token , _ = self . parse_raw_token ( user_token )
if token is not None :
params = kwargs . get ( 'params' , { } )
params [ 'access_token' ] = token
kwargs [ 'params' ] = params
return super ( OAuth2Client , self ) . request ( method , url , ** kwargs ) |
def get_cytoband_names ( ) :
"""Returns the names of available cytoband data files
> > get _ cytoband _ names ( )
[ ' ucsc - hg38 ' , ' ucsc - hg19 ' ]""" | return [ n . replace ( ".json.gz" , "" ) for n in pkg_resources . resource_listdir ( __name__ , _data_dir ) if n . endswith ( ".json.gz" ) ] |
def search_on ( self , * fields , ** query ) :
"""Search for query on given fields .
Query modifier can be one of these :
* exact
* contains
* startswith
* endswith
* range
* lte
* gte
Args :
\*fields (str): Field list to be searched on
\*\*query: Search query. While it's implemented as \*\*kw... | search_type = list ( query . keys ( ) ) [ 0 ]
parsed_query = self . _parse_query_modifier ( search_type , query [ search_type ] , False )
self . add_query ( [ ( "OR_QRY" , dict ( [ ( f , parsed_query ) for f in fields ] ) , True ) ] ) |
def get_log_metric ( self , metric_name , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Gets a logs - based metric .
Example :
> > > from google . cloud import logging _ v2
> > > client = logging _ v2 . MetricsSer... | # Wrap the transport method to add retry and timeout logic .
if "get_log_metric" not in self . _inner_api_calls :
self . _inner_api_calls [ "get_log_metric" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . get_log_metric , default_retry = self . _method_configs [ "GetLogMetric" ] . retry... |
def draw ( self ) :
'''Draws samples from the ` fake ` distribution .
Returns :
` np . ndarray ` of samples .''' | observed_arr = self . extract_conditions ( )
conv_arr = self . inference ( observed_arr )
if self . __conditon_noise_sampler is not None :
self . __conditon_noise_sampler . output_shape = conv_arr . shape
noise_arr = self . __conditon_noise_sampler . generate ( )
conv_arr += noise_arr
deconv_arr = self . __... |
def cli ( obj , username ) :
"""Authenticate using Azure , Github , Gitlab , Google OAuth2 , OpenID or
Basic Auth username / password instead of using an API key .""" | client = obj [ 'client' ]
provider = obj [ 'provider' ]
client_id = obj [ 'client_id' ]
try :
if provider == 'azure' :
token = azure . login ( client , obj [ 'azure_tenant' ] , client_id ) [ 'token' ]
elif provider == 'github' :
token = github . login ( client , obj [ 'github_url' ] , client_id ... |
def get_neighbor_sentence_ngrams ( mention , d = 1 , attrib = "words" , n_min = 1 , n_max = 1 , lower = True ) :
"""Get the ngrams that are in the neighoring Sentences of the given Mention .
Note that if a candidate is passed in , all of its Mentions will be searched .
: param mention : The Mention whose neighb... | spans = _to_spans ( mention )
for span in spans :
for ngram in chain . from_iterable ( [ tokens_to_ngrams ( getattr ( sentence , attrib ) , n_min = n_min , n_max = n_max , lower = lower ) for sentence in span . sentence . document . sentences if abs ( sentence . position - span . sentence . position ) <= d and sent... |
def login ( self , client_id , username , password , connection , id_token = None , grant_type = 'password' , device = None , scope = 'openid' ) :
"""Login using username and password
Given the user credentials and the connection specified , it will do
the authentication on the provider and return a dict with t... | warnings . warn ( "/oauth/ro will be deprecated in future releases" , DeprecationWarning )
return self . post ( 'https://{}/oauth/ro' . format ( self . domain ) , data = { 'client_id' : client_id , 'username' : username , 'password' : password , 'id_token' : id_token , 'connection' : connection , 'device' : device , 'g... |
def find_unrelated ( x , plim = 0.1 , axis = 0 ) :
"""Find indicies of insignificant un - / correlated variables
Example :
i , j = find _ unrelated ( x , plim , rlim )""" | # transpose if axis < > 0
if axis is not 0 :
x = x . T
# read dimensions and allocate variables
_ , c = x . shape
pairs = [ ]
# compute each ( i , j ) - th correlation
for i in range ( 0 , c ) :
for j in range ( i + 1 , c ) :
_ , p = scipy . stats . pearsonr ( x [ : , i ] , x [ : , j ] )
if p > ... |
def full_shutdown ( self , stop_process = False ) :
'''Terminate all the slave agencies and shutdowns itself .''' | return self . _shutdown ( full_shutdown = True , stop_process = stop_process , gentle = True ) |
def getRenderModelName ( self , unRenderModelIndex , pchRenderModelName , unRenderModelNameLen ) :
"""Use this to get the names of available render models . Index does not correlate to a tracked device index , but
is only used for iterating over all available render models . If the index is out of range , this fu... | fn = self . function_table . getRenderModelName
result = fn ( unRenderModelIndex , pchRenderModelName , unRenderModelNameLen )
return result |
def union ( self , * others , ** kwargs ) :
"""Returns the union of variants in a several VariantCollection objects .""" | return self . _combine_variant_collections ( combine_fn = set . union , variant_collections = ( self , ) + others , kwargs = kwargs ) |
def hostingServers ( self ) :
"""Returns the objects to manage site ' s hosted services . It returns
AGSAdministration object if the site is Portal and it returns a
hostedservice . Services object if it is AGOL .""" | portals = self . portals
portal = portals . portalSelf
urls = portal . urls
if 'error' in urls :
print ( urls )
return
services = [ ]
if urls != { } :
if 'urls' in urls :
if 'features' in urls [ 'urls' ] :
if 'https' in urls [ 'urls' ] [ 'features' ] :
for https in urls [... |
def forTypes ( klass , key , classes , description , extraValidator = None ) :
"""Create a L { Field } that must be an instance of a given set of types .
@ param key : The name of the field , the key which refers to it ,
e . g . C { " path " } .
@ ivar classes : A C { list } of allowed Python classes for this... | fixedClasses = [ ]
for k in classes :
if k is None :
k = type ( None )
if k not in _JSON_TYPES :
raise TypeError ( "%s is not JSON-encodeable" % ( k , ) )
fixedClasses . append ( k )
fixedClasses = tuple ( fixedClasses )
def validate ( value ) :
if not isinstance ( value , fixedClasses )... |
def derivative ( self , x , der = 1 ) :
"""Return the derivate of the log - like summed over the energy
bins
Parameters
x : ` ~ numpy . ndarray `
Array of N x M values
der : int
Order of the derivate
Returns
der _ val : ` ~ numpy . ndarray `
Array of negative log - likelihood values .""" | if len ( x . shape ) == 1 :
der_val = np . zeros ( ( 1 ) )
else :
der_val = np . zeros ( ( x . shape [ 1 : ] ) )
for i , xv in enumerate ( x ) :
der_val += self . _loglikes [ i ] . interp . derivative ( xv , der = der )
return der_val |
def get_args ( ) :
"""Supports the command - line arguments listed below .""" | parser = argparse . ArgumentParser ( description = "Provision multiple VM's through mist.io. You can get " "information returned with the name of the virtual machine created " "and its main mac and ip address in IPv4 format. A post-script can be " "specified for post-processing." )
parser . add_argument ( '-b' , '--bas... |
def _display_interval ( i ) :
"""Convert a time interval into a human - readable string .
: param i : The interval to convert , in seconds .""" | sigils = [ "d" , "h" , "m" , "s" ]
factors = [ 24 * 60 * 60 , 60 * 60 , 60 , 1 ]
remain = int ( i )
result = ""
for fac , sig in zip ( factors , sigils ) :
if remain < fac :
continue
result += "{}{}" . format ( remain // fac , sig )
remain = remain % fac
return result |
def bootstrappable_neighbors ( self ) :
"""Get a : class : ` list ` of ( ip , port ) : class : ` tuple ` pairs suitable for
use as an argument to the bootstrap method .
The server should have been bootstrapped
already - this is just a utility for getting some neighbors and then
storing them if this server i... | neighbors = self . protocol . router . find_neighbors ( self . node )
return [ tuple ( n ) [ - 2 : ] for n in neighbors ] |
def authorize_role ( self , role , protocol , from_port , to_port , cidr_ip ) :
"""Authorize access to machines in a given role from a given network .""" | if ( protocol != 'tcp' and protocol != 'udp' ) :
raise RuntimeError ( 'error: expected protocol to be tcp or udp ' 'but got %s' % ( protocol ) )
self . _check_role_name ( role )
role_group_name = self . _group_name_for_role ( role )
# Revoke first to avoid InvalidPermission . Duplicate error
self . ec2 . revoke_sec... |
def main ( ) :
"""Main function of this example .""" | parser = argparse . ArgumentParser ( )
parser . add_argument ( '--digest' , default = "md5" , help = "Digest to use" , choices = sorted ( getattr ( hashlib , 'algorithms' , None ) or hashlib . algorithms_available ) )
parser . add_argument ( '--url' , default = "http://example.org" , help = "URL to load" )
parser . add... |
def process_all ( self ) :
"""Process every batch group and return as single result""" | results = [ ]
veto_info = [ ]
while 1 :
result , veto = self . _process_batch ( )
if result is False :
return False
if result is None :
break
results . append ( result )
veto_info += veto
result = self . combine_results ( results )
if self . max_triggers_in_batch :
sort = result ... |
def validate_message ( self , msg , * parameters ) :
"""Validates given message using template defined with ` New Message ` and
field values given as optional arguments .
Examples :
| Validate message | $ { msg } |
| Validate message | $ { msg } | status : 0 |""" | _ , message_fields , header_fields = self . _get_parameters_with_defaults ( parameters )
self . _validate_message ( msg , message_fields , header_fields ) |
def get_formats ( self , token : dict = None , format_code : str = None , prot : str = "https" ) -> dict :
"""Get formats .
: param str token : API auth token
: param str format _ code : code of a specific format
: param str prot : https [ DEFAULT ] or http
( use it only for dev and tracking needs ) .""" | # if specific format
if isinstance ( format_code , str ) :
specific_format = "/{}" . format ( format_code )
else :
specific_format = ""
# search request
req_url = "{}://v1.{}.isogeo.com/formats{}" . format ( prot , self . api_url , specific_format )
req = self . get ( req_url , headers = self . header , proxies... |
def parse_with_retrieved ( self , retrieved ) :
"""Parse output data folder , store results in database .
: param retrieved : a dictionary of retrieved nodes , where
the key is the link name
: returns : a tuple with two values ` ` ( bool , node _ list ) ` ` ,
where :
* ` ` bool ` ` : variable to tell if t... | from aiida . orm . data . singlefile import SinglefileData
success = False
node_list = [ ]
# Check that the retrieved folder is there
try :
out_folder = retrieved [ 'retrieved' ]
except KeyError :
self . logger . error ( "No retrieved folder found" )
return success , node_list
# Check the folder content is ... |
def estimate_tt_to_rectify ( self , order , slitlet2d = None ) :
"""Estimate the polynomial transformation to rectify the image .
Parameters
order : int
Order of the polynomial transformation .
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
and intersecting points ove... | # protections
if self . x_inter_orig is None or self . y_inter_orig is None or self . x_inter_rect is None or self . y_inter_rect is None :
raise ValueError ( 'Intersection points not computed' )
npoints = len ( self . x_inter_orig )
if len ( self . y_inter_orig ) != npoints or len ( self . x_inter_rect ) != npoint... |
def set_burn_in_from_config ( self , cp ) :
"""Sets the burn in class from the given config file .
If no burn - in section exists in the file , then this just set the
burn - in class to None .""" | try :
bit = self . burn_in_class . from_config ( cp , self )
except ConfigParser . Error :
bit = None
self . set_burn_in ( bit ) |
def cpfs ( self , state : Sequence [ tf . Tensor ] , action : Sequence [ tf . Tensor ] , noise : Optional [ Noise ] = None ) -> Tuple [ List [ TensorFluent ] , List [ TensorFluent ] ] :
'''Compiles the intermediate and next state fluent CPFs given
the current ` state ` and ` action ` .
Args :
state ( Sequence... | scope = self . transition_scope ( state , action )
batch_size = int ( state [ 0 ] . shape [ 0 ] )
interm_fluents , next_state_fluents = self . compile_cpfs ( scope , batch_size , noise )
interms = [ fluent for _ , fluent in interm_fluents ]
next_state = [ fluent for _ , fluent in next_state_fluents ]
return interms , n... |
def _assert_valid_start ( start_int , count_int , total_int ) :
"""Assert that the number of objects visible to the active subject is higher than
the requested start position for the slice .
This ensures that it ' s possible to create a valid slice .""" | if total_int and start_int >= total_int :
raise d1_common . types . exceptions . InvalidRequest ( 0 , 'Requested a non-existing slice. start={} count={} total={}' . format ( start_int , count_int , total_int ) , ) |
def action_is_satisfied ( action ) :
'''Returns False if the parse would raise an error if no more arguments are given to this action , True otherwise .''' | num_consumed_args = getattr ( action , 'num_consumed_args' , 0 )
if action . nargs == ONE_OR_MORE and num_consumed_args < 1 :
return False
else :
if action . nargs is None :
action . nargs = 1
try :
return num_consumed_args == action . nargs
except :
return True |
def delete_issue_link_type ( self , issue_link_type_id ) :
"""Delete the specified issue link type .""" | url = 'rest/api/2/issueLinkType/{issueLinkTypeId}' . format ( issueLinkTypeId = issue_link_type_id )
return self . delete ( url ) |
async def apply ( self , ID : str , method : str , * args : Any , ** kwargs : Any ) :
"""执行注册的函数或者实例的方法 .
如果函数或者方法是协程则执行协程 , 如果是函数则使用执行器执行 , 默认使用的是多进程 .
Parameters :
ID ( str ) : 任务的ID
method ( str ) : 任务调用的函数名
args ( Any ) : 位置参数
kwargs ( Any ) : 关键字参数
Raise :
( RPCRuntimeError ) : - 当执行调用后抛出了异常 , ... | func = None
try : # check to see if a matching function has been registered
func = self . funcs [ method ]
except KeyError :
if self . instance is not None : # check for a _ dispatch method
try :
func = resolve_dotted_attribute ( self . instance , method , self . allow_dotted_names )
... |
def data_from_stream ( self , stream ) :
"""Creates a data element reading a representation from the given stream .
: returns : object implementing
: class : ` everest . representers . interfaces . IExplicitDataElement `""" | parser = self . _make_representation_parser ( stream , self . resource_class , self . _mapping )
return parser . run ( ) |
def _humanize_time ( amount , units ) :
"""Chopped and changed from http : / / stackoverflow . com / a / 6574789/205832""" | intervals = ( 1 , 60 , 60 * 60 , 60 * 60 * 24 , 604800 , 2419200 , 29030400 )
names = ( ( "second" , "seconds" ) , ( "minute" , "minutes" ) , ( "hour" , "hours" ) , ( "day" , "days" ) , ( "week" , "weeks" ) , ( "month" , "months" ) , ( "year" , "years" ) , )
result = [ ]
unit = [ x [ 1 ] for x in names ] . index ( unit... |
def relaxNGValidatePushElement ( self , doc , elem ) :
"""Push a new element start on the RelaxNG validation stack .""" | if doc is None :
doc__o = None
else :
doc__o = doc . _o
if elem is None :
elem__o = None
else :
elem__o = elem . _o
ret = libxml2mod . xmlRelaxNGValidatePushElement ( self . _o , doc__o , elem__o )
return ret |
def get_step_input ( section , default_input ) :
'''Find step input''' | step_input : sos_targets = sos_targets ( )
dynamic_input = True
# look for input statement .
input_idx = find_statement ( section , 'input' )
if input_idx is None :
return step_input , dynamic_input
# input statement
stmt = section . statements [ input_idx ] [ 2 ]
try :
svars = [ 'output_from' , 'named_output' ... |
def fieldHistogram2d ( self , colname , rowname , q = "*:*" , fq = None , ncols = 10 , nrows = 10 ) :
"""Generates a 2d histogram of values . Expects the field to be integer or
floating point .
@ param name1 ( string ) Name of field1 columns to compute
@ param name2 ( string ) Name of field2 rows to compute
... | def _mkQterm ( name , minv , maxv , isint , isfirst , islast ) :
q = ''
if isint :
minv = int ( minv )
maxv = int ( maxv )
if isfirst :
q = '%s:[* TO %d]' % ( name , maxv )
elif islast :
q = '%s:[%d TO *]' % ( name , maxv )
else :
q = '... |
def geocode ( self , commit = False , force = False ) :
"""Do a backend geocoding if needed""" | if self . need_geocoding ( ) or force :
result = get_cached ( getattr ( self , self . geocoded_by ) , provider = 'google' )
if result . status == 'OK' :
for attribute , components in self . required_address_components . items ( ) :
for component in components :
if not getattr... |
def sls_exists ( mods , test = None , queue = False , ** kwargs ) :
'''Tests for the existance the of a specific SLS or list of SLS files on the
master . Similar to : py : func : ` state . show _ sls < salt . modules . state . show _ sls > ` ,
rather than returning state details , returns True or False . The de... | return isinstance ( show_sls ( mods , test = test , queue = queue , ** kwargs ) , dict ) |
def create_assets_if_needed ( corpus , path , entry ) :
"""Create File / Utterance / Issuer , if they not already exist and return utt - idx .""" | file_idx = entry [ 1 ]
if file_idx not in corpus . utterances . keys ( ) :
speaker_idx = entry [ 0 ]
transcription = entry [ 2 ]
age = CommonVoiceReader . map_age ( entry [ 5 ] )
gender = CommonVoiceReader . map_gender ( entry [ 6 ] )
file_path = os . path . join ( path , 'clips' , '{}.wav' . format... |
def product_of_integers ( a , b ) :
"""This function calculates the product of two integers without utilizing the * operator .
Example :
> > > product _ of _ integers ( 10 , 20)
200
> > > product _ of _ integers ( 5 , 10)
50
> > > product _ of _ integers ( 4 , 8)
32""" | if ( b < 0 ) :
return - product_of_integers ( a , - b )
elif ( b == 0 ) :
return 0
elif ( b == 1 ) :
return a
else :
return a + product_of_integers ( a , b - 1 ) |
def remove ( self , cond = None , doc_ids = None , eids = None ) :
"""Remove all matching documents .
: param cond : the condition to check against
: type cond : query
: param doc _ ids : a list of document IDs
: type doc _ ids : list
: returns : a list containing the removed document ' s ID""" | doc_ids = _get_doc_ids ( doc_ids , eids )
if cond is None and doc_ids is None :
raise RuntimeError ( 'Use purge() to remove all documents' )
return self . process_elements ( lambda data , doc_id : data . pop ( doc_id ) , cond , doc_ids ) |
def getDirectoryDictionary ( self , args ) :
"""This is an internal method to compute a dictionary containing
all the directories that potentially contain ( more ) input .
The dictionary ' table ' indicates which of its contents are part of the input :
table [ directory ] = = ' ALL ' means that its entire con... | table = { }
for element in args . path : # If the element is a directory , the dictionary entry is set to ' ALL ' :
if os . path . isdir ( element ) :
if element not in table :
table [ element ] = 'ALL'
# If the element is a file , its extension is added to the dictionary entry :
else :
... |
def create_dashboards ( resource_root , dashboard_list ) :
"""Creates the list of dashboards . If any of the dashboards already exist
this whole command will fail and no dashboards will be created .
@ since : API v6
@ return : The list of dashboards created .""" | return call ( resource_root . post , DASHBOARDS_PATH , ApiDashboard , ret_is_list = True , data = dashboard_list ) |
def GaussianLogDensity ( x , mu , log_var , name = 'GaussianLogDensity' , EPSILON = 1e-6 ) :
'''GaussianLogDensity loss calculation for layer wise loss''' | c = mx . sym . ones_like ( log_var ) * 2.0 * 3.1416
c = mx . symbol . log ( c )
var = mx . sym . exp ( log_var )
x_mu2 = mx . symbol . square ( x - mu )
# [ Issue ] not sure the dim works or not ?
x_mu2_over_var = mx . symbol . broadcast_div ( x_mu2 , var + EPSILON )
log_prob = - 0.5 * ( c + log_var + x_mu2_over_var )
... |
def deserialize ( cls , value ) :
"""Creates a new Node instance via a JSON map string .
Note that ` port ` and ` ip ` and are required keys for the JSON map ,
` peer ` and ` host ` are optional . If ` peer ` is not present , the new Node
instance will use the current peer . If ` host ` is not present , the
... | if getattr ( value , "decode" , None ) :
value = value . decode ( )
logger . debug ( "Deserializing node data: '%s'" , value )
parsed = json . loads ( value )
if "port" not in parsed :
raise ValueError ( "No port defined for node." )
if "ip" not in parsed :
raise ValueError ( "No IP address defined for node... |
def crop ( self , data ) :
'''Crop a data dictionary down to its common time
Parameters
data : dict
As produced by pumpp . transform
Returns
data _ cropped : dict
Like ` data ` but with all time - like axes truncated to the
minimum common duration''' | duration = self . data_duration ( data )
data_out = dict ( )
for key in data :
idx = [ slice ( None ) ] * data [ key ] . ndim
for tdim in self . _time . get ( key , [ ] ) :
idx [ tdim ] = slice ( duration )
data_out [ key ] = data [ key ] [ tuple ( idx ) ]
return data_out |
def fromExpiresIn ( cls , expires_in , handle , secret , assoc_type ) :
"""This is an alternate constructor used by the OpenID consumer
library to create associations . C { L { OpenIDStore
< openid . store . interface . OpenIDStore > } } implementations
shouldn ' t use this constructor .
@ param expires _ i... | issued = int ( time . time ( ) )
lifetime = expires_in
return cls ( handle , secret , issued , lifetime , assoc_type ) |
def _from_dict ( cls , _dict ) :
"""Initialize a LogQueryResponseResult object from a json dictionary .""" | args = { }
if 'environment_id' in _dict :
args [ 'environment_id' ] = _dict . get ( 'environment_id' )
if 'customer_id' in _dict :
args [ 'customer_id' ] = _dict . get ( 'customer_id' )
if 'document_type' in _dict :
args [ 'document_type' ] = _dict . get ( 'document_type' )
if 'natural_language_query' in _d... |
def add_callback ( self , func ) :
"""Registers a call back function""" | if func is None :
return
func_list = to_list ( func )
if not hasattr ( self , 'callback_list' ) :
self . callback_list = func_list
else :
self . callback_list . extend ( func_list ) |
def carry_in ( value , carry , base ) :
"""Add a carry digit to a number represented by ` ` value ` ` .
: param value : the value
: type value : list of int
: param int carry : the carry digit ( > = 0)
: param int base : the base ( > = 2)
: returns : carry - out and result
: rtype : tuple of int * ( lis... | if base < 2 :
raise BasesValueError ( base , "base" , "must be at least 2" )
if any ( x < 0 or x >= base for x in value ) :
raise BasesValueError ( value , "value" , "elements must be at least 0 and less than %s" % base )
if carry < 0 or carry >= base :
raise BasesValueError ( carry , "carry" , "carry must ... |
def stop ( self ) :
"""Stops the playing thread and close""" | with self . lock :
self . halting = True
self . go . clear ( ) |
def p_casecontent_condition_single ( self , p ) :
'casecontent _ condition : casecontent _ condition COMMA expression' | p [ 0 ] = p [ 1 ] + ( p [ 3 ] , )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def msetnx ( self , mapping ) :
"""Sets key / values based on a mapping if none of the keys are already set .
Mapping is a dictionary of key / value pairs . Both keys and values
should be strings or types that can be cast to a string via str ( ) .
Returns a boolean indicating if the operation was successful .... | items = [ ]
for pair in iteritems ( mapping ) :
items . extend ( pair )
return self . execute_command ( 'MSETNX' , * items ) |
def serialize ( self , value , primitive = False ) :
"""Serialize this field .""" | if hasattr ( value , 'serialize' ) : # i . e . value is a nested model
return value . serialize ( primitive = primitive )
else :
return value |
def _get_socket ( self , sid ) :
"""Return the socket object for a given session .""" | try :
s = self . sockets [ sid ]
except KeyError :
raise KeyError ( 'Session not found' )
if s . closed :
del self . sockets [ sid ]
raise KeyError ( 'Session is disconnected' )
return s |
def search ( self ) :
"""Looks up the current search terms from the xdk files that are loaded .""" | QApplication . instance ( ) . setOverrideCursor ( Qt . WaitCursor )
terms = nativestring ( self . uiSearchTXT . text ( ) )
html = [ ]
entry_html = '<a href="%(url)s">%(title)s</a><br/>' '<small>%(url)s</small>'
for i in range ( self . uiContentsTREE . topLevelItemCount ( ) ) :
item = self . uiContentsTREE . topLeve... |
def plotting_class ( cls , obj ) :
"""Given an object or Element class , return the suitable plotting
class needed to render it with the current renderer .""" | if isinstance ( obj , AdjointLayout ) or obj is AdjointLayout :
obj = Layout
if isinstance ( obj , type ) :
element_type = obj
else :
element_type = obj . type if isinstance ( obj , HoloMap ) else type ( obj )
try :
plotclass = Store . registry [ cls . backend ] [ element_type ]
except KeyError :
ra... |
def get_available_backends ( ) :
"""Returns a dictionary of defined backend classes . For example :
' default ' : ' django . core . mail . backends . smtp . EmailBackend ' ,
' locmem ' : ' django . core . mail . backends . locmem . EmailBackend ' ,""" | backends = get_config ( ) . get ( 'BACKENDS' , { } )
if backends :
return backends
# Try to get backend settings from old style
# POST _ OFFICE = {
# ' EMAIL _ BACKEND ' : ' mybackend '
backend = get_config ( ) . get ( 'EMAIL_BACKEND' )
if backend :
warnings . warn ( 'Please use the new POST_OFFICE["BACKENDS"] ... |
def delete ( self , obj , force = False ) :
"""Deletes all of the fields at the specified locations .
args :
` ` obj = ` ` \ * OBJECT *
the object to remove the fields from
` ` force = ` ` \ * BOOL *
if True , missing attributes do not raise errors . Otherwise ,
the first failure raises an exception wit... | # TODO : this could be a whole lot more efficient !
if not force :
for fs in self :
try :
fs . get ( obj )
except FieldSelectorException :
raise
for fs in self :
try :
fs . delete ( obj )
except FieldSelectorException :
pass |
def disconnect ( self ) :
"""Disconnect from the Graphite server if connected .""" | if self . sock is not None :
try :
self . sock . close ( )
except socket . error :
pass
finally :
self . sock = None |
def create ( cls , fqdn , duration , owner , admin , tech , bill , nameserver , extra_parameter , background ) :
"""Create a domain .""" | fqdn = fqdn . lower ( )
if not background and not cls . intty ( ) :
background = True
result = cls . call ( 'domain.available' , [ fqdn ] )
while result [ fqdn ] == 'pending' :
time . sleep ( 1 )
result = cls . call ( 'domain.available' , [ fqdn ] )
if result [ fqdn ] == 'unavailable' :
raise DomainNotA... |
def timeout ( self , value ) :
'''Specifies a timeout on the search query''' | if not self . params :
self . params = dict ( timeout = value )
return self
self . params [ 'timeout' ] = value
return self |
def set_top_n ( self , value ) :
'''setter''' | if isinstance ( value , int ) is False :
raise TypeError ( "The type of __top_n must be int." )
self . __top_n = value |
def list_users ( self , objectmask = None , objectfilter = None ) :
"""Lists all users on an account
: param string objectmask : Used to overwrite the default objectmask .
: param dictionary objectfilter : If you want to use an objectfilter .
: returns : A list of dictionaries that describe each user
Exampl... | if objectmask is None :
objectmask = """mask[id, username, displayName, userStatus[name], hardwareCount, virtualGuestCount,
email, roles]"""
return self . account_service . getUsers ( mask = objectmask , filter = objectfilter ) |
def fetchUrls ( cls , url , data , urlSearch ) :
"""Search all entries for given XPath in a HTML page .""" | searchUrls = [ ]
if cls . css :
searchFun = data . cssselect
else :
searchFun = data . xpath
searches = makeSequence ( urlSearch )
for search in searches :
for match in searchFun ( search ) :
try :
for attrib in html_link_attrs :
if attrib in match . attrib :
... |
def get_app ( self , reference_app = None ) :
"""Helper method that implements the logic to look up an application .""" | if reference_app is not None :
return reference_app
if self . app is not None :
return self . app
ctx = stack . top
if ctx is not None :
return ctx . app
raise RuntimeError ( 'Application not registered on Bouncer' ' instance and no application bound' ' to current context' ) |
def _invoke ( task , args ) :
'''Invoke a task with the appropriate args ; return the remaining args .''' | kwargs = task . defaults . copy ( )
if task . kwargs :
temp_kwargs , args = getopt . getopt ( args , '' , task . kwargs )
temp_kwargs = _opts_to_dict ( * temp_kwargs )
kwargs . update ( temp_kwargs )
if task . args :
for arg in task . args :
if not len ( args ) :
abort ( LOCALE [ 'er... |
def _findFiles ( self , pushdir , files = None ) :
"""Find all files , return dict , where key is filename
files [ filename ] = dictionary
where dictionary has keys :
[ ' mtime ' ] = modification time""" | # If no file list given , go through all
if not files :
files = os . listdir ( pushdir )
dfiles = { }
for fn in files : # Skip . files
if fn [ 0 ] == '.' :
continue
fullfile = os . path . join ( pushdir , fn )
d = { }
d [ 'mtime' ] = os . path . getmtime ( fullfile )
dfiles [ fn ] = d
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.