signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def as_curl ( self , endpoint , encoded_data , headers ) :
"""Return the send as a curl command .
Useful for debugging . This will write out the encoded data to a local
file named ` encrypted . data `
: param endpoint : Push service endpoint URL
: type endpoint : basestring
: param encoded _ data : byte a... | header_list = [ '-H "{}: {}" \\ \n' . format ( key . lower ( ) , val ) for key , val in headers . items ( ) ]
data = ""
if encoded_data :
with open ( "encrypted.data" , "wb" ) as f :
f . write ( encoded_data )
data = "--data-binary @encrypted.data"
if 'content-length' not in headers :
header_list . ... |
def populate ( self , other ) :
"""Like update , but clears the contents first .""" | self . clear ( )
self . update ( other )
self . reset_all_changes ( ) |
def schaffer ( self , x ) :
"""Schaffer function x0 in [ - 100 . . 100]""" | N = len ( x )
s = x [ 0 : N - 1 ] ** 2 + x [ 1 : N ] ** 2
return sum ( s ** 0.25 * ( np . sin ( 50 * s ** 0.1 ) ** 2 + 1 ) ) |
def create_account ( self , balance = 0 , address = None , concrete_storage = False , dynamic_loader = None , creator = None , ) -> Account :
"""Create non - contract account .
: param address : The account ' s address
: param balance : Initial balance for the account
: param concrete _ storage : Interpret ac... | address = address if address else self . _generate_new_address ( creator )
new_account = Account ( address , balance = balance , dynamic_loader = dynamic_loader , concrete_storage = concrete_storage , )
self . _put_account ( new_account )
return new_account |
def stream ( self ) :
"""Returns a generator of lines instead of a list of lines .""" | st = self . _stream ( )
for l in next ( st ) :
yield l . rstrip ( "\n" ) |
def main ( ) :
"""Main entry function .""" | if len ( sys . argv ) < 3 :
print ( 'Usage: <project-name> <filetype> <list-of-path to traverse>' )
print ( '\tfiletype can be python/cpp/all' )
exit ( - 1 )
_HELPER . project_name = sys . argv [ 1 ]
file_type = sys . argv [ 2 ]
allow_type = [ ]
if file_type == 'python' or file_type == 'all' :
allow_typ... |
def momentum ( self , exponent = 1 , errorrequested = True ) :
"""Calculate momenta ( integral of y times x ^ exponent )
The integration is done by the trapezoid formula ( np . trapz ) .
Inputs :
exponent : the exponent of q in the integration .
errorrequested : True if error should be returned ( true Gauss... | y = self . Intensity * self . q ** exponent
m = np . trapz ( y , self . q )
if errorrequested :
err = self . Error * self . q ** exponent
dm = errtrapz ( self . q , err )
return ErrorValue ( m , dm )
else :
return m |
def get_inspect_for_image ( image , registry , insecure = False , dockercfg_path = None ) :
"""Return inspect for image .
: param image : ImageName , the remote image to inspect
: param registry : str , URI for registry , if URI schema is not provided ,
https : / / will be used
: param insecure : bool , whe... | all_man_digests = get_all_manifests ( image , registry , insecure = insecure , dockercfg_path = dockercfg_path )
blob_config = None
config_digest = None
image_inspect = { }
# we have manifest list ( get digest for 1st platform )
if 'v2_list' in all_man_digests :
man_list_json = all_man_digests [ 'v2_list' ] . json ... |
def index ( self , key ) :
"""Return the index of the given item .
: param key :
: return :""" | if isinstance ( key , int ) :
if 0 <= key < len ( self . __keys ) :
return key
raise IndexError ( key )
elif isinstance ( key , str ) :
try :
return self . __keys . index ( key )
except ValueError :
raise KeyError ( key )
else :
raise TypeError ( key ) |
def search ( cls , query , search_opts = None ) :
"""Search pools .
Maps to the function : py : func : ` nipap . backend . Nipap . search _ pool ` in
the backend . Please see the documentation for the backend function
for information regarding input arguments and return values .""" | if search_opts is None :
search_opts = { }
xmlrpc = XMLRPCConnection ( )
try :
search_result = xmlrpc . connection . search_pool ( { 'query' : query , 'search_options' : search_opts , 'auth' : AuthOptions ( ) . options } )
except xmlrpclib . Fault as xml_fault :
raise _fault_to_exception ( xml_fault )
resul... |
def writeFasta ( sequence , sequence_name , output_file ) :
"""Writes a fasta sequence into a file .
: param sequence : a string with the sequence to be written
: param sequence _ name : name of the the fasta sequence
: param output _ file : / path / to / file . fa to be written
: returns : nothing""" | i = 0
f = open ( output_file , 'w' )
f . write ( ">" + str ( sequence_name ) + "\n" )
while i <= len ( sequence ) :
f . write ( sequence [ i : i + 60 ] + "\n" )
i = i + 60
f . close ( ) |
def check_api_version ( resource_root , min_version ) :
"""Checks if the resource _ root ' s API version it at least the given minimum
version .""" | if resource_root . version < min_version :
raise Exception ( "API version %s is required but %s is in use." % ( min_version , resource_root . version ) ) |
def compute_Pi_J ( self , CDR3_seq , J_usage_mask ) :
"""Compute Pi _ J .
This function returns the Pi array from the model factors of the J genomic
contributions , P ( delJ | J ) . This corresponds to J ( D ) ^ { x _ 4 } .
For clarity in parsing the algorithm implementation , we include which
instance attr... | # Note , the cutJ _ genomic _ CDR3 _ segs INCLUDE the palindromic insertions and thus are max _ palindrome nts longer than the template .
# furthermore , the genomic sequence should be pruned to start at a conserved region on the J side
Pi_J = [ ]
# Holds the aggregate weight for each nt possiblity and position
r_J_usa... |
async def list_state ( self , request ) :
"""Fetches list of data entries , optionally filtered by address prefix .
Request :
query :
- head : The id of the block to use as the head of the chain
- address : Return entries whose addresses begin with this
prefix
Response :
data : An array of leaf object... | paging_controls = self . _get_paging_controls ( request )
head , root = await self . _head_to_root ( request . url . query . get ( 'head' , None ) )
validator_query = client_state_pb2 . ClientStateListRequest ( state_root = root , address = request . url . query . get ( 'address' , None ) , sorting = self . _get_sortin... |
def QA_indicator_OBV ( DataFrame ) :
"""能量潮""" | VOL = DataFrame . volume
CLOSE = DataFrame . close
return pd . DataFrame ( { 'OBV' : np . cumsum ( IF ( CLOSE > REF ( CLOSE , 1 ) , VOL , IF ( CLOSE < REF ( CLOSE , 1 ) , - VOL , 0 ) ) ) / 10000 } ) |
def get_string_length ( self ) :
"""Attempts to parse array size out of the address""" | try :
return self . get_array_size ( )
except :
match = re . search ( r"(?<=\.)\d+" , self . get_address ( ) )
try :
return int ( match . group ( 0 ) )
except Exception as ex :
raise Exception ( 'Could not get string size of {0} address {1}' . format ( self . name , self . get_address ( ... |
def plot ( self , plot_intermediate_solutions = True , plot_observed_data = True , plot_starting_trajectory = True , plot_optimal_trajectory = True , filter_plots_function = None , legend = True , kwargs_observed_data = None , kwargs_starting_trajectories = None , kwargs_optimal_trajectories = None , kwargs_intermediat... | from matplotlib import pyplot as plt
if filter_plots_function is None :
filter_plots_function = lambda x : True
observed_trajectories = self . observed_trajectories
starting_trajectories = self . starting_trajectories
optimal_trajectories = self . optimal_trajectories
if plot_intermediate_solutions :
intermedia... |
def read ( self ) :
"""Read stdout and stdout pipes if process is no longer running .""" | if self . _process and self . _process . poll ( ) is not None :
ip = get_ipython ( )
err = ip . user_ns [ 'error' ] . read ( ) . decode ( )
out = ip . user_ns [ 'output' ] . read ( ) . decode ( )
else :
out = ''
err = ''
return out , err |
def base_image_inspect ( self ) :
"""inspect base image
: return : dict""" | if self . _base_image_inspect is None :
if self . base_from_scratch :
self . _base_image_inspect = { }
elif self . parents_pulled or self . custom_base_image :
try :
self . _base_image_inspect = self . tasker . inspect_image ( self . base_image )
except docker . errors . NotF... |
def uploadFileToIM ( self , directory , filename , title ) :
"""Parameters as they look in the form for uploading packages to IM""" | self . logger . debug ( "uploadFileToIM(" + "{},{},{})" . format ( directory , filename , title ) )
parameters = { 'data-filename-placement' : 'inside' , 'title' : str ( filename ) , 'filename' : str ( filename ) , 'type' : 'file' , 'name' : 'files' , 'id' : 'fileToUpload' , 'multiple' : '' }
file_dict = { 'files' : ( ... |
def add_volume ( self , volume ) :
"""Add a volume to self . volumes if it isn ' t already present""" | for old_vol in self . volumes :
if volume == old_vol :
return
self . volumes . append ( volume ) |
def _regex_strings ( self ) :
"""A property to link into IntentEngine ' s _ regex _ strings .
Warning : this is only for backwards compatiblility and should not be used if you
intend on using domains .
Returns : the domains _ regex _ strings from its IntentEngine""" | domain = 0
if domain not in self . domains :
self . register_domain ( domain = domain )
return self . domains [ domain ] . _regex_strings |
def find_zero_constrained_reactions ( model ) :
"""Return list of reactions that are constrained to zero flux .""" | return [ rxn for rxn in model . reactions if rxn . lower_bound == 0 and rxn . upper_bound == 0 ] |
def measure_board_rms ( control_board , n_samples = 10 , sampling_ms = 10 , delay_between_samples_ms = 0 ) :
'''Read RMS voltage samples from control board high - voltage feedback circuit .''' | try :
results = control_board . measure_impedance ( n_samples , sampling_ms , delay_between_samples_ms , True , True , [ ] )
except RuntimeError : # ` RuntimeError ` may be raised if , for example , current limit was
# reached during measurement . In such cases , return an empty frame .
logger . warning ( 'Erro... |
def set_attributes_from_headers ( self , headers ) :
"""Set instance attributes with HTTP header
: param headers : HTTP header""" | self . total_count = headers . get ( 'x-total-count' , None )
self . current_page = headers . get ( 'x-current-page' , None )
self . per_page = headers . get ( 'x-per-page' , None )
self . user_type = headers . get ( 'x-user-type' , None )
if self . total_count :
self . total_count = int ( self . total_count )
if s... |
def advertise ( self , routers = None , name = None , timeout = None , router_file = None , jitter = None , ) :
"""Make a service available on the Hyperbahn routing mesh .
This will make contact with a Hyperbahn host from a list of known
Hyperbahn routers . Additional Hyperbahn connections will be established
... | name = name or self . name
if not self . is_listening ( ) :
self . listen ( )
return hyperbahn . advertise ( self , name , routers , timeout , router_file , jitter , ) |
def exists ( self ) :
""": return : True if the submodule exists , False otherwise . Please note that
a submodule may exist ( in the . gitmodules file ) even though its module
doesn ' t exist on disk""" | # keep attributes for later , and restore them if we have no valid data
# this way we do not actually alter the state of the object
loc = locals ( )
for attr in self . _cache_attrs :
try :
if hasattr ( self , attr ) :
loc [ attr ] = getattr ( self , attr )
# END if we have the attribute ... |
def write_yaml ( self , data , encoding = None , errors = None , newline = None , ** kwargs ) :
"""Read * data * to this path as a YAML document .
The * encoding * , * errors * , and * newline * keywords are passed to
: meth : ` open ` . The remaining * kwargs * are passed to : meth : ` yaml . dump ` .""" | import yaml
with self . open ( mode = 'wt' , encoding = encoding , errors = errors , newline = newline ) as f :
return yaml . dump ( data , stream = f , ** kwargs ) |
def from_binary_string ( cls , stream ) :
"""Read feedback information from the stream and unpack it .
: param stream : A stream of feedback data from APN . Can contain multiple
feedback tuples , as defined in the feedback service protocol .
: return A list containing all unpacked feedbacks .""" | offset = 0
length = len ( stream )
feedbacks = [ ]
while offset < length :
timestamp , token_length = struct . unpack ( cls . FORMAT_PREFIX , stream [ offset : offset + 6 ] )
when = datetime . fromtimestamp ( timestamp )
offset += 6
token = struct . unpack ( '>{0}s' . format ( token_length ) , stream [ ... |
def iat ( x , maxlag = None ) :
"""Calculate the integrated autocorrelation time ( IAT ) , given the trace from a Stochastic .""" | if not maxlag : # Calculate maximum lag to which autocorrelation is calculated
maxlag = _find_max_lag ( x )
acr = [ autocorr ( x , lag ) for lag in range ( 1 , maxlag + 1 ) ]
# Calculate gamma values
gammas = [ ( acr [ 2 * i ] + acr [ 2 * i + 1 ] ) for i in range ( maxlag // 2 ) ]
cut = _cut_time ( gammas )
if cut ... |
def explode ( self ) :
"""If the current Line entity consists of multiple line
break it up into n Line entities .
Returns
exploded : ( n , ) Line entities""" | points = np . column_stack ( ( self . points , self . points ) ) . ravel ( ) [ 1 : - 1 ] . reshape ( ( - 1 , 2 ) )
exploded = [ Line ( i ) for i in points ]
return exploded |
def delayed_close ( self ) :
"""Delayed close - won ' t close immediately , but on the next reactor
loop .""" | self . state = SESSION_STATE . CLOSING
reactor . callLater ( 0 , self . close ) |
def documentation ( default = None , api_version = None , api = None , ** kwargs ) :
"""returns documentation for the current api""" | api_version = default or api_version
if api :
return api . http . documentation ( base_url = "" , api_version = api_version ) |
def clear_data ( self ) :
"""Clear menu data from previous menu generation .""" | self . __header . title = None
self . __header . subtitle = None
self . __prologue . text = None
self . __epilogue . text = None
self . __items_section . items = None |
def clientConnectionFailed ( self , err , address : Address ) :
"""Called when we fail to connect to an endpoint
Args :
err : Twisted Failure instance
address : the address we failed to connect to""" | if type ( err . value ) == error . TimeoutError :
logger . debug ( f"Failed connecting to {address} connection timed out" )
elif type ( err . value ) == error . ConnectError :
ce = err . value
if len ( ce . args ) > 0 :
logger . debug ( f"Failed connecting to {address} {ce.args[0].value}" )
else... |
def perform_request ( self , request ) :
'''Sends an HTTPRequest to Azure Storage and returns an HTTPResponse . If
the response code indicates an error , raise an HTTPError .
: param HTTPRequest request :
The request to serialize and send .
: return : An HTTPResponse containing the parsed HTTP response .
... | # Verify the body is in bytes or either a file - like / stream object
if request . body :
request . body = _get_data_bytes_or_stream_only ( 'request.body' , request . body )
# Construct the URI
uri = self . protocol . lower ( ) + '://' + request . host + request . path
# Send the request
response = self . session .... |
def ansi_split ( text , _re = re . compile ( u"(\x1b\\[(\\d*;?)*\\S)" ) ) :
"""Yields ( is _ ansi , text )""" | for part in _re . split ( text ) :
if part :
yield ( bool ( _re . match ( part ) ) , part ) |
def frameify ( self , state , data ) :
"""Split data into a sequence of lines .""" | # Pull in any partially - processed data
data = state . recv_buf + data
# Loop over the data
while data :
line , sep , rest = data . partition ( '\n' )
# Did we have a whole line ?
if sep != '\n' :
break
# OK , update the data . . .
data = rest
# Now , strip off carriage return , if ther... |
def refine_pi_cation_laro ( self , all_picat , stacks ) :
"""Just important for constellations with histidine involved . If the histidine ring is positioned in stacking
position to an aromatic ring in the ligand , there is in most cases stacking and pi - cation interaction reported
as histidine also carries a p... | i_set = [ ]
for picat in all_picat :
exclude = False
for stack in stacks :
if whichrestype ( stack . proteinring . atoms [ 0 ] ) == 'HIS' and picat . ring . obj == stack . ligandring . obj :
exclude = True
if not exclude :
i_set . append ( picat )
return i_set |
def pitch_shift ( y , sr , n_steps , rbargs = None ) :
'''Apply a pitch shift to an audio time series .
Parameters
y : np . ndarray [ shape = ( n , ) or ( n , c ) ]
Audio time series , either single or multichannel
sr : int > 0
Sampling rate of ` y `
n _ steps : float
Shift by ` n _ steps ` semitones ... | if n_steps == 0 :
return y
if rbargs is None :
rbargs = dict ( )
rbargs . setdefault ( '--pitch' , n_steps )
return __rubberband ( y , sr , ** rbargs ) |
def _genEmptyResults ( self ) :
"""Uses allowed keys to generate a empty dict to start counting from
: return :""" | allowedKeys = self . _allowedKeys
keysDict = OrderedDict ( )
# Note : list comprehension take 0 then 2 then 1 then 3 etc for some reason . we want strict order
for k in allowedKeys :
keysDict [ k ] = 0
resultsByClass = keysDict
return resultsByClass |
def get_xdsl_stats ( self ) :
"""Get all stats about your xDSL connection
: return : A dict with all stats about your xdsl connection ( see API doc )
: rtype : dict""" | self . bbox_auth . set_access ( BboxConstant . AUTHENTICATION_LEVEL_PUBLIC , BboxConstant . AUTHENTICATION_LEVEL_PRIVATE )
self . bbox_url . set_api_name ( BboxConstant . API_WAN , "xdsl/stats" )
api = BboxApiCall ( self . bbox_url , BboxConstant . HTTP_METHOD_GET , None , self . bbox_auth )
resp = api . execute_api_re... |
def to_path_value ( self , obj ) :
"""Takes value and turn it into a string suitable for inclusion in
the path , by url - encoding .
: param obj : object or string value .
: return string : quoted value .""" | if type ( obj ) == list :
return ',' . join ( obj )
else :
return str ( obj ) |
def start ( self , request , application , extra_roles = None ) :
"""Continue the state machine at first state .""" | # Get the authentication of the current user
roles = self . _get_roles_for_request ( request , application )
if extra_roles is not None :
roles . update ( extra_roles )
# Ensure current user is authenticated . If user isn ' t applicant ,
# leader , delegate or admin , they probably shouldn ' t be here .
if 'is_auth... |
def filenames ( self ) :
"""list of file names the data is originally being read from .
Returns
names : list of str
list of file names at the beginning of the input chain .""" | if self . _is_reader :
assert self . _filenames is not None
return self . _filenames
else :
return self . data_producer . filenames |
def get_mac_acl_for_intf_input_direction ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_mac_acl_for_intf = ET . Element ( "get_mac_acl_for_intf" )
config = get_mac_acl_for_intf
input = ET . SubElement ( get_mac_acl_for_intf , "input" )
direction = ET . SubElement ( input , "direction" )
direction . text = kwargs . pop ( 'direction' )
callback = kwargs . pop ( 'callba... |
def union ( self , * others : 'Substitution' ) -> 'Substitution' :
"""Try to merge the substitutions .
If a variable occurs in multiple substitutions , try to merge the replacements .
See : meth : ` union _ with _ variable ` to see how replacements are merged .
Does not modify any of the original substitution... | new_subst = Substitution ( self )
for other in others :
for variable_name , replacement in other . items ( ) :
new_subst . try_add_variable ( variable_name , replacement )
return new_subst |
def find_commands ( management_dir ) :
"""Given a path to a management directory , returns a list of all the command
names that are available .
Returns an empty list if no commands are defined .""" | command_dir = os . path . join ( management_dir , 'commands' )
try :
return [ f [ : - 3 ] for f in os . listdir ( command_dir ) if not f . startswith ( '_' ) and f . endswith ( '.py' ) ]
except OSError :
return [ ] |
def isJournal ( self , dbname = abrevDBname , manualDB = manualDBname , returnDict = 'both' , checkIfExcluded = False ) :
"""Returns ` True ` if the ` Citation ` ' s ` journal ` field is a journal abbreviation from the WOS listing found at [ http : / / images . webofknowledge . com / WOK46 / help / WOS / A _ abrvjt... | global abbrevDict
if abbrevDict is None :
abbrevDict = getj9dict ( dbname = dbname , manualDB = manualDB , returnDict = returnDict )
if not hasattr ( self , 'journal' ) :
return False
elif checkIfExcluded and self . journal :
try :
if abbrevDict . get ( self . journal , [ True ] ) [ 0 ] :
... |
def load_consumer_metadata_for_group ( self , group ) :
"""Determine broker for the consumer metadata for the specified group
Returns a deferred which callbacks with True if the group ' s coordinator
could be determined , or errbacks with
ConsumerCoordinatorNotAvailableError if not .
Parameters
group :
... | group = _coerce_consumer_group ( group )
log . debug ( "%r: load_consumer_metadata_for_group(%r)" , self , group )
# If we are already loading the metadata for this group , then
# just return the outstanding deferred
if group in self . coordinator_fetches :
d = defer . Deferred ( )
self . coordinator_fetches [ ... |
def iter_sections ( self , order = Tree . ipreorder , neurite_order = NeuriteIter . FileOrder ) :
'''iteration over section nodes
Parameters :
order : section iteration order within a given neurite . Must be one of :
Tree . ipreorder : Depth - first pre - order iteration of tree nodes
Tree . ipreorder : Dep... | return iter_sections ( self , iterator_type = order , neurite_order = neurite_order ) |
def vertical_headers ( self , value ) :
"""Setter for * * self . _ _ vertical _ headers * * attribute .
: param value : Attribute value .
: type value : OrderedDict""" | if value is not None :
assert type ( value ) is OrderedDict , "'{0}' attribute: '{1}' type is not 'OrderedDict'!" . format ( "vertical_headers" , value )
self . __vertical_headers = value |
def delete_user ( self , username ) :
"""Deletes a user from the server .
: param string username : Name of the user to delete from the server .""" | path = Client . urls [ 'users_by_name' ] % username
return self . _call ( path , 'DELETE' ) |
def HasDateExceptionOn ( self , date , exception_type = _EXCEPTION_TYPE_ADD ) :
"""Test if this service period has a date exception of the given type .
Args :
date : a string of form " YYYYMMDD "
exception _ type : the exception type the date should have . Defaults to
_ EXCEPTION _ TYPE _ ADD
Returns :
... | if date in self . date_exceptions :
return exception_type == self . date_exceptions [ date ] [ 0 ]
return False |
def query_nds2 ( cls , name , host = None , port = None , connection = None , type = None ) :
"""Query an NDS server for channel information
Parameters
name : ` str `
name of requested channel
host : ` str ` , optional
name of NDS2 server .
port : ` int ` , optional
port number for NDS2 connection
c... | return ChannelList . query_nds2 ( [ name ] , host = host , port = port , connection = connection , type = type , unique = True ) [ 0 ] |
def sort_diclist ( undecorated , sort_on ) :
"""Sort a list of dictionaries by the value in each
dictionary for the sorting key
Parameters
undecorated : list of dicts
sort _ on : str , numeric
key that is present in all dicts to sort on
Returns
ordered list of dicts
Examples
> > > lst = [ { ' key1... | decorated = [ ( len ( dict_ [ sort_on ] ) if hasattr ( dict_ [ sort_on ] , '__len__' ) else dict_ [ sort_on ] , index ) for ( index , dict_ ) in enumerate ( undecorated ) ]
decorated . sort ( )
return [ undecorated [ index ] for ( key , index ) in decorated ] |
def get_staged_files ( ) :
"""Get all files staged for the current commit .""" | proc = subprocess . Popen ( ( 'git' , 'status' , '--porcelain' ) , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
out , _ = proc . communicate ( )
staged_files = modified_re . findall ( out )
return staged_files |
def children ( self , parent ) :
"""Return set of children of parent .
Parameters
parent : : class : ` katcp . Sensor ` object
Parent whose children to return .
Returns
children : set of : class : ` katcp . Sensor ` objects
The child sensors of parent .""" | if parent not in self . _parent_to_children :
raise ValueError ( "Parent sensor %r not in tree." % parent )
return self . _parent_to_children [ parent ] . copy ( ) |
def publish ( self ) :
'''Function to publish cmdvel .''' | self . lock . acquire ( )
tw = cmdvel2Twist ( self . data )
self . lock . release ( )
self . pub . publish ( tw ) |
def is_plugin ( plugin ) :
"""Returns true if the plugin implements the ` Plugin ` interface .
: param plugin : The plugin to check .
: returns : True if plugin , False otherwise .
: rtype : bool""" | try :
return isinstance ( plugin , Plugin ) or issubclass ( plugin , Plugin )
except TypeError :
return False |
def get ( self , * args , ** kwargs ) :
"""The base activation logic ; subclasses should leave this method
alone and implement activate ( ) , which is called from this
method .""" | extra_context = { }
try :
activated_user = self . activate ( * args , ** kwargs )
except ActivationError as e :
extra_context [ 'activation_error' ] = { 'message' : e . message , 'code' : e . code , 'params' : e . params }
else :
signals . user_activated . send ( sender = self . __class__ , user = activated... |
def getOutputColumn ( self , columnAlias ) :
"""Returns a Column .""" | result = None
for column in self . __outputColumns :
if column . getColumnAlias ( ) == columnAlias :
result = column
break
return result |
def close ( self , * args , ** kwargs ) :
"""Engine closed , copy file to DB if it has changed""" | super ( DatabaseWrapper , self ) . close ( * args , ** kwargs )
signature_version = self . settings_dict . get ( "SIGNATURE_VERSION" , "s3v4" )
s3 = boto3 . resource ( 's3' , config = botocore . client . Config ( signature_version = signature_version ) , )
try :
with open ( self . settings_dict [ 'NAME' ] , 'rb' ) ... |
def move ( self , fnames = None , directory = None ) :
"""Move files / directories""" | if fnames is None :
fnames = self . get_selected_filenames ( )
orig = fixpath ( osp . dirname ( fnames [ 0 ] ) )
while True :
self . redirect_stdio . emit ( False )
if directory is None :
folder = getexistingdirectory ( self , _ ( "Select directory" ) , orig )
else :
folder = directory
... |
def flatten ( iterable ) :
"""Fully flattens an iterable :
In : flatten ( [ 1,2,3,4 , [ 5,6 , [ 7,8 ] ] ] )
Out : [ 1,2,3,4,5,6,7,8]""" | container = iterable . __class__
placeholder = [ ]
for item in iterable :
try :
placeholder . extend ( flatten ( item ) )
except TypeError :
placeholder . append ( item )
return container ( placeholder ) |
def _get_char ( self , win , char ) :
def get_check_next_byte ( ) :
char = win . getch ( )
if 128 <= char <= 191 :
return char
else :
raise UnicodeError
bytes = [ ]
if char <= 127 : # 1 bytes
bytes . append ( char )
# elif 194 < = char < = 223:
... | while 0 in bytes :
bytes . remove ( 0 )
if version_info < ( 3 , 0 ) :
out = '' . join ( [ chr ( b ) for b in bytes ] )
else :
buf = bytearray ( bytes )
out = self . _decode_string ( buf )
# out = buf . decode ( ' utf - 8 ' )
return out |
def mp_spawn ( self ) :
"""Spawn worker processes ( using multiprocessing )""" | processes = [ ]
for x in range ( self . queue_worker_amount ) :
process = multiprocessing . Process ( target = self . mp_worker )
process . start ( )
processes . append ( process )
for process in processes :
process . join ( ) |
def cosh ( x ) :
"""Hyperbolic cosine""" | if isinstance ( x , UncertainFunction ) :
mcpts = np . cosh ( x . _mcpts )
return UncertainFunction ( mcpts )
else :
return np . cosh ( x ) |
def has_edge ( self , node1_name , node2_name , account_for_direction = True ) :
"""Proxies a call to the _ _ has _ edge method""" | return self . __has_edge ( node1_name = node1_name , node2_name = node2_name , account_for_direction = account_for_direction ) |
def _sort_layers ( self ) :
"""Sort the layers by depth .""" | self . _layers = OrderedDict ( sorted ( self . _layers . items ( ) , key = lambda t : t [ 0 ] ) ) |
def percent_point ( self , y , V ) :
"""Compute the inverse of conditional cumulative distribution : math : ` C ( u | v ) ^ - 1 `
Args :
y : ` np . ndarray ` value of : math : ` C ( u | v ) ` .
v : ` np . ndarray ` given value of v .""" | self . check_fit ( )
if self . theta < 0 :
return V
else :
a = np . power ( y , self . theta / ( - 1 - self . theta ) )
b = np . power ( V , self . theta )
u = np . power ( ( a + b - 1 ) / b , - 1 / self . theta )
return u |
def get_existing_item ( self , item ) :
"""Lookup item in remote service based on keys .
: param item : D4S2Item data contains keys we will use for lookup .
: return : requests . Response containing the successful result""" | params = { 'project_id' : item . project_id , 'from_user_id' : item . from_user_id , 'to_user_id' : item . to_user_id , }
resp = requests . get ( self . make_url ( item . destination ) , headers = self . json_headers , params = params )
self . check_response ( resp )
return resp |
def add_leverage ( self ) :
"""Adds leverage term to the model
Returns
None ( changes instance attributes )""" | if self . leverage is True :
pass
else :
self . leverage = True
self . z_no += 1
for i in range ( len ( self . X_names ) * 2 + 3 ) :
self . latent_variables . z_list . pop ( )
for parm in range ( len ( self . X_names ) ) :
self . latent_variables . add_z ( 'Vol Beta ' + self . X_name... |
def get_repository_nodes ( self , repository_id , ancestor_levels , descendant_levels , include_siblings ) :
"""Gets a portion of the hierarchy for the given repository .
arg : repository _ id ( osid . id . Id ) : the ` ` Id ` ` to query
arg : ancestor _ levels ( cardinal ) : the maximum number of
ancestor le... | # Implemented from template for
# osid . resource . BinHierarchySession . get _ bin _ nodes
return objects . RepositoryNode ( self . get_repository_node_ids ( repository_id = repository_id , ancestor_levels = ancestor_levels , descendant_levels = descendant_levels , include_siblings = include_siblings ) . _my_map , run... |
def sub_retab ( match ) :
r"""Remove all tabs and convert them into spaces .
PARAMETERS :
match - - regex match ; uses re _ retab pattern : \ 1 is text before tab ,
\2 is a consecutive string of tabs .
A simple substitution of 4 spaces would result in the following :
to \ tlive # original
to live # simp... | before = match . group ( 1 )
tabs = len ( match . group ( 2 ) )
return before + ( ' ' * ( TAB_SIZE * tabs - len ( before ) % TAB_SIZE ) ) |
def on_peer_down ( self , peer ) :
"""Peer down handler .
Cleans up the paths in global tables that was received from this peer .""" | LOG . debug ( 'Cleaning obsolete paths whose source/version: %s/%s' , peer . ip_address , peer . version_num )
# Launch clean - up for each global tables .
self . _table_manager . clean_stale_routes ( peer ) |
def get_server_networks ( self , network , public = False , private = False , key = None ) :
"""Creates the dict of network UUIDs required by Cloud Servers when
creating a new server with isolated networks . By default , the UUID
values are returned with the key of " net - id " , which is what novaclient
expe... | return _get_server_networks ( network , public = public , private = private , key = key ) |
def __add_delayed_assert_failure ( self ) :
"""Add a delayed _ assert failure into a list for future processing .""" | current_url = self . driver . current_url
message = self . __get_exception_message ( )
self . __delayed_assert_failures . append ( "CHECK #%s: (%s)\n %s" % ( self . __delayed_assert_count , current_url , message ) ) |
def run ( xmin , ymin , xmax , ymax , step , range_ , range_x , range_y , t ) :
pt = numpy . zeros ( ( range_x , range_y ) )
"omp parallel for private ( i , j , k , tmp )" | for i in xrange ( range_x ) :
for j in xrange ( range_y ) :
xi , yj = xmin + step * i , ymin + step * j
for k in xrange ( t . shape [ 0 ] ) :
tmp = 6368. * math . acos ( math . cos ( xi ) * math . cos ( t [ k , 0 ] ) * math . cos ( ( yj ) - t [ k , 1 ] ) + math . sin ( xi ) * math . sin ... |
def modify_model_backprop ( model , backprop_modifier ) :
"""Creates a copy of model by modifying all activations to use a custom op to modify the backprop behavior .
Args :
model : The ` keras . models . Model ` instance .
backprop _ modifier : One of ` { ' guided ' , ' rectified ' } `
Returns :
A copy o... | # The general strategy is as follows :
# - Save original model so that upstream callers don ' t see unexpected results with their models .
# - Call backend specific function that registers the custom op and loads the model under modified context manager .
# - Maintain cache to save this expensive process on subsequent ... |
def create_source ( self , datapusher = True ) :
"""Populate ckan directory from preloaded image and copy
who . ini and schema . xml info conf directory""" | task . create_source ( self . target , self . _preload_image ( ) , datapusher ) |
def getSettingsPath ( ) :
"""Returns the path where the settings are stored""" | parser = SafeConfigParser ( )
try :
parser . read ( os . path . normpath ( pyGeno_SETTINGS_DIR + '/config.ini' ) )
return parser . get ( 'pyGeno_config' , 'settings_dir' )
except :
createDefaultConfigFile ( )
return getSettingsPath ( ) |
def post_op ( self , id : str , path_data : Union [ dict , None ] , post_data : Any ) -> dict :
"""Modifies the ESI by looking up an operation id .
Args :
path : raw ESI URL path
path _ data : data to format the path with ( can be None )
post _ data : data to send to ESI
Returns :
ESI data""" | path = self . _get_path_for_op_id ( id )
return self . post_path ( path , path_data , post_data ) |
def Connect ( self , Username , WaitConnected = False ) :
"""Connects application to user .
: Parameters :
Username : str
Name of the user to connect to .
WaitConnected : bool
If True , causes the method to wait until the connection is established .
: return : If ` ` WaitConnected ` ` is True , returns ... | if WaitConnected :
self . _Connect_Event = threading . Event ( )
self . _Connect_Stream = [ None ]
self . _Connect_Username = Username
self . _Connect_ApplicationStreams ( self , self . Streams )
self . _Owner . RegisterEventHandler ( 'ApplicationStreams' , self . _Connect_ApplicationStreams )
s... |
def _find_ssh_exe ( ) :
'''Windows only : search for Git ' s bundled ssh . exe in known locations''' | # Known locations for Git ' s ssh . exe in Windows
globmasks = [ os . path . join ( os . getenv ( 'SystemDrive' ) , os . sep , 'Program Files*' , 'Git' , 'usr' , 'bin' , 'ssh.exe' ) , os . path . join ( os . getenv ( 'SystemDrive' ) , os . sep , 'Program Files*' , 'Git' , 'bin' , 'ssh.exe' ) ]
for globmask in globmasks... |
def parse ( path ) :
"""Parse URL path and convert it to regexp if needed .""" | parsed = re . sre_parse . parse ( path )
for case , _ in parsed :
if case not in ( re . sre_parse . LITERAL , re . sre_parse . ANY ) :
break
else :
return path
path = path . strip ( '^$' )
def parse_ ( match ) :
[ part ] = match . groups ( )
match = DYNR_RE . match ( part )
params = match . ... |
def _parse_lsb_release_content ( lines ) :
"""Parse the output of the lsb _ release command .
Parameters :
* lines : Iterable through the lines of the lsb _ release output .
Each line must be a unicode string or a UTF - 8 encoded byte
string .
Returns :
A dictionary containing all information items .""" | props = { }
for line in lines :
kv = line . strip ( '\n' ) . split ( ':' , 1 )
if len ( kv ) != 2 : # Ignore lines without colon .
continue
k , v = kv
props . update ( { k . replace ( ' ' , '_' ) . lower ( ) : v . strip ( ) } )
return props |
def cropped ( self , t0 , t1 ) :
"""returns a cropped copy of this segment which starts at
self . point ( t0 ) and ends at self . point ( t1 ) .""" | return Line ( self . point ( t0 ) , self . point ( t1 ) ) |
def runProcess ( cmd , * args ) :
"""Run ` cmd ` ( which is searched for in the executable path ) with ` args ` and
return the exit status .
In general ( unless you know what you ' re doing ) use : :
runProcess ( ' program ' , filename )
rather than : :
os . system ( ' program % s ' % filename )
because... | from os import spawnvp , P_WAIT
return spawnvp ( P_WAIT , cmd , ( cmd , ) + args ) |
def execution_engine_model_changed ( self , model , prop_name , info ) :
"""High light active state machine .""" | notebook = self . view [ 'notebook' ]
active_state_machine_id = self . model . state_machine_manager . active_state_machine_id
if active_state_machine_id is None : # un - mark all state machine that are marked with execution - running style class
for tab in self . tabs . values ( ) :
label = notebook . get_... |
def add ( self , rule : ControlRule = None , * , supply : float ) :
"""Register a new rule above a given ` ` supply ` ` threshold
Registration supports a single - argument form for use as a decorator ,
as well as a two - argument form for direct application .
Use the former for ` ` def ` ` or ` ` class ` ` de... | if supply in self . _thresholds :
raise ValueError ( 'rule for threshold %s re-defined' % supply )
if rule is not None :
self . rules . append ( ( supply , rule ) )
self . _thresholds . add ( supply )
return rule
else :
return partial ( self . add , supply = supply ) |
def mac_address_table_static_vlanid ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
mac_address_table = ET . SubElement ( config , "mac-address-table" , xmlns = "urn:brocade.com:mgmt:brocade-mac-address-table" )
static = ET . SubElement ( mac_address_table , "static" )
mac_address_key = ET . SubElement ( static , "mac-address" )
mac_address_key . text = kwargs . pop ... |
def highest_expr_genes ( adata , n_top = 30 , show = None , save = None , ax = None , gene_symbols = None , ** kwds ) :
"""Fraction of counts assigned to each gene over all cells .
Computes , for each gene , the fraction of counts assigned to that gene within
a cell . The ` n _ top ` genes with the highest mean... | from scipy . sparse import issparse
# compute the percentage of each gene per cell
dat = normalize_per_cell ( adata , counts_per_cell_after = 100 , copy = True )
# identify the genes with the highest mean
if issparse ( dat . X ) :
dat . var [ 'mean_percent' ] = dat . X . mean ( axis = 0 ) . A1
else :
dat . var ... |
def _get_django_sites ( ) :
"""Get a list of sites as dictionaries { site _ id : ' domain . name ' }""" | deployed = version_state ( 'deploy_project' )
if not env . sites and 'django.contrib.sites' in env . INSTALLED_APPS and deployed :
with cd ( '/' . join ( [ deployment_root ( ) , 'env' , env . project_fullname , 'project' , env . project_package_name , 'sitesettings' ] ) ) :
venv = '/' . join ( [ deployment_... |
def _encode ( self ) :
"""Encode the message and return a bytestring .""" | data = ByteBuffer ( )
if not hasattr ( self , '__fields__' ) :
return data . tostring ( )
for field in self . __fields__ :
field . encode ( self , data )
return data . tostring ( ) |
def get_credentials ( ) :
"""Get the credentials to use . We try application credentials first , followed by
user credentials . The path to the application credentials can be overridden
by pointing the GOOGLE _ APPLICATION _ CREDENTIALS environment variable to some file ;
the path to the user credentials can ... | try :
credentials , _ = google . auth . default ( )
credentials = google . auth . credentials . with_scopes_if_required ( credentials , CREDENTIAL_SCOPES )
return credentials
except Exception as e : # Try load user creds from file
cred_file = get_config_dir ( ) + '/credentials'
if os . path . exists... |
def datasetScalarTimeStepChunk ( lines , numberColumns , numberCells ) :
"""Process the time step chunks for scalar datasets""" | END_DATASET_TAG = 'ENDDS'
# Define the result object
result = { 'iStatus' : None , 'timestamp' : None , 'cellArray' : None , 'rasterText' : None }
# Split the chunks
timeStep = pt . splitLine ( lines . pop ( 0 ) )
# Extract cells , ignoring the status indicators
startCellsIndex = numberCells
# Handle case when status c... |
def uncshare ( self ) :
"""The UNC mount point for this path .
This is empty for paths on local drives .""" | unc , r = self . module . splitunc ( self )
return self . _next_class ( unc ) |
def error ( self , msg , indent = 0 , ** kwargs ) :
"""invoke ` ` self . logger . error ` `""" | return self . logger . error ( self . _indent ( msg , indent ) , ** kwargs ) |
def X_less ( self ) :
"""Zoom out on the x - axis .""" | self . parent . value ( 'window_length' , self . parent . value ( 'window_length' ) / 2 )
self . parent . overview . update_position ( ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.