signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def add_section ( self , name ) :
"""Append ` section ` to model
Arguments :
name ( str ) : Name of section""" | assert isinstance ( name , str )
# Skip existing sections
for section in self . sections :
if section . name == name :
return section
item = defaults [ "common" ] . copy ( )
item [ "name" ] = name
item [ "itemType" ] = "section"
item = self . add_item ( item )
self . sections . append ( item )
return item |
def get_contents_static ( self , block_alias , context ) :
"""Returns contents of a static block .""" | if 'request' not in context : # No use in further actions as we won ' t ever know current URL .
return ''
current_url = context [ 'request' ] . path
# Resolve current view name to support view names as block URLs .
try :
resolver_match = resolve ( current_url )
namespace = ''
if resolver_match . namespa... |
def send_cons3rt_agent_logs ( self ) :
"""Sends a Slack message with an attachment for each cons3rt agent log
: return :""" | log = logging . getLogger ( self . cls_logger + '.send_cons3rt_agent_logs' )
log . debug ( 'Searching for log files in directory: {d}' . format ( d = self . dep . cons3rt_agent_log_dir ) )
for item in os . listdir ( self . dep . cons3rt_agent_log_dir ) :
item_path = os . path . join ( self . dep . cons3rt_agent_log... |
def calculate_convolution_output_shapes ( operator ) :
'''Allowed input / output patterns are
1 . [ N , C , H , W ] - - - > [ N , C , H ' , W ' ]''' | check_input_and_output_numbers ( operator , input_count_range = 1 , output_count_range = 1 )
params = operator . raw_operator . convolution
input_shape = operator . inputs [ 0 ] . type . shape
operator . outputs [ 0 ] . type . shape = [ 0 , 0 , 0 , 0 ]
# Initialize output shape . It will be modified below .
output_shap... |
def get_lemma_by_id ( self , mongo_id ) :
'''Builds a Lemma object from the database entry with the given
ObjectId .
Arguments :
- ` mongo _ id ` : a bson . objectid . ObjectId object''' | cache_hit = None
if self . _lemma_cache is not None :
cache_hit = self . _lemma_cache . get ( mongo_id )
if cache_hit is not None :
return cache_hit
lemma_dict = self . _mongo_db . lexunits . find_one ( { '_id' : mongo_id } )
if lemma_dict is not None :
lemma = Lemma ( self , lemma_dict )
if self . _lem... |
def showInvLines ( rh ) :
"""Produce help output related to command synopsis
Input :
Request Handle""" | if rh . subfunction != '' :
rh . printLn ( "N" , "Usage:" )
rh . printLn ( "N" , " python " + rh . cmdName + " GetHost " + "diskpoolnames" )
rh . printLn ( "N" , " python " + rh . cmdName + " GetHost " + "diskpoolspace <poolName>" )
rh . printLn ( "N" , " python " + rh . cmdName + " GetHost fcpdevices" )
rh . pr... |
def recursive_merge_dicts ( x , y , misses = "report" , verbose = None ) :
"""Merge dictionary y into a copy of x , overwriting elements of x when there
is a conflict , except if the element is a dictionary , in which case recurse .
misses : what to do if a key in y is not in x
' insert ' - > set x [ key ] = ... | def recurse ( x , y , misses = "report" , verbose = 1 ) :
found = True
for k , v in y . items ( ) :
found = False
if k in x :
found = True
if isinstance ( x [ k ] , dict ) :
if not isinstance ( v , dict ) :
msg = f"Attempted to overwrit... |
def get_delete_url_link ( self , text = None , cls = None , icon_class = None , ** attrs ) :
"""Gets the html delete link for the object .""" | if text is None :
text = 'Delete'
return build_link ( href = self . get_delete_url ( ) , text = text , cls = cls , icon_class = icon_class , ** attrs ) |
def signed_session ( self , session = None ) :
"""Sign requests session with the token . This method is called every time a request is going on the wire .
The user is responsible for updating the token with the preferred tool / SDK .
In general there are two options :
- override this method to update the toke... | session = session or requests . Session ( )
session . headers [ 'Authorization' ] = "Bearer {}" . format ( self . token )
return session |
def check_type ( stochastic ) :
"""type , shape = check _ type ( stochastic )
Checks the type of a stochastic ' s value . Output value ' type ' may be
bool , int , float , or complex . Nonnative numpy dtypes are lumped into
these categories . Output value ' shape ' is ( ) if the stochastic ' s value
is scal... | val = stochastic . value
if val . __class__ in bool_dtypes :
return bool , ( )
elif val . __class__ in integer_dtypes :
return int , ( )
elif val . __class__ in float_dtypes :
return float , ( )
elif val . __class__ in complex_dtypes :
return complex , ( )
elif isinstance ( val , ndarray ) :
if obj2... |
def to_array ( self ) :
"""Serializes this EncryptedCredentials to a dictionary .
: return : dictionary representation of this object .
: rtype : dict""" | array = super ( EncryptedCredentials , self ) . to_array ( )
array [ 'data' ] = u ( self . data )
# py2 : type unicode , py3 : type str
array [ 'hash' ] = u ( self . hash )
# py2 : type unicode , py3 : type str
array [ 'secret' ] = u ( self . secret )
# py2 : type unicode , py3 : type str
return array |
def replace_subject ( rdf , fromuri , touri ) :
"""Replace occurrences of fromuri as subject with touri in given model .
If touri = None , will delete all occurrences of fromuri instead .
If touri is a list or tuple of URIRefs , all values will be inserted .""" | if fromuri == touri :
return
for p , o in rdf . predicate_objects ( fromuri ) :
rdf . remove ( ( fromuri , p , o ) )
if touri is not None :
if not isinstance ( touri , ( list , tuple ) ) :
touri = [ touri ]
for uri in touri :
rdf . add ( ( uri , p , o ) ) |
def headinside ( self ) :
"""The head inside the well
Returns
array ( length number of screens )
Head inside the well for each screen""" | h = self . model . head ( self . xw + self . rw , self . yw , layers = self . layers )
return h - self . resfac * self . parameters [ : , 0 ] |
def version_dict ( version ) :
"""Turn a version string into a dict with major / minor / . . . info .""" | match = version_re . match ( str ( version ) or '' )
letters = 'alpha pre' . split ( )
numbers = 'major minor1 minor2 minor3 alpha_ver pre_ver' . split ( )
if match :
d = match . groupdict ( )
for letter in letters :
d [ letter ] = d [ letter ] if d [ letter ] else None
for num in numbers :
... |
def parse_accept_header ( accept ) :
"""Parse an HTTP Accept header .
Parses * accept * , returning a list with pairs of
( media _ type , q _ value ) , ordered by q values .
Adapted from < https : / / djangosnippets . org / snippets / 1042 / >""" | result = [ ]
for media_range in accept . split ( "," ) :
parts = media_range . split ( ";" )
media_type = parts . pop ( 0 ) . strip ( )
media_params = [ ]
q = 1.0
for part in parts :
( key , value ) = part . lstrip ( ) . split ( "=" , 1 )
if key == "q" :
q = float ( value... |
def find_nearest_color_hexstr ( hexdigits , color_table = None , method = 'euclid' ) :
'''Given a three or six - character hex digit string , return the nearest
color index .
Arguments :
hexdigits : a three / 6 digit hex string , e . g . ' b0b ' , ' 123456'
Returns :
int , None : index , or None on error ... | triplet = [ ]
try :
if len ( hexdigits ) == 3 :
for digit in hexdigits :
digit = int ( digit , 16 )
triplet . append ( ( digit * 16 ) + digit )
elif len ( hexdigits ) == 6 :
triplet . extend ( int ( hexdigits [ i : i + 2 ] , 16 ) for i in ( 0 , 2 , 4 ) )
else :
... |
def connect ( self , signal , ** kwargs ) :
"""Connect a specific signal type to this receiver .""" | signal . connect ( self , ** kwargs )
self . connections . append ( ( signal , kwargs ) ) |
async def result ( self , timeout : Optional [ float ] = None , * , pole_delay : float = 0.5 ) -> Any :
"""Get the result of the job , including waiting if it ' s not yet available . If the job raised an exception ,
it will be raised here .
: param timeout : maximum time to wait for the job result before raisin... | async for delay in poll ( pole_delay ) :
info = await self . result_info ( )
if info :
result = info . result
if info . success :
return result
else :
raise result
if timeout is not None and delay > timeout :
raise asyncio . TimeoutError ( ) |
def pCOH ( self ) :
"""Partial coherence .
. . math : : \ mathrm { pCOH } _ { ij } ( f ) = \\ frac { G _ { ij } ( f ) }
{ \ sqrt { G _ { ii } ( f ) G _ { jj } ( f ) } }
References
P . J . Franaszczuk , K . J . Blinowska , M . Kowalczyk . The application of
parametric multichannel spectral estimates in the... | G = self . G ( )
# TODO : can we do that more efficiently ?
return G / np . sqrt ( np . einsum ( 'ii..., jj... ->ij...' , G , G ) ) |
def smallest_prime_factor ( Q ) :
"""Find the smallest number factorable by the small primes 2 , 3 , 4 , and 7
that is larger than the argument Q""" | A = Q ;
while ( A != 1 ) :
if ( np . mod ( A , 2 ) == 0 ) :
A = A / 2
elif ( np . mod ( A , 3 ) == 0 ) :
A = A / 3
elif ( np . mod ( A , 5 ) == 0 ) :
A = A / 5
elif ( np . mod ( A , 7 ) == 0 ) :
A = A / 7 ;
else :
A = Q + 1 ;
Q = A ;
return Q |
def nn_setsockopt ( socket , level , option , value ) :
"""set a socket option
socket - socket number
level - option level
option - option
value - a readable byte buffer ( not a Unicode string ) containing the value
returns - 0 on success or < 0 on error""" | try :
return _nn_setsockopt ( socket , level , option , ctypes . addressof ( value ) , len ( value ) )
except ( TypeError , AttributeError ) :
buf_value = ctypes . create_string_buffer ( value )
return _nn_setsockopt ( socket , level , option , ctypes . addressof ( buf_value ) , len ( value ) ) |
def str ( self , local = False , ifempty = None ) :
"""Returns the string representation of the datetime""" | ts = self . get ( local )
if not ts :
return ifempty
return ts . strftime ( '%Y-%m-%d %H:%M:%S' ) |
def filter_db_names ( paths : List [ str ] ) -> List [ str ] :
"""Returns a filtered list of ` paths ` , where every name matches our format .
Args :
paths : A list of file names .""" | return [ db_path for db_path in paths if VERSION_RE . match ( os . path . basename ( db_path ) ) ] |
def get_lightcurve ( self , star_id , return_1d = True ) :
"""Get the light curves for the given ID
Parameters
star _ id : int
A valid integer star id representing an object in the dataset
return _ 1d : boolean ( default = True )
Specify whether to return 1D arrays of ( t , y , dy , filts ) or
2D arrays... | filename = '{0}/{1}.dat' . format ( self . dirname , star_id )
try :
data = np . loadtxt ( self . data . extractfile ( filename ) )
except KeyError :
raise ValueError ( "invalid star id: {0}" . format ( star_id ) )
RA = data [ : , 0 ]
DEC = data [ : , 1 ]
t = data [ : , 2 : : 3 ]
y = data [ : , 3 : : 3 ]
dy = d... |
def sort_by_padding ( instances : List [ Instance ] , sorting_keys : List [ Tuple [ str , str ] ] , # pylint : disable = invalid - sequence - index
vocab : Vocabulary , padding_noise : float = 0.0 ) -> List [ Instance ] :
"""Sorts the instances by their padding lengths , using the keys in
` ` sorting _ keys ` ` (... | instances_with_lengths = [ ]
for instance in instances : # Make sure instance is indexed before calling . get _ padding
instance . index_fields ( vocab )
padding_lengths = cast ( Dict [ str , Dict [ str , float ] ] , instance . get_padding_lengths ( ) )
if padding_noise > 0.0 :
noisy_lengths = { }
... |
def gen_lower ( x : Iterable [ str ] ) -> Generator [ str , None , None ] :
"""Args :
x : iterable of strings
Yields :
each string in lower case""" | for string in x :
yield string . lower ( ) |
def onAuthenticate ( self , signature , extra ) :
"""Callback fired when a client responds to an authentication challenge .""" | log . msg ( "onAuthenticate: {} {}" . format ( signature , extra ) )
# # if there is a pending auth , and the signature provided by client matches . .
if self . _pending_auth :
if signature == self . _pending_auth . signature : # # accept the client
return types . Accept ( authid = self . _pending_auth . ui... |
def p_bexpr_func ( p ) :
"""bexpr : ID bexpr""" | args = make_arg_list ( make_argument ( p [ 2 ] , p . lineno ( 2 ) ) )
p [ 0 ] = make_call ( p [ 1 ] , p . lineno ( 1 ) , args )
if p [ 0 ] is None :
return
if p [ 0 ] . token in ( 'STRSLICE' , 'VAR' , 'STRING' ) :
entry = SYMBOL_TABLE . access_call ( p [ 1 ] , p . lineno ( 1 ) )
entry . accessed = True
... |
def send_msg ( self , chat_id , msg_type , ** kwargs ) :
"""deprecated , use ` send ` instead""" | return self . send ( chat_id , msg_type , ** kwargs ) |
def is_token_revoked ( decoded_token ) :
"""Checks if the given token is revoked or not . Because we are adding all the
tokens that we create into this database , if the token is not present
in the database we are going to consider it revoked , as we don ' t know where
it was created .""" | jti = decoded_token [ 'jti' ]
try :
token = TokenBlacklist . query . filter_by ( jti = jti ) . one ( )
return token . revoked
except NoResultFound :
return True |
def add_member ( self , member ) :
"""Add a single member to the scope .
You may only edit the list of members if the pykechain credentials allow this .
: param member : single username to be added to the scope list of members
: type member : basestring
: raises APIError : when unable to update the scope me... | select_action = 'add_member'
self . _update_scope_project_team ( select_action = select_action , user = member , user_type = 'member' ) |
def _copy_chunk ( src , dst , length ) :
"Copy length bytes from file src to file dst ." | BUFSIZE = 128 * 1024
while length > 0 :
l = min ( BUFSIZE , length )
buf = src . read ( l )
assert len ( buf ) == l
dst . write ( buf )
length -= l |
def _parse_metadata ( cls , line , meta , parse_remarks = True ) :
"""Parse a metadata line .
The metadata is organized as a ` ` key : value ` ` statement which
is split into the proper key and the proper value .
Arguments :
line ( str ) : the line containing the metadata
parse _ remarks ( bool , optional... | key , value = line . split ( ':' , 1 )
key , value = key . strip ( ) , value . strip ( )
if parse_remarks and "remark" in key : # Checking that the ' : ' is not
if 0 < value . find ( ': ' ) < 20 : # not too far avoid parsing a sentence
try : # containing a ' : ' as a key : value
cls . _parse_met... |
def send ( self ) :
"""Entrypoint to send data to Zabbix
If debug is enabled , items are sent one by one
If debug isn ' t enable , we send items in bulk
Returns a list of results ( 1 if no debug , as many as items in other case )""" | if self . logger : # pragma : no cover
self . logger . info ( "Starting to send %d items" % len ( self . _items_list ) )
try : # Zabbix trapper send a maximum of 250 items in bulk
# We have to respect that , in case of enforcement on zabbix server side
# Special case if debug is enabled : we need to send items one ... |
def add_grammar ( self , customization_id , grammar_name , grammar_file , content_type , allow_overwrite = None , ** kwargs ) :
"""Add a grammar .
Adds a single grammar file to a custom language model . Submit a plain text file in
UTF - 8 format that defines the grammar . Use multiple requests to submit multipl... | if customization_id is None :
raise ValueError ( 'customization_id must be provided' )
if grammar_name is None :
raise ValueError ( 'grammar_name must be provided' )
if grammar_file is None :
raise ValueError ( 'grammar_file must be provided' )
if content_type is None :
raise ValueError ( 'content_type ... |
def _split_lines ( self , original_lines : List [ str ] ) -> List [ str ] :
"""Splits the original lines list according to the current console width and group indentations .
: param original _ lines : The original lines list to split .
: return : A list of the new width - formatted lines .""" | console_width = get_console_width ( )
# We take indent into account only in the inner group lines .
max_line_length = console_width - len ( self . LINE_SEP ) - self . _last_position - ( self . indents_sum if not self . _is_first_line else self . indents_sum - self . _indents [ - 1 ] )
lines = [ ]
for i , line in enumer... |
def structure_transform ( self , original_structure , new_structure , refine_rotation = True ) :
"""Transforms a tensor from one basis for an original structure
into a new basis defined by a new structure .
Args :
original _ structure ( Structure ) : structure corresponding
to the basis of the current tenso... | sm = StructureMatcher ( )
if not sm . fit ( original_structure , new_structure ) :
warnings . warn ( "original and new structures do not match!" )
trans_1 = self . get_ieee_rotation ( original_structure , refine_rotation )
trans_2 = self . get_ieee_rotation ( new_structure , refine_rotation )
# Get the ieee format ... |
def replace_masked_values ( tensor : torch . Tensor , mask : torch . Tensor , replace_with : float ) -> torch . Tensor :
"""Replaces all masked values in ` ` tensor ` ` with ` ` replace _ with ` ` . ` ` mask ` ` must be broadcastable
to the same shape as ` ` tensor ` ` . We require that ` ` tensor . dim ( ) = = m... | if tensor . dim ( ) != mask . dim ( ) :
raise ConfigurationError ( "tensor.dim() (%d) != mask.dim() (%d)" % ( tensor . dim ( ) , mask . dim ( ) ) )
return tensor . masked_fill ( ( 1 - mask ) . byte ( ) , replace_with ) |
def program ( self , * , vertex_shader , fragment_shader = None , geometry_shader = None , tess_control_shader = None , tess_evaluation_shader = None , varyings = ( ) ) -> 'Program' :
'''Create a : py : class : ` Program ` object .
Only linked programs will be returned .
A single shader in the ` shaders ` param... | if type ( varyings ) is str :
varyings = ( varyings , )
varyings = tuple ( varyings )
res = Program . __new__ ( Program )
res . mglo , ls1 , ls2 , ls3 , ls4 , ls5 , res . _subroutines , res . _geom , res . _glo = self . mglo . program ( vertex_shader , fragment_shader , geometry_shader , tess_control_shader , tess_... |
def snapshots_create ( container , name = None , remote_addr = None , cert = None , key = None , verify_cert = True ) :
'''Create a snapshot for a container
container :
The name of the container to get .
name :
The name of the snapshot .
remote _ addr :
An URL to a remote server . The ' cert ' and ' key... | cont = container_get ( container , remote_addr , cert , key , verify_cert , _raw = True )
if not name :
name = datetime . now ( ) . strftime ( '%Y%m%d%H%M%S' )
cont . snapshots . create ( name )
for c in snapshots_all ( container ) . get ( container ) :
if c . get ( 'name' ) == name :
return { 'name' : ... |
def convert_pro_to_hyp ( pro ) :
"""Converts a pro residue to a hydroxypro residue .
All metadata associated with the original pro will be lost i . e . tags .
As a consequence , it is advisable to relabel all atoms in the structure
in order to make them contiguous .
Parameters
pro : ampal . Residue
The ... | with open ( str ( REF_PATH / 'hydroxyproline_ref_1bkv_0_6.pickle' ) , 'rb' ) as inf :
hyp_ref = pickle . load ( inf )
align_nab ( hyp_ref , pro )
to_remove = [ 'CB' , 'CG' , 'CD' ]
for ( label , atom ) in pro . atoms . items ( ) :
if atom . element == 'H' :
to_remove . append ( label )
for label in to_r... |
def prepend ( self , key , val , time = 0 , min_compress_len = 0 ) :
'''Prepend the value to the beginning of the existing key ' s value .
Only stores in memcache if key already exists .
Also see L { append } .
@ return : Nonzero on success .
@ rtype : int''' | return self . _set ( "prepend" , key , val , time , min_compress_len ) |
def groups ( self , user , include = None ) :
"""Retrieve the groups for this user .
: param include : list of objects to sideload . ` Side - loading API Docs
< https : / / developer . zendesk . com / rest _ api / docs / core / side _ loading > ` _ _ .
: param user : User object or id""" | return self . _query_zendesk ( self . endpoint . groups , 'group' , id = user , include = include ) |
def qhashform ( o ) :
'''qhashform ( o ) yields a version of o , if possible , that yields a hash that can be reproduced
across instances . This correctly handles quantities and numpy arrays , among other things .''' | if is_quantity ( o ) :
return ( '__#quant' , qhashform ( mag ( o ) ) , str ( o . u ) )
elif isinstance ( o , np . ndarray ) and np . issubdtype ( o . dtype , np . dtype ( np . number ) . type ) :
return ( '__#ndarray' , o . tobytes ( ) )
elif isinstance ( o , ( set , frozenset ) ) :
return ( '__#set' , tupl... |
def _update_params_on_kvstore_nccl ( param_arrays , grad_arrays , kvstore , param_names ) :
"""Perform update of param _ arrays from grad _ arrays on NCCL kvstore .""" | valid_indices = [ index for index , grad_list in enumerate ( grad_arrays ) if grad_list [ 0 ] is not None ]
valid_grad_arrays = [ grad_arrays [ i ] for i in valid_indices ]
valid_param_arrays = [ param_arrays [ i ] for i in valid_indices ]
valid_param_names = [ param_names [ i ] for i in valid_indices ]
size = len ( va... |
def get_path ( self , name , default = None ) :
"""Retrieves an environment variable as a filesystem path .
Requires the ` pathlib ` _ library if using Python < = 3.4.
Args :
name ( str ) : The case - insensitive , unprefixed variable name .
default : If provided , a default value will be returned
instead... | if name not in self :
if default is not None :
return default
raise EnvironmentError . not_found ( self . _prefix , name )
return pathlib . Path ( self [ name ] ) |
def scaled_euclid_dist ( self , X , X2 ) : # pragma : no cover
"""Returns | ( X - X2T ) / lengthscales | ( L2 - norm ) .""" | warnings . warn ( 'scaled_euclid_dist is deprecated and will be removed ' 'in GPflow version 1.4.0. For stationary kernels, ' 'define K_r(r) instead.' , DeprecationWarning )
r2 = self . scaled_square_dist ( X , X2 )
return self . _clipped_sqrt ( r2 ) |
def network_del_notif ( self , tenant_id , tenant_name , net_id ) :
"""Network delete notification .""" | if not self . fw_init :
return
self . network_delete_notif ( tenant_id , tenant_name , net_id ) |
def getctime ( self , path = None , client_kwargs = None , header = None ) :
"""Return the creation time of path .
Args :
path ( str ) : File path or URL .
client _ kwargs ( dict ) : Client arguments .
header ( dict ) : Object header .
Returns :
float : The number of seconds since the epoch
( see the ... | return self . _getctime_from_header ( self . head ( path , client_kwargs , header ) ) |
def do_child_count ( self , params ) :
"""\x1b [1mNAME \x1b [0m
child _ count - Prints the child count for paths
\x1b [1mSYNOPSIS \x1b [0m
child _ count [ path ] [ depth ]
\x1b [1mOPTIONS \x1b [0m
* path : the path ( default : cwd )
* max _ depth : max recursion limit ( 0 is no limit ) ( default : 1)
... | for child , level in self . _zk . tree ( params . path , params . depth , full_path = True ) :
self . show_output ( "%s: %d" , child , self . _zk . child_count ( child ) ) |
def frontage ( self ) :
"""Length in Feet ( f )""" | if self . length and self . area :
return round ( self . area / self . length ) |
def fix_ar_analyses_inconsistencies ( portal ) :
"""Fixes inconsistencies between analyses and the ARs they belong to when
the AR is in a " cancelled " , " invalidated " or " rejected state""" | def fix_analyses ( request , status ) :
wf_id = "bika_analysis_workflow"
workflow = api . get_tool ( "portal_workflow" ) . getWorkflowById ( wf_id )
review_states = [ 'assigned' , 'unassigned' , 'to_be_verified' ]
query = dict ( portal_type = "Analysis" , getRequestUID = api . get_uid ( request ) , revi... |
def is_full ( self ) :
"""Return whether the activity is full .""" | capacity = self . get_true_capacity ( )
if capacity != - 1 :
num_signed_up = self . eighthsignup_set . count ( )
return num_signed_up >= capacity
return False |
def rank_remove ( self , rank , items , cutoff ) :
"""remove tokens or stems ( specified in items ) based on rank ' s ( df or
tfidf ) value being less than cutoff to remove all words with rank R or
less , specify cutoff = self . xxx _ ranking [ R ] [ 1]""" | def remove ( tokens ) :
return [ t for t in tokens if t not in to_remove ]
if rank == "df" :
to_remove = set ( [ t [ 0 ] for t in self . df_ranking if t [ 1 ] <= cutoff ] )
elif rank == "tfidf" :
to_remove = set ( [ t [ 0 ] for t in self . tfidf_ranking if t [ 1 ] <= cutoff ] )
else :
raise ValueError (... |
def make_full_path ( basedir , outkey , origname ) :
"""Make a full file path by combining tokens
Parameters
basedir : str
The top level output area
outkey : str
The key for the particular instance of the analysis
origname : str
Template for the output file name
Returns
outpath : str
This will b... | return os . path . join ( basedir , outkey , os . path . basename ( origname ) . replace ( '.fits' , '_%s.fits' % outkey ) ) |
def get_ancestor_tag_names ( mention ) :
"""Return the HTML tag of the Mention ' s ancestors .
For example , [ ' html ' , ' body ' , ' p ' ] .
If a candidate is passed in , only the ancestors of its first Mention are returned .
: param mention : The Mention to evaluate
: rtype : list of strings""" | span = _to_span ( mention )
tag_names = [ ]
i = _get_node ( span . sentence )
while i is not None :
tag_names . insert ( 0 , str ( i . tag ) )
i = i . getparent ( )
return tag_names |
def reload_class ( self , verbose = True , reload_module = True ) :
"""special class reloading function
This function is often injected as rrr of classes""" | import utool as ut
verbose = verbose or VERBOSE_CLASS
classname = self . __class__ . __name__
try :
modname = self . __class__ . __module__
if verbose :
print ( '[class] reloading ' + classname + ' from ' + modname )
# - - HACK - -
if hasattr ( self , '_on_reload' ) :
if verbose > 1 :
... |
def _try_coerce_args ( self , values , other ) :
"""Coerce values and other to dtype ' i8 ' . NaN and NaT convert to
the smallest i8 , and will correctly round - trip to NaT if converted
back in _ try _ coerce _ result . values is always ndarray - like , other
may not be
Parameters
values : ndarray - like... | values = values . view ( 'i8' )
if isinstance ( other , bool ) :
raise TypeError
elif is_null_datetimelike ( other ) :
other = tslibs . iNaT
elif isinstance ( other , ( datetime , np . datetime64 , date ) ) :
other = self . _box_func ( other )
if getattr ( other , 'tz' ) is not None :
raise Type... |
def read_csv ( csv_file , ext = '.csv' , format = None , delete_empty_keys = False , fieldnames = [ ] , rowlimit = 100000000 , numbers = False , normalize_names = True , unique_names = True , verbosity = 0 ) :
r"""Read a csv file from a path or file pointer , returning a dict of lists , or list of lists ( according... | if not csv_file :
return
if isinstance ( csv_file , basestring ) : # truncate ` csv _ file ` in case it is a string buffer containing GBs of data
path = csv_file [ : 1025 ]
try : # see http : / / stackoverflow . com / a / 4169762/623735 before trying ' rU '
fpin = open ( path , 'rUb' )
# U =... |
def GetInput ( self ) :
"""Yield client urns .""" | client_list = GetAllClients ( token = self . token )
logging . debug ( "Got %d clients" , len ( client_list ) )
for client_group in collection . Batch ( client_list , self . client_chunksize ) :
for fd in aff4 . FACTORY . MultiOpen ( client_group , mode = "r" , aff4_type = aff4_grr . VFSGRRClient , token = self . t... |
def from_pkcs12 ( cls , key , email , scopes , subject = None , passphrase = PKCS12_PASSPHRASE ) :
"""Alternate constructor intended for using . p12 files .
Args :
key ( dict ) - Parsed JSON with service account credentials .
email ( str ) - Service account email .
scopes ( Union [ str , collections . Itera... | key = OpenSSL . crypto . load_pkcs12 ( key , passphrase ) . get_privatekey ( )
return cls ( key = key , email = email , scopes = scopes , subject = subject ) |
def _pidExists ( pid ) :
"""This will return True if the process associated with pid is still running on the machine .
This is based on stackoverflow question 568271.
: param int pid : ID of the process to check for
: return : True / False
: rtype : bool""" | assert pid > 0
try :
os . kill ( pid , 0 )
except OSError as err :
if err . errno == errno . ESRCH : # ESRCH = = No such process
return False
else :
raise
else :
return True |
def disk_usage ( path , human = False ) :
"""disk usage in bytes or human readable format ( e . g . ' 2,1GB ' )""" | command = [ 'du' , '-s' , path ]
if human :
command . append ( '-h' )
return subprocess . check_output ( command ) . split ( ) [ 0 ] . decode ( 'utf-8' ) |
def _load_output_data_port_models ( self ) :
"""Reloads the output data port models directly from the the state""" | if not self . state_copy_initialized :
return
self . output_data_ports = [ ]
for output_data_port_m in self . state_copy . output_data_ports :
new_op_m = deepcopy ( output_data_port_m )
new_op_m . parent = self
new_op_m . data_port = output_data_port_m . data_port
self . output_data_ports . append (... |
def imwrite ( file , data = None , shape = None , dtype = None , ** kwargs ) :
"""Write numpy array to TIFF file .
Refer to the TiffWriter class and its asarray function for documentation .
A BigTIFF file is created if the data size in bytes is larger than 4 GB
minus 32 MB ( for metadata ) , and ' bigtiff ' i... | tifargs = parse_kwargs ( kwargs , 'append' , 'bigtiff' , 'byteorder' , 'imagej' )
if data is None :
dtype = numpy . dtype ( dtype )
size = product ( shape ) * dtype . itemsize
byteorder = dtype . byteorder
else :
try :
size = data . nbytes
byteorder = data . dtype . byteorder
except ... |
def _get_all_set_properties ( self ) :
"""Collect names of set properties .
Returns :
set : Set containing names of all properties , which are set to non - None value .""" | return set ( property_name for property_name in worker_mapping ( ) . keys ( ) if getattr ( self , property_name ) is not None ) |
def optionsFromEnvironment ( defaults = None ) :
"""Fetch root URL and credentials from the standard TASKCLUSTER _ . . .
environment variables and return them in a format suitable for passing to a
client constructor .""" | options = defaults or { }
credentials = options . get ( 'credentials' , { } )
rootUrl = os . environ . get ( 'TASKCLUSTER_ROOT_URL' )
if rootUrl :
options [ 'rootUrl' ] = rootUrl
clientId = os . environ . get ( 'TASKCLUSTER_CLIENT_ID' )
if clientId :
credentials [ 'clientId' ] = clientId
accessToken = os . envi... |
def _smcra_to_str ( self , smcra , temp_dir = '/tmp/' ) :
"""WHATIF ' s input are PDB format files .
Converts a SMCRA object to a PDB formatted string .""" | temp_path = tempfile . mktemp ( '.pdb' , dir = temp_dir )
io = PDBIO ( )
io . set_structure ( smcra )
io . save ( temp_path )
f = open ( temp_path , 'r' )
string = f . read ( )
f . close ( )
os . remove ( temp_path )
return string |
def webfont_cookie ( request ) :
'''Adds WEBFONT Flag to the context''' | if hasattr ( request , 'COOKIES' ) and request . COOKIES . get ( WEBFONT_COOKIE_NAME , None ) :
return { WEBFONT_COOKIE_NAME . upper ( ) : True }
return { WEBFONT_COOKIE_NAME . upper ( ) : False } |
def _getter ( self ) :
"""Return a function object suitable for the " get " side of the attribute
property descriptor .""" | def get_attr_value ( obj ) :
attr_str_value = obj . get ( self . _clark_name )
if attr_str_value is None :
return self . _default
return self . _simple_type . from_xml ( attr_str_value )
get_attr_value . __doc__ = self . _docstring
return get_attr_value |
def _get_non_tempy_contents ( self ) :
"""Returns rendered Contents and non - DOMElement stuff inside this Tag .""" | for thing in filter ( lambda x : not issubclass ( x . __class__ , DOMElement ) , self . childs ) :
yield thing |
def pyeapi_nxos_api_args ( ** prev_kwargs ) :
'''. . versionadded : : 2019.2.0
Return the key - value arguments used for the authentication arguments for the
: mod : ` pyeapi execution module < salt . module . arista _ pyeapi > ` .
CLI Example :
. . code - block : : bash
salt ' * ' napalm . pyeapi _ nxos ... | kwargs = { }
napalm_opts = salt . utils . napalm . get_device_opts ( __opts__ , salt_obj = __salt__ )
optional_args = napalm_opts [ 'OPTIONAL_ARGS' ]
kwargs [ 'host' ] = napalm_opts [ 'HOSTNAME' ]
kwargs [ 'username' ] = napalm_opts [ 'USERNAME' ]
kwargs [ 'password' ] = napalm_opts [ 'PASSWORD' ]
kwargs [ 'timeout' ] ... |
def get_sponsored_special_coverage_query ( only_recent = False ) :
"""Reference to all SpecialCovearge queries .
: param only _ recent : references RECENT _ SPONSORED _ OFFSET _ HOURS from django settings .
Used to return sponsored content within a given configuration of hours .
: returns : Djes . LazySearch ... | special_coverages = get_sponsored_special_coverages ( )
es_query = SearchParty ( special_coverages ) . search ( )
if only_recent :
offset = getattr ( settings , "RECENT_SPONSORED_OFFSET_HOURS" , 0 )
es_query = es_query . filter ( Published ( after = timezone . now ( ) - timezone . timedelta ( hours = offset ) )... |
def telnet_login ( self , pri_prompt_terminator = r"#\s*$" , alt_prompt_terminator = r">\s*$" , username_pattern = r"(?:user:|username|login|user name)" , pwd_pattern = r"assword" , delay_factor = 1 , max_loops = 20 , ) :
"""Telnet login . Can be username / password or just password .
: param pri _ prompt _ termi... | delay_factor = self . select_delay_factor ( delay_factor )
time . sleep ( 1 * delay_factor )
output = ""
return_msg = ""
i = 1
while i <= max_loops :
try :
output = self . read_channel ( )
return_msg += output
# Search for username pattern / send username
if re . search ( username_pa... |
def __is_surrogate_escaped ( self , text ) :
"""Checks if surrogate is escaped""" | try :
text . encode ( 'utf-8' )
except UnicodeEncodeError as e :
if e . reason == 'surrogates not allowed' :
return True
return False |
def unassigned ( data , as_json = False ) :
"""https : / / sendgrid . com / docs / API _ Reference / api _ v3 . html # ip - addresses
The / ips rest endpoint returns information about the IP addresses
and the usernames assigned to an IP
unassigned returns a listing of the IP addresses that are allocated
but... | no_subusers = set ( )
if not isinstance ( data , list ) :
return format_ret ( no_subusers , as_json = as_json )
for current in data :
num_subusers = len ( current [ "subusers" ] )
if num_subusers == 0 :
current_ip = current [ "ip" ]
no_subusers . add ( current_ip )
ret_val = format_ret ( no_... |
def fit_circular_gaussian ( samples , high = np . pi , low = 0 ) :
"""Compute the circular mean for samples in a range
Args :
samples ( ndarray ) : a one or two dimensional array . If one dimensional we calculate the fit using all
values . If two dimensional , we fit the Gaussian for every set of samples over... | cl_func = SimpleCLFunction . from_string ( '''
void compute(global mot_float_type* samples,
global mot_float_type* means,
global mot_float_type* stds,
int nmr_samples,
int low,
int high){
... |
def _copy ( source , destination , ignore = None ) :
"""Effective copy""" | if os . path . isdir ( source ) :
shutil . copytree ( source , destination , symlinks = True , ignore = ignore )
else :
shutil . copy ( source , destination )
shutil . copystat ( source , destination ) |
def _call ( self , command , ignore_errors = None ) :
"""Call remote command with logging .""" | if ignore_errors is None :
ignore_errors = [ ]
command = self . _get_command ( command )
logger . debug ( "Cmd %s" % command )
null = open ( '/dev/null' , 'w' )
retcode = subprocess . call ( command , stdout = null , stderr = null )
null . close ( )
if retcode in ignore_errors :
logger . debug ( "<-- Cmd %s ret... |
def is_trusted_subject ( request ) :
"""Determine if calling subject is fully trusted .""" | logging . debug ( 'Active subjects: {}' . format ( ', ' . join ( request . all_subjects_set ) ) )
logging . debug ( 'Trusted subjects: {}' . format ( ', ' . join ( get_trusted_subjects ( ) ) ) )
return not request . all_subjects_set . isdisjoint ( get_trusted_subjects ( ) ) |
def archive ( self ) :
"""Archives the resource .""" | self . _client . _put ( "{0}/archived" . format ( self . __class__ . base_url ( self . sys [ 'space' ] . id , self . sys [ 'id' ] , environment_id = self . _environment_id ) , ) , { } , headers = self . _update_headers ( ) )
return self . reload ( ) |
def fetch ( self , link , into = None ) :
"""Fetch the binary content associated with the link and write to a file .
: param link : The : class : ` Link ` to fetch .
: keyword into : If specified , write into the directory ` ` into ` ` . If ` ` None ` ` , creates a new
temporary directory that persists for th... | target = os . path . join ( into or safe_mkdtemp ( ) , link . filename )
if os . path . exists ( target ) : # Assume that if the local file already exists , it is safe to use .
return target
with TRACER . timed ( 'Fetching %s' % link . url , V = 2 ) :
target_tmp = '%s.%s' % ( target , uuid . uuid4 ( ) )
wit... |
def get_last_response_xml ( self , pretty_print_if_possible = False ) :
"""Retrieves the raw XML ( decrypted ) of the last SAML response ,
or the last Logout Response generated or processed
: returns : SAML response XML
: rtype : string | None""" | response = None
if self . __last_response is not None :
if isinstance ( self . __last_response , basestring ) :
response = self . __last_response
else :
response = tostring ( self . __last_response , pretty_print = pretty_print_if_possible )
return response |
def output_forecasts_csv ( self , forecasts , mode , csv_path , run_date_format = "%Y%m%d-%H%M" ) :
"""Output hail forecast values to csv files by run date and ensemble member .
Args :
forecasts :
mode :
csv _ path :
Returns :""" | merged_forecasts = pd . merge ( forecasts [ "condition" ] , forecasts [ "dist" ] , on = [ "Step_ID" , "Track_ID" , "Ensemble_Member" , "Forecast_Hour" ] )
all_members = self . data [ mode ] [ "combo" ] [ "Ensemble_Member" ]
members = np . unique ( all_members )
all_run_dates = pd . DatetimeIndex ( self . data [ mode ] ... |
def _setup_time ( self , basemap ) :
"""generates CartoCSS for time - based maps ( torque )""" | # validate time column information
if self . geom_type != 'point' :
raise ValueError ( 'Cannot do time-based maps with data in ' '`{query}` since this table does not contain ' 'point geometries' . format ( query = self . orig_query ) )
elif self . style_cols [ self . time [ 'column' ] ] not in ( 'number' , 'date' ,... |
def _bool_method_SERIES ( cls , op , special ) :
"""Wrapper function for Series arithmetic operations , to avoid
code duplication .""" | op_name = _get_op_name ( op , special )
def na_op ( x , y ) :
try :
result = op ( x , y )
except TypeError :
assert not isinstance ( y , ( list , ABCSeries , ABCIndexClass ) )
if isinstance ( y , np . ndarray ) : # bool - bool dtype operations should be OK , should not get here
... |
def complete_filename ( text ) :
'''complete a filename''' | # ensure directories have trailing slashes :
list = glob . glob ( text + '*' )
for idx , val in enumerate ( list ) :
if os . path . isdir ( val ) :
list [ idx ] = ( val + os . path . sep )
return list |
def get_long ( ) :
"""Generates a random long . The length of said long varies by platform .""" | # The C long type to populate .
pbRandomData = c_ulong ( )
# Determine the byte size of this machine ' s long type .
size_of_long = wintypes . DWORD ( sizeof ( pbRandomData ) )
# Used to keep track of status . 1 = success , 0 = error .
ok = c_int ( )
# Provider ?
hProv = c_ulong ( )
ok = windll . Advapi32 . CryptAcquir... |
def remove_params ( self , * args ) :
"""Remove [ possibly many ] parameters from the Assembly .
E . g . ,
remove _ params ( ' color ' , ' visibility ' )""" | for a in args :
self . _orig_kwargs . pop ( a )
self . kwargs = self . _orig_kwargs . copy ( ) |
def log_before ( attr , level = logging . DEBUG ) :
'''Decorator to log attribute ' s value ( s ) before function call .
Implementation allows usage only for methods belonging to class . The class
instance needs to have a : attr : ` logger ` that is derived from
: py : class : ` ~ creamas . logging . ObjectLo... | def deco ( func ) :
@ wraps ( func )
def wrapper ( * args , ** kwargs ) :
logger = getattr ( args [ 0 ] , 'logger' , None )
if logger is not None :
logger . log_attr ( level , attr )
return func ( * args , ** kwargs )
return wrapper
return deco |
def set_current_canvas ( canvas ) :
"""Make a canvas active . Used primarily by the canvas itself .""" | # Notify glir
canvas . context . _do_CURRENT_command = True
# Try to be quick
if canvasses and canvasses [ - 1 ] ( ) is canvas :
return
# Make this the current
cc = [ c ( ) for c in canvasses if c ( ) is not None ]
while canvas in cc :
cc . remove ( canvas )
cc . append ( canvas )
canvasses [ : ] = [ weakref . ... |
def main ( pargs ) :
"""This should only be used for testing . The primary mode of operation is
as an imported library .""" | input_file = sys . argv [ 1 ]
fp = ParseFileLineByLine ( input_file )
for i in fp :
print ( i ) |
def memoize ( Class , * args , ** kwargs ) :
'''Memoize / record a function inside this vlermv . : :
@ Vlermv . cache ( ' ~ / . http ' )
def get ( url ) :
return requests . get ( url , auth = ( ' username ' , ' password ' ) )
The args and kwargs get passed to the Vlermv with some slight changes .
Here are... | def decorator ( func ) :
if len ( args ) == 0 :
if hasattr ( func , '__name__' ) :
_args = ( func . __name__ , )
else :
raise ValueError ( 'You must specify the location to store the vlermv.' )
else :
_args = args
v = Class ( * _args , ** kwargs )
v . func... |
def assign_proficiency_to_objective_bank ( self , proficiency_id , objective_bank_id ) :
"""Adds an existing ` ` Proficiency ` ` to a ` ` ObjectiveBank ` ` .
arg : proficiency _ id ( osid . id . Id ) : the ` ` Id ` ` of the
` ` Proficiency ` `
arg : objective _ bank _ id ( osid . id . Id ) : the ` ` Id ` ` of... | # Implemented from template for
# osid . resource . ResourceBinAssignmentSession . assign _ resource _ to _ bin
mgr = self . _get_provider_manager ( 'LEARNING' , local = True )
lookup_session = mgr . get_objective_bank_lookup_session ( proxy = self . _proxy )
lookup_session . get_objective_bank ( objective_bank_id )
# ... |
def is_in_path ( program ) :
'''Check if a program is in the system ` ` PATH ` ` .
Checks if a given program is in the user ' s ` ` PATH ` ` or not .
Args :
program ( str ) : The program to try to find in ` ` PATH ` ` .
Returns :
bool : Is the program in ` ` PATH ` ` ?''' | if sys . version_info . major == 2 :
path = os . getenv ( 'PATH' )
if os . name == 'nt' :
path = path . split ( ';' )
else :
path = path . split ( ':' )
else :
path = os . get_exec_path ( )
for i in path :
if os . path . isdir ( i ) :
if program in os . listdir ( i ) :
... |
def cmd_dns_lookup_reverse ( ip_address , verbose ) :
"""Perform a reverse lookup of a given IP address .
Example :
$ $ habu . dns . lookup . reverse 8.8.8.8
" hostname " : " google - public - dns - a . google . com " """ | if verbose :
logging . basicConfig ( level = logging . INFO , format = '%(message)s' )
print ( "Looking up %s..." % ip_address , file = sys . stderr )
answer = lookup_reverse ( ip_address )
if answer :
print ( json . dumps ( answer , indent = 4 ) )
else :
print ( "[X] %s is not valid IPv4/IPV6 address" ... |
def _linux_cpudata ( ) :
'''Return some CPU information for Linux minions''' | # Provides :
# num _ cpus
# cpu _ model
# cpu _ flags
grains = { }
cpuinfo = '/proc/cpuinfo'
# Parse over the cpuinfo file
if os . path . isfile ( cpuinfo ) :
with salt . utils . files . fopen ( cpuinfo , 'r' ) as _fp :
grains [ 'num_cpus' ] = 0
for line in _fp :
comps = line . split ( '... |
def save_data ( self , trigger_id , ** data ) :
"""let ' s save the data
: param trigger _ id : trigger ID from which to save data
: param data : the data to check to be used and save
: type trigger _ id : int
: type data : dict
: return : the status of the save statement
: rtype : boolean""" | title , content = super ( ServiceMastodon , self ) . save_data ( trigger_id , ** data )
# check if we have a ' good ' title
if self . title_or_content ( title ) :
content = str ( "{title} {link}" ) . format ( title = title , link = data . get ( 'link' ) )
content += get_tags ( Mastodon , trigger_id )
# if not t... |
def restore_default_configuration ( ) :
"""Restores the sys . stdout and the sys . stderr buffer streams to their default
values without regard to what step has currently overridden their values .
This is useful during cleanup outside of the running execution block""" | def restore ( target , default_value ) :
if target == default_value :
return default_value
if not isinstance ( target , RedirectBuffer ) :
return target
try :
target . active = False
target . close ( )
except Exception :
pass
return default_value
sys . stdout ... |
def get ( self , path , payload = None , headers = None ) :
"""HTTP GET operation .
: param path : URI Path
: param payload : HTTP Body
: param headers : HTTP Headers
: raises ApiError : Raises if the remote server encountered an error .
: raises ApiConnectionError : Raises if there was a connectivity iss... | return self . _request ( 'get' , path , payload , headers ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.