signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def print_archive ( self , format = True ) :
"""Prints out archived WCS keywords .""" | if len ( list ( self . orig_wcs . keys ( ) ) ) > 0 :
block = 'Original WCS keywords for ' + self . rootname + '\n'
block += ' backed up on ' + repr ( self . orig_wcs [ 'WCSCDATE' ] ) + '\n'
if not format :
for key in self . wcstrans . keys ( ) :
block += key . upper ( ) + " = " + repr... |
def print_dataset_summary ( self ) :
"""Prints information about the the BIDS data and the files currently selected .""" | print ( '--- DATASET INFORMATION ---' )
print ( '--- Subjects ---' )
if self . raw_data_exists :
if self . BIDS . get_subjects ( ) :
print ( 'Number of subjects (in dataset): ' + str ( len ( self . BIDS . get_subjects ( ) ) ) )
print ( 'Subjects (in dataset): ' + ', ' . join ( self . BIDS . get_subj... |
def Parse ( self , stat , file_object , knowledge_base ) :
"""Parse the History file .""" | _ = knowledge_base
# TODO ( user ) : Convert this to use the far more intelligent plaso parser .
chrome = ChromeParser ( file_object )
for timestamp , entry_type , url , data1 , _ , _ in chrome . Parse ( ) :
if entry_type == "CHROME_DOWNLOAD" :
yield rdf_webhistory . BrowserHistoryItem ( url = url , domain ... |
def infer_typing_attr ( node , context = None ) :
"""Infer a typing . X [ . . . ] subscript""" | try :
value = next ( node . value . infer ( ) )
except InferenceError as exc :
raise UseInferenceDefault from exc
if not value . qname ( ) . startswith ( "typing." ) :
raise UseInferenceDefault
node = extract_node ( TYPING_TYPE_TEMPLATE . format ( value . qname ( ) . split ( "." ) [ - 1 ] ) )
return node . ... |
def find_view_function ( module_name , function_name , fallback_app = None , fallback_template = None , verify_decorator = True ) :
'''Finds a view function , class - based view , or template view .
Raises ViewDoesNotExist if not found .''' | dmp = apps . get_app_config ( 'django_mako_plus' )
# I ' m first calling find _ spec first here beacuse I don ' t want import _ module in
# a try / except - - there are lots of reasons that importing can fail , and I just want to
# know whether the file actually exists . find _ spec raises AttributeError if not found .... |
def _joliet_name_and_parent_from_path ( self , joliet_path ) : # type : ( bytes ) - > Tuple [ bytes , dr . DirectoryRecord ]
'''An internal method to find the parent directory record and name given a
Joliet path . If the parent is found , return a tuple containing the
basename of the path and the parent directo... | splitpath = utils . split_path ( joliet_path )
name = splitpath . pop ( )
if len ( name ) > 64 :
raise pycdlibexception . PyCdlibInvalidInput ( 'Joliet names can be a maximum of 64 characters' )
parent = self . _find_joliet_record ( b'/' + b'/' . join ( splitpath ) )
return ( name . decode ( 'utf-8' ) . encode ( 'u... |
def get_data ( self ) :
"Return one SNMP response list for all status OIDs , and one list for all metric OIDs ." | alarm_oids = [ netsnmp . Varbind ( status_mib [ alarm_id ] [ 'oid' ] ) for alarm_id in self . models [ self . modem_type ] [ 'alarms' ] ]
metric_oids = [ netsnmp . Varbind ( metric_mib [ metric_id ] [ 'oid' ] ) for metric_id in self . models [ self . modem_type ] [ 'metrics' ] ]
response = self . snmp_session . get ( n... |
async def execute_command ( self , * args : bytes , timeout : NumType = None ) -> SMTPResponse :
"""Sends an SMTP command along with any args to the server , and returns
a response .""" | command = b" " . join ( args ) + b"\r\n"
await self . write_and_drain ( command , timeout = timeout )
response = await self . read_response ( timeout = timeout )
return response |
def http_request ( self , path , method = 'GET' , content = None , content_type = "application/json" , response_format = FMT_JSON ) :
"""Perform an administrative HTTP request . This request is sent out to
the administrative API interface ( i . e . the " Management / REST API " )
of the cluster .
Note that th... | imeth = None
if not method in METHMAP :
raise E . ArgumentError . pyexc ( "Unknown HTTP Method" , method )
imeth = METHMAP [ method ]
return self . _http_request ( type = LCB . LCB_HTTP_TYPE_MANAGEMENT , path = path , method = imeth , content_type = content_type , post_data = content , response_format = response_fo... |
def get ( self , bucket = None , versions = missing , uploads = missing ) :
"""Get list of objects in the bucket .
: param bucket : A : class : ` invenio _ files _ rest . models . Bucket ` instance .
: returns : The Flask response .""" | if uploads is not missing :
return self . multipart_listuploads ( bucket )
else :
return self . listobjects ( bucket , versions ) |
def get_order_columns_list ( self , list_columns = None ) :
"""Returns the columns that can be ordered
: param list _ columns : optional list of columns name , if provided will
use this list only .""" | ret_lst = list ( )
list_columns = list_columns or self . get_columns_list ( )
for col_name in list_columns :
if hasattr ( self . obj , col_name ) :
if not hasattr ( getattr ( self . obj , col_name ) , "__call__" ) :
ret_lst . append ( col_name )
else :
ret_lst . append ( col_name )
r... |
def write ( self ) :
"""attempt to get a chunk of data to write to our child process ' s
stdin , then write it . the return value answers the questions " are we
done writing forever ? " """ | # get _ chunk may sometimes return bytes , and sometimes return strings
# because of the nature of the different types of STDIN objects we
# support
try :
chunk = self . get_chunk ( )
if chunk is None :
raise DoneReadingForever
except DoneReadingForever :
self . log . debug ( "done reading" )
if... |
def _input_as_lines ( self , data ) :
"""Write sequence of lines to temp file , return filename
data : a sequence to be written to a file , each element of the
sequence will compose a line in the file
* Note : ' \n ' will be stripped off the end of each sequence
element before writing to a file in order to ... | self . _input_filename = self . getTmpFilename ( self . WorkingDir , suffix = '.fasta' )
with open ( self . _input_filename , 'w' ) as f : # Use lazy iteration instead of list comprehension to
# prevent reading entire file into memory
for line in data :
f . write ( str ( line ) . strip ( '\n' ) )
f ... |
def convert ( input , width = 132 , output = None , keep = False ) :
"""Input ASCII trailer file " input " will be read .
The contents will then be written out to a FITS file in the same format
as used by ' stwfits ' from IRAF .
Parameters
input : str
Filename of input ASCII trailer file
width : int
N... | # open input trailer file
trl = open ( input )
# process all lines
lines = np . array ( [ i for text in trl . readlines ( ) for i in textwrap . wrap ( text , width = width ) ] )
# close ASCII trailer file now that we have processed all the lines
trl . close ( )
if output is None : # create fits file
rootname , suff... |
def _augment ( graph , capacity , flow , val , u , target , visit ) :
"""Find an augmenting path from u to target with value at most val""" | visit [ u ] = True
if u == target :
return val
for v in graph [ u ] :
cuv = capacity [ u ] [ v ]
if not visit [ v ] and cuv > flow [ u ] [ v ] : # reachable arc
res = min ( val , cuv - flow [ u ] [ v ] )
delta = _augment ( graph , capacity , flow , res , v , target , visit )
if delta... |
def _return_result ( self , done ) :
"""Called set the returned future ' s state that of the future
we yielded , and set the current future for the iterator .""" | chain_future ( done , self . _running_future )
self . current_future = done
self . current_index = self . _unfinished . pop ( done ) |
def watch ( self , key , criteria , callback ) :
"""Registers a new watch under [ key ] ( which can be used with ` unwatch ( ) `
to remove the watch ) that filters messages using [ criteria ] ( may be a
predicate or a ' criteria dict ' [ see the README for more info there ] ) .
Matching messages are passed to... | if hasattr ( criteria , '__call__' ) :
pred = criteria
else :
pred = lambda incoming : _match_criteria ( criteria , incoming )
with self . _watches_lock :
self . _watches [ key ] = ( pred , callback ) |
def stopDtmfAcknowledge ( ) :
"""STOP DTMF ACKNOWLEDGE Section 9.3.30""" | a = TpPd ( pd = 0x3 )
b = MessageType ( mesType = 0x32 )
# 00110010
packet = a / b
return packet |
def required_for_output ( inputs , outputs , connections ) :
"""Collect the nodes whose state is required to compute the final network output ( s ) .
: param inputs : list of the input identifiers
: param outputs : list of the output node identifiers
: param connections : list of ( input , output ) connection... | required = set ( outputs )
s = set ( outputs )
while 1 : # Find nodes not in S whose output is consumed by a node in s .
t = set ( a for ( a , b ) in connections if b in s and a not in s )
if not t :
break
layer_nodes = set ( x for x in t if x not in inputs )
if not layer_nodes :
break
... |
def VictoryEnum ( ctx ) :
"""Victory Type Enumeration .""" | return Enum ( ctx , standard = 0 , conquest = 1 , exploration = 2 , ruins = 3 , artifacts = 4 , discoveries = 5 , gold = 6 , time_limit = 7 , score = 8 , standard2 = 9 , regicide = 10 , last_man = 11 ) |
def connect ( self ) :
"""Connect to host and get meta information .""" | self . urlobj = getImageObject ( self . url , self . referrer , self . session )
content_type = unquote ( self . urlobj . headers . get ( 'content-type' , 'application/octet-stream' ) )
content_type = content_type . split ( ';' , 1 ) [ 0 ]
if '/' in content_type :
maintype , subtype = content_type . split ( '/' , 1... |
def _seconds_to_days ( cls , val , ** kwargs ) :
'''converts a number of seconds to days''' | zero_value = kwargs . get ( 'zero_value' , 0 )
if val is not None :
if val == zero_value :
return 0
return val / 86400
else :
return 'Not Defined' |
def load_symbols_elf ( filename ) :
"""Load the symbol tables contained in the file""" | f = open ( filename , 'rb' )
elffile = ELFFile ( f )
symbols = [ ]
for section in elffile . iter_sections ( ) :
if not isinstance ( section , SymbolTableSection ) :
continue
if section [ 'sh_entsize' ] == 0 :
logger . warn ( "Symbol table {} has a sh_entsize of zero." . format ( section . name )... |
def _hasViewChangeQuorum ( self ) : # This method should just be present for master instance .
"""Checks whether n - f nodes completed view change and whether one
of them is the next primary""" | num_of_ready_nodes = len ( self . _view_change_done )
diff = self . quorum - num_of_ready_nodes
if diff > 0 :
logger . info ( '{} needs {} ViewChangeDone messages' . format ( self , diff ) )
return False
logger . info ( "{} got view change quorum ({} >= {})" . format ( self . name , num_of_ready_nodes , self . ... |
def _volume ( shape ) :
"""Return the volume of a shape .""" | prod = 1
for start , stop in shape :
prod *= stop - start
return prod |
def IsTensorFlowEventsFile ( path ) :
"""Check the path name to see if it is probably a TF Events file .
Args :
path : A file path to check if it is an event file .
Raises :
ValueError : If the path is an empty string .
Returns :
If path is formatted like a TensorFlowEventsFile .""" | if not path :
raise ValueError ( 'Path must be a nonempty string' )
return 'tfevents' in tf . compat . as_str_any ( os . path . basename ( path ) ) |
def dprintx ( passeditem , special = False ) :
"""Print Text if DEBUGALL set , optionally with PrettyPrint .
Args :
passeditem ( str ) : item to print
special ( bool ) : determines if item prints with PrettyPrint
or regular print .""" | if DEBUGALL :
if special :
from pprint import pprint
pprint ( passeditem )
else :
print ( "%s%s%s" % ( C_TI , passeditem , C_NORM ) ) |
def to_bytes ( x , blocksize = 0 ) :
"""Converts input to a byte string .
Typically used in PyCrypto as an argument ( e . g . , key , iv )
: param x : string ( does nothing ) , bytearray , array with numbers
: return :""" | if isinstance ( x , bytearray ) :
return left_zero_pad ( bytes ( x ) , blocksize )
elif isinstance ( x , basestring ) :
return left_zero_pad ( x , blocksize )
elif isinstance ( x , ( list , tuple ) ) :
return left_zero_pad ( bytes ( bytearray ( x ) ) , blocksize )
elif isinstance ( x , ( long , int ) ) :
... |
def windings_aligned ( triangles , normals_compare ) :
"""Given a list of triangles and a list of normals determine if the
two are aligned
Parameters
triangles : ( n , 3 , 3 ) float
Vertex locations in space
normals _ compare : ( n , 3 ) float
List of normals to compare
Returns
aligned : ( n , ) boo... | triangles = np . asanyarray ( triangles , dtype = np . float64 )
if not util . is_shape ( triangles , ( - 1 , 3 , 3 ) ) :
raise ValueError ( 'Triangles must be (n,3,3)!' )
calculated , valid = normals ( triangles )
difference = util . diagonal_dot ( calculated , normals_compare [ valid ] )
aligned = np . zeros ( le... |
def get_schema_from_list ( table_name , frum ) :
"""SCAN THE LIST FOR COLUMN TYPES""" | columns = UniqueIndex ( keys = ( "name" , ) )
_get_schema_from_list ( frum , "." , parent = "." , nested_path = ROOT_PATH , columns = columns )
return Schema ( table_name = table_name , columns = list ( columns ) ) |
def remove ( cls , resource_id , parent_id = None , grandparent_id = None , wait = True , timeout = None ) :
"""Delete the required resource .""" | raise exception . NotSupported ( feature = "DELETE" , context = "VirtualSwitchManager" ) |
def itervalues ( self , key = _absent ) :
"""Parity with dict . itervalues ( ) except the optional < key > parameter has
been added . If < key > is provided , only values from items with the
provided key are iterated over . KeyError is raised if < key > is provided
and not in the dictionary .
Example :
om... | if key is not _absent :
if key in self :
return iter ( [ node . value for node in self . _map [ key ] ] )
raise KeyError ( key )
return iter ( [ nodes [ 0 ] . value for nodes in six . itervalues ( self . _map ) ] ) |
def sort_tuples ( tuples_list , order_list ) :
"""This function sorts the tuples based on an order defined by the list ' order _ list ' .
Examples :
> > > sort _ tuples ( [ ( 4 , 3 ) , ( 1 , 9 ) , ( 2 , 10 ) , ( 3 , 2 ) ] , [ 1 , 4 , 2 , 3 ] )
[ ( 1 , 9 ) , ( 4 , 3 ) , ( 2 , 10 ) , ( 3 , 2 ) ]
> > > sort _ ... | tuples_dict = dict ( tuples_list )
sorted_tuples = [ ( key , tuples_dict [ key ] ) for key in order_list ]
return sorted_tuples |
def inputindex ( input ) :
"""Handler for showing keyboard or mouse page with day and total links .""" | stats = { }
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
tables = ( "moves" , "clicks" , "scrolls" ) if "mouse" == input else ( "keys" , "combos" )
for table in tables :
stats [ table ] = db . fetchone ( "counts" , countminmax , type = table )
stats [ table ] [ "days" ] = db . fetch ... |
def run ( command , ** kwargs ) :
"""Excecutes the given command while transfering control , till the execution is complete .""" | print command
p = Popen ( shlex . split ( command ) , ** kwargs )
p . wait ( )
return p . returncode |
def bake ( self ) :
"""Find absolute times for all keys .
Absolute time is stored in the KeyFrame dictionary as the variable
_ _ abs _ time _ _ .""" | self . unbake ( )
for key in self . dct :
self . get_absolute_time ( key )
self . is_baked = True |
def _formatVals ( self , val_list ) :
"""Formats value list from Munin Graph and returns multi - line value
entries for the plugin fetch cycle .
@ param val _ list : List of name - value pairs .
@ return : Multi - line text .""" | vals = [ ]
for ( name , val ) in val_list :
if val is not None :
if isinstance ( val , float ) :
vals . append ( "%s.value %f" % ( name , val ) )
else :
vals . append ( "%s.value %s" % ( name , val ) )
else :
vals . append ( "%s.value U" % ( name , ) )
return "\n"... |
def make_interactive_tree ( matrix = None , labels = None ) :
'''make interactive tree will return complete html for an interactive tree
: param title : a title for the plot , if not defined , will be left out .''' | from scipy . cluster . hierarchy import ( dendrogram , linkage , to_tree )
d3 = None
from scipy . cluster . hierarchy import cophenet
from scipy . spatial . distance import pdist
if isinstance ( matrix , pandas . DataFrame ) :
Z = linkage ( matrix , 'ward' )
# clusters
T = to_tree ( Z , rd = False )
if ... |
def read_dict_from_properties ( desired_type : Type [ dict ] , file_object : TextIOBase , logger : Logger , conversion_finder : ConversionFinder , ** kwargs ) -> Dict [ str , Any ] :
"""Helper method to read a dictionary from a . properties file ( java - style ) using jprops .
Since jprops does not provide automa... | # right now jprops relies on a byte stream . So we convert back our nicely decoded Text stream to a unicode
# byte stream ! ( urgh )
class Unicoder :
def __init__ ( self , file_object ) :
self . f = file_object
def __iter__ ( self ) :
return self
def __next__ ( self ) :
line = self .... |
def _compile_device_specific_prims ( self , debug = False , stages = None , stagenames = None ) :
"""Using the data stored in the CommandQueue , Extract and align compatible sequences of Primitives and compile / optimize the Primitives down into a stream of Level 2 device agnostic primitives .
BACKGROUND :
Devi... | # # # # # # GROUPING BY EXEC BOUNDARIES ! # # # # #
fences = [ ]
fence = [ self [ 0 ] ]
for p in self [ 1 : ] :
if type ( fence [ 0 ] ) . _layer == type ( p ) . _layer and isinstance ( fence [ 0 ] , DeviceTarget ) == isinstance ( p , DeviceTarget ) :
fence . append ( p )
else :
fences . append (... |
def v1_tag_list ( tags , tag = '' ) :
'''List all direct children tags of the given parent .
If no parent is specified , then list all top - level tags .
The JSON returned for ` ` / dossier / v1 / tags / list / foo / bar ` `
might look like this :
. . code - block : : python
' children ' : [
{ ' name ' ... | tag = tag . decode ( 'utf-8' ) . strip ( )
return { 'children' : tags . list ( tag ) } |
def remove_group_by_id ( self , group_id , recursive = True ) :
"""Remove the group matching the given group _ id . If recursive is True , all descendants of this group are also removed .
: param group _ id : The group id to be removed
: param recursive : All descendants should be removed as well
: return : T... | group = self . objects [ group_id ]
if group is None :
return False
result = True
# iterate over the children and determine if they are file / group and call the right method .
for subgroup_id in list ( group . children ) :
subgroup = self . objects [ subgroup_id ]
if subgroup is None :
return False... |
def add_from_xmlnode ( self , element ) :
"""Load ui definition from xml . etree . Element node .""" | if self . tree is None :
root = ET . Element ( 'interface' )
root . append ( element )
self . tree = tree = ET . ElementTree ( root )
self . root = tree . getroot ( )
self . objects = { }
# ET . dump ( tree )
else : # TODO : append to current tree
pass |
def get_compound_pd ( self ) :
"""Get the CompoundPhaseDiagram object , which can then be used for
plotting .
Returns :
( CompoundPhaseDiagram )""" | # For this plot , since the reactions are reported in formation
# energies , we need to set the energies of the terminal compositions
# to 0 . So we make create copies with 0 energy .
entry1 = PDEntry ( self . entry1 . composition , 0 )
entry2 = PDEntry ( self . entry2 . composition , 0 )
cpd = CompoundPhaseDiagram ( s... |
def extract ( self , item ) :
"""Runs the HTML - response trough a list of initialized extractors , a cleaner and compares the results .
: param item : NewscrawlerItem to be processed .
: return : An updated NewscrawlerItem including the results of the extraction""" | article_candidates = [ ]
for extractor in self . extractor_list :
article_candidates . append ( extractor . extract ( item ) )
article_candidates = self . cleaner . clean ( article_candidates )
article = self . comparer . compare ( item , article_candidates )
item [ 'article_title' ] = article . title
item [ 'artic... |
def update_gradients_full ( self , dL_dK , X , X2 = None ) :
"""derivative of the covariance matrix with respect to the parameters ( shape is N x num _ inducing x num _ params )""" | if X2 is None :
X2 = X
FX = self . _cos ( self . basis_alpha [ None , : ] , self . basis_omega [ None , : ] , self . basis_phi [ None , : ] ) ( X )
FX2 = self . _cos ( self . basis_alpha [ None , : ] , self . basis_omega [ None , : ] , self . basis_phi [ None , : ] ) ( X2 )
La = np . column_stack ( ( self . a [ 0 ]... |
def account_setup ( remote , token , resp ) :
"""Perform additional setup after user have been logged in .
: param remote : The remote application .
: param token : The token value .
: param resp : The response .""" | gh = github3 . login ( token = resp [ 'access_token' ] )
with db . session . begin_nested ( ) :
me = gh . me ( )
token . remote_account . extra_data = { 'login' : me . login , 'id' : me . id }
# Create user < - > external id link .
oauth_link_external_id ( token . remote_account . user , dict ( id = str... |
def ignore ( self , event ) :
"""Ignores events .""" | if hasattr ( event , 'inaxes' ) :
if event . inaxes != self . ax :
return True
else :
return False |
def get_raster_array ( image ) :
"""Return the array data from any Raster or Image type""" | if isinstance ( image , RGB ) :
rgb = image . rgb
data = np . dstack ( [ np . flipud ( rgb . dimension_values ( d , flat = False ) ) for d in rgb . vdims ] )
else :
data = image . dimension_values ( 2 , flat = False )
if type ( image ) is Raster :
data = data . T
else :
data = np . f... |
def filterRead ( self , read ) :
"""Filter a read , according to our set of filters .
@ param read : A C { Read } instance or one of its subclasses .
@ return : C { False } if the read fails any of our filters , else the
C { Read } instance returned by our list of filters .""" | for filterFunc in self . _filters :
filteredRead = filterFunc ( read )
if filteredRead is False :
return False
else :
read = filteredRead
return read |
def get_azm_dip ( inp , iz , ninpz , intpts , isdipole , strength , name , verb ) :
r"""Get angles , interpolation weights and normalization weights .
This check - function is called from one of the modelling routines in
: mod : ` model ` . Consult these modelling routines for a detailed description
of the in... | global _min_off
# Get this di - / bipole
if ninpz == 1 : # If there is only one distinct depth , all at once
tinp = inp
else : # If there are several depths , we take the current one
if isdipole :
tinp = [ np . atleast_1d ( inp [ 0 ] [ iz ] ) , np . atleast_1d ( inp [ 1 ] [ iz ] ) , np . atleast_1d ( in... |
def _get_plot_data ( data , ndim = None ) :
"""Get plot data out of an input object
Parameters
data : array - like , ` phate . PHATE ` or ` scanpy . AnnData `
ndim : int , optional ( default : None )
Minimum number of dimensions""" | out = data
if isinstance ( data , PHATE ) :
out = data . transform ( )
else :
try :
if isinstance ( data , anndata . AnnData ) :
try :
out = data . obsm [ 'X_phate' ]
except KeyError :
raise RuntimeError ( "data.obsm['X_phate'] not found. " "Please... |
def do_GET ( self ) :
"""Handle a HTTP GET request .""" | # Example session :
# in : GET / wsapi / decrypt ? otp = ftftftccccdvvbfcfduvvcubikngtchlubtutucrld HTTP / 1.0
# out : OK counter = 0004 low = f585 high = 3e use = 03
if self . path . startswith ( self . serve_url ) :
from_key = self . path [ len ( self . serve_url ) : ]
val_res = self . decrypt_yubikey_otp ( f... |
def add ( self , statement , parameters = None ) :
"""Adds a : class : ` . Statement ` and optional sequence of parameters
to be used with the statement to the batch .
Like with other statements , parameters must be a sequence , even
if there is only one item .""" | if isinstance ( statement , six . string_types ) :
if parameters :
encoder = Encoder ( ) if self . _session is None else self . _session . encoder
statement = bind_params ( statement , parameters , encoder )
self . _add_statement_and_params ( False , statement , ( ) )
elif isinstance ( statement... |
def force_flush ( ) :
"""force _ flush""" | if SPLUNK_DEBUG :
print ( '{} -------------------------------' . format ( rnow ( ) ) )
print ( '{} splunkpub: force_flush - start' . format ( rnow ( ) ) )
worked = True
for instance in instances :
try :
instance . force_flush ( )
except Exception as e :
worked = False
if SPLUNK_D... |
def positional ( self , argument_dest , arg_type = None , ** kwargs ) :
"""Register a positional argument for the given command scope using a knack . arguments . CLIArgumentType
: param argument _ dest : The destination argument to add this argument type to
: type argument _ dest : str
: param arg _ type : Pr... | self . _check_stale ( )
if not self . _applicable ( ) :
return
if self . command_scope not in self . command_loader . command_table :
raise ValueError ( "command authoring error: positional argument '{}' cannot be registered to a group-level " "scope '{}'. It must be registered to a specific command." . format ... |
def insert ( collection_name , docs , check_keys , safe , last_error_args , continue_on_error , opts ) :
"""Get an * * insert * * message .""" | options = 0
if continue_on_error :
options += 1
data = struct . pack ( "<i" , options )
data += bson . _make_c_string ( collection_name )
encoded = [ bson . BSON . encode ( doc , check_keys , opts ) for doc in docs ]
if not encoded :
raise InvalidOperation ( "cannot do an empty bulk insert" )
max_bson_size = ma... |
def modularity_louvain_und_sign ( W , gamma = 1 , qtype = 'sta' , seed = None ) :
'''The optimal community structure is a subdivision of the network into
nonoverlapping groups of nodes in a way that maximizes the number of
within - group edges , and minimizes the number of between - group edges .
The modulari... | rng = get_rng ( seed )
n = len ( W )
# number of nodes
W0 = W * ( W > 0 )
# positive weights matrix
W1 = - W * ( W < 0 )
# negative weights matrix
s0 = np . sum ( W0 )
# weight of positive links
s1 = np . sum ( W1 )
# weight of negative links
if qtype == 'smp' :
d0 = 1 / s0
d1 = 1 / s1
# dQ = dQ0 / s0 - sQ1... |
def encipher ( self , string , keep_punct = False ) :
"""Encipher string using Atbash cipher .
Example : :
ciphertext = Atbash ( ) . encipher ( plaintext )
: param string : The string to encipher .
: param keep _ punct : if true , punctuation and spacing are retained . If false , it is all removed . Default... | if not keep_punct :
string = self . remove_punctuation ( string )
ret = ''
for c in string . upper ( ) :
if c . isalpha ( ) :
ret += self . key [ self . a2i ( c ) ]
else :
ret += c
return ret |
async def put ( self , cid ) :
"""Update price of current content
Accepts :
Query string args :
- " cid " - int
Request body params :
- " access _ type " - str
- " price " - int
- " coinid " - str
Returns :
dict with following fields :
- " confirmed " : None
- " txid " - str
- " description ... | if settings . SIGNATURE_VERIFICATION :
super ( ) . verify ( )
try :
body = json . loads ( self . request . body )
except :
self . set_status ( 400 )
self . write ( { "error" : 400 , "reason" : "Unexpected data format. JSON required" } )
raise tornado . web . Finish
# Get data from signed message
pub... |
def __get_wbfmt_format_txt ( self , data_nt ) :
"""Return format for text cell from namedtuple field , ' format _ txt ' .""" | format_txt_val = getattr ( data_nt , "format_txt" )
if format_txt_val == 1 :
return self . fmtname2wbfmtobj . get ( "very light grey" )
if format_txt_val == 2 :
return self . fmtname2wbfmtobj . get ( "light grey" )
return self . fmtname2wbfmtobj . get ( format_txt_val ) |
def copy ( self ) :
"""Return a deep copy of the current scene
Returns
copied : trimesh . Scene
Copy of the current scene""" | # use the geometries copy method to
# allow them to handle references to unpickle - able objects
geometry = { n : g . copy ( ) for n , g in self . geometry . items ( ) }
# create a new scene with copied geometry and graph
copied = Scene ( geometry = geometry , graph = self . graph . copy ( ) )
return copied |
def get ( self , * args , ** kwargs ) :
"""Works just like the default Manager ' s : func : ` get ` method , but
you can pass an additional keyword argument named ` ` path ` ` specifying
the full path of the object you want to retrieve , e . g .
` ` " path / to / folder / readme . txt " ` ` .""" | if 'path' in kwargs :
kwargs = self . get_filter_args_with_path ( True , ** kwargs )
return super ( FileNodeManager , self ) . get ( * args , ** kwargs ) |
def set ( self , ctype , key , data ) :
"""Set or update cache content .
: param ctype : cache type
: param key : the key to be set value
: param data : cache data""" | with zvmutils . acquire_lock ( self . _lock ) :
target_cache = self . _get_ctype_cache ( ctype )
target_cache [ 'data' ] [ key ] = data |
def do_config ( self , arg ) :
"""Usage :
config print
config reload
config help""" | if arg [ 'print' ] :
self . print_config ( arg )
elif arg [ 'reload' ] :
self . reload_config ( arg )
else :
self . help_server ( ) |
def md5sum ( file_path , blocksize = 65536 ) :
"""Compute the md5 of a file . Pretty fast .""" | md5 = hashlib . md5 ( )
with open ( file_path , "rb" ) as f :
for block in iter ( lambda : f . read ( blocksize ) , "" ) :
md5 . update ( block )
return md5 . hexdigest ( ) |
def extract_fragment ( self , iri : str ) -> str :
'''Pulls only for code / ID from the iri
I only add the str ( ) conversion for the iri because rdflib objects need to be converted .''' | fragment = str ( iri ) . rsplit ( '/' ) [ - 1 ] . split ( ':' , 1 ) [ - 1 ] . split ( '#' , 1 ) [ - 1 ] . split ( '_' , 1 ) [ - 1 ]
return fragment |
def from_array ( array ) :
"""Deserialize a new InputLocationMessageContent from a given dictionary .
: return : new InputLocationMessageContent instance .
: rtype : InputLocationMessageContent""" | if array is None or not array :
return None
# end if
assert_type_or_raise ( array , dict , parameter_name = "array" )
data = { }
data [ 'latitude' ] = float ( array . get ( 'latitude' ) )
data [ 'longitude' ] = float ( array . get ( 'longitude' ) )
data [ 'live_period' ] = int ( array . get ( 'live_period' ) ) if a... |
def add_binding ( self , binding : Binding ) :
"""Stores binding""" | binding . add_error_info = lambda error : error . add_view_info ( self . _xml_node . view_info )
self . _bindings . append ( binding ) |
def find_id ( self , element_id ) :
"""Find element by its id .
Parameters
element _ id : str
ID of the element to find
Returns
FigureElement
one of the children element with the given ID .""" | find = etree . XPath ( "//*[@id=$id]" )
return FigureElement ( find ( self . root , id = element_id ) [ 0 ] ) |
def _get_stddevs ( self , C , mag , stddev_types , num_sites ) :
"""Return standard deviation as defined in eq . 11 page 319.""" | std = C [ 'c16' ] + np . zeros ( num_sites )
if mag < 7.4 :
std -= 0.07 * mag
else :
std -= 0.518
# only the ' total ' standard deviation is supported , therefore the
# std is always the same for all types
stddevs = [ std for _ in stddev_types ]
return stddevs |
def get_letter_as_image ( self , pixelletter_id ) :
"""Get specified letter as image
: param pixelletter _ id : ID of the letter
: return : JPG - Letter - Unicode - String if successful else None""" | image_letter = self . _make_get_request ( 'letters/previews/{}_1.jpg' . format ( pixelletter_id ) )
if image_letter :
return image_letter
return None |
def partition ( self , ref = None , ** kwargs ) :
"""Returns partition by ref .""" | from . exc import NotFoundError
from six import text_type
if ref :
for p in self . partitions : # This is slow for large datasets , like Census years .
if ( text_type ( ref ) == text_type ( p . name ) or text_type ( ref ) == text_type ( p . id ) or text_type ( ref ) == text_type ( p . vid ) ) :
... |
def _build_keys ( self , slug , date = None , granularity = 'all' ) :
"""Builds redis keys used to store metrics .
* ` ` slug ` ` - - a slug used for a metric , e . g . " user - signups "
* ` ` date ` ` - - ( optional ) A ` ` datetime . datetime ` ` object used to
generate the time period for the metric . If ... | slug = slugify ( slug )
# Ensure slugs have a consistent format
if date is None :
date = datetime . utcnow ( )
patts = self . _build_key_patterns ( slug , date )
if granularity == "all" :
return list ( patts . values ( ) )
return [ patts [ granularity ] ] |
def get_build_info_for_date ( self , date , build_index = None ) :
"""Return the build information for a given date .""" | url = urljoin ( self . base_url , self . monthly_build_list_regex )
has_time = date and date . time ( )
self . logger . info ( 'Retrieving list of builds from %s' % url )
parser = self . _create_directory_parser ( url )
regex = r'%(DATE)s-(\d+-)+%(BRANCH)s%(L10N)s%(PLATFORM)s$' % { 'DATE' : date . strftime ( '%Y-%m-%d'... |
def open_output_file ( self , test_record ) :
"""Open file based on pattern .""" | # Ignore keys for the log filename to not convert larger data structures .
record_dict = data . convert_to_base_types ( test_record , ignore_keys = ( 'code_info' , 'phases' , 'log_records' ) )
pattern = self . filename_pattern
if isinstance ( pattern , six . string_types ) or callable ( pattern ) :
output_file = se... |
def matches_address ( self , address ) :
"""returns whether this account knows about an email address
: param str address : address to look up
: rtype : bool""" | if self . address == address :
return True
for alias in self . aliases :
if alias == address :
return True
if self . _alias_regexp and self . _alias_regexp . match ( address ) :
return True
return False |
def old_values ( self ) :
'''Returns the old values from the diff''' | def get_old_values_and_key ( item ) :
values = item . old_values
values . update ( { self . _key : item . past_dict [ self . _key ] } )
return values
return [ get_old_values_and_key ( el ) for el in self . _get_recursive_difference ( 'all' ) if el . diffs and el . past_dict ] |
def resources ( self , start = 1 , num = 10 ) :
"""Resources lists all file resources for the organization . The start
and num paging parameters are supported .
Inputs :
start - the number of the first entry in the result set response
The index number is 1 - based and the default is 1
num - the maximum nu... | url = self . _url + "/resources"
params = { "f" : "json" , "start" : start , "num" : num }
return self . _get ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) |
def remove_users_from_group ( self , group_id , body , ** kwargs ) : # noqa : E501
"""Remove users from a group . # noqa : E501
An endpoint for removing users from groups . * * Example usage : * * ` curl - X DELETE https : / / api . us - east - 1 . mbedcloud . com / v3 / policy - groups / { group - id } / users -... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . remove_users_from_group_with_http_info ( group_id , body , ** kwargs )
# noqa : E501
else :
( data ) = self . remove_users_from_group_with_http_info ( group_id , body , ** kwargs )
# noqa : E501
return data |
def upload_tree ( self ) :
"""upload _ tree : sends processed channel data to server to create tree
Args : None
Returns : link to uploadedchannel""" | from datetime import datetime
start_time = datetime . now ( )
root , channel_id = self . add_channel ( )
self . node_count_dict = { "upload_count" : 0 , "total_count" : self . channel . count ( ) }
config . LOGGER . info ( "\tPreparing fields..." )
self . truncate_fields ( self . channel )
self . add_nodes ( root , sel... |
def _generate_corpus_table ( self , labels , ngrams ) :
"""Returns an HTML table containing data on each corpus ' n - grams .""" | html = [ ]
for label in labels :
html . append ( self . _render_corpus_row ( label , ngrams ) )
return '\n' . join ( html ) |
def list_groups ( name ) :
'''Return a list of groups the named user belongs to
Args :
name ( str ) : The user name for which to list groups
Returns :
list : A list of groups to which the user belongs
CLI Example :
. . code - block : : bash
salt ' * ' user . list _ groups foo''' | if six . PY2 :
name = _to_unicode ( name )
ugrp = set ( )
try :
user = info ( name ) [ 'groups' ]
except KeyError :
return False
for group in user :
ugrp . add ( group . strip ( ' *' ) )
return sorted ( list ( ugrp ) ) |
def get_batch ( sentences , token_dict , ignore_case = False , unk_index = 1 , eos_index = 2 ) :
"""Get a batch of inputs and outputs from given sentences .
: param sentences : A list of list of tokens .
: param token _ dict : The dict that maps a token to an integer . ` < UNK > ` and ` < EOS > ` should be pres... | batch_size = len ( sentences )
max_sentence_len = max ( map ( len , sentences ) )
inputs = [ [ 0 ] * max_sentence_len for _ in range ( batch_size ) ]
outputs_forward = [ [ 0 ] * max_sentence_len for _ in range ( batch_size ) ]
outputs_backward = [ [ 0 ] * max_sentence_len for _ in range ( batch_size ) ]
for i , sentenc... |
def _matches_docs ( self , docs , other_docs ) :
"""Overridable method .""" | for doc , other_doc in zip ( docs , other_docs ) :
if not self . _match_map ( doc , other_doc ) :
return False
return True |
def _check_modes ( self , modes ) :
"""Check that the image is in one of the given * modes * , raise an exception otherwise .""" | if not isinstance ( modes , ( tuple , list , set ) ) :
modes = [ modes ]
if self . mode not in modes :
raise ValueError ( "Image not in suitable mode, expected: %s, got: %s" % ( modes , self . mode ) ) |
def load_definition_by_name ( name : str ) -> dict :
"""Look up and return a definition by name ( name is expected to correspond to
the filename of the definition , with the . json extension ) and return it or
raise an exception
: param name : A string to use for looking up a labware defintion previously
sa... | def_path = 'shared_data/definitions2/{}.json' . format ( name . lower ( ) )
labware_def = json . loads ( pkgutil . get_data ( 'opentrons' , def_path ) )
# type : ignore # NOQA
return labware_def |
def _register_elements ( self , elements ) :
"""Takes elements from the metadata class and creates a base model for all backend models .""" | self . elements = elements
for key , obj in elements . items ( ) :
obj . contribute_to_class ( self . metadata , key )
# Create the common Django fields
fields = { }
for key , obj in elements . items ( ) :
if obj . editable :
field = obj . get_field ( )
if not field . help_text :
if ... |
def on_tweet ( self , tweet ) :
"""Callback to receive tweet from : class : ` ~ responsebot . responsebot _ stream . ResponseBotStream ` . Tries to forward the
received tweet to registered handlers .
: param tweet : An object containing a tweet ' s text and metadata
: type tweet : : class : ` ~ responsebot . ... | logging . info ( u'Received tweet: `{message}`' . format ( message = tweet . text ) )
for handler in self . handlers :
if not handler . catch_self_tweets and self . is_self_tweet ( tweet ) :
continue
if not handler . filter . match_tweet ( tweet = tweet , user_stream = self . client . config . get ( 'us... |
def _reindex ( self ) :
"""Create a case - insensitive index of the paths""" | self . index = [ ]
for path in self . paths :
target_path = os . path . normpath ( os . path . join ( BASE_PATH , path ) )
for root , subdirs , files in os . walk ( target_path ) :
for f in files :
self . index . append ( ( os . path . join ( root , f ) . lower ( ) , os . path . join ( root ... |
def getAllCellsInColumns ( columns , cellsPerColumn ) :
"""Calculate all cell indices in the specified columns .
@ param columns ( numpy array )
@ param cellsPerColumn ( int )
@ return ( numpy array )
All cells within the specified columns . The cells are in the same order as the
provided columns , so the... | # Add
# [ [ beginningOfColumn0 ] ,
# [ beginningOfColumn1 ] ,
# to
# [0 , 1 , 2 , . . . , cellsPerColumn - 1]
# to get
# [ beginningOfColumn0 + 0 , beginningOfColumn0 + 1 , . . .
# beginningOfColumn1 + 0 , . . .
# then flatten it .
return ( ( columns * cellsPerColumn ) . reshape ( ( - 1 , 1 ) ) + np . arange ( cellsPer... |
def name ( self ) :
'''Returns the name of this template ( if created from a file ) or " string " if not''' | if self . mako_template . filename :
return os . path . basename ( self . mako_template . filename )
return 'string' |
def daily_hold ( self ) :
'每日交易结算时的持仓表' | data = self . trade . cumsum ( )
if len ( data ) < 1 :
return None
else : # print ( data . index . levels [ 0 ] )
data = data . assign ( account_cookie = self . account_cookie ) . assign ( date = pd . to_datetime ( data . index . levels [ 0 ] ) . date )
data . date = pd . to_datetime ( data . date )
dat... |
def create_environment ( self , ** kwargs ) :
"""Return a new Jinja environment .
Derived classes may override method to pass additional parameters or to change the template
loader type .""" | environment = super ( ) . create_environment ( ** kwargs )
environment . tests . update ( { 'type' : self . test_type , 'kind' : self . test_kind , 'opposite_before_self' : self . test_opposite_before_self , } )
environment . filters . update ( { 'docstringline' : self . filter_docstringline , 'pyquotesingle' : self . ... |
def to_json ( self , * attributes , ** options ) :
"""Returns the selected field * attributes * for each : class : ` Field ` * nested *
in the ` Container ` as a JSON formatted string .
The * attributes * of each : class : ` Field ` for containers * nested * in the
` Container ` are viewed as well ( chained m... | nested = options . pop ( 'nested' , False )
fieldnames = options . pop ( 'fieldnames' , attributes )
if 'cls' in options . keys ( ) :
return json . dumps ( self . view_fields ( * attributes , nested = nested , fieldnames = fieldnames ) , ** options )
else :
return json . dumps ( self . view_fields ( * attribute... |
def get_configs ( args , command_args , ansible_args = ( ) ) :
"""Glob the current directory for Molecule config files , instantiate config
objects , and returns a list .
: param args : A dict of options , arguments and commands from the CLI .
: param command _ args : A dict of options passed to the subcomman... | configs = [ config . Config ( molecule_file = util . abs_path ( c ) , args = args , command_args = command_args , ansible_args = ansible_args , ) for c in glob . glob ( MOLECULE_GLOB ) ]
_verify_configs ( configs )
return configs |
def train_batch ( self , batch_info : BatchInfo ) -> None :
"""Batch - the most atomic unit of learning .
For this reinforforcer , that involves :
1 . Roll out the environmnent using current policy
2 . Use that rollout to train the policy""" | # Calculate environment rollout on the evaluation version of the model
self . model . train ( )
rollout = self . env_roller . rollout ( batch_info , self . model , self . settings . number_of_steps )
# Process rollout by the ' algo ' ( e . g . perform the advantage estimation )
rollout = self . algo . process_rollout (... |
def backend ( self ) :
"""Returns the backend class""" | from indico_livesync . plugin import LiveSyncPlugin
return LiveSyncPlugin . instance . backend_classes . get ( self . backend_name ) |
def prepare_batch ( self ) :
"""Propagates exception on failure
: return : byte array to put on the blockchain""" | for cert in self . certificates_to_issue :
self . certificate_handler . validate_certificate ( cert )
self . merkle_tree . populate ( self . get_certificate_generator ( ) )
logging . info ( 'here is the op_return_code data: %s' , b2h ( self . merkle_tree . get_blockchain_data ( ) ) )
return self . merkle_tree . get... |
def deploy_snmp ( snmp , host = None , admin_username = None , admin_password = None , module = None ) :
'''Change the QuickDeploy SNMP community string , used for switches as well
CLI Example :
. . code - block : : bash
salt dell dracr . deploy _ snmp SNMP _ STRING
host = < remote DRAC or CMC > admin _ use... | return __execute_cmd ( 'deploy -v SNMPv2 {0} ro' . format ( snmp ) , host = host , admin_username = admin_username , admin_password = admin_password , module = module ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.