signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _convert ( tup , dictlist ) :
""": param tup : a list of tuples
: param di : a dictionary converted from tup
: return : dictionary""" | di = { }
for a , b in tup :
di . setdefault ( a , [ ] ) . append ( b )
for key , val in di . items ( ) :
dictlist . append ( ( key , val ) )
return dictlist |
def handler_all ( func = None ) :
"""Decorator that registers a function as a webhook handler for ALL webhook events .
Handles all webhooks regardless of event type or sub - type .""" | if not func :
return functools . partial ( handler_all )
registrations_global . append ( func )
return func |
def check_if_needs_inversion ( tomodir ) :
"""check of we need to run CRTomo in a given tomodir""" | required_files = ( 'grid' + os . sep + 'elem.dat' , 'grid' + os . sep + 'elec.dat' , 'exe' + os . sep + 'crtomo.cfg' , )
needs_inversion = True
for filename in required_files :
if not os . path . isfile ( tomodir + os . sep + filename ) :
needs_inversion = False
# check for crmod OR modeling capabilities
if... |
def add_sibling ( self , pos = None , ** kwargs ) :
"""Adds a new node as a sibling to the current node object .""" | pos = self . _prepare_pos_var_for_add_sibling ( pos )
if len ( kwargs ) == 1 and 'instance' in kwargs : # adding the passed ( unsaved ) instance to the tree
newobj = kwargs [ 'instance' ]
if newobj . pk :
raise NodeAlreadySaved ( "Attempted to add a tree node that is " "already in the database" )
else :... |
def locale ( self , value ) :
"""The locale property .
Args :
value ( string ) . the property value .""" | if value == self . _defaults [ 'ai.device.locale' ] and 'ai.device.locale' in self . _values :
del self . _values [ 'ai.device.locale' ]
else :
self . _values [ 'ai.device.locale' ] = value |
def modify_product ( self , product_id , name = None , description = None , attributes = { } ) :
'''modify _ product ( self , product _ id , name = None , description = None , attributes = { } )
Modify an existing product
: Parameters :
* * product _ id * ( ` string ` ) - - identifier of an existing product
... | request_data = { 'id' : product_id }
if name :
request_data [ 'name' ] = name
if description :
request_data [ 'description' ] = description
if attributes :
request_data [ 'attributes' ] = attributes
return self . _call_rest_api ( 'post' , '/products' , data = request_data , error = 'Failed to modify a new p... |
async def zrevrangebyscore ( self , name , max , min , start = None , num = None , withscores = False , score_cast_func = float ) :
"""Return a range of values from the sorted set ` ` name ` ` with scores
between ` ` min ` ` and ` ` max ` ` in descending order .
If ` ` start ` ` and ` ` num ` ` are specified , ... | if ( start is not None and num is None ) or ( num is not None and start is None ) :
raise RedisError ( "``start`` and ``num`` must both be specified" )
pieces = [ 'ZREVRANGEBYSCORE' , name , max , min ]
if start is not None and num is not None :
pieces . extend ( [ b ( 'LIMIT' ) , start , num ] )
if withscores ... |
def setup_logging ( args = None ) :
"""Setup logging module .
Args :
args ( optional ) : The arguments returned by the argparse module .""" | logging_level = logging . WARNING
if args is not None and args . verbose :
logging_level = logging . INFO
config = { "level" : logging_level , "format" : "jtlocalize:%(message)s" }
if args is not None and args . log_path != "" :
config [ "filename" ] = args . log_path
logging . basicConfig ( ** config ) |
def address_qubits ( program , qubit_mapping = None ) :
"""Takes a program which contains placeholders and assigns them all defined values .
Either all qubits must be defined or all undefined . If qubits are
undefined , you may provide a qubit mapping to specify how placeholders get mapped
to actual qubits . ... | fake_qubits , real_qubits , qubits = _what_type_of_qubit_does_it_use ( program )
if real_qubits :
if qubit_mapping is not None :
warnings . warn ( "A qubit mapping was provided but the program does not " "contain any placeholders to map!" )
return program
if qubit_mapping is None :
qubit_mapping = {... |
def _safe_release_connection ( self ) :
"""Try to release a connection . If an exception is hit , log and return
the error string .""" | try :
self . adapter . release_connection ( )
except Exception as exc :
logger . debug ( 'Error releasing connection for node {}: {!s}\n{}' . format ( self . node . name , exc , traceback . format_exc ( ) ) )
return dbt . compat . to_string ( exc )
return None |
def downsample ( in_bam , data , target_counts , work_dir = None ) :
"""Downsample a BAM file to the specified number of target counts .""" | index ( in_bam , data [ "config" ] , check_timestamp = False )
ds_pct = get_downsample_pct ( in_bam , target_counts , data )
if ds_pct :
out_file = "%s-downsample%s" % os . path . splitext ( in_bam )
if work_dir :
out_file = os . path . join ( work_dir , os . path . basename ( out_file ) )
if not ut... |
def remove_positive_retrain ( X , y , model_generator , method_name , num_fcounts = 11 ) :
"""Remove Positive ( retrain )
xlabel = " Max fraction of features removed "
ylabel = " Negative mean model output "
transform = " negate "
sort _ order = 11""" | return __run_measure ( measures . remove_retrain , X , y , model_generator , method_name , 1 , num_fcounts , __mean_pred ) |
def usage ( self ) :
"""A usage string that describes the signature .""" | return u' ' . join ( u'<%s>' % pattern . usage for pattern in self . patterns ) |
def get_body ( name ) :
"""Retrieve a given body orbits and parameters
Args :
name ( str ) : Object name
Return :
Body :""" | try :
body , propag = _bodies [ name . lower ( ) ]
# attach a propagator to the object
body . propagate = propag . propagate
except KeyError as e :
raise UnknownBodyError ( e . args [ 0 ] )
return body |
def head ( bucket , path = '' , key = None , keyid = None , service_url = None , verify_ssl = None , kms_keyid = None , location = None , role_arn = None , path_style = None , https_enable = None ) :
'''Return the metadata for a bucket , or an object in a bucket .
CLI Examples :
. . code - block : : bash
salt... | key , keyid , service_url , verify_ssl , kms_keyid , location , role_arn , path_style , https_enable = _get_key ( key , keyid , service_url , verify_ssl , kms_keyid , location , role_arn , path_style , https_enable , )
return __utils__ [ 's3.query' ] ( method = 'HEAD' , bucket = bucket , path = path , key = key , keyid... |
def _draw_tiles ( self , x_offset , y_offset , bg ) :
"""Render all visible tiles a layer at a time .""" | count = 0
for layer_name , c_filters , t_filters in self . _get_features ( ) :
colour = ( self . _256_PALETTE [ layer_name ] if self . _screen . colours >= 256 else self . _16_PALETTE [ layer_name ] )
for x , y , z , tile , satellite in sorted ( self . _tiles . values ( ) , key = lambda k : k [ 0 ] ) : # Don ' ... |
def _read_line ( self , f ) :
"""Reads one non empty line ( if it ' s a comment , it skips it ) .""" | l = f . readline ( ) . strip ( )
while l == "" or l [ 0 ] == "#" : # comment or an empty line
l = f . readline ( ) . strip ( )
return l |
def parse_entry ( source , loc , tokens ) :
"""Converts the tokens of an entry into an Entry instance . If no applicable
type is available , an UnsupportedEntryType exception is raised .""" | type_ = tokens [ 1 ] . lower ( )
entry_type = structures . TypeRegistry . get_type ( type_ )
if entry_type is None or not issubclass ( entry_type , structures . Entry ) :
raise exceptions . UnsupportedEntryType ( "%s is not a supported entry type" % type_ )
new_entry = entry_type ( )
new_entry . name = tokens [ 3 ]... |
def full_signature ( self ) :
"""The full signature of a ` ` " function " ` ` node .
* * Return * *
: class : ` python : str `
The full signature of the function , including template , return type ,
name , and parameter types .
* * Raises * *
: class : ` python : RuntimeError `
If ` ` self . kind ! = ... | if self . kind == "function" :
return "{template}{return_type} {name}({parameters})" . format ( template = "template <{0}> " . format ( ", " . join ( self . template ) ) if self . template else "" , return_type = self . return_type , name = self . name , parameters = ", " . join ( self . parameters ) )
raise Runtim... |
def _build_hline ( self , is_header = False ) :
"""Return a string used to separated rows or separate header from
rows""" | horiz = self . _char_horiz
if ( is_header ) :
horiz = self . _char_header
# compute cell separator
s = "%s%s%s" % ( horiz , [ horiz , self . _char_corner ] [ self . _has_vlines ( ) ] , horiz )
# build the line
l = s . join ( [ horiz * n for n in self . _width ] )
# add border if needed
if self . _has_border ( ) :
... |
def update_data_flows ( model , data_flow_dict , tree_dict_combos ) :
"""Updates data flow dictionary and combo dictionary of the widget according handed model .
: param model : model for which the data _ flow _ dict and tree _ dict _ combos should be updated
: param data _ flow _ dict : dictionary that holds a... | data_flow_dict [ 'internal' ] = { }
data_flow_dict [ 'external' ] = { }
tree_dict_combos [ 'internal' ] = { }
tree_dict_combos [ 'external' ] = { }
# free input ports and scopes are real to _ keys and real states
[ free_to_port_internal , from_ports_internal ] = find_free_keys ( model )
[ free_to_port_external , from_p... |
def create_ssh_key ( kwargs = None , call = None ) :
'''Create an ssh key''' | if call == 'action' :
raise SaltCloudSystemExit ( 'The create_ssh_key function must be called with ' '-f or --function' )
conn = get_conn ( )
# Assemble the composite SshKey object .
ssh_key = _get_ssh_key ( kwargs )
data = conn . create_ssh_key ( ssh_key = ssh_key )
return { 'SshKey' : data } |
def load_location ( url , base_path = None , module = False ) :
"""Read a single Python file in as code and extract members from it .
Args :
url - - a URL either absolute ( contains ' : ' ) or relative
base _ path - - if url is relative , base _ path is prepended to it .
The resulting URL needs to look some... | if base_path and ':' not in url :
slashes = base_path . endswith ( '/' ) + url . startswith ( '/' )
if slashes == 0 :
url = base_path + '/' + url
elif slashes == 1 :
url = base_path + url
else :
url = base_path [ : - 1 ] + url
slash = url . rfind ( '/' )
url_root , filepath = url... |
def RemoveEmptyDirectoryTree ( path , silent = False , recursion = 0 ) :
"""Delete tree of empty directories .
Parameters
path : string
Path to root of directory tree .
silent : boolean [ optional : default = False ]
Turn off log output .
recursion : int [ optional : default = 0]
Indicates level of re... | if not silent and recursion is 0 :
goodlogging . Log . Info ( "UTIL" , "Starting removal of empty directory tree at: {0}" . format ( path ) )
try :
os . rmdir ( path )
except OSError :
if not silent :
goodlogging . Log . Info ( "UTIL" , "Removal of empty directory tree terminated at: {0}" . format (... |
def update_tile_extent_bounds ( self ) :
"""Updates the : attr : ` tile _ beg _ min ` and : attr : ` tile _ end _ max `
data members according to : attr : ` tile _ bounds _ policy ` .""" | if self . tile_bounds_policy == NO_BOUNDS :
self . tile_beg_min = self . array_start - self . halo [ : , 0 ]
self . tile_end_max = self . array_start + self . array_shape + self . halo [ : , 1 ]
elif self . tile_bounds_policy == ARRAY_BOUNDS :
self . tile_beg_min = self . array_start
self . tile_end_max... |
def DbGetProperty ( self , argin ) :
"""Get free object property
: param argin : Str [ 0 ] = Object name
Str [ 1 ] = Property name
Str [ n ] = Property name
: type : tango . DevVarStringArray
: return : Str [ 0 ] = Object name
Str [ 1 ] = Property number
Str [ 2 ] = Property name
Str [ 3 ] = Propert... | self . _log . debug ( "In DbGetProperty()" )
object_name = argin [ 0 ]
return self . db . get_property ( object_name , argin [ 1 : ] ) |
def BuildFindSpecs ( self , artifact_filter_names , environment_variables = None ) :
"""Builds find specifications from artifact definitions .
Args :
artifact _ filter _ names ( list [ str ] ) : names of artifact definitions that are
used for filtering file system and Windows Registry key paths .
environmen... | find_specs = [ ]
for name in artifact_filter_names :
definition = self . _artifacts_registry . GetDefinitionByName ( name )
if not definition :
logger . debug ( 'undefined artifact definition: {0:s}' . format ( name ) )
continue
logger . debug ( 'building find spec from artifact definition: ... |
def _tarboton_slopes_directions ( self , data , dX , dY ) :
"""Calculate the slopes and directions based on the 8 sections from
Tarboton http : / / www . neng . usu . edu / cee / faculty / dtarb / 96wr03137 . pdf""" | return _tarboton_slopes_directions ( data , dX , dY , self . facets , self . ang_adj ) |
def depth_first ( start , descend ) :
"""Performs a depth - first search of a graph - like structure .
: param start : Node to start the search from
: param expand : Function taking a node as an argument and returning iterable
of its child nodes
: return : Iterable of nodes in the DFS order
Example : :
... | ensure_callable ( descend )
def generator ( ) :
stack = [ start ]
while stack :
node = stack . pop ( )
yield node
stack . extend ( descend ( node ) )
return generator ( ) |
def num2bytes ( value , size ) :
"""Convert an unsigned integer to MSB - first bytes with specified size .""" | res = [ ]
for _ in range ( size ) :
res . append ( value & 0xFF )
value = value >> 8
assert value == 0
return bytes ( bytearray ( list ( reversed ( res ) ) ) ) |
def do_cat ( self , line ) :
"""cat FILENAME . . .
Concatenates files and sends to stdout .""" | # note : when we get around to supporting cat from stdin , we ' ll need
# to write stdin to a temp file , and then copy the file
# since we need to know the filesize when copying to the pyboard .
args = self . line_to_args ( line )
for filename in args :
filename = resolve_path ( filename )
mode = auto ( get_mo... |
def name ( self ) :
"""The identifier of the machine .""" | name = self . __class__ . __name__
for i , character in enumerate ( name ) :
if character . isdigit ( ) :
return name [ : i ] + "-" + name [ i : ]
return name |
def put_vmss_vm ( access_token , subscription_id , resource_group , vmss_name , vm_id , vm_body ) :
'''Update a VMSS VM . E . g . add / remove a data disk from a specifc VM in a scale set ( preview ) .
Note : Only currently enabled for Azure Canary regions .
Args :
access _ token ( str ) : A valid Azure authe... | endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourceGroups/' , resource_group , '/providers/Microsoft.Compute/virtualMachineScaleSets/' , vmss_name , '/virtualMachines/' , str ( vm_id ) , '?api-version=' , COMP_API ] )
body = json . dumps ( vm_body )
return do_put ( endpoint ,... |
def parse_last_period ( last ) :
"""Parse the - - last value and return the time difference in seconds .""" | wordmap = { 'hour' : '1h' , 'day' : '1d' , 'week' : '1w' , 'month' : '1m' }
# seconds
multmap = { 'h' : 3600 , 'd' : 86400 , 'w' : 604800 , 'm' : 2592000 }
if last in wordmap :
last = wordmap [ last ]
cat = last [ - 1 : ] . lower ( )
if cat not in multmap :
raise TypeError
try :
num = int ( last [ : - 1 ] )... |
def GetOrderKey ( self ) :
"""Return a tuple that can be used to sort problems into a consistent order .
Returns :
A list of values .""" | context_attributes = [ '_type' ]
context_attributes . extend ( ExceptionWithContext . CONTEXT_PARTS )
context_attributes . extend ( self . _GetExtraOrderAttributes ( ) )
tokens = [ ]
for context_attribute in context_attributes :
tokens . append ( getattr ( self , context_attribute , None ) )
return tokens |
def get_contents_as_string ( self , headers = None , cb = None , num_cb = 10 , torrent = False , version_id = None , response_headers = None , callback = None ) :
"""Retrieve an object from S3 using the name of the Key object as the
key in S3 . Return the contents of the object as a string .
See get _ contents ... | fp = StringIO . StringIO ( )
def got_contents_as_string ( response ) :
if callable ( callback ) :
callback ( fp . getvalue ( ) )
self . get_contents_to_file ( fp , headers , cb , num_cb , torrent = torrent , version_id = version_id , response_headers = response_headers , callback = got_contents_as_string ) |
def replace_function_node ( node , annotation ) :
"""Replace a node annotated by ` nni . function _ choice ` .
node : the AST node to replace
annotation : annotation string""" | target , funcs = parse_nni_function ( annotation )
FuncReplacer ( funcs , target ) . visit ( node )
return node |
def service_search ( auth = None , ** kwargs ) :
'''Search services
CLI Example :
. . code - block : : bash
salt ' * ' keystoneng . service _ search
salt ' * ' keystoneng . service _ search name = glance
salt ' * ' keystoneng . service _ search name = 135f0403f8e544dc9008c6739ecda860''' | cloud = get_operator_cloud ( auth )
kwargs = _clean_kwargs ( ** kwargs )
return cloud . search_services ( ** kwargs ) |
def transformer_base_vq1_16_nb1_packed_dan_b01_scales ( ) :
"""Set of hyperparameters .""" | hparams = transformer_base_vq_ada_32ex_packed ( )
hparams . use_scales = int ( True )
hparams . moe_num_experts = 16
hparams . moe_k = 1
hparams . beta = 0.1
hparams . ema = False
return hparams |
def get_tpm_status ( d_info ) :
"""Get the TPM support status .
Get the TPM support status of the node .
: param d _ info : the list of ipmitool parameters for accessing a node .
: returns : TPM support status""" | # note :
# Get TPM support status : ipmi cmd ' 0xF5 ' , valid flags ' 0xC0'
# $ ipmitool raw 0x2E 0xF5 0x80 0x28 0x00 0x81 0xC0
# Raw response :
# 80 28 00 C0 C0 : True
# 80 28 00 - - - - : False ( other values than ' C0 C0 ' )
ipmicmd = ipmi_command . Command ( bmc = d_info [ 'irmc_address' ] , userid = d_info [ 'irmc... |
def sign_report ( self , device_id , root , data , ** kwargs ) :
"""Sign a buffer of report data on behalf of a device .
Args :
device _ id ( int ) : The id of the device that we should encrypt for
root ( int ) : The root key type that should be used to generate the report
data ( bytearray ) : The data that... | report_key = self . _verify_derive_key ( device_id , root , ** kwargs )
# We sign the SHA256 hash of the message
message_hash = hashlib . sha256 ( data ) . digest ( )
hmac_calc = hmac . new ( report_key , message_hash , hashlib . sha256 )
result = bytearray ( hmac_calc . digest ( ) )
return { 'signature' : result , 'ro... |
def output ( self , stream , value ) :
"""SPL output port assignment expression .
Arguments :
stream ( Stream ) : Output stream the assignment is for .
value ( str ) : SPL expression used for an output assignment . This can be a string , a constant , or an : py : class : ` Expression ` .
Returns :
Express... | if stream not in self . outputs :
raise ValueError ( "Stream is not an output of this operator." )
e = self . expression ( value )
e . _stream = stream
return e |
def find_attr_start_line ( self , lines , min_line = 4 , max_line = 9 ) :
"""Return line number of the first real attribute and value .
The first line is 0 . If the ' ATTRIBUTE _ NAME ' header is not
found , return the index after max _ line .""" | for idx , line in enumerate ( lines [ min_line : max_line ] ) :
col = line . split ( )
if len ( col ) > 1 and col [ 1 ] == 'ATTRIBUTE_NAME' :
return idx + min_line + 1
self . log . warn ( 'ATTRIBUTE_NAME not found in second column of' ' smartctl output between lines %d and %d.' % ( min_line , max_line )... |
def node_hist_fig ( node_color_distribution , title = "Graph Node Distribution" , width = 400 , height = 300 , top = 60 , left = 25 , bottom = 60 , right = 25 , bgcolor = "rgb(240,240,240)" , y_gridcolor = "white" , ) :
"""Define the plotly plot representing the node histogram
Parameters
node _ color _ distribu... | text = [ "{perc}%" . format ( ** locals ( ) ) for perc in [ d [ "perc" ] for d in node_color_distribution ] ]
pl_hist = go . Bar ( y = [ d [ "height" ] for d in node_color_distribution ] , marker = dict ( color = [ d [ "color" ] for d in node_color_distribution ] ) , text = text , hoverinfo = "y+text" , )
hist_layout =... |
def add_get ( self , path : str , handler : _WebHandler , * , name : Optional [ str ] = None , allow_head : bool = True , ** kwargs : Any ) -> AbstractRoute :
"""Shortcut for add _ route with method GET , if allow _ head is true another
route is added allowing head requests to the same endpoint""" | resource = self . add_resource ( path , name = name )
if allow_head :
resource . add_route ( hdrs . METH_HEAD , handler , ** kwargs )
return resource . add_route ( hdrs . METH_GET , handler , ** kwargs ) |
def save ( self , filepath = None , password = None , keyfile = None ) :
"""This method saves the database .
It ' s possible to parse a data path to an alternative file .""" | if ( password is None and keyfile is not None and keyfile != "" and type ( keyfile ) is str ) :
self . keyfile = keyfile
elif ( keyfile is None and password is not None and password != "" and type ( password is str ) ) :
self . password = password
elif ( keyfile is not None and password is not None and keyfile ... |
def export ( self , top = True ) :
"""Exports object to its string representation .
Args :
top ( bool ) : if True appends ` internal _ name ` before values .
All non list objects should be exported with value top = True ,
all list objects , that are embedded in as fields inlist objects
should be exported ... | out = [ ]
if top :
out . append ( self . _internal_name )
out . append ( self . _to_str ( self . leapyear_observed ) )
out . append ( self . _to_str ( self . daylight_saving_start_day ) )
out . append ( self . _to_str ( self . daylight_saving_end_day ) )
out . append ( str ( len ( self . holidays ) ) )
for obj in s... |
def get_alert ( self , id , ** kwargs ) : # noqa : E501
"""Get a specific alert # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . get _ alert ( id , async _ req = True )
> > > res... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . get_alert_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . get_alert_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def delete_option_by_id ( cls , option_id , ** kwargs ) :
"""Delete Option
Delete an instance of Option by its ID .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . delete _ option _ by _ id ( option _ id , async =... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _delete_option_by_id_with_http_info ( option_id , ** kwargs )
else :
( data ) = cls . _delete_option_by_id_with_http_info ( option_id , ** kwargs )
return data |
def decode_index_value ( self , index , value ) :
"""Decodes a secondary index value into the correct Python type .
: param index : the name of the index
: type index : str
: param value : the value of the index entry
: type value : str
: rtype str or int""" | if index . endswith ( "_int" ) :
return int ( value )
else :
return bytes_to_str ( value ) |
def warningObject ( object , cat , format , * args ) :
"""Log a warning message in the given category .
This is used for non - fatal problems .""" | doLog ( WARN , object , cat , format , args ) |
def get_wcxf ( self , C_out , scale_out ) :
"""Return the Wilson coefficients ` C _ out ` as a wcxf . WC instance .
Note that the Wilson coefficients are rotated into the Warsaw basis
as defined in WCxf , i . e . to the basis where the down - type and charged
lepton mass matrices are diagonal .""" | import wcxf
C = self . rotate_defaultbasis ( C_out )
d = wcxf . translators . smeft . arrays2wcxf ( C )
basis = wcxf . Basis [ 'SMEFT' , 'Warsaw' ]
d = { k : v for k , v in d . items ( ) if k in basis . all_wcs and v != 0 }
keys_dim5 = [ 'llphiphi' ]
keys_dim6 = list ( set ( definitions . WC_keys_0f + definitions . WC_... |
def steal ( self , instr ) :
"""Steal the jump index off of ` instr ` .
This makes anything that would have jumped to ` instr ` jump to
this Instruction instead .
Parameters
instr : Instruction
The instruction to steal the jump sources from .
Returns
self : Instruction
The instruction that owns this... | instr . _stolen_by = self
for jmp in instr . _target_of :
jmp . arg = self
self . _target_of = instr . _target_of
instr . _target_of = set ( )
return self |
def replace_namespaced_replica_set ( self , name , namespace , body , ** kwargs ) :
"""replace the specified ReplicaSet
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . replace _ namespaced _ replica _ set ( na... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_namespaced_replica_set_with_http_info ( name , namespace , body , ** kwargs )
else :
( data ) = self . replace_namespaced_replica_set_with_http_info ( name , namespace , body , ** kwargs )
return data |
def build ( cls , blockchain_opts , end_block_id , state_engine , expected_snapshots = { } , tx_filter = None ) :
"""Top - level call to process all blocks in the blockchain .
Goes and fetches all data - bearing transactions in order ,
and feeds them into the state engine implementation .
Note that this metho... | first_block_id = state_engine . lastblock + 1
if first_block_id >= end_block_id : # built
log . debug ( "Up-to-date ({} >= {})" . format ( first_block_id , end_block_id ) )
return True
rc = True
batch_size = config . BLOCK_BATCH_SIZE
log . debug ( "Sync virtualchain state from {} to {}" . format ( first_block_i... |
def _init_figure ( ax , figsize ) :
"""Initializes the ` ` matplotlib ` ` ` ` figure ` ` , one of the first things that every plot must do . No figure is
initialized ( and , consequentially , the ` ` figsize ` ` argument is ignored ) if a pre - existing ` ` ax ` ` is passed to
the method . This is necessary for... | if not ax :
fig = plt . figure ( figsize = figsize )
return fig |
def activities ( self ) :
"""An iterator of reverse - chronological : class : ` stravalib . model . Activity ` activities for this club .""" | if self . _activities is None :
self . assert_bind_client ( )
self . _activities = self . bind_client . get_club_activities ( self . id )
return self . _activities |
def set_projection_attrs ( self , area_id , proj4_info ) :
"""Assign projection attributes per GRB standard""" | proj4_info [ 'a' ] , proj4_info [ 'b' ] = proj4_radius_parameters ( proj4_info )
if proj4_info [ "proj" ] == "geos" :
p = self . projection = self . nc . createVariable ( "fixedgrid_projection" , 'i4' )
self . image_data . grid_mapping = "fixedgrid_projection"
p . short_name = area_id
p . grid_mapping_n... |
def add_capability_list ( self , capability_list = None ) :
"""Add a capability list .
Adds either a CapabiltyList object specified in capability _ list
or else creates a Resource with the URI given in capability _ list
and adds that to the Source Description""" | if ( hasattr ( capability_list , 'uri' ) ) :
r = Resource ( uri = capability_list . uri , capability = capability_list . capability_name )
if ( capability_list . describedby is not None ) :
r . link_set ( rel = 'describedby' , href = capability_list . describedby )
else :
r = Resource ( uri = capabi... |
def get_caffe_pb ( ) :
"""Get caffe protobuf .
Returns :
The imported caffe protobuf module .""" | dir = get_dataset_path ( 'caffe' )
caffe_pb_file = os . path . join ( dir , 'caffe_pb2.py' )
if not os . path . isfile ( caffe_pb_file ) :
download ( CAFFE_PROTO_URL , dir )
assert os . path . isfile ( os . path . join ( dir , 'caffe.proto' ) )
if sys . version_info . major == 3 :
cmd = "protoc --ve... |
def shape ( self ) :
"""The shape of the Texture / RenderBuffer attached to this FrameBuffer""" | if self . color_buffer is not None :
return self . color_buffer . shape [ : 2 ]
# in case its a texture
if self . depth_buffer is not None :
return self . depth_buffer . shape [ : 2 ]
if self . stencil_buffer is not None :
return self . stencil_buffer . shape [ : 2 ]
raise RuntimeError ( 'FrameBuffer wi... |
def time_range_to_frame_range ( self , start , end , sr ) :
"""Calculate the frames containing samples from the given time range in seconds .
Args :
start ( float ) : Start time in seconds .
end ( float ) : End time in seconds .
sr ( int ) : The sampling rate to use for time - to - sample conversion .
Ret... | start_sample = seconds_to_sample ( start , sr )
end_sample = seconds_to_sample ( end , sr )
return self . sample_to_frame_range ( start_sample ) [ 0 ] , self . sample_to_frame_range ( end_sample - 1 ) [ 1 ] |
def on_event ( self , event ) :
"""Callback to receive events from : class : ` ~ responsebot . responsebot _ stream . ResponseBotStream ` . Tries to forward the
received event to registered handlers .
: param event : The received event
: type event : : class : ` ~ responsebot . models . Event `
error from a... | if event . event not in TWITTER_NON_TWEET_EVENTS :
logging . warning ( u'Received unknown twitter event {event}' . format ( event = event . event ) )
return
logging . info ( u'Received event {event}' . format ( event = event . event ) )
for handler in self . handlers :
handler . on_event ( event ) |
def register_group ( self , name , policies = None , mount_point = DEFAULT_MOUNT_POINT ) :
"""Register a new group and maps a set of policies to it .
Supported methods :
POST : / auth / { mount _ point } / groups / { name } . Produces : 204 ( empty body )
: param name : The name of the group .
: type name :... | params = { 'policies' : policies , }
api_path = '/v1/auth/{mount_point}/groups/{name}' . format ( mount_point = mount_point , name = name , )
return self . _adapter . post ( url = api_path , json = params , ) |
def _maybe_download_corpus ( tmp_dir , vocab_type ) :
"""Download and unpack the corpus .
Args :
tmp _ dir : directory containing dataset .
vocab _ type : which vocabulary are we using .
Returns :
The list of names of files .""" | if vocab_type == text_problems . VocabType . CHARACTER :
dataset_url = ( "https://s3.amazonaws.com/research.metamind.io/wikitext" "/wikitext-103-raw-v1.zip" )
dir_name = "wikitext-103-raw"
else :
dataset_url = ( "https://s3.amazonaws.com/research.metamind.io/wikitext" "/wikitext-103-v1.zip" )
dir_name =... |
def edit_script_to_strings ( edit_script , use_colors = True ) :
"""Convert an edit script to a pair of strings representing the operation in a human readable way .
: param edit _ script : The edit script as a list of operations , where each operation is a dictionary .
: param use _ colors : Boolean indicating ... | colors = collections . defaultdict ( str )
if use_colors :
colors [ 'red' ] = '\x1b[31m'
colors [ 'normal' ] = '\x1b[m'
colors [ 'green' ] = '\x1b[32m'
colors [ 'on_red' ] = '\x1b[41m'
src_txt = ''
dst_txt = ''
for op in edit_script :
if op [ 'op_code' ] == 'match' :
width = max ( len ( op [... |
def add_missing_placeholders ( self ) :
"""Add missing placeholders from templates . Return ` True ` if any missing
placeholders were created .""" | content_type = ContentType . objects . get_for_model ( self )
result = False
if self . layout :
for data in self . layout . get_placeholder_data ( ) :
placeholder , created = Placeholder . objects . update_or_create ( parent_type = content_type , parent_id = self . pk , slot = data . slot , defaults = dict ... |
def applied ( self , context : typing . Any = None , setenv : typing . Callable = operator . setitem , delenv : typing . Callable = None , getenv : typing . Callable = operator . getitem , ) :
"""Apply this environment to the context .
If no context is supplied , os . environ is used .
If you pass setenv = and ... | if context is None :
context = os . environ
if hasattr ( context , "setenv" ) : # context is probably pytest ' s MonkeyPatch
setenv = context . setenv
delenv = functools . partial ( context . delenv , raising = False )
getenv = functools . partial ( operator . getitem , os . environ )
elif delenv is Non... |
def nested_key_indices ( nested_dict ) :
"""Give an ordering to the outer and inner keys used in a dictionary that
maps to dictionaries .""" | outer_keys , inner_keys = collect_nested_keys ( nested_dict )
outer_key_indices = { k : i for ( i , k ) in enumerate ( outer_keys ) }
inner_key_indices = { k : i for ( i , k ) in enumerate ( inner_keys ) }
return outer_key_indices , inner_key_indices |
def validate_tracer ( * args ) :
"""Validate and finishes a tracer by adding mandatory extra attributes .
: param \ * args : Arguments .
: type \ * args : \ *
: return : Validated wrapped object .
: rtype : object""" | object , wrapped = args
if is_traced ( object ) or is_untracable ( object ) or get_object_name ( object ) in UNTRACABLE_NAMES :
return object
set_tracer_hook ( wrapped , object )
set_traced ( wrapped )
return wrapped |
def postinit ( self , key = None , value = None , generators = None ) :
"""Do some setup after initialisation .
: param key : What produces the keys .
: type key : NodeNG or None
: param value : What produces the values .
: type value : NodeNG or None
: param generators : The generators that are looped th... | self . key = key
self . value = value
if generators is None :
self . generators = [ ]
else :
self . generators = generators |
def firmware_bundles ( self ) :
"""Gets the FirmwareBundles API client .
Returns :
FirmwareBundles :""" | if not self . __firmware_bundles :
self . __firmware_bundles = FirmwareBundles ( self . __connection )
return self . __firmware_bundles |
def __substitute_replace_pairs ( self ) :
"""Substitutes all replace pairs in the source of the stored routine .""" | self . _set_magic_constants ( )
routine_source = [ ]
i = 0
for line in self . _routine_source_code_lines :
self . _replace [ '__LINE__' ] = "'%d'" % ( i + 1 )
for search , replace in self . _replace . items ( ) :
tmp = re . findall ( search , line , re . IGNORECASE )
if tmp :
line = ... |
def getSiblings ( self , retracted = False ) :
"""Return the list of duplicate analyses that share the same Request and
are included in the same Worksheet as the current analysis . The current
duplicate is excluded from the list .
: param retracted : If false , retracted / rejected siblings are dismissed
: ... | worksheet = self . getWorksheet ( )
requestuid = self . getRequestUID ( )
if not requestuid or not worksheet :
return [ ]
siblings = [ ]
retracted_states = [ STATE_RETRACTED , STATE_REJECTED ]
analyses = worksheet . getAnalyses ( )
for analysis in analyses :
if analysis . UID ( ) == self . UID ( ) : # Exclude m... |
def get_exchangeinsertion ( cls ) :
"""Return the complete string related to the definition of exchange
items to be inserted into the string of the template file .
> > > from hydpy . auxs . xmltools import XSDWriter
> > > print ( XSDWriter . get _ exchangeinsertion ( ) ) # doctest : + ELLIPSIS
< complexType... | indent = 1
subs = [ cls . get_mathitemsinsertion ( indent ) ]
for groupname in ( 'setitems' , 'additems' , 'getitems' ) :
subs . append ( cls . get_itemsinsertion ( groupname , indent ) )
subs . append ( cls . get_itemtypesinsertion ( groupname , indent ) )
return '\n' . join ( subs ) |
def find_N_peaks ( array , N = 4 , max_iterations = 100 , rec_max_iterations = 3 , recursion = 1 ) :
"""This will run the find _ peaks algorythm , adjusting the baseline until exactly N peaks are found .""" | if recursion < 0 :
return None
# get an initial guess as to the baseline
ymin = min ( array )
ymax = max ( array )
for n in range ( max_iterations ) : # bisect the range to estimate the baseline
y1 = ( ymin + ymax ) / 2.0
# now see how many peaks this finds . p could have 40 for all we know
p , s , i = ... |
def convert_nonParametricSeismicSource ( self , node ) :
"""Convert the given node into a non parametric source object .
: param node :
a node with tag areaGeometry
: returns :
a : class : ` openquake . hazardlib . source . NonParametricSeismicSource `
instance""" | trt = node . attrib . get ( 'tectonicRegion' )
rup_pmf_data = [ ]
rups_weights = None
if 'rup_weights' in node . attrib :
tmp = node . attrib . get ( 'rup_weights' )
rups_weights = numpy . array ( [ float ( s ) for s in tmp . split ( ) ] )
for i , rupnode in enumerate ( node ) :
probs = pmf . PMF ( valid . ... |
def create_source ( self , name , src_dict , build_index = True , merge_sources = True , rescale = True ) :
"""Add a new source to the ROI model from a dictionary or an
existing source object .
Parameters
name : str
src _ dict : dict or ` ~ fermipy . roi _ model . Source `
Returns
src : ` ~ fermipy . ro... | src_dict = copy . deepcopy ( src_dict )
if isinstance ( src_dict , dict ) :
src_dict [ 'name' ] = name
src = Model . create_from_dict ( src_dict , self . skydir , rescale = rescale )
else :
src = src_dict
src . set_name ( name )
if isinstance ( src , Source ) :
src . set_roi_direction ( self . skydi... |
def get_guardians ( self , run ) :
"""Return a list of nodes on whom the specific node is control dependent in the control dependence graph""" | if run in self . _graph . nodes ( ) :
return list ( self . _graph . predecessors ( run ) )
else :
return [ ] |
def convert_values ( args_list ) :
"""convert _ value in bulk .
: param args _ list : list of value , source , target currency pairs
: return : map of converted values""" | rate_map = get_rates ( map ( itemgetter ( 1 , 2 ) , args_list ) )
value_map = { }
for value , source , target in args_list :
args = ( value , source , target )
if source == target :
value_map [ args ] = value
else :
value_map [ args ] = value * rate_map [ ( source , target ) ]
return value_m... |
def _create_rpmmacros ( runas = 'root' ) :
'''Create the . rpmmacros file in user ' s home directory''' | home = os . path . expanduser ( '~' )
rpmbuilddir = os . path . join ( home , 'rpmbuild' )
if not os . path . isdir ( rpmbuilddir ) :
__salt__ [ 'file.makedirs_perms' ] ( name = rpmbuilddir , user = runas , group = 'mock' )
mockdir = os . path . join ( home , 'mock' )
if not os . path . isdir ( mockdir ) :
__sa... |
def addUsersToRole ( self , rolename , users ) :
"""Assigns a role to multiple users""" | params = { "f" : "json" , "rolename" : rolename , "users" : users }
rURL = self . _url + "/roles/addUsersToRole"
return self . _post ( url = rURL , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) |
def save_formset_with_author ( formset , user ) :
"""Проставляет моделям из набора форм автора
: param formset : набор форм
: param user : автор
: return :""" | instances = formset . save ( commit = False )
for obj in formset . deleted_objects :
obj . delete ( )
for instance in instances :
if user . is_authenticated ( ) and hasattr ( instance , 'author' ) and not instance . author :
instance . author = user
instance . save ( )
formset . save_m2m ( ) |
def print_prompt_values ( values , message = None , sub_attr = None ) :
"""Prints prompt title and choices with a bit of formatting .""" | if message :
prompt_message ( message )
for index , entry in enumerate ( values ) :
if sub_attr :
line = '{:2d}: {}' . format ( index , getattr ( utf8 ( entry ) , sub_attr ) )
else :
line = '{:2d}: {}' . format ( index , utf8 ( entry ) )
with indent ( 3 ) :
print_message ( line ) |
def in6_getifaddr ( ) :
"""Returns a list of 3 - tuples of the form ( addr , scope , iface ) where
' addr ' is the address of scope ' scope ' associated to the interface
' iface ' .
This is the list of all addresses of all interfaces available on
the system .""" | # List all network interfaces
if OPENBSD :
try :
f = os . popen ( "%s" % conf . prog . ifconfig )
except OSError :
log_interactive . warning ( "Failed to execute ifconfig." )
return [ ]
# Get the list of network interfaces
splitted_line = [ ]
for l in f :
if "flags" i... |
def active_path ( context , pattern , css = None ) :
"""Highlight menu item based on path .
Returns a css class if ` ` request . path ` ` is in given ` ` pattern ` ` .
: param pattern :
Regex url pattern .
: param css :
Css class to be returned for highlighting . Return active if none set .""" | request = context [ 'request' ]
# pattern = " ^ " + pattern + " $ "
if re . search ( pattern , request . path ) :
return css if css else 'active'
return '' |
def write ( self , data ) :
"""Write DATA to the underlying SSL channel . Returns
number of bytes of DATA actually transmitted .""" | while True :
try :
return self . _sslobj . write ( data )
except SSLError :
ex = sys . exc_info ( ) [ 1 ]
if ex . args [ 0 ] == SSL_ERROR_WANT_READ :
if self . timeout == 0.0 :
raise
six . exc_clear ( )
self . _io . wait_read ( timeout ... |
def hook ( self , name ) :
"""Return a decorator that attaches a callback to a hook . See
: meth : ` add _ hook ` for details .""" | def decorator ( func ) :
self . add_hook ( name , func )
return func
return decorator |
def lspcn ( body , et , abcorr ) :
"""Compute L _ s , the planetocentric longitude of the sun , as seen
from a specified body .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / lspcn _ c . html
: param body : Name of central body .
: type body : str
: param et : Epoch in sec... | body = stypes . stringToCharP ( body )
et = ctypes . c_double ( et )
abcorr = stypes . stringToCharP ( abcorr )
return libspice . lspcn_c ( body , et , abcorr ) |
def num_forward_until ( self , condition ) :
"""Forward until one of the provided matches is found .
: param condition : set of valid strings""" | i , c = 0 , ''
while self . hasNext ( ) and not condition ( self . peek ( ) ) :
c += self . forward ( 1 )
i += 1
assert self . backward ( i ) == c
return i |
def _parse_singlefile ( self , desired_type : Type [ T ] , file_path : str , encoding : str , logger : Logger , options : Dict [ str , Dict [ str , Any ] ] ) -> T :
"""Implementation of AnyParser API""" | # first use the base parser to parse something compliant with the conversion chain
first = self . _base_parser . _parse_singlefile ( self . _converter . from_type , file_path , encoding , logger , options )
# then apply the conversion chain
return self . _converter . convert ( desired_type , first , logger , options ) |
def getent ( refresh = False ) :
'''Return the list of all info for all users
CLI Example :
. . code - block : : bash
salt ' * ' user . getent''' | if 'user.getent' in __context__ and not refresh :
return __context__ [ 'user.getent' ]
ret = [ ]
for data in pwd . getpwall ( ) :
ret . append ( _format_info ( data ) )
__context__ [ 'user.getent' ] = ret
return ret |
def is_same_geometry ( ls1 , ls2 ) :
"""Check if LineString geometries in two edges are the same , in
normal or reversed order of points .
Parameters
ls1 : LineString
the first edge ' s geometry
ls2 : LineString
the second edge ' s geometry
Returns
bool""" | # extract geometries from each edge data dict
geom1 = [ list ( coords ) for coords in ls1 . xy ]
geom2 = [ list ( coords ) for coords in ls2 . xy ]
# reverse the first edge ' s list of x ' s and y ' s to look for a match in
# either order
geom1_r = [ list ( reversed ( list ( coords ) ) ) for coords in ls1 . xy ]
# if t... |
def parse ( duration , context = None ) :
"""parse the duration string which contains a human readable duration and
return a datetime . timedelta object representing that duration
arguments :
duration - the duration string following a notation like so :
"1 hour "
"1 month and 3 days " " 1 year 2 weeks and... | matcher = _PATTERN . match ( duration )
if matcher is None or matcher . end ( ) < len ( duration ) :
raise Exception ( 'unsupported duration "%s"' % duration )
else :
result = timedelta ( )
if context is None :
context = datetime . now ( )
year = context . year
month = context . month
da... |
def get_directory_properties ( self , share_name , directory_name , timeout = None , snapshot = None ) :
'''Returns all user - defined metadata and system properties for the
specified directory . The data returned does not include the directory ' s
list of files .
: param str share _ name :
Name of existing... | _validate_not_none ( 'share_name' , share_name )
_validate_not_none ( 'directory_name' , directory_name )
request = HTTPRequest ( )
request . method = 'GET'
request . host_locations = self . _get_host_locations ( )
request . path = _get_path ( share_name , directory_name )
request . query = { 'restype' : 'directory' , ... |
def get_or_add_bgPr ( self ) :
"""Return ` p : bg / p : bgPr ` grandchild .
If no such grandchild is present , any existing ` p : bg ` child is first
removed and a new default ` p : bg ` with noFill settings is added .""" | bg = self . bg
if bg is None or bg . bgPr is None :
self . _change_to_noFill_bg ( )
return self . bg . bgPr |
def validate_harvester_notifications ( user ) :
'''Notify admins about pending harvester validation''' | if not user . sysadmin :
return [ ]
notifications = [ ]
# Only fetch required fields for notification serialization
# Greatly improve performances and memory usage
qs = HarvestSource . objects ( validation__state = VALIDATION_PENDING )
qs = qs . only ( 'id' , 'created_at' , 'name' )
for source in qs :
notificat... |
def get_file_samples ( file_ids ) :
"""Get TCGA associated sample barcodes for a list of file IDs .
Params
file _ ids : Iterable
The file IDs .
Returns
` pandas . Series `
Series containing file IDs as index and corresponding sample barcodes .""" | assert isinstance ( file_ids , Iterable )
# query TCGA API to get sample barcodes associated with file IDs
payload = { "filters" : json . dumps ( { "op" : "in" , "content" : { "field" : "files.file_id" , "value" : list ( file_ids ) , } } ) , "fields" : "file_id,cases.samples.submitter_id" , "size" : 10000 }
r = request... |
def model_macros ( vk , model ) :
"""Fill the model with macros
model [ ' macros ' ] = { ' name ' : value , . . . }""" | model [ 'macros' ] = { }
# API Macros
macros = [ x for x in vk [ 'registry' ] [ 'enums' ] if x . get ( '@type' ) not in ( 'bitmask' , 'enum' ) ]
# TODO : Check theses values
special_values = { '1000.0f' : '1000.0' , '(~0U)' : 0xffffffff , '(~0ULL)' : - 1 , '(~0U-1)' : 0xfffffffe , '(~0U-2)' : 0xfffffffd }
for macro in ... |
async def on_request ( self , domain , address , identity , mechanism , credentials , ) :
"""Handle a ZAP request .""" | logger . debug ( "Request in domain %s for %s (%r): %r (%r)" , domain , address , identity , mechanism , credentials , )
user_id = None
metadata = { }
if self . whitelist :
if address not in self . whitelist :
raise ZAPAuthenticationFailure ( "IP address is not in the whitelist" , )
elif self . blacklist :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.