signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def wrap_sync ( func ) :
"""Wraps a synchronous function into an asynchronous function .""" | @ functools . wraps ( func )
def wrapped ( * args , ** kwargs ) :
fut = asyncio . Future ( )
def green ( ) :
try :
fut . set_result ( func ( * args , ** kwargs ) )
except BaseException as e :
fut . set_exception ( e )
greenlet . greenlet ( green ) . switch ( )
ret... |
def _from_binary_sec_desc ( cls , binary_stream ) :
"""See base class .""" | header = SecurityDescriptorHeader . create_from_binary ( binary_stream [ : SecurityDescriptorHeader . get_representation_size ( ) ] )
owner_sid = SID . create_from_binary ( binary_stream [ header . owner_sid_offset : ] )
group_sid = SID . create_from_binary ( binary_stream [ header . group_sid_offset : ] )
dacl = None
... |
def normalize ( self , axis ) :
"""Returns new histogram where all values along axis ( in one bin of the other axes ) sum to 1""" | axis = self . get_axis_number ( axis )
sum_along_axis = np . sum ( self . histogram , axis = axis )
# Don ' t do anything for subspaces without any entries - - this avoids nans everywhere
sum_along_axis [ sum_along_axis == 0 ] = 1
hist = self . histogram / sum_along_axis [ self . _simsalabim_slice ( axis ) ]
return His... |
def selectedOptions ( self ) -> NodeList :
"""Return all selected option nodes .""" | return NodeList ( list ( opt for opt in self . options if opt . selected ) ) |
def get_external_store ( self , project_name , store_name ) :
"""get the logstore meta info
Unsuccessful opertaion will cause an LogException .
: type project _ name : string
: param project _ name : the Project name
: type store _ name : string
: param store _ name : the logstore name
: return : GetLog... | headers = { }
params = { }
resource = "/externalstores/" + store_name
( resp , header ) = self . _send ( "GET" , project_name , None , resource , params , headers )
# add storeName if not existing
if 'externalStoreName' not in resp :
resp [ 'externalStoreName' ] = store_name
return GetExternalStoreResponse ( resp ,... |
def parse_line ( self , statement , element , mode ) :
"""Parses the contents of the specified line and adds its representation
to the specified element ( if applicable ) .
: arg statement : the lines of code that was added / removed / changed on the
element after it had alread been parsed . The lines togethe... | if element . incomplete : # We need to check for the end _ token so we can close up the incomplete
# status for the instance .
if element . end_token in statement :
element . incomplete = False
return
# The line can either be related to an assignment or a dependency since
# those are the only releva... |
def list_files ( tag = None , sat_id = None , data_path = None , format_str = None ) :
"""Return a Pandas Series of every file for chosen satellite data
Parameters
tag : ( string or NoneType )
Denotes type of file to load . Accepted types are ' 1min ' and ' 5min ' .
( default = None )
sat _ id : ( string ... | if format_str is None and data_path is not None :
if ( tag == '1min' ) | ( tag == '5min' ) :
min_fmt = '' . join ( [ 'omni_hro_' , tag , '{year:4d}{month:02d}{day:02d}_v01.cdf' ] )
files = pysat . Files . from_os ( data_path = data_path , format_str = min_fmt )
# files are by month , just ad... |
def _node_to_dict ( cls , node , json , json_fields ) :
"""Helper method for ` ` get _ tree ` ` .""" | if json :
pk_name = node . get_pk_name ( )
# jqTree or jsTree format
result = { 'id' : getattr ( node , pk_name ) , 'label' : node . __repr__ ( ) }
if json_fields :
result . update ( json_fields ( node ) )
else :
result = { 'node' : node }
return result |
def parse ( ignore_file = '.gitignore' , git_dir = '.git' , additional_files = ( ) , global_ = True , root_dir = None , defaults = True ) :
"""Collects a list of all ignore patterns configured in a local Git repository
as specified in the Git documentation . See
https : / / git - scm . com / docs / gitignore # ... | result = IgnoreListCollection ( )
if root_dir is None :
if git_dir is None :
raise ValueError ( "root_dir or git_dir must be specified" )
root_dir = os . path . dirname ( os . path . abspath ( git_dir ) )
def parse ( filename , root = None ) :
if os . path . isfile ( filename ) :
if root is ... |
def _set_lacp_pdu_forward ( self , v , load = False ) :
"""Setter method for lacp _ pdu _ forward , mapped from YANG variable / interface / ethernet / lacp _ pdu _ forward ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ lacp _ pdu _ forward is considered a... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = lacp_pdu_forward . lacp_pdu_forward , is_container = 'container' , presence = False , yang_name = "lacp-pdu-forward" , rest_name = "lacp-pdu-forward" , parent = self , path_helper = self . _path_helper , extmethods = self . _... |
def DecoderLayer ( feature_depth , feedforward_depth , num_heads , dropout , mode ) :
"""Transformer decoder layer .
Args :
feature _ depth : int : depth of embedding
feedforward _ depth : int : depth of feed - forward layer
num _ heads : int : number of attention heads
dropout : float : dropout rate ( ho... | return layers . Serial ( layers . Residual ( # Self - attention block .
layers . LayerNorm ( ) , layers . Branch ( ) , layers . Parallel ( layers . Identity ( ) , # activation for ( q , k , v )
layers . CausalMask ( axis = - 2 ) ) , # attention mask
layers . MultiHeadedAttention ( feature_depth , num_heads = num_heads ... |
def getCountKwargs ( func ) :
"""Returns a list [ " count kwarg " , " count _ max kwarg " ] for a
given function . Valid combinations are defined in
` progress . validCountKwargs ` .
Returns None if no keyword arguments are found .""" | # Get all arguments of the function
if hasattr ( func , "__code__" ) :
func_args = func . __code__ . co_varnames [ : func . __code__ . co_argcount ]
for pair in validCountKwargs :
if ( pair [ 0 ] in func_args and pair [ 1 ] in func_args ) :
return pair
# else
return None |
def apply_binding ( self , binding , msg_str , destination = "" , relay_state = "" , response = False , sign = False , ** kwargs ) :
"""Construct the necessary HTTP arguments dependent on Binding
: param binding : Which binding to use
: param msg _ str : The return message as a string ( XML ) if the message is ... | # unless if BINDING _ HTTP _ ARTIFACT
if response :
typ = "SAMLResponse"
else :
typ = "SAMLRequest"
if binding == BINDING_HTTP_POST :
logger . info ( "HTTP POST" )
# if self . entity _ type = = ' sp ' :
# info = self . use _ http _ post ( msg _ str , destination , relay _ state ,
# typ )
# i... |
def update ( self , identifier , new_instance ) :
"""Update an existing model with a new one .
: raises ` ModelNotFoundError ` if there is no existing model""" | with self . flushing ( ) :
instance = self . retrieve ( identifier )
self . merge ( instance , new_instance )
instance . updated_at = instance . new_timestamp ( )
return instance |
def dump ( self ) :
"""Dump topology to disk""" | try :
topo = project_to_topology ( self )
path = self . _topology_file ( )
log . debug ( "Write %s" , path )
with open ( path + ".tmp" , "w+" , encoding = "utf-8" ) as f :
json . dump ( topo , f , indent = 4 , sort_keys = True )
shutil . move ( path + ".tmp" , path )
except OSError as e :
... |
def plot_grid_to_ax ( self , ax , ** kwargs ) :
"""Other Parameters
plot _ electrode _ numbers : bool , optional
Plot electrode numbers in the grid , default : False""" | all_xz = [ ]
for x , z in zip ( self . grid [ 'x' ] , self . grid [ 'z' ] ) :
tmp = np . vstack ( ( x , z ) ) . T
all_xz . append ( tmp )
collection = mpl . collections . PolyCollection ( all_xz , edgecolor = 'k' , facecolor = 'none' , linewidth = 0.4 , )
ax . add_collection ( collection )
if self . electrodes ... |
def Cx ( mt , x ) :
"""Return the Cx""" | return ( ( 1 / ( 1 + mt . i ) ) ** ( x + 1 ) ) * mt . dx [ x ] * ( ( 1 + mt . i ) ** 0.5 ) |
def create_device ( self , parent , device , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Creates a device in a device registry .
Example :
> > > from google . cloud import iot _ v1
> > > client = iot _ v1 . Devi... | # Wrap the transport method to add retry and timeout logic .
if "create_device" not in self . _inner_api_calls :
self . _inner_api_calls [ "create_device" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . create_device , default_retry = self . _method_configs [ "CreateDevice" ] . retry , ... |
def calc_pan_pct ( self , viewer , pad = 0 ) :
"""Calculate values for vertical / horizontal panning by percentages
from the current pan position .""" | limits = viewer . get_limits ( )
tr = viewer . tform [ 'data_to_scrollbar' ]
# calculate the corners of the entire image in unscaled cartesian
mxwd , mxht = limits [ 1 ] [ : 2 ]
mxwd , mxht = mxwd + pad , mxht + pad
mnwd , mnht = limits [ 0 ] [ : 2 ]
mnwd , mnht = mnwd - pad , mnht - pad
arr = np . array ( [ ( mnwd , m... |
def coerce ( self , value , ** kwargs ) :
"""Coerces the value to the proper type .""" | if value is None :
return None
return self . _coercion . coerce ( value , ** kwargs ) |
def get_calculator_impstr ( calculator_name ) :
"""Returns the import string for the calculator""" | if calculator_name . lower ( ) == "gpaw" or calculator_name is None :
return "from gpaw import GPAW as custom_calculator"
elif calculator_name . lower ( ) == "espresso" :
return "from espresso import espresso as custom_calculator"
else :
possibilities = { "abinit" : "abinit.Abinit" , "aims" : "aims.Aims" , ... |
def get_likes ( self , offset = 0 , limit = 50 ) :
"""Get user ' s likes .""" | response = self . client . get ( self . client . USER_LIKES % ( self . name , offset , limit ) )
return self . _parse_response ( response , strack ) |
def vacuum ( self , threshold = 0.3 ) :
'''Force garbage collection
: param float threshold ( optional ) : The threshold is optional , and
will not change the default threshold .
: rtype : boolean''' | url = ( "http://{master_addr}:{master_port}/" "vol/vacuum?garbageThreshold={threshold}" ) . format ( master_addr = self . master_addr , master_port = self . master_port , threshold = threshold )
res = self . conn . get_data ( url )
if res is not None :
return True
return False |
def create ( cls , propertyfile , allow_unknown ) :
"""Create a Property instance by attempting to parse the given property file .
@ param propertyfile : A file name of a property file
@ param allow _ unknown : Whether to accept unknown properties""" | with open ( propertyfile ) as f :
content = f . read ( ) . strip ( )
# parse content for known properties
is_svcomp = False
known_properties = [ ]
only_known_svcomp_property = True
if content == 'OBSERVER AUTOMATON' or content == 'SATISFIABLE' :
known_properties = [ _PROPERTY_NAMES [ content ] ]
elif content . ... |
def children_sum ( self , children , node ) :
"""Calculate children ' s total sum""" | return sum ( [ self . value ( value , node ) for value in children ] ) |
def read ( self , session , count ) :
"""Reads data from device or interface synchronously .
Corresponds to viRead function of the VISA library .
: param session : Unique logical identifier to a session .
: param count : Number of bytes to be read .
: return : data read , return value of the library call . ... | # from the session handle , dispatch to the read method of the session object .
try :
ret = self . sessions [ session ] . read ( count )
except KeyError :
return 0 , StatusCode . error_invalid_object
if ret [ 1 ] < 0 :
raise errors . VisaIOError ( ret [ 1 ] )
return ret |
def make_data ( n , width ) :
"""make _ data : compute matrix distance and time windows .""" | x = dict ( [ ( i , 100 * random . random ( ) ) for i in range ( 1 , n + 1 ) ] )
y = dict ( [ ( i , 100 * random . random ( ) ) for i in range ( 1 , n + 1 ) ] )
c = { }
for i in range ( 1 , n + 1 ) :
for j in range ( 1 , n + 1 ) :
if j != i :
c [ i , j ] = distance ( x [ i ] , y [ i ] , x [ j ] ,... |
def make_aliased_type ( cls , other_base ) :
"""Factory for making Aliased { Filter , Factor , Classifier } .""" | docstring = dedent ( """
A {t} that names another {t}.
Parameters
----------
term : {t}
{{name}}
""" ) . format ( t = other_base . __name__ )
doc = format_docstring ( owner_name = other_base . __name__ , docstring = docstring , formatters = { 'nam... |
def sendPdu ( self , snmpEngine , transportDomain , transportAddress , messageProcessingModel , securityModel , securityName , securityLevel , contextEngineId , contextName , pduVersion , PDU , expectResponse , timeout = 0 , cbFun = None , cbCtx = None ) :
"""PDU dispatcher - - prepare and serialize a request or no... | # 4.1.1.2
k = int ( messageProcessingModel )
if k in snmpEngine . messageProcessingSubsystems :
mpHandler = snmpEngine . messageProcessingSubsystems [ k ]
else :
raise error . StatusInformation ( errorIndication = errind . unsupportedMsgProcessingModel )
debug . logger & debug . FLAG_DSP and debug . logger ( 's... |
def emitTriggered ( self , action ) :
"""Emits the triggered action for this widget .
: param action | < QAction >""" | self . currentActionChanged . emit ( action )
self . currentIndexChanged . emit ( self . indexOf ( action ) )
if not self . signalsBlocked ( ) :
self . triggered . emit ( action ) |
def build ( self , builder ) :
"""Build XML by appending to builder""" | params = dict ( StudyEventOID = self . oid , Mandatory = bool_to_yes_no ( self . mandatory ) )
if self . _order_number is not None :
params [ "OrderNumber" ] = self . _order_number
builder . start ( "StudyEventRef" , params )
builder . end ( "StudyEventRef" ) |
def get_content ( path ) :
"""Get content of file .""" | with codecs . open ( abs_path ( path ) , encoding = 'utf-8' ) as f :
return f . read ( ) |
def make_classify_tab ( self ) :
"""initial set up of classification tab""" | self . pick_frame = tk . Frame ( self . tab_classify )
self . pick_frame2 = tk . Frame ( self . tab_classify )
self . solar_class_var = tk . IntVar ( )
self . solar_class_var . set ( 0 )
# initialize to unlabeled
buttonnum = 0
frame = [ self . pick_frame , self . pick_frame2 ]
for text , value in self . config . solar_... |
def _validate_virtual_media ( self , device ) :
"""Check if the device is valid device .
: param device : virtual media device
: raises : IloInvalidInputError , if the device is not valid .""" | if device not in VIRTUAL_MEDIA_MAP :
msg = ( self . _ ( "Invalid device '%s'. Valid devices: FLOPPY or " "CDROM." ) % device )
LOG . debug ( msg )
raise exception . IloInvalidInputError ( msg ) |
def get_pool_size ( usr_config_value , num_tasks ) :
"""Determine size of thread / process - pool for parallel processing .
This examines the cpu _ count to decide and return the right pool
size to use . Also take into account the user ' s wishes via the config
object value , if specified . On top of that , d... | if not can_parallel :
return 1
# Give priority to their specified cfg value , over the actual cpu count
if usr_config_value is not None :
if num_tasks is None :
return usr_config_value
else : # usr _ config _ value may be needlessly high
return min ( usr_config_value , num_tasks )
# they hav... |
def _send ( self , data , msg_type = 'ok' , silent = False ) :
"""Send a response to the frontend and return an execute message
@ param data : response to send
@ param msg _ type ( str ) : message type : ' ok ' , ' raw ' , ' error ' , ' multi '
@ param silent ( bool ) : suppress output
@ return ( dict ) : t... | # Data to send back
if data is not None : # log the message
try :
self . _klog . debug ( u"msg to frontend (%d): %.160s..." , silent , data )
except Exception as e :
self . _klog . warn ( u"can't log response: %s" , e )
# send it to the frontend
if not silent :
if msg_type != 'ra... |
def _convert_to_list ( self , stanza_key , name_key ) :
"""Convert self [ stanza _ key ] to a list . For each k , v
k , v = self [ stanza _ key ] . iteritems ( ) assign
v [ name _ key ] = k""" | converted_list = [ ]
for k , v in self . get ( stanza_key , { } ) . iteritems ( ) :
v [ name_key ] = k
converted_list . append ( v )
return converted_list |
def detect_fold_level ( self , prev_block , block ) :
"""Detects fold level by looking at the block indentation .
: param prev _ block : previous text block
: param block : current block to highlight""" | text = block . text ( )
prev_lvl = TextBlockHelper ( ) . get_fold_lvl ( prev_block )
# round down to previous indentation guide to ensure contiguous block
# fold level evolution .
indent_len = 0
if ( prev_lvl and prev_block is not None and not self . editor . is_comment ( prev_block ) ) : # ignore commented lines ( cou... |
def randomise_branch_lengths ( self , i = ( 1 , 1 ) , l = ( 1 , 1 ) , distribution_func = random . gammavariate , inplace = False , ) :
"""Replaces branch lengths with values drawn from the specified
distribution _ func . Parameters of the distribution are given in the
tuples i and l , for interior and leaf nod... | if not inplace :
t = self . copy ( )
else :
t = self
for n in t . _tree . preorder_node_iter ( ) :
if n . is_internal ( ) :
n . edge . length = max ( 0 , distribution_func ( * i ) )
else :
n . edge . length = max ( 0 , distribution_func ( * l ) )
t . _dirty = True
return t |
def get_event ( self ) :
'''return next event or None''' | if self . event_queue . qsize ( ) == 0 :
return None
evt = self . event_queue . get ( )
while isinstance ( evt , win_layout . WinLayout ) :
win_layout . set_layout ( evt , self . set_layout )
if self . event_queue . qsize ( ) == 0 :
return None
evt = self . event_queue . get ( )
return evt |
def science_object_update ( self , pid_old , path , pid_new , format_id = None ) :
"""Obsolete a Science Object on a Member Node with a different one .""" | self . _queue_science_object_update ( pid_old , path , pid_new , format_id ) |
def exists ( self ) :
"""Uses ` ` HEAD ` ` requests for efficiency .""" | try :
self . s3_object . load ( )
return True
except botocore . exceptions . ClientError :
return False |
def MemoryExceeded ( self ) :
"""Returns True if our memory footprint is too large .""" | rss_size = self . proc . memory_info ( ) . rss
return rss_size // 1024 // 1024 > config . CONFIG [ "Client.rss_max" ] |
def parse_subject ( content , reference_id = None , clean = True ) :
"""Parses and returns the subject of a cable . If the cable has no subject , an
empty string is returned .
` content `
The cable ' s content .
` reference _ id `
The ( optional ) reference id of the cable . Used for error msgs
` clean ... | def to_unicodechar ( match ) :
return unichr ( int ( match . group ( 1 ) ) )
m = _SUBJECT_MAX_PATTERN . search ( content )
max_idx = m . start ( ) if m else _MAX_HEADER_IDX
m = _SUBJECT_PATTERN . search ( content , 0 , max_idx )
if not m :
return u''
res = m . group ( 1 ) . strip ( )
res = _NL_PATTERN . sub ( u... |
def shellPrintOverview ( g , opts = { 'labels' : False } ) :
"""overview of graph invoked from command line
@ todo
add pagination via something like this
# import pydoc
# pydoc . pager ( " SOME _ VERY _ LONG _ TEXT " )""" | ontologies = g . all_ontologies
# get opts
try :
labels = opts [ 'labels' ]
except :
labels = False
print ( Style . BRIGHT + "Namespaces\n-----------" + Style . RESET_ALL )
if g . namespaces :
for p , u in g . namespaces :
row = Fore . GREEN + "%s" % p + Fore . BLACK + " %s" % u + Fore . RESET
... |
def loglevel ( leveltype = None , isequal = False ) :
"""Set or get the logging level of Quilt
: type leveltype : string or integer
: param leveltype : Choose the logging level . Possible choices are none ( 0 ) , debug ( 10 ) , info ( 20 ) , warning ( 30 ) , error ( 40 ) and critical ( 50 ) .
: type isequal :... | log = logging . getLogger ( __name__ )
leveltype = leveltype
loglevels = { "none" : 0 , "debug" : 10 , "info" : 20 , "warning" : 30 , "error" : 40 , "critical" : 50 }
if leveltype is None and isequal is False :
return log . getEffectiveLevel ( )
if leveltype is not None and isequal is True :
if leveltype in log... |
def compare ( what , imt , calc_ids , files , samplesites = 100 , rtol = .1 , atol = 1E-4 ) :
"""Compare the hazard curves or maps of two or more calculations""" | sids , imtls , poes , arrays = getdata ( what , calc_ids , samplesites )
try :
levels = imtls [ imt ]
except KeyError :
sys . exit ( '%s not found. The available IMTs are %s' % ( imt , list ( imtls ) ) )
imt2idx = { imt : i for i , imt in enumerate ( imtls ) }
head = [ 'site_id' ] if files else [ 'site_id' , 'c... |
async def open ( self ) -> 'Issuer' :
"""Explicit entry . Perform ancestor opening operations ,
then synchronize revocation registry to tails tree content .
: return : current object""" | LOGGER . debug ( 'Issuer.open >>>' )
await super ( ) . open ( )
for path_rr_id in Tails . links ( self . _dir_tails , self . did ) :
await self . _sync_revoc ( basename ( path_rr_id ) )
LOGGER . debug ( 'Issuer.open <<<' )
return self |
def unsubscribe ( self , channel ) :
"""Remove the channel from this socket ' s channels , and from the
list of subscribed session IDs for the channel . Return False
if not subscribed , otherwise True .""" | try :
CHANNELS [ channel ] . remove ( self . socket . session . session_id )
self . channels . remove ( channel )
except ValueError :
return False
return True |
def _create_network_interface ( self , ip_config_name , nic_name , public_ip , region , resource_group_name , subnet , accelerated_networking = False ) :
"""Create a network interface in the resource group .
Attach NIC to the subnet and public IP provided .""" | nic_config = { 'location' : region , 'ip_configurations' : [ { 'name' : ip_config_name , 'private_ip_allocation_method' : 'Dynamic' , 'subnet' : { 'id' : subnet . id } , 'public_ip_address' : { 'id' : public_ip . id } , } ] }
if accelerated_networking :
nic_config [ 'enable_accelerated_networking' ] = True
try :
... |
def imshow ( x , y , z , ax , ** kwargs ) :
"""Image plot of 2d DataArray using matplotlib . pyplot
Wraps : func : ` matplotlib : matplotlib . pyplot . imshow `
While other plot methods require the DataArray to be strictly
two - dimensional , ` ` imshow ` ` also accepts a 3D array where some
dimension can b... | if x . ndim != 1 or y . ndim != 1 :
raise ValueError ( 'imshow requires 1D coordinates, try using ' 'pcolormesh or contour(f)' )
# Centering the pixels - Assumes uniform spacing
try :
xstep = ( x [ 1 ] - x [ 0 ] ) / 2.0
except IndexError : # Arbitrary default value , similar to matplotlib behaviour
xstep = ... |
def create_table ( self , dataset , table , schema , expiration_time = None , time_partitioning = False , project_id = None ) :
"""Create a new table in the dataset .
Parameters
dataset : str
The dataset to create the table in
table : str
The name of the table to create
schema : dict
The table schema ... | project_id = self . _get_project_id ( project_id )
body = { 'schema' : { 'fields' : schema } , 'tableReference' : { 'tableId' : table , 'projectId' : project_id , 'datasetId' : dataset } }
if expiration_time is not None :
body [ 'expirationTime' ] = expiration_time
if time_partitioning :
body [ 'timePartitionin... |
def parse_cctop_regions ( infile ) :
"""Parse a CCTOP XML results file and return a dictionary of labeled TM domains in the format : :
{ ' I1 ' : [ 31 , 32 , 33 , 34 , 35 , 36 ] ,
' I2 ' : [ 73 , 74 , 75 , 76 , 77 , 78 ] ,
' I3 ' : [ 133 , . . . ] ,
Where the regions are labeled as they are sequentially fou... | parsed = parse_cctop_full ( infile )
if not parsed :
return { }
return ssbio . utils . label_sequential_regions ( parsed ) |
def create_instance ( cls , values , classname = "weka.core.DenseInstance" , weight = 1.0 ) :
"""Creates a new instance .
: param values : the float values ( internal format ) to use , numpy array or list .
: type values : ndarray or list
: param classname : the classname of the instance ( eg weka . core . De... | jni_classname = classname . replace ( "." , "/" )
if type ( values ) is list :
for i in range ( len ( values ) ) :
values [ i ] = float ( values [ i ] )
values = numpy . array ( values )
return Instance ( javabridge . make_instance ( jni_classname , "(D[D)V" , weight , javabridge . get_env ( ) . make_do... |
def find_max ( num1 , num2 ) :
"""A Python function to find the greater of two numbers .
Args :
num1 : The first number .
num2 : The second number .
Examples :
find _ max ( 5 , 10 ) - > 10
find _ max ( - 1 , - 2 ) - > - 1
find _ max ( 9 , 7 ) - > 9
Returns :
The largest of the two input numbers ."... | return num1 if num1 >= num2 else num2 |
def is_address_executable ( self , address ) :
"""Determines if an address belongs to a commited and executable page .
The page may or may not have additional permissions .
@ note : Returns always C { False } for kernel mode addresses .
@ type address : int
@ param address : Memory address to query .
@ rt... | try :
mbi = self . mquery ( address )
except WindowsError :
e = sys . exc_info ( ) [ 1 ]
if e . winerror == win32 . ERROR_INVALID_PARAMETER :
return False
raise
return mbi . is_executable ( ) |
def setJobGroup ( self , groupId , description , interruptOnCancel = False ) :
"""Assigns a group ID to all the jobs started by this thread until the group ID is set to a
different value or cleared .
Often , a unit of execution in an application consists of multiple Spark actions or jobs .
Application program... | self . _jsc . setJobGroup ( groupId , description , interruptOnCancel ) |
def get_market_iex_volume ( * args , ** kwargs ) :
"""MOVED to iexfinance . stocks . get _ market _ iex _ volume""" | import warnings
warnings . warn ( WNG_MSG , ( "get_market_iex_volume" , "stocks.get_market_iex_volume" ) )
return stocks . get_market_iex_volume ( * args , ** kwargs ) |
def extract_path_info ( environ_or_baseurl , path_or_url , charset = 'utf-8' , errors = 'replace' , collapse_http_schemes = True ) :
"""Extracts the path info from the given URL ( or WSGI environment ) and
path . The path info returned is a unicode string , not a bytestring
suitable for a WSGI environment . The... | def _normalize_netloc ( scheme , netloc ) :
parts = netloc . split ( u'@' , 1 ) [ - 1 ] . split ( u':' , 1 )
if len ( parts ) == 2 :
netloc , port = parts
if ( scheme == u'http' and port == u'80' ) or ( scheme == u'https' and port == u'443' ) :
port = None
else :
netloc =... |
def _get_log_entries ( self ) -> List [ Tuple [ int , bytes , List [ int ] , bytes ] ] :
"""Return the log entries for this computation and its children .
They are sorted in the same order they were emitted during the transaction processing , and
include the sequential counter as the first element of the tuple ... | if self . is_error :
return [ ]
else :
return sorted ( itertools . chain ( self . _log_entries , * ( child . _get_log_entries ( ) for child in self . children ) ) ) |
def overlay_mask ( self , image , predictions ) :
"""Adds the instances contours for each predicted object .
Each label has a different color .
Arguments :
image ( np . ndarray ) : an image as returned by OpenCV
predictions ( BoxList ) : the result of the computation by the model .
It should contain the f... | masks = predictions . get_field ( "mask" ) . numpy ( )
labels = predictions . get_field ( "labels" )
colors = self . compute_colors_for_labels ( labels ) . tolist ( )
for mask , color in zip ( masks , colors ) :
thresh = mask [ 0 , : , : , None ]
contours , hierarchy = cv2_util . findContours ( thresh , cv2 . R... |
def _check_filter_includes ( self , includes : list , resource : str = "metadata" ) :
"""Check if specific _ resources parameter is valid .
: param list includes : sub resources to check
: param str resource : resource type to check sub resources .
Must be one of : metadata | keyword .""" | # check resource parameter
if resource == "metadata" :
ref_subresources = _SUBRESOURCES_MD
elif resource == "keyword" :
ref_subresources = _SUBRESOURCES_KW
else :
raise ValueError ( "Must be one of: metadata | keyword." )
# sub resources manager
if isinstance ( includes , str ) and includes . lower ( ) == "... |
def ports_as_list ( port_str ) :
"""Parses a ports string into two list of individual tcp and udp ports .
@ input string containing a port list
e . g . T : 1,2,3,5-8 U : 22,80,600-1024
@ return two list of sorted integers , for tcp and udp ports respectively .""" | if not port_str :
LOGGER . info ( "Invalid port value" )
return [ None , None ]
if ports_str_check_failed ( port_str ) :
LOGGER . info ( "{0}: Port list malformed." )
return [ None , None ]
tcp_list = list ( )
udp_list = list ( )
ports = port_str . replace ( ' ' , '' )
b_tcp = ports . find ( "T" )
b_udp... |
def summary ( self , raw ) :
"""Return one taxonomy summarizing the reported tags
If there is only one tag , use it as the predicate
If there are multiple tags , use " entries " as the predicate
Use the total count as the value
Use the most malicious level found
Examples :
Input
" name " : SCANNER1,
... | try :
taxonomies = [ ]
if raw . get ( 'records' ) :
final_level = None
taxonomy_data = defaultdict ( int )
for record in raw . get ( 'records' , [ ] ) :
name = record . get ( 'name' , 'unknown' )
intention = record . get ( 'intention' , 'unknown' )
tax... |
def is_generic_type ( tp ) :
"""Test if the given type is a generic type . This includes Generic itself , but
excludes special typing constructs such as Union , Tuple , Callable , ClassVar .
Examples : :
is _ generic _ type ( int ) = = False
is _ generic _ type ( Union [ int , str ] ) = = False
is _ gener... | if NEW_TYPING :
return ( isinstance ( tp , type ) and issubclass ( tp , Generic ) or isinstance ( tp , _GenericAlias ) and tp . __origin__ not in ( Union , tuple , ClassVar , collections . abc . Callable ) )
# SMA : refering to is _ callable _ type and is _ tuple _ type to avoid duplicate code
return isinstance ( t... |
def add_bands ( data , bands ) :
"""Add bands so that they match * bands *""" | # Add R , G and B bands , remove L band
if 'L' in data [ 'bands' ] . data and 'R' in bands . data :
lum = data . sel ( bands = 'L' )
new_data = xr . concat ( ( lum , lum , lum ) , dim = 'bands' )
new_data [ 'bands' ] = [ 'R' , 'G' , 'B' ]
data = new_data
# Add alpha band
if 'A' not in data [ 'bands' ] .... |
def _arrange_xfms ( transforms , num_files , tmp_folder ) :
"""Convenience method to arrange the list of transforms that should be applied
to each input file""" | base_xform = [ '#Insight Transform File V1.0' , '#Transform 0' ]
# Initialize the transforms matrix
xfms_T = [ ]
for i , tf_file in enumerate ( transforms ) : # If it is a deformation field , copy to the tfs _ matrix directly
if guess_type ( tf_file ) [ 0 ] != 'text/plain' :
xfms_T . append ( [ tf_file ] * ... |
def iflat_tasks ( self , status = None , op = "==" , nids = None ) :
"""Generator to iterate over all the tasks of the : class : ` Flow ` .
If status is not None , only the tasks whose status satisfies
the condition ( task . status op status ) are selected
status can be either one of the flags defined in the ... | return self . _iflat_tasks_wti ( status = status , op = op , nids = nids , with_wti = False ) |
def sync_unwanted ( database ) :
"""Context manager for preventing unwanted sync queries .
` UnwantedSyncQueryError ` exception will raise on such query .
NOTE : sync _ unwanted ( ) context manager is * * deprecated * * , use
database ' s ` . allow _ sync ( ) ` context manager or ` Manager . allow _ sync ( ) ... | warnings . warn ( "sync_unwanted() context manager is deprecated, " "use database's `.allow_sync()` context manager or " "`Manager.allow_sync()` context manager. " , DeprecationWarning )
old_allow_sync = database . _allow_sync
database . _allow_sync = False
yield
database . _allow_sync = old_allow_sync |
def write_lammpsdata ( structure , filename , atom_style = 'full' ) :
"""Output a LAMMPS data file .
Outputs a LAMMPS data file in the ' full ' atom style format . Assumes use
of ' real ' units . See http : / / lammps . sandia . gov / doc / atom _ style . html for
more information on atom styles .
Parameter... | if atom_style not in [ 'atomic' , 'charge' , 'molecular' , 'full' ] :
raise ValueError ( 'Atom style "{}" is invalid or is not currently supported' . format ( atom_style ) )
xyz = np . array ( [ [ atom . xx , atom . xy , atom . xz ] for atom in structure . atoms ] )
forcefield = True
if structure [ 0 ] . type == ''... |
def _get_time ( header , keys , name ) :
"""Get time from header
Args :
header ( dict ) : Object header .
keys ( tuple of str ) : Header keys .
name ( str ) : Method name .
Returns :
float : The number of seconds since the epoch""" | for key in keys :
try :
return _to_timestamp ( header . pop ( key ) )
except KeyError :
continue
raise _UnsupportedOperation ( name ) |
def check_payment ( state_engine , state_op_type , nameop , fee_block_id , token_address , burn_address , name_fee , block_id ) :
"""Verify that the right payment was made , in the right cryptocurrency units .
Does not check any accounts or modify the nameop in any way ; it only checks that the name was paid for ... | assert state_op_type in [ 'NAME_REGISTRATION' , 'NAME_RENEWAL' ] , 'Invalid op type {}' . format ( state_op_type )
assert name_fee is not None
assert isinstance ( name_fee , ( int , long ) )
name = nameop [ 'name' ]
namespace_id = get_namespace_from_name ( name )
namespace = state_engine . get_namespace ( namespace_id ... |
def dump_all ( documents , stream = None , Dumper = Dumper , default_style = None , default_flow_style = None , canonical = None , indent = None , width = None , allow_unicode = None , line_break = None , encoding = 'utf-8' , explicit_start = None , explicit_end = None , version = None , tags = None ) :
"""Serializ... | getvalue = None
if stream is None :
if encoding is None :
from StringIO import StringIO
else :
from cStringIO import StringIO
stream = StringIO ( )
getvalue = stream . getvalue
dumper = Dumper ( stream , default_style = default_style , default_flow_style = default_flow_style , canonical ... |
def fibs ( n , m ) :
"""Yields Fibonacci numbers starting from ` ` n ` ` and ending at ` ` m ` ` .""" | a = b = 1
for x in range ( 3 , m + 1 ) :
a , b = b , a + b
if x >= n :
yield b |
def missingDataValue ( self ) :
"""Returns the value to indicate missing data . None if no missing - data value is specified .""" | value = variableMissingValue ( self . _ncVar )
fieldNames = self . _ncVar . dtype . names
# If the missing value attibute is a list with the same length as the number of fields ,
# return the missing value for field that equals the self . nodeName .
if hasattr ( value , '__len__' ) and len ( value ) == len ( fieldNames... |
def _textParameterToView ( parameter ) :
"""Return a L { TextParameterView } adapter for C { TEXT _ INPUT } , C { PASSWORD _ INPUT } ,
and C { FORM _ INPUT } L { Parameter } instances .""" | if parameter . type == TEXT_INPUT :
return TextParameterView ( parameter )
if parameter . type == PASSWORD_INPUT :
return PasswordParameterView ( parameter )
if parameter . type == FORM_INPUT :
return FormInputParameterView ( parameter )
return None |
def get_instance ( self , payload ) :
"""Build an instance of WorkflowInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . taskrouter . v1 . workspace . workflow . WorkflowInstance
: rtype : twilio . rest . taskrouter . v1 . workspace . workflow . WorkflowInstance""" | return WorkflowInstance ( self . _version , payload , workspace_sid = self . _solution [ 'workspace_sid' ] , ) |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'input' ) and self . input is not None :
_dict [ 'input' ] = self . input . _to_dict ( )
return _dict |
def pow ( requestContext , seriesList , factor ) :
"""Takes one metric or a wildcard seriesList followed by a constant , and
raises the datapoint by the power of the constant provided at each point .
Example : :
& target = pow ( Server . instance01 . threads . busy , 10)
& target = pow ( Server . instance *... | for series in seriesList :
series . name = "pow(%s,%g)" % ( series . name , float ( factor ) )
series . pathExpression = series . name
for i , value in enumerate ( series ) :
series [ i ] = safePow ( value , factor )
return seriesList |
def do_set ( self , params ) :
"""\x1b [1mNAME \x1b [0m
set - Updates the znode ' s value
\x1b [1mSYNOPSIS \x1b [0m
set < path > < value > [ version ]
\x1b [1mOPTIONS \x1b [0m
* version : only update if version matches ( default : - 1)
\x1b [1mEXAMPLES \x1b [0m
> set / foo ' bar '
> set / foo ' very... | self . set ( params . path , decoded ( params . value ) , version = params . version ) |
def configure ( self , app ) :
'''Load configuration from application configuration .
For each storage , the configuration is loaded with the following pattern : :
FS _ { BACKEND _ NAME } _ { KEY } then
{ STORAGE _ NAME } _ FS _ { KEY }
If no configuration is set for a given key , global config is taken as ... | config = Config ( )
prefix = PREFIX . format ( self . name . upper ( ) )
backend_key = '{0}BACKEND' . format ( prefix )
self . backend_name = app . config . get ( backend_key , app . config [ 'FS_BACKEND' ] )
self . backend_prefix = BACKEND_PREFIX . format ( self . backend_name . upper ( ) )
backend_excluded_keys = [ '... |
def search ( self , params , validate = False ) :
"""Return a generator of section objects for the given search params .
: param params : Dictionary of course search parameters .
: param validate : Optional . Set to true to enable request validation .
> > > cis100s = r . search ( { ' course _ id ' : ' cis ' ,... | if self . val_info is None :
self . val_info = self . search_params ( )
if validate :
errors = self . validate ( self . val_info , params )
if not validate or len ( errors ) == 0 :
return self . _iter_response ( ENDPOINTS [ 'SEARCH' ] , params )
else :
return { 'Errors' : errors } |
def get_groups ( self ) :
"""Get groups via provisioning API .
If you get back an error 999 , then the provisioning API is not enabled .
: returns : list of groups
: raises : HTTPResponseError in case an HTTP error status was returned""" | res = self . _make_ocs_request ( 'GET' , self . OCS_SERVICE_CLOUD , 'groups' )
if res . status_code == 200 :
tree = ET . fromstring ( res . content )
groups = [ x . text for x in tree . findall ( 'data/groups/element' ) ]
return groups
raise HTTPResponseError ( res ) |
def _update_physical_disk_details ( raid_config , server ) :
"""Adds the physical disk details to the RAID configuration passed .""" | raid_config [ 'physical_disks' ] = [ ]
physical_drives = server . get_physical_drives ( )
for physical_drive in physical_drives :
physical_drive_dict = physical_drive . get_physical_drive_dict ( )
raid_config [ 'physical_disks' ] . append ( physical_drive_dict ) |
def __valid_url ( cls , url ) :
"""Expects input to already be a valid string""" | bits = urlparse ( url )
return ( ( bits . scheme == "http" or bits . scheme == "https" ) and _PATTERN_URL_PART . match ( bits . netloc ) and _PATTERN_URL_PART . match ( bits . path ) ) |
def check_env_cache ( opts , env_cache ) :
'''Returns cached env names , if present . Otherwise returns None .''' | if not os . path . isfile ( env_cache ) :
return None
try :
with salt . utils . files . fopen ( env_cache , 'rb' ) as fp_ :
log . trace ( 'Returning env cache data from %s' , env_cache )
serial = salt . payload . Serial ( opts )
return salt . utils . data . decode ( serial . load ( fp_ )... |
def fetch_transaction_status ( self , transaction_id ) :
"""Get the transaction current status .
: param transaction _ id :
: return :""" | url = "%s%s%s/status" % ( self . api_endpoint , constants . TRANSACTION_STATUS_ENDPOINT , transaction_id )
username = self . base . get_username ( )
password = self . base . get_password ( username = username , request_url = url )
response = requests . get ( url , auth = HTTPBasicAuth ( username = username , password =... |
def ParseOptions ( cls , options , output_module ) :
"""Parses and validates options .
Args :
options ( argparse . Namespace ) : parser options .
output _ module ( OutputModule ) : output module to configure .
Raises :
BadConfigObject : when the output module object is of the wrong type .
BadConfigOptio... | if not isinstance ( output_module , sqlite_4n6time . SQLite4n6TimeOutputModule ) :
raise errors . BadConfigObject ( 'Output module is not an instance of SQLite4n6TimeOutputModule' )
shared_4n6time_output . Shared4n6TimeOutputArgumentsHelper . ParseOptions ( options , output_module )
filename = getattr ( options , '... |
def set_of_vars ( lovs ) :
"""Build set of variables from list .
Args :
lovs : nested lists of variables such as the one produced by
: func : ` list _ of _ vars ` .
Returns :
set of str : flattened set of all the variables present in the
nested lists .""" | return set ( var for pvars in lovs for svars in pvars for var in svars ) |
def fill_profile ( profile , array , weights = None , return_indices = False ) :
"""Fill a ROOT profile with a NumPy array .
Parameters
profile : ROOT TProfile , TProfile2D , or TProfile3D
The ROOT profile to fill .
array : numpy array of shape [ n _ samples , n _ dimensions ]
The values to fill the histo... | import ROOT
array = np . asarray ( array , dtype = np . double )
if array . ndim != 2 :
raise ValueError ( "array must be 2-dimensional" )
if array . shape [ 1 ] != profile . GetDimension ( ) + 1 :
raise ValueError ( "there must be one more column than the " "dimensionality of the profile" )
if weights is not N... |
def guest_reboot ( self , userid ) :
"""Reboot a guest vm .""" | LOG . info ( "Begin to reboot vm %s" , userid )
self . _smtclient . guest_reboot ( userid )
LOG . info ( "Complete reboot vm %s" , userid ) |
def is_volume ( self ) :
"""Check if a mesh has all the properties required to represent
a valid volume , rather than just a surface .
These properties include being watertight , having consistent
winding and outward facing normals .
Returns
valid : bool
Does the mesh represent a volume""" | valid = bool ( self . is_watertight and self . is_winding_consistent and np . isfinite ( self . center_mass ) . all ( ) and self . volume > 0.0 )
return valid |
def on_train_end ( self , ** kwargs : Any ) -> None :
"Cleanup learn model weights disturbed during LRFinder exploration ." | self . learn . load ( 'tmp' , purge = False )
if hasattr ( self . learn . model , 'reset' ) :
self . learn . model . reset ( )
for cb in self . callbacks :
if hasattr ( cb , 'reset' ) :
cb . reset ( )
print ( 'LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.' ) |
def augmented_dickey_fuller ( x , param ) :
"""The Augmented Dickey - Fuller test is a hypothesis test which checks whether a unit root is present in a time
series sample . This feature calculator returns the value of the respective test statistic .
See the statsmodels implementation for references and more det... | res = None
try :
res = adfuller ( x )
except LinAlgError :
res = np . NaN , np . NaN , np . NaN
except ValueError : # occurs if sample size is too small
res = np . NaN , np . NaN , np . NaN
except MissingDataError : # is thrown for e . g . inf or nan in the data
res = np . NaN , np . NaN , np . NaN
retu... |
def decode ( cls , line ) :
"""Remove backslash escaping from line . value .""" | if line . encoded :
encoding = getattr ( line , 'encoding_param' , None )
if encoding and encoding . upper ( ) == cls . base64string :
line . value = b64decode ( line . value )
else :
line . value = stringToTextValues ( line . value ) [ 0 ]
line . encoded = False |
def add_upsert ( self , action , meta_action , doc_source , update_spec ) :
"""Function which stores sources for " insert " actions
and decide if for " update " action has to add docs to
get source buffer""" | # Whenever update _ spec is provided to this method
# it means that doc source needs to be retrieved
# from Elasticsearch . It means also that source
# is not stored in local buffer
if update_spec :
self . bulk_index ( action , meta_action )
# -1 - > to get latest index number
# -1 - > to get action instead... |
def _check_error ( response ) :
"""Raises an exception if the Spark Cloud returned an error .""" | if ( not response . ok ) or ( response . status_code != 200 ) :
raise Exception ( response . json ( ) [ 'error' ] + ': ' + response . json ( ) [ 'error_description' ] ) |
def get_sigma_tables ( self , imt , rctx , stddev_types ) :
"""Returns modification factors for the standard deviations , given the
rupture and intensity measure type .
: returns :
List of standard deviation modification tables , each as an array
of [ Number Distances , Number Levels ]""" | output_tables = [ ]
for stddev_type in stddev_types : # For PGA and PGV only needs to apply magnitude interpolation
if imt . name in 'PGA PGV' :
interpolator = interp1d ( self . magnitudes , self . sigma [ stddev_type ] [ imt . name ] , axis = 2 )
output_tables . append ( interpolator ( rctx . mag )... |
def read ( filename ) :
"""reads a Horn SAT formula from a text file
: file format :
# comment
A # clause with unique positive literal
: - A # clause with unique negative literal
A : - B , C , D # clause where A is positive and B , C , D negative
# variables are strings without spaces""" | formula = [ ]
for line in open ( filename , 'r' ) :
line = line . strip ( )
if line [ 0 ] == "#" :
continue
lit = line . split ( ":-" )
if len ( lit ) == 1 :
posvar = lit [ 0 ]
negvars = [ ]
else :
assert len ( lit ) == 2
posvar = lit [ 0 ] . strip ( )
... |
def get_raise_description_indexes ( self , data , prev = None ) :
"""Get from a docstring the next raise ' s description .
In javadoc style it is after @ param .
: param data : string to parse
: param prev : index after the param element name ( Default value = None )
: returns : start and end indexes of fou... | start , end = - 1 , - 1
if not prev :
_ , prev = self . get_raise_indexes ( data )
if prev < 0 :
return - 1 , - 1
m = re . match ( r'\W*(\w+)' , data [ prev : ] )
if m :
first = m . group ( 1 )
start = data [ prev : ] . find ( first )
if start >= 0 :
start += prev
if self . style [ '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.