signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_repository ( self , repository = None , params = None ) :
"""Return information about registered repositories .
` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / modules - snapshots . html > ` _
: arg repository : A comma - separated list of repository names
: arg ... | return self . transport . perform_request ( 'GET' , _make_path ( '_snapshot' , repository ) , params = params ) |
def info ( self , media_id ) :
"""Получить информацию по файлу
: param media _ id :
: rtype : requests . Response""" | dr = self . __app . native_api_call ( 'media' , 'i/' + media_id , { } , self . __options , False , None , False , http_path = "/api/meta/v1/" , http_method = 'GET' )
return json . loads ( dr . text ) |
def authenticate ( self , transport , account_name , password ) :
"""Authenticates account , if no password given tries to pre - authenticate .
@ param transport : transport to use for method calls
@ param account _ name : account name
@ param password : account password
@ return : AuthToken if authenticati... | if not isinstance ( transport , ZimbraClientTransport ) :
raise ZimbraClientException ( 'Invalid transport' )
if util . empty ( account_name ) :
raise AuthException ( 'Empty account name' ) |
def is_degraded ( graph : BELGraph , node : BaseEntity ) -> bool :
"""Return true if over any of the node ' s edges , it is degraded .""" | return _node_has_modifier ( graph , node , DEGRADATION ) |
def start ( self ) :
"""Clone objects from one container to another .
This method was built to clone a container between data - centers while
using the same credentials . The method assumes that an authentication
token will be valid within the two data centers .""" | LOG . info ( 'Clone warm up...' )
# Create the target args
self . _target_auth ( )
last_list_obj = None
while True :
self . indicator_options [ 'msg' ] = 'Gathering object list'
with indicator . Spinner ( ** self . indicator_options ) :
objects_list = self . _list_contents ( single_page_return = True , ... |
def register_fetcher ( self , name , fetcher ) :
"""Register a fetcher .
: param name : Fetcher name .
: param fetcher : The new fetcher .""" | assert name not in self . fetchers
self . fetchers [ name ] = fetcher |
def parse_filters ( ) :
"""Parse variant filters from the request object .""" | genes_str = request . args . get ( 'gene_symbol' )
filters = { }
for key in ( 'frequency' , 'cadd' , 'sv_len' ) :
try :
filters [ key ] = float ( request . args . get ( key ) )
except ( ValueError , TypeError ) :
pass
filters [ 'gene_symbols' ] = genes_str . split ( ',' ) if genes_str else None
... |
def __encryptKeyTransportMessage ( self , bare_jids , encryption_callback , bundles = None , expect_problems = None , ignore_trust = False ) :
"""bare _ jids : iterable < string >
encryption _ callback : A function which is called using an instance of cryptography . hazmat . primitives . ciphers . CipherContext ,... | yield self . runInactiveDeviceCleanup ( )
# parameter preparation #
if isinstance ( bare_jids , string_type ) :
bare_jids = set ( [ bare_jids ] )
else :
bare_jids = set ( bare_jids )
if bundles == None :
bundles = { }
if expect_problems == None :
expect_problems = { }
else :
for bare_jid in expect_p... |
def _iterate_object ( obj ) :
"""Return iterator over object attributes . Respect objects with
defined _ _ slots _ _ .""" | d = { }
try :
d = vars ( obj )
except TypeError : # maybe we have named tuple here ?
if hasattr ( obj , '_asdict' ) :
d = obj . _asdict ( )
for item in iteritems ( d ) :
yield item
try :
slots = obj . __slots__
except AttributeError :
pass
else :
for key in slots :
if key != '__d... |
def show ( dataset , ** kwargs ) :
"""Display the dataset as an image .""" | img = get_enhanced_image ( dataset . squeeze ( ) , ** kwargs )
img . show ( )
return img |
def load ( filename : str , format : str = None ) :
"""Load a task file and get a ` ` Project ` ` back .""" | path = Path ( filename ) . resolve ( )
with path . open ( ) as file :
data = file . read ( )
if format is None :
loader , error_class = _load_autodetect , InvalidMofileFormat
else :
try :
loader , error_class = formats [ format ]
except KeyError :
raise InvalidMofileFormat ( f'Unknown fi... |
def pt_reflect ( pt = ( 0.0 , 0.0 ) , plane = [ None , None ] ) :
'''Return given point reflected around planes in N dimensions .
There must be the same number of planes as dimensions , but the value of each
plane may be None to indicate no reflection .''' | assert isinstance ( pt , tuple )
l_pt = len ( pt )
assert l_pt > 1
for i in pt :
assert isinstance ( i , float )
assert isinstance ( plane , list )
l_pl = len ( plane )
assert l_pl == l_pt
for i in plane :
assert isinstance ( i , float ) or i is None
return tuple ( [ pt [ i ] if plane [ i ] is None else ( 2 * p... |
def truncate ( data , l = 20 ) :
"truncate a string" | info = ( data [ : l ] + '..' ) if len ( data ) > l else data
return info |
def save_form ( self , form , request , ** resources ) :
"""Save self form .""" | resource = yield from super ( PWAdminHandler , self ) . save_form ( form , request , ** resources )
resource . save ( )
return resource |
def createFromMaskedArray ( cls , masked_arr ) :
"""Creates an ArrayWithMak
: param masked _ arr : a numpy MaskedArray or numpy array
: return : ArrayWithMask""" | if isinstance ( masked_arr , ArrayWithMask ) :
return masked_arr
check_class ( masked_arr , ( np . ndarray , ma . MaskedArray ) )
# A MaskedConstant ( i . e . masked ) is a special case of MaskedArray . It does not seem to have
# a fill _ value so we use None to use the default .
# https : / / docs . scipy . org / ... |
def get_scheme_dirs ( ) :
"""Return a set of all scheme directories .""" | scheme_glob = rel_to_cwd ( 'schemes' , '**' , '*.yaml' )
scheme_groups = glob ( scheme_glob )
scheme_groups = [ get_parent_dir ( path ) for path in scheme_groups ]
return set ( scheme_groups ) |
def init_device ( self ) :
"""Device constructor .""" | start_time = time . time ( )
Device . init_device ( self )
self . _pb_id = ''
LOG . debug ( 'init PB device %s, time taken %.6f s (total: %.2f s)' , self . get_name ( ) , ( time . time ( ) - start_time ) , ( time . time ( ) - self . _start_time ) )
self . set_state ( DevState . STANDBY ) |
def generate ( env ) :
"""Add Builders and construction variables for ar to an Environment .""" | as_module . generate ( env )
env [ 'AS' ] = '386asm'
env [ 'ASFLAGS' ] = SCons . Util . CLVar ( '' )
env [ 'ASPPFLAGS' ] = '$ASFLAGS'
env [ 'ASCOM' ] = '$AS $ASFLAGS $SOURCES -o $TARGET'
env [ 'ASPPCOM' ] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $SOURCES -o $TARGET'
addPharLapPaths ( env ) |
def get_formset ( self ) :
"""Provide the formset corresponding to this DataTable .
Use this to validate the formset and to get the submitted data back .""" | if self . folder :
queryset = self . folder . files . all ( )
else :
queryset = File . objects . none ( )
if self . _formset is None :
self . _formset = self . formset_class ( self . request . POST or None , initial = self . _get_formset_data ( ) , prefix = self . _meta . name , queryset = queryset )
return... |
def relative_to ( base , relativee ) :
"""Gets ' relativee ' relative to ' basepath ' .
i . e . ,
> > > relative _ to ( ' / home / ' , ' / home / radix / ' )
' radix '
> > > relative _ to ( ' . ' , ' / home / radix / Projects / Twisted ' ) # curdir is / home / radix
' Projects / Twisted '
The ' relative... | basepath = os . path . abspath ( base )
relativee = os . path . abspath ( relativee )
if relativee . startswith ( basepath ) :
relative = relativee [ len ( basepath ) : ]
if relative . startswith ( os . sep ) :
relative = relative [ 1 : ]
return os . path . join ( base , relative )
raise ValueError ... |
def lookup_hlr ( self , phonenumber , params = None ) :
"""Retrieve the information of a specific HLR lookup .""" | if params is None :
params = { }
return HLR ( ) . load ( self . request ( 'lookup/' + str ( phonenumber ) + '/hlr' , 'GET' , params ) ) |
def _install_wrappers ( self ) :
"""Install our PluginLoader monkey patches and update global variables
with references to the real functions .""" | global action_loader__get
action_loader__get = ansible_mitogen . loaders . action_loader . get
ansible_mitogen . loaders . action_loader . get = wrap_action_loader__get
global connection_loader__get
connection_loader__get = ansible_mitogen . loaders . connection_loader . get
ansible_mitogen . loaders . connection_loade... |
def init_genome_coordinates ( self ) :
"""Creates the self . seqpos2genome dictionary that converts positions
relative to the sequence to genome coordinates .""" | self . seqpos2genome = { }
# record genome positions for each sequence position
seq_pos = 0
for estart , eend in self . exons :
for genome_pos in range ( estart , eend ) :
if self . strand == '+' :
self . seqpos2genome [ seq_pos ] = genome_pos
elif self . strand == '-' :
tmp ... |
def challenge_hash ( peer_challenge , authenticator_challenge , username ) :
"""ChallengeHash""" | sha_hash = hashlib . sha1 ( )
sha_hash . update ( peer_challenge )
sha_hash . update ( authenticator_challenge )
sha_hash . update ( username )
return sha_hash . digest ( ) [ : 8 ] |
def _invoke ( self , argv , stream = sys . stdout , resubmit_failed = False ) :
"""Invoke this object to preform a particular action
Parameters
argv : list
List of command line arguments , passed to helper classes
stream : ` file `
Stream that this function will print to ,
must have ' write ' function .... | args = self . _run_argparser ( argv )
if args . action not in ACTIONS :
sys . stderr . write ( "Unrecognized action %s, options are %s\n" % ( args . action , ACTIONS ) )
if args . action == 'skip' :
return JobStatus . no_job
elif args . action in [ 'run' , 'resubmit' , 'check_status' , 'config' ] :
self . _... |
def _load_yaml_file ( self , file ) :
"""Load data from yaml file
: param file : Readable object or path to file
: type file : FileIO | str | unicode
: return : Yaml data
: rtype : None | int | float | str | unicode | list | dict
: raises IOError : Failed to load""" | try :
res = load_yaml_file ( file )
except :
self . exception ( "Failed to load from {}" . format ( file ) )
raise IOError ( "Loading file failed" )
return res |
def group ( self , * args , ** kwargs ) :
"""A shortcut decorator for declaring and attaching a group to
the group . This takes the same arguments as : func : ` group ` but
immediately registers the created command with this instance by
calling into : meth : ` add _ command ` .""" | def decorator ( f ) :
cmd = group ( * args , ** kwargs ) ( f )
self . add_command ( cmd )
return cmd
return decorator |
def to_list ( self ) :
"""To a list of dicts ( each dict is an instances )""" | ret = [ ]
for instance in self . instances :
ret . append ( instance . to_dict ( ) )
return ret |
def route ( self , dst , dev = None ) :
"""Provide best route to IPv6 destination address , based on Scapy6
internal routing table content .
When a set of address is passed ( e . g . 2001 : db8 : cafe : * : : 1-5 ) an address
of the set is used . Be aware of that behavior when using wildcards in
upper parts... | # Transform " 2001 : db8 : cafe : * : : 1-5:0/120 " to one IPv6 address of the set
dst = dst . split ( "/" ) [ 0 ]
savedst = dst
# In case following inet _ pton ( ) fails
dst = dst . replace ( "*" , "0" )
l = dst . find ( "-" )
while l >= 0 :
m = ( dst [ l : ] + ":" ) . find ( ":" )
dst = dst [ : l ] + dst [ l ... |
def _check_timeseries_input ( data ) :
"""Checks response time series input data ( e . g . , for ISC analysis )
Input data should be a n _ TRs by n _ voxels by n _ subjects ndarray
( e . g . , brainiak . image . MaskedMultiSubjectData ) or a list where each
item is a n _ TRs by n _ voxels ndarray for a given ... | # Convert list input to 3d and check shapes
if type ( data ) == list :
data_shape = data [ 0 ] . shape
for i , d in enumerate ( data ) :
if d . shape != data_shape :
raise ValueError ( "All ndarrays in input list " "must be the same shape!" )
if d . ndim == 1 :
data [ i ]... |
def login ( ) :
"""Does the login via OpenID . Has to call into ` oid . try _ login `
to start the OpenID machinery .""" | # if we are already logged in , go back to were we came from
if g . user is not None :
return redirect ( oid . get_next_url ( ) )
if request . method == 'POST' :
openid = request . form . get ( 'openid' )
if openid :
return oid . try_login ( openid , ask_for = [ 'email' , 'fullname' , 'nickname' ] )... |
def get_keys_containing ( search_string , input_dict , default = None , first_found = True ) :
"""Searches a dictionary for all keys containing the search string ( as long as the keys are not functions ) and
returns a filtered dictionary of only those keys
: param search _ string : str , string we are looking f... | output = { }
for k , v in iteritems ( input_dict ) :
if search_string in k and not callable ( k ) :
output [ k ] = v
if first_found :
try :
output = output [ next ( iter ( output ) ) ]
except StopIteration :
pass
return output or default |
def hset ( self , key , field , value ) :
"""Set the string value of a hash field .""" | return self . execute ( b'HSET' , key , field , value ) |
def cl_mutect ( self , params , tmp_dir ) :
"""Define parameters to run the mutect paired algorithm .""" | gatk_jar = self . _get_jar ( "muTect" , [ "mutect" ] )
# Decrease memory slightly from configuration to avoid memory allocation errors
jvm_opts = config_utils . adjust_opts ( self . _jvm_opts , { "algorithm" : { "memory_adjust" : { "magnitude" : 1.1 , "direction" : "decrease" } } } )
return [ "java" ] + jvm_opts + get_... |
def start_heartbeat ( self ) :
"""Reset hearbeat timer""" | self . stop_heartbeat ( )
self . _heartbeat_timer = task . LoopingCall ( self . _heartbeat )
self . _heartbeat_timer . start ( self . _heartbeat_interval , False ) |
def destroy ( self , request , * args , ** kwargs ) :
"""Destroy a model instance .
If ` ` delete _ content ` ` flag is set in query parameters , also all
Data objects contained in entity will be deleted .""" | obj = self . get_object ( )
user = request . user
if strtobool ( request . query_params . get ( 'delete_content' , 'false' ) ) :
for data in obj . data . all ( ) :
if user . has_perm ( 'edit_data' , data ) :
data . delete ( )
# If all data objects in an entity are removed , the entity may
... |
def step ( self ) :
"""Runs one step of the trial event loop .
Callers should typically run this method repeatedly in a loop . They
may inspect or modify the runner ' s state in between calls to step ( ) .""" | if self . is_finished ( ) :
raise TuneError ( "Called step when all trials finished?" )
with warn_if_slow ( "on_step_begin" ) :
self . trial_executor . on_step_begin ( )
next_trial = self . _get_next_trial ( )
# blocking
if next_trial is not None :
with warn_if_slow ( "start_trial" ) :
self . trial_... |
def properties ( self ) : # type : ( ) - > list
"""Returns :
( list [ str ] ) List of public properties""" | _type = type ( self )
return [ _property for _property in dir ( _type ) if self . _is_property ( _property ) ] |
def log_p ( self , z ) :
"""The unnormalized log posterior components ( the quantity we want to approximate )
RAO - BLACKWELLIZED !""" | return np . array ( [ self . log_p_blanket ( i ) for i in z ] ) |
def add_log ( self , x , flag_also_show = False ) :
"""Logs to 4 different outputs : conditionally to 3 , and certainly to get _ python _ logger ( )""" | self . _add_log_no_logger ( x , flag_also_show )
a99 . get_python_logger ( ) . info ( x ) |
def add_plugin ( self , plugin ) :
"""Append ` plugin ` to model
Arguments :
plugin ( dict ) : Serialised plug - in from pyblish - rpc
Schema :
plugin . json""" | item = { }
item . update ( defaults [ "common" ] )
item . update ( defaults [ "plugin" ] )
for member in [ "pre11" , "name" , "label" , "optional" , "category" , "actions" , "id" , "order" , "doc" , "type" , "module" , "match" , "hasRepair" , "families" , "contextEnabled" , "instanceEnabled" , "__instanceEnabled__" , "... |
def get_sequence_rule_enabler_form ( self , * args , ** kwargs ) :
"""Pass through to provider SequenceRuleEnablerAdminSession . get _ sequence _ rule _ enabler _ form _ for _ update""" | # Implemented from kitosid template for -
# osid . resource . ResourceAdminSession . get _ resource _ form _ for _ update
# This method might be a bit sketchy . Time will tell .
if isinstance ( args [ - 1 ] , list ) or 'sequence_rule_enabler_record_types' in kwargs :
return self . get_sequence_rule_enabler_form_for... |
def gen ( ctx , num , lo , hi , size , struct ) :
'''Generate deformed structures''' | frmt = ctx . parent . params [ 'frmt' ]
action = ctx . parent . params [ 'action' ]
cryst = ase . io . read ( struct , format = frmt )
fn_tmpl = action
if frmt == 'vasp' :
fn_tmpl += '_%03d.POSCAR'
kwargs = { 'vasp5' : True , 'direct' : True }
elif frmt == 'abinit' :
fn_tmpl += '_%03d.abinit'
kwargs = {... |
def get_or_create ( self , ** kwargs ) :
"""Looks up an object with the given kwargs , creating one if necessary .
Returns a tuple of ( object , created ) , where created is a boolean
specifying whether an object was created .""" | assert kwargs , "get_or_create() must be passed at least one keyword argument"
defaults = kwargs . pop ( "defaults" , { } )
lookup = kwargs . copy ( )
try :
return self . get ( ** lookup ) , False
except self . resource . DoesNotExist :
params = dict ( [ ( k , v ) for k , v in kwargs . items ( ) ] )
params ... |
def _GetRowValue ( self , query_hash , row , value_name ) :
"""Retrieves a value from the row .
Args :
query _ hash ( int ) : hash of the query , that uniquely identifies the query
that produced the row .
row ( sqlite3 . Row ) : row .
value _ name ( str ) : name of the value .
Returns :
object : value... | keys_name_to_index_map = self . _keys_per_query . get ( query_hash , None )
if not keys_name_to_index_map :
keys_name_to_index_map = { name : index for index , name in enumerate ( row . keys ( ) ) }
self . _keys_per_query [ query_hash ] = keys_name_to_index_map
value_index = keys_name_to_index_map . get ( value... |
def GetValueByName ( self , name ) :
"""Retrieves a value by name .
Value names are not unique and pyregf provides first match for the value .
Args :
name ( str ) : name of the value or an empty string for the default value .
Returns :
WinRegistryValue : Windows Registry value if a corresponding value was... | pyregf_value = self . _pyregf_key . get_value_by_name ( name )
if not pyregf_value :
return None
return REGFWinRegistryValue ( pyregf_value ) |
def get_call_signature ( fn : FunctionType , args : ArgsType , kwargs : KwargsType , debug_cache : bool = False ) -> str :
"""Takes a function and its args / kwargs , and produces a string description
of the function call ( the call signature ) suitable for use indirectly as a
cache key . The string is a JSON r... | # Note that the function won ' t have the _ _ self _ _ argument ( as in
# fn . _ _ self _ _ ) , at this point , even if it ' s a member function .
try :
call_sig = json_encode ( ( fn . __qualname__ , args , kwargs ) )
except TypeError :
log . critical ( "\nTo decorate using @django_cache_function without specif... |
def acquire ( self , timeout : Union [ float , datetime . timedelta ] = None ) -> Awaitable [ _ReleasingContextManager ] :
"""Attempt to lock . Returns an awaitable .
Returns an awaitable , which raises ` tornado . util . TimeoutError ` after a
timeout .""" | return self . _block . acquire ( timeout ) |
def national_significant_number ( numobj ) :
"""Gets the national significant number of a phone number .
Note that a national significant number doesn ' t contain a national prefix
or any formatting .
Arguments :
numobj - - The PhoneNumber object for which the national significant number
is needed .
Ret... | # If leading zero ( s ) have been set , we prefix this now . Note this is not a
# national prefix .
national_number = U_EMPTY_STRING
if numobj . italian_leading_zero :
num_zeros = numobj . number_of_leading_zeros
if num_zeros is None :
num_zeros = 1
if num_zeros > 0 :
national_number = U_ZER... |
def _compute ( self , feed_dict , shard ) :
"""Call the tensorflow compute""" | try :
descriptor , enq = self . _tfrun ( self . _tf_expr [ shard ] , feed_dict = feed_dict )
self . _inputs_waiting . decrement ( shard )
except Exception as e :
montblanc . log . exception ( "Compute Exception" )
raise |
def get_extended_stats ( self , field = None ) :
"""Create an extended _ stats aggregation object and add it to the aggregation dict
: param field : the field present in the index that is to be aggregated
: returns : self , which allows the method to be chainable with the other methods""" | if not field :
raise AttributeError ( "Please provide field to apply aggregation to!" )
agg = A ( "extended_stats" , field = field )
self . aggregations [ 'extended_stats_' + field ] = agg
return self |
def lock_variable ( self , key , block = False ) :
"""Locks a global variable
: param key : the key of the global variable to be locked
: param block : a flag to specify if to wait for locking the variable in blocking mode""" | key = str ( key )
# watch out for releasing the _ _ dictionary _ lock properly
try :
if key in self . __variable_locks : # acquire without arguments is blocking
lock_successful = self . __variable_locks [ key ] . acquire ( False )
if lock_successful or block :
if ( not lock_successful ) ... |
def errorprint ( ) :
"""Print out descriptions from ConfigurationError .""" | try :
yield
except ConfigurationError as e :
click . secho ( '%s' % e , err = True , fg = 'red' )
sys . exit ( 1 ) |
def query ( cls , offset = None , limit = None , api = None ) :
"""Query ( List ) divisions .
: param offset : Pagination offset .
: param limit : Pagination limit .
: param api : Api instance .
: return : Collection object .""" | api = api if api else cls . _API
return super ( Division , cls ) . _query ( url = cls . _URL [ 'query' ] , offset = offset , limit = limit , fields = '_all' , api = api ) |
def deconvolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True , apply_w = None , apply_b = None ) :
"""Deconvolution layer .
Args :
inp ( ~ nnabla . Variable ) : N - D... | if w_init is None :
w_init = UniformInitializer ( calc_uniform_lim_glorot ( outmaps , inp . shape [ base_axis ] , tuple ( kernel ) ) , rng = rng )
if with_bias and b_init is None :
b_init = ConstantInitializer ( )
w = get_parameter_or_create ( "W" , ( inp . shape [ base_axis ] , outmaps // group ) + tuple ( ker... |
def check_keystore_json ( jsondata ) :
"""Check if ` ` jsondata ` ` has the structure of a keystore file version 3.
Note that this test is not complete , e . g . it doesn ' t check key derivation or cipher parameters .
: param jsondata : dictionary containing the data from the json file
: returns : ` True ` i... | if 'crypto' not in jsondata and 'Crypto' not in jsondata :
return False
if 'version' not in jsondata :
return False
if jsondata [ 'version' ] != 3 :
return False
crypto = jsondata . get ( 'crypto' , jsondata . get ( 'Crypto' ) )
if 'cipher' not in crypto :
return False
if 'ciphertext' not in crypto :
... |
def get_group_index ( labels , shape , sort , xnull ) :
"""For the particular label _ list , gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations , * as long as * this space fits within int64 bounds ;
otherwise , though group indices... | def _int64_cut_off ( shape ) :
acc = 1
for i , mul in enumerate ( shape ) :
acc *= int ( mul )
if not acc < _INT64_MAX :
return i
return len ( shape )
def maybe_lift ( lab , size ) : # promote nan values ( assigned - 1 label in lab array )
# so that all output values are non - ne... |
def pip_install ( package , fatal = False , upgrade = False , venv = None , constraints = None , ** options ) :
"""Install a python package""" | if venv :
venv_python = os . path . join ( venv , 'bin/pip' )
command = [ venv_python , "install" ]
else :
command = [ "install" ]
available_options = ( 'proxy' , 'src' , 'log' , 'index-url' , )
for option in parse_options ( options , available_options ) :
command . append ( option )
if upgrade :
co... |
def exactly_n ( l , n = 1 ) :
'''Tests that exactly N items in an iterable are " truthy " ( neither None ,
False , nor 0 ) .''' | i = iter ( l )
return all ( any ( i ) for j in range ( n ) ) and not any ( i ) |
def check_siblings ( self , individual_1_id , individual_2_id ) :
"""Check if two family members are siblings .
Arguments :
individual _ 1 _ id ( str ) : The id of an individual
individual _ 2 _ id ( str ) : The id of an individual
Returns :
bool : True if the individuals are siblings
False if they are ... | self . logger . debug ( "Checking if {0} and {1} are siblings" . format ( individual_1_id , individual_2_id ) )
ind_1 = self . individuals [ individual_1_id ]
ind_2 = self . individuals [ individual_2_id ]
if ( ( ind_1 . father != '0' and ind_1 . father == ind_2 . father ) or ( ind_1 . mother != '0' and ind_1 . mother ... |
def parse_signature ( signature ) :
"""Parse a signature into its input and return parameter types .
This will also collect the types that are required by any of the input
and return types .
: sig : ( str ) - > Tuple [ List [ str ] , str , Set [ str ] ]
: param signature : Signature to parse .
: return : ... | if " -> " not in signature : # signature comment : no parameters , treat variable type as return type
param_types , return_type = None , signature . strip ( )
else :
lhs , return_type = [ s . strip ( ) for s in signature . split ( " -> " ) ]
csv = lhs [ 1 : - 1 ] . strip ( )
# remove the parentheses aro... |
def update ( cls , first_name = None , middle_name = None , last_name = None , public_nick_name = None , address_main = None , address_postal = None , avatar_uuid = None , tax_resident = None , document_type = None , document_number = None , document_country_of_issuance = None , document_front_attachment_id = None , do... | if custom_headers is None :
custom_headers = { }
api_client = client . ApiClient ( cls . _get_api_context ( ) )
request_map = { cls . FIELD_FIRST_NAME : first_name , cls . FIELD_MIDDLE_NAME : middle_name , cls . FIELD_LAST_NAME : last_name , cls . FIELD_PUBLIC_NICK_NAME : public_nick_name , cls . FIELD_ADDRESS_MAIN... |
def stdrepr_object ( self , title , elements , * , cls = None , short = False , quote_string_keys = False , delimiter = None ) :
"""Helper function to represent objects .
Arguments :
title : A title string displayed above the box containing
the elements , or a pair of two strings that will be
displayed left... | H = self . H
if delimiter is None and quote_string_keys is True :
delimiter = ' ↦ '
def wrap ( x ) :
if not quote_string_keys and isinstance ( x , str ) :
return x
else :
return self ( x )
if short :
contents = [ ]
for k , v in elements :
kv = H . div [ 'hrepr-object-kvpair' ... |
def interval_tree ( intervals ) :
"""Construct an interval tree
: param intervals : list of half - open intervals
encoded as value pairs * [ left , right ) *
: assumes : intervals are lexicographically ordered
` ` > > > assert intervals = = sorted ( intervals ) ` `
: returns : the root of the interval tre... | if intervals == [ ] :
return None
center = intervals [ len ( intervals ) // 2 ] [ 0 ]
L = [ ]
R = [ ]
C = [ ]
for I in intervals :
if I [ 1 ] <= center :
L . append ( I )
elif center < I [ 0 ] :
R . append ( I )
else :
C . append ( I )
by_low = sorted ( ( I [ 0 ] , I ) for I in C... |
def thread_counter ( finalize ) :
"""Modifies a thread target function , such that the number of active
threads is counted . If the count reaches zero , a finalizer is called .""" | n_threads = 0
lock = threading . Lock ( )
def target_modifier ( target ) :
@ functools . wraps ( target )
def modified_target ( * args , ** kwargs ) :
nonlocal n_threads , lock
with lock :
n_threads += 1
return_value = target ( * args , ** kwargs )
with lock :
... |
def maybe_convert_values ( self , identifier : Identifier , data : Dict [ str , Any ] , ) -> Dict [ str , Any ] :
"""Takes a dictionary of raw values for a specific identifier , as parsed
from the YAML file , and depending upon the type of db column the data
is meant for , decides what to do with the value ( eg... | raise NotImplementedError |
def read ( self , size ) :
"""Read wrapper .
Parameters
size : int
Number of bytes to read .""" | try :
return self . handle . read ( size )
except ( OSError , serial . SerialException ) :
print ( )
print ( "Piksi disconnected" )
print ( )
self . handle . close ( )
raise IOError |
def text_to_qcolor ( text ) :
"""Create a QColor from specified string
Avoid warning from Qt when an invalid QColor is instantiated""" | color = QColor ( )
if not is_string ( text ) : # testing for QString ( PyQt API # 1)
text = str ( text )
if not is_text_string ( text ) :
return color
if text . startswith ( '#' ) and len ( text ) == 7 :
correct = '#0123456789abcdef'
for char in text :
if char . lower ( ) not in correct :
... |
def disable_command ( self , command : str , message_to_print : str ) -> None :
"""Disable a command and overwrite its functions
: param command : the command being disabled
: param message _ to _ print : what to print when this command is run or help is called on it while disabled
The variable COMMAND _ NAME... | import functools
# If the commands is already disabled , then return
if command in self . disabled_commands :
return
# Make sure this is an actual command
command_function = self . cmd_func ( command )
if command_function is None :
raise AttributeError ( "{} does not refer to a command" . format ( command ) )
h... |
def _columns_sql ( self , with_namespace = False , ** kwargs ) :
"""SQL for Columns clause for INSERT queries
: param with _ namespace :
Remove from kwargs , never format the column terms with namespaces since only one table can be inserted into""" | return ' ({columns})' . format ( columns = ',' . join ( term . get_sql ( with_namespace = False , ** kwargs ) for term in self . _columns ) ) |
def environ ( request : httputil . HTTPServerRequest ) -> Dict [ Text , Any ] :
"""Converts a ` tornado . httputil . HTTPServerRequest ` to a WSGI environment .""" | hostport = request . host . split ( ":" )
if len ( hostport ) == 2 :
host = hostport [ 0 ]
port = int ( hostport [ 1 ] )
else :
host = request . host
port = 443 if request . protocol == "https" else 80
environ = { "REQUEST_METHOD" : request . method , "SCRIPT_NAME" : "" , "PATH_INFO" : to_wsgi_str ( esc... |
def prepare_data ( dt , features , response , sequence , id_column = None , seq_align = "end" , trim_seq_len = None ) :
"""Prepare data for Concise . train or ConciseCV . train .
Args :
dt : A pandas DataFrame containing all the required data .
features ( List of strings ) : Column names of ` dt ` used to pro... | if type ( response ) is str :
response = [ response ]
X_feat = np . array ( dt [ features ] , dtype = "float32" )
y = np . array ( dt [ response ] , dtype = "float32" )
X_seq = encodeDNA ( seq_vec = dt [ sequence ] , maxlen = trim_seq_len , seq_align = seq_align )
X_seq = np . array ( X_seq , dtype = "float32" )
id... |
def input_file ( self , _container ) :
"""Find the input path of a uchroot container .""" | p = local . path ( _container )
if set_input_container ( p , CFG ) :
return
p = find_hash ( CFG [ "container" ] [ "known" ] . value , container )
if set_input_container ( p , CFG ) :
return
raise ValueError ( "The path '{0}' does not exist." . format ( p ) ) |
def set_data ( self , data , copy = False , ** kwargs ) :
"""Set data ( deferred operation )
Parameters
data : ndarray
Data to be uploaded
copy : bool
Since the operation is deferred , data may change before
data is actually uploaded to GPU memory .
Asking explicitly for a copy will prevent this behav... | data = self . _prepare_data ( data , ** kwargs )
self . _dtype = data . dtype
self . _stride = data . strides [ - 1 ]
self . _itemsize = self . _dtype . itemsize
Buffer . set_data ( self , data = data , copy = copy ) |
async def field ( self , elem = None , elem_type = None , params = None ) :
"""Archive field
: param elem :
: param elem _ type :
: param params :
: return :""" | elem_type = elem_type if elem_type else elem . __class__
fvalue = None
etype = self . _get_type ( elem_type )
if self . _is_type ( etype , UVarintType ) :
fvalue = await self . uvarint ( get_elem ( elem ) )
elif self . _is_type ( etype , IntType ) :
fvalue = await self . uint ( elem = get_elem ( elem ) , elem_t... |
def _WX28_clipped_agg_as_bitmap ( agg , bbox ) :
"""Convert the region of a the agg buffer bounded by bbox to a wx . Bitmap .
Note : agg must be a backend _ agg . RendererAgg instance .""" | l , b , width , height = bbox . bounds
r = l + width
t = b + height
srcBmp = wx . BitmapFromBufferRGBA ( int ( agg . width ) , int ( agg . height ) , agg . buffer_rgba ( ) )
srcDC = wx . MemoryDC ( )
srcDC . SelectObject ( srcBmp )
destBmp = wx . EmptyBitmap ( int ( width ) , int ( height ) )
destDC = wx . MemoryDC ( )... |
def generate_with_pattern ( self , pattern = None ) :
"""Algorithm that creates the list
based on a given pattern
The pattern must be like string format patter :
e . g : a @ b will match an ' a ' follow by any character follow by a ' b '""" | curlen = utils . get_pattern_length ( pattern )
if curlen > 0 :
str_generator = product ( self . charset , repeat = curlen )
pattern = pattern + self . delimiter
fstring = utils . pattern_to_fstring ( pattern )
for each in str_generator :
yield fstring . format ( * each ) |
def is_point ( self ) :
"""figures out if item is a point , that is if it has two subelements of type float
Args :
self :
Returns : if item is a point ( True ) or not ( False )""" | if self . childCount ( ) == 2 :
if self . child ( 0 ) . valid_values == float and self . child ( 1 ) . valid_values == float :
return True
else :
return False |
def add_recipe_actions ( self , recipe_actions ) :
"""Add additional valid recipe actions to RecipeManager
args :
recipe _ actions ( list ) : List of tuples . First value of tuple is the classname ,
second value of tuple is RecipeAction Object""" | for action_name , action in recipe_actions :
self . _recipe_actions [ action_name ] = action |
def certify ( self , subject , level = SignatureType . Generic_Cert , ** prefs ) :
"""Sign a key or a user id within a key .
: param subject : The user id or key to be certified .
: type subject : : py : obj : ` PGPKey ` , : py : obj : ` PGPUID `
: param level : : py : obj : ` ~ constants . SignatureType . Ge... | hash_algo = prefs . pop ( 'hash' , None )
sig_type = level
if isinstance ( subject , PGPKey ) :
sig_type = SignatureType . DirectlyOnKey
sig = PGPSignature . new ( sig_type , self . key_algorithm , hash_algo , self . fingerprint . keyid )
# signature options that only make sense in certifications
usage = prefs . po... |
def order_by ( self , * orderings : str ) -> "QuerySet" :
"""Accept args to filter by in format like this :
. . code - block : : python3
. order _ by ( ' name ' , ' - tournament _ _ name ' )
Supports ordering by related models too .""" | queryset = self . _clone ( )
new_ordering = [ ]
for ordering in orderings :
order_type = Order . asc
if ordering [ 0 ] == "-" :
field_name = ordering [ 1 : ]
order_type = Order . desc
else :
field_name = ordering
if not ( field_name . split ( "__" ) [ 0 ] in self . model . _meta ... |
def printLn ( self , respType , respString ) :
"""Add one or lines of output to the response list .
Input :
Response type : One or more characters indicate type of response .
E - Error message
N - Normal message
S - Output should be logged
W - Warning message""" | if 'E' in respType :
respString = '(Error) ' + respString
if 'W' in respType :
respString = '(Warning) ' + respString
if 'S' in respType :
self . printSysLog ( respString )
self . results [ 'response' ] = ( self . results [ 'response' ] + respString . splitlines ( ) )
return |
def prefix ( self , name ) :
""": param string name : the name of an attribute to look up .
: return : the prefix component of the named attribute ' s name ,
or None .""" | a_node = self . adapter . get_node_attribute_node ( self . impl_element , name )
if a_node is None :
return None
return a_node . prefix |
def get_all_conversion_chains_to_type ( self , to_type : Type [ Any ] ) -> Tuple [ List [ Converter ] , List [ Converter ] , List [ Converter ] ] :
"""Utility method to find all converters to a given type
: param to _ type :
: return :""" | return self . get_all_conversion_chains ( to_type = to_type ) |
def until ( self , regex ) :
"""Wait until the regex encountered""" | logger . debug ( 'waiting for %s' , regex )
r = re . compile ( regex , re . M )
self . tn . expect ( [ r ] ) |
def mnemonic_phrase ( self , length : int = 12 ) -> str :
"""Generate pseudo mnemonic phrase .
: param length : Number of words .
: return : Mnemonic code .""" | words = self . __words [ 'normal' ]
return ' ' . join ( self . random . choice ( words ) for _ in range ( length ) ) |
def move_phasecenter ( d , l1 , m1 , u , v ) :
"""Handler function for phaseshift _ threaded""" | logger . info ( 'Rephasing data to (l, m)=(%.4f, %.4f).' % ( l1 , m1 ) )
data_resamp = numpyview ( data_resamp_mem , 'complex64' , datashape ( d ) )
rtlib . phaseshift_threaded ( data_resamp , d , l1 , m1 , u , v ) |
def print_update ( self , stream = sys . stdout , job_stats = None ) :
"""Print an update about the current number of jobs running""" | if job_stats is None :
job_stats = JobStatusVector ( )
job_det_list = [ ]
job_det_list += self . _scatter_link . jobs . values ( )
for job_dets in job_det_list :
if job_dets . status == JobStatus . no_job :
continue
job_stats [ job_dets . status ] += 1
stream . write ( "Statu... |
def update_thumbnail_via_upload ( api_key , api_secret , video_key , local_video_image_path = '' , api_format = 'json' , ** kwargs ) :
"""Function which updates the thumbnail for a particular video object with a locally saved image .
: param api _ key : < string > JWPlatform api - key
: param api _ secret : < s... | jwplatform_client = jwplatform . Client ( api_key , api_secret )
logging . info ( "Updating video thumbnail." )
try :
response = jwplatform_client . videos . thumbnails . update ( video_key = video_key , ** kwargs )
except jwplatform . errors . JWPlatformError as e :
logging . error ( "Encountered an error upda... |
def group ( self ) :
"""Get group .""" | for group in self . _server . groups :
if self . identifier in group . clients :
return group |
def get_metric_group_infos ( self ) :
"""Get the faked metric group definitions for this context object
that are to be returned from its create operation , in the format
needed for the " Create Metrics Context " operation response .
Returns :
" metric - group - infos " JSON object as described for the " Cre... | mg_defs = self . get_metric_group_definitions ( )
mg_infos = [ ]
for mg_def in mg_defs :
metric_infos = [ ]
for metric_name , metric_type in mg_def . types :
metric_infos . append ( { 'metric-name' : metric_name , 'metric-type' : metric_type , } )
mg_info = { 'group-name' : mg_def . name , 'metric-i... |
def determinant ( self ) :
"""The determinant of the transform matrix . This value
is equal to the area scaling factor when the transform
is applied to a shape .""" | a , b , c , d , e , f , g , h , i = self
return a * e - b * d |
def call_antlr4 ( arg ) :
"calls antlr4 on grammar file" | # pylint : disable = unused - argument , unused - variable
antlr_path = os . path . join ( ROOT_DIR , "java" , "antlr-4.7-complete.jar" )
classpath = os . pathsep . join ( [ "." , "{:s}" . format ( antlr_path ) , "$CLASSPATH" ] )
generated = os . path . join ( ROOT_DIR , 'src' , 'pymoca' , 'generated' )
cmd = "java -Xm... |
def maybe_convert_to_index_date_type ( index , date ) :
"""Convert a datetime - like object to the index ' s date type .
Datetime indexing in xarray can be done using either a pandas
DatetimeIndex or a CFTimeIndex . Both support partial - datetime string
indexing regardless of the calendar type of the underly... | if isinstance ( date , str ) :
return date
if isinstance ( index , pd . DatetimeIndex ) :
if isinstance ( date , np . datetime64 ) :
return date
else :
return np . datetime64 ( str ( date ) )
else :
date_type = index . date_type
if isinstance ( date , date_type ) :
return dat... |
def functions ( context ) :
"""Manage AWS Lambda functions""" | # find lambder . json in CWD
config_file = "./lambder.json"
if os . path . isfile ( config_file ) :
context . obj = FunctionConfig ( config_file )
pass |
def in_segmentlist ( column , segmentlist ) :
"""Return the index of values lying inside the given segmentlist
A ` ~ gwpy . segments . Segment ` represents a semi - open interval ,
so for any segment ` [ a , b ) ` , a value ` x ` is ' in ' the segment if
a < = x < b""" | segmentlist = type ( segmentlist ) ( segmentlist ) . coalesce ( )
idx = column . argsort ( )
contains = numpy . zeros ( column . shape [ 0 ] , dtype = bool )
j = 0
try :
segstart , segend = segmentlist [ j ]
except IndexError : # no segments , return all False
return contains
i = 0
while i < contains . shape [ ... |
def activate_membercard ( self , membership_number , code , ** kwargs ) :
"""激活会员卡 - 接口激活方式
详情请参见
https : / / mp . weixin . qq . com / wiki ? t = resource / res _ main & id = mp1451025283
参数示例 :
" init _ bonus " : 100,
" init _ bonus _ record " : " 旧积分同步 " ,
" init _ balance " : 200,
" membership _ nu... | kwargs [ 'membership_number' ] = membership_number
kwargs [ 'code' ] = code
return self . _post ( 'card/membercard/activate' , data = kwargs ) |
def parse ( self , configManager , config ) :
"""Parses commandline arguments , given a series of configuration options .
Inputs : configManager - Our parent ConfigManager instance which is constructing the Config object .
config - The _ Config object containing configuration options populated thus far .
Outp... | argParser = self . getArgumentParser ( configManager , config )
return vars ( argParser . parse_args ( ) ) |
def validate_is_callable_or_none ( option , value ) :
"""Validates that ' value ' is a callable .""" | if value is None :
return value
if not callable ( value ) :
raise ValueError ( "%s must be a callable" % ( option , ) )
return value |
def colRowIsOnSciencePixelList ( self , col , row , padding = DEFAULT_PADDING ) :
"""similar to colRowIsOnSciencePixelList ( ) but takes lists as input""" | out = np . ones ( len ( col ) , dtype = bool )
col_arr = np . array ( col )
row_arr = np . array ( row )
mask = np . bitwise_or ( col_arr < 12. - padding , col_arr > 1111 + padding )
out [ mask ] = False
mask = np . bitwise_or ( row_arr < 20. - padding , row_arr > 1043 + padding )
out [ mask ] = False
return out |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.