signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def cursor ( self , query , * args , prefetch = None , timeout = None ) :
"""Return a * cursor factory * for the specified query .
: param args : Query arguments .
: param int prefetch : The number of rows the * cursor iterator *
will prefetch ( defaults to ` ` 50 ` ` . )
: param float timeout : Optional ti... | self . _check_open ( )
return cursor . CursorFactory ( self , query , None , args , prefetch , timeout ) |
def handle_label_relation ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults :
"""Handle statements like ` ` p ( X ) label " Label for X " ` ` .
: raises : RelabelWarning""" | subject_node_dsl = self . ensure_node ( tokens [ SUBJECT ] )
description = tokens [ OBJECT ]
if self . graph . has_node_description ( subject_node_dsl ) :
raise RelabelWarning ( line_number = self . get_line_number ( ) , line = line , position = position , node = self . graph . node , old_label = self . graph . get... |
def prepare ( self , data_batch , sparse_row_id_fn = None ) :
'''Prepares the module for processing a data batch .
Usually involves switching bucket and reshaping .
For modules that contain ` row _ sparse ` parameters in KVStore ,
it prepares the ` row _ sparse ` parameters based on the sparse _ row _ id _ fn... | # perform bind if haven ' t done so
assert self . binded and self . params_initialized
bucket_key = data_batch . bucket_key
original_bucket_key = self . _curr_bucket_key
data_shapes = data_batch . provide_data
label_shapes = data_batch . provide_label
self . switch_bucket ( bucket_key , data_shapes , label_shapes )
sel... |
def loadTargets ( self , filename , cols = None , everyNrows = 1 , delim = ' ' , checkEven = 1 ) :
"""Loads targets from file .""" | self . loadTargetsFromFile ( filename , cols , everyNrows , delim , checkEven ) |
def remove_lower_overlapping ( current , higher ) :
"""> > > remove _ lower _ overlapping ( [ ] , [ ( ' a ' , 0 , 5 ) ] )
[ ( ' a ' , 0 , 5 ) ]
> > > remove _ lower _ overlapping ( [ ( ' z ' , 0 , 4 ) ] , [ ( ' a ' , 0 , 5 ) ] )
[ ( ' a ' , 0 , 5 ) ]
> > > remove _ lower _ overlapping ( [ ( ' z ' , 5 , 6 ) ... | for ( match , h_start , h_end ) in higher :
overlaps = list ( overlapping_at ( h_start , h_end , current ) )
for overlap in overlaps :
del current [ overlap ]
if len ( overlaps ) > 0 : # Keeps order in place
current . insert ( overlaps [ 0 ] , ( match , h_start , h_end ) )
else :
... |
def _fix_channels ( op_name , attrs , inputs , proto_obj ) :
"""A workaround for getting ' channels ' or ' units ' since onnx don ' t provide
these attributes . We check the shape of weights provided to get the number .""" | weight_name = inputs [ 1 ] . name
if not weight_name in proto_obj . _params :
raise ValueError ( "Unable to get channels/units attr from onnx graph." )
else :
wshape = proto_obj . _params [ weight_name ] . shape
assert len ( wshape ) >= 2 , "Weights shape is invalid: {}" . format ( wshape )
if op_name =... |
def _ge_from_le ( self , other ) :
"""Return a > = b . Computed by @ total _ ordering from ( not a < = b ) or ( a = = b ) .""" | op_result = self . __le__ ( other )
if op_result is NotImplemented :
return NotImplemented
return not op_result or self == other |
def add_command ( self , command ) :
"""Adds a command to the history and reset history index .""" | try :
self . _history . remove ( command )
except ValueError :
pass
self . _history . insert ( 0 , command )
self . _index = - 1 |
def thing_type_exists ( thingTypeName , region = None , key = None , keyid = None , profile = None ) :
'''Given a thing type name , check to see if the given thing type exists
Returns True if the given thing type exists and returns False if the
given thing type does not exist .
. . versionadded : : 2016.11.0 ... | try :
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
res = conn . describe_thing_type ( thingTypeName = thingTypeName )
if res . get ( 'thingTypeName' ) :
return { 'exists' : True }
else :
return { 'exists' : False }
except ClientError as e :
err... |
def f_comb ( self , pos , sample ) :
"""return the value of the f _ comb when epoch = pos
Parameters
pos : int
the epoch number of the position you want to predict
sample : list
sample is a ( 1 * NUM _ OF _ FUNCTIONS ) matrix , representing { w1 , w2 , . . . wk }
Returns
int
The expected matrix at p... | ret = 0
for i in range ( self . effective_model_num ) :
model = self . effective_model [ i ]
y = self . predict_y ( model , pos )
ret += sample [ i ] * y
return ret |
def _forget_page ( self , page ) :
"""Remove a page from document page dict .""" | pid = id ( page )
if pid in self . _page_refs :
self . _page_refs [ pid ] = None |
def check_mq_connection ( self ) :
"""RabbitMQ checks the connection
It displays on the screen whether or not you have a connection .""" | import pika
from zengine . client_queue import BLOCKING_MQ_PARAMS
from pika . exceptions import ProbableAuthenticationError , ConnectionClosed
try :
connection = pika . BlockingConnection ( BLOCKING_MQ_PARAMS )
channel = connection . channel ( )
if channel . is_open :
print ( __ ( u"{0}RabbitMQ is w... |
def shunting_yard ( expression , named_ranges , ref = None , tokenize_range = False ) :
"""Tokenize an excel formula expression into reverse polish notation
Core algorithm taken from wikipedia with varargs extensions from
http : / / www . kallisti . net . nz / blog / 2008/02 / extension - to - the - shunting - ... | # remove leading =
if expression . startswith ( '=' ) :
expression = expression [ 1 : ]
p = ExcelParser ( tokenize_range = tokenize_range ) ;
p . parse ( expression )
# insert tokens for ' ( ' and ' ) ' , to make things clearer below
tokens = [ ]
for t in p . tokens . items :
if t . ttype == "function" and t . ... |
def disconnect ( self ) :
"""Closes connection to Scratch""" | try : # connection may already be disconnected , so catch exceptions
self . socket . shutdown ( socket . SHUT_RDWR )
# a proper disconnect
except socket . error :
pass
self . socket . close ( )
self . connected = False |
def parse_assign ( string ) :
"""Parse an assignment line :
> > > parse _ assign ( " scenario8 . Actuator _ MagazinVacuumOn = TRUE " )
( " scenario8 . Actuator _ MagazinVacuumOn " , " TRUE " )""" | try :
a , b = string . split ( " = " )
return a . strip ( ) , b . strip ( )
except :
print ( "Error with assignment: %s" % string , file = sys . stderr )
return None , None |
def is_internal_attribute ( obj , attr ) :
"""Test if the attribute given is an internal python attribute . For
example this function returns ` True ` for the ` func _ code ` attribute of
python objects . This is useful if the environment method
: meth : ` ~ SandboxedEnvironment . is _ safe _ attribute ` is o... | if isinstance ( obj , FunctionType ) :
if attr in UNSAFE_FUNCTION_ATTRIBUTES :
return True
elif isinstance ( obj , MethodType ) :
if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES :
return True
elif isinstance ( obj , type ) :
if attr == 'mro' :
return True
el... |
def write ( self , data , debug_info = None ) :
"""Write data to YHSM device .""" | self . num_write_bytes += len ( data )
if self . debug :
if not debug_info :
debug_info = str ( len ( data ) )
sys . stderr . write ( "%s: WRITE %s:\n%s\n" % ( self . __class__ . __name__ , debug_info , pyhsm . util . hexdump ( data ) ) )
return self . ser . write ( data ) |
def check_appt ( self , complex : str , house : str , appt : str ) -> bool :
"""Check if given appartment exists in the rumetr database""" | self . check_house ( complex , house )
if '%s__%s__%s' % ( complex , house , appt ) in self . _checked_appts :
return True
try :
self . get ( 'developers/{developer}/complexes/{complex}/houses/{house}/appts/{appt}' . format ( developer = self . developer , complex = complex , house = house , appt = appt , ) )
e... |
def _processCheckAuthResponse ( self , response , server_url ) :
"""Process the response message from a check _ authentication
request , invalidating associations if requested .""" | is_valid = response . getArg ( OPENID_NS , 'is_valid' , 'false' )
invalidate_handle = response . getArg ( OPENID_NS , 'invalidate_handle' )
if invalidate_handle is not None :
logging . info ( 'Received "invalidate_handle" from server %s' % ( server_url , ) )
if self . store is None :
logging . error ( '... |
def refresh_db ( ** kwargs ) :
'''Update ports with ` ` port selfupdate ` `
CLI Example :
. . code - block : : bash
salt mac pkg . refresh _ db''' | # Remove rtag file to keep multiple refreshes from happening in pkg states
salt . utils . pkg . clear_rtag ( __opts__ )
cmd = [ 'port' , 'selfupdate' ]
return salt . utils . mac_utils . execute_return_success ( cmd ) |
def match ( self , filename , isdir ) :
"""Match the specified * filename * . If * isdir * is False , directory - only
patterns will be ignored .
Returns one of
- # MATCH _ DEFAULT
- # MATCH _ IGNORE
- # MATCH _ INCLUDE""" | fnmatch = _fnmatch . fnmatch
ignored = False
filename = self . convert_path ( filename )
basename = os . path . basename ( filename )
for pattern in self . patterns :
if pattern . dir_only and not isdir :
continue
if ( not ignored or pattern . invert ) and pattern . match ( filename ) :
if patte... |
def create_tree ( self , tree , base_tree = '' ) :
"""Create a tree on this repository .
: param list tree : ( required ) , specifies the tree structure .
Format : [ { ' path ' : ' path / file ' , ' mode ' :
' filemode ' , ' type ' : ' blob or tree ' , ' sha ' : ' 44bfc6d . . . ' } ]
: param str base _ tree... | json = None
if tree and isinstance ( tree , list ) :
data = { 'tree' : tree , 'base_tree' : base_tree }
url = self . _build_url ( 'git' , 'trees' , base_url = self . _api )
json = self . _json ( self . _post ( url , data = data ) , 201 )
return Tree ( json ) if json else None |
def get_all_anchors ( stride = None , sizes = None ) :
"""Get all anchors in the largest possible image , shifted , floatbox
Args :
stride ( int ) : the stride of anchors .
sizes ( tuple [ int ] ) : the sizes ( sqrt area ) of anchors
Returns :
anchors : SxSxNUM _ ANCHORx4 , where S = = ceil ( MAX _ SIZE /... | if stride is None :
stride = cfg . RPN . ANCHOR_STRIDE
if sizes is None :
sizes = cfg . RPN . ANCHOR_SIZES
# Generates a NAx4 matrix of anchor boxes in ( x1 , y1 , x2 , y2 ) format . Anchors
# are centered on stride / 2 , have ( approximate ) sqrt areas of the specified
# sizes , and aspect ratios as given .
ce... |
def abort ( self ) :
"""Abort a running command .
@ return : A new ApiCommand object with the updated information .""" | if self . id == ApiCommand . SYNCHRONOUS_COMMAND_ID :
return self
path = self . _path ( ) + '/abort'
resp = self . _get_resource_root ( ) . post ( path )
return ApiCommand . from_json_dict ( resp , self . _get_resource_root ( ) ) |
def path_exists ( path , properties = None , hadoop_conf_dir = None ) :
"""Return : obj : ` True ` if ` ` path ` ` exists in the default HDFS .
Keyword arguments are passed to : func : ` dfs ` .
This function does the same thing as : func : ` hdfs . path . exists
< pydoop . hdfs . path . exists > ` , but it u... | try :
dfs ( [ "-stat" , path ] , properties , hadoop_conf_dir = hadoop_conf_dir )
except RuntimeError :
return False
return True |
def kdf ( self ) :
"""Returns the name of the key derivation function to use .
: return :
A unicode from of one of the following : " pbkdf1 " , " pbkdf2 " ,
" pkcs12 _ kdf " """ | encryption_algo = self [ 'algorithm' ] . native
if encryption_algo == 'pbes2' :
return self [ 'parameters' ] [ 'key_derivation_func' ] [ 'algorithm' ] . native
if encryption_algo . find ( '.' ) == - 1 :
if encryption_algo . find ( '_' ) != - 1 :
encryption_algo , _ = encryption_algo . split ( '_' , 1 )
... |
def counts ( self , ids = None , setdata = False , output_format = 'DataFrame' ) :
"""Return the counts in each of the specified measurements .
Parameters
ids : [ hashable | iterable of hashables | None ]
Keys of measurements to get counts of .
If None is given get counts of all measurements .
setdata : b... | return self . apply ( lambda x : x . counts , ids = ids , setdata = setdata , output_format = output_format ) |
def create_parameterized_CAG ( input , output , filename = "CAG_with_indicators_and_values.pdf" ) :
"""Create a CAG with mapped and parameterized indicators""" | with open ( input , "rb" ) as f :
G = pickle . load ( f )
G . parameterize ( year = 2017 , month = 4 )
G . get_timeseries_values_for_indicators ( )
with open ( output , "wb" ) as f :
pickle . dump ( G , f ) |
def make_parser ( ) :
"""Returns an argparse instance for this script .""" | parser = argparse . ArgumentParser ( description = "generate HTML from crawler JSON" )
parser . add_argument ( "--data-dir" , default = "data" , help = u"Directory containing JSON data from crawler [%(default)s]" )
parser . add_argument ( "--output-dir" , default = "html" , help = u"Directory to output the resulting HT... |
def sheet2matrix ( self , x , y ) :
"""Convert a point ( x , y ) in Sheet coordinates to continuous
matrix coordinates .
Returns ( float _ row , float _ col ) , where float _ row corresponds to
y , and float _ col to x .
Valid for scalar or array x and y .
Note about Bounds For a Sheet with
BoundingBox ... | # First translate to ( left , top ) , which is [ 0,0 ] in the matrix ,
# then scale to the size of the matrix . The y coordinate needs
# to be flipped , because the points are moving down in the
# sheet as the y index increases in the matrix .
xdensity = self . __xdensity
if ( ( isinstance ( x , np . ndarray ) and x . ... |
def searchString ( self , instring , maxMatches = _MAX_INT ) :
"""Another extension to scanString , simplifying the access to the tokens found
to match the given parse expression . May be called with optional
maxMatches argument , to clip searching after ' n ' matches are found .""" | return ParseResults ( [ t for t , s , e in self . scanString ( instring , maxMatches ) ] ) |
def chk_date_arg ( s ) :
"""Checks if the string ` s ` is a valid date string .
Return True of False .""" | if re_date . search ( s ) is None :
return False
comp = s . split ( '-' )
try :
dt = datetime . date ( int ( comp [ 0 ] ) , int ( comp [ 1 ] ) , int ( comp [ 2 ] ) )
return True
except Exception as e :
return False |
def p_taskvardecls ( self , p ) :
'taskvardecls : taskvardecls taskvardecl' | p [ 0 ] = p [ 1 ] + ( p [ 2 ] , )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def basic_interior_combine ( intersections , max_edges = 10 ) :
"""Combine intersections that don ' t involve tangencies .
. . note : :
This is a helper used only by : func : ` combine _ intersections ` .
. . note : :
This helper assumes ` ` intersections ` ` isn ' t empty , but doesn ' t
enforce it .
A... | unused = intersections [ : ]
result = [ ]
while unused :
start = unused . pop ( )
curr_node = start
next_node = get_next ( curr_node , intersections , unused )
edge_ends = [ ( curr_node , next_node ) ]
while next_node is not start :
curr_node = to_front ( next_node , intersections , unused )... |
def to_xdr_object ( self ) :
"""Creates an XDR Operation object that represents this
: class : ` Inflation ` .""" | self . body . type = Xdr . const . INFLATION
return super ( Inflation , self ) . to_xdr_object ( ) |
def generate_slug ( self , model_instance ) :
"""Returns a unique slug .""" | queryset = model_instance . __class__ . _default_manager . all ( )
# Only count slugs that match current length to prevent issues
# when pre - existing slugs are a different length .
lookup = { '%s__regex' % self . attname : r'^.{%s}$' % self . length }
if queryset . filter ( ** lookup ) . count ( ) >= len ( self . cha... |
def urlencode ( query , doseq = False , safe = '' , encoding = None , errors = None ) :
"""Encode a sequence of two - element tuples or dictionary into a URL query string .
If any values in the query arg are sequences and doseq is true , each
sequence element is converted to a separate parameter .
If the quer... | if hasattr ( query , "items" ) :
query = query . items ( )
else : # It ' s a bother at times that strings and string - like objects are
# sequences .
try : # non - sequence items should not work with len ( )
# non - empty strings will fail this
if len ( query ) and not isinstance ( query [ 0 ] , tup... |
def is_op ( call , op ) :
""": param call : The specific operator instance ( a method call )
: param op : The the operator we are testing against
: return : isinstance ( call , op ) , but faster""" | try :
return call . id == op . id
except Exception as e :
return False |
def save ( self , filename , ftype = 'HDF5' ) : # pragma : no coverage
"""Save all the model parameters into a file ( HDF5 by default ) .
This is not supported yet . We are working on having a consistent ,
human readable way of saving and loading GPy models . This only
saves the parameter array to a hdf5 file... | from . . param import Param
def gather_params ( self , plist ) :
if isinstance ( self , Param ) :
plist . append ( self )
plist = [ ]
self . traverse ( gather_params , plist )
names = self . parameter_names ( adjust_for_printing = True )
if ftype == 'HDF5' :
try :
import h5py
f = h5py . ... |
def update_display ( self , iteration , disp_level , col_width = 12 ) : # pragma : no cover
"""Prints information about the optimization procedure to standard output
Parameters
iteration : int
The current iteration . Must either a positive integer or - 1 , which indicates the end of the algorithm
disp _ lev... | # exit and print nothing if disp _ level is zero
if disp_level == 0 :
return
else : # simple update , no table
if disp_level == 1 and iteration >= 0 :
print ( '[Iteration %i]' % iteration )
# fancy table updates
if disp_level > 1 : # get the metadata from this iteration
data = valmap ( l... |
def sendmail ( self , to , message ) :
"""Send mail to one or more recipients . The required arguments are a
list of RFC 822 to - address strings ( a bare string will be treated as a
list with 1 address ) , and a message string .""" | # If we were passed a bare string as the To : address , convert it to
# a single element list .
if isinstance ( to , str ) :
to = [ to , ]
# Send one email with the appropriate recipient list .
server = self . _smtp_server ( )
server . sendmail ( self . get_rfc2822_address ( ) , to , message )
server . quit ( ) |
def bic ( self ) :
r"""Returns the corrected Bayesian Information Criterion ( BIC ) for all chains loaded into ChainConsumer .
If a chain does not have a posterior , number of data points , and number of free parameters
loaded , this method will return ` None ` for that chain . Formally , the BIC is defined as ... | bics = [ ]
bics_bool = [ ]
for i , chain in enumerate ( self . parent . chains ) :
p , n_data , n_free = chain . posterior , chain . num_eff_data_points , chain . num_free_params
if p is None or n_data is None or n_free is None :
bics_bool . append ( False )
missing = ""
if p is None :
... |
def dueling_model ( img_in , num_actions , scope , noisy = False , reuse = False , concat_softmax = False ) :
"""As described in https : / / arxiv . org / abs / 1511.06581""" | with tf . variable_scope ( scope , reuse = reuse ) :
out = img_in
with tf . variable_scope ( "convnet" ) : # original architecture
out = layers . convolution2d ( out , num_outputs = 32 , kernel_size = 8 , stride = 4 , activation_fn = tf . nn . relu )
out = layers . convolution2d ( out , num_outp... |
def request ( self , * args , ** kwargs ) :
"""Overrided method . Returns jsonrpc response
or fetches exception ? returns appropriate data to client
and response mail to administrator .""" | try :
import settings
with open ( os . path . join ( settings . BASE_DIR , "keys.json" ) ) as f :
keys = json . load ( f )
privkey = keys [ "privkey" ]
message = json . dumps ( kwargs )
signature = Bip32Keys . sign_message ( message , privkey )
result = super ( ) . request ( method_n... |
def save_data ( fpath , data , ** kwargs ) :
"""More generic interface to write data""" | ext = splitext ( fpath ) [ 1 ]
if ext in [ '.pickle' , '.cPkl' , '.pkl' ] :
return save_cPkl ( fpath , data , ** kwargs )
elif ext in [ '.json' ] :
return save_json ( fpath , data , ** kwargs )
elif ext in [ '.hdf5' ] :
return save_hdf5 ( fpath , data , ** kwargs )
elif ext in [ '.txt' ] :
return save_t... |
def correct_invalid_fifth_foot ( self , scansion : str ) -> str :
"""The ' inverted amphibrach ' : stressed _ unstressed _ stressed syllable pattern is invalid
in hexameters , so here we coerce it to stressed when it occurs at the end of a line
: param scansion : the scansion pattern
: return corrected scansi... | scansion_wo_spaces = scansion . replace ( " " , "" ) [ : - 1 ] + self . constants . OPTIONAL_ENDING
if scansion_wo_spaces . endswith ( self . constants . DACTYL + self . constants . IAMB + self . constants . OPTIONAL_ENDING ) :
matches = list ( re . compile ( r"{}\s*{}\s*{}\s*{}\s*{}" . format ( self . constants . ... |
def extension ( self , file_type : Optional [ FileType ] = None ) -> str :
"""Get a random file extension from list .
: param file _ type : Enum object FileType .
: return : Extension of the file .
: Example :
. py""" | key = self . _validate_enum ( item = file_type , enum = FileType )
extensions = EXTENSIONS [ key ]
return self . random . choice ( extensions ) |
def duration ( cls , seconds , first = True ) :
"""Constructs a human readable string to indicate the time duration for the given seconds
: param int seconds :
: param bool first : Just return the first unit instead of all
: rtype : str""" | num_units = [ ]
for unit in reversed ( TimeUnit ) :
if seconds >= unit . seconds :
name = unit . name . lower ( )
count = int ( seconds / unit . seconds )
num_units . append ( f'{count} {plural(name, count=count)}' )
seconds -= count * unit . seconds
if first or not seconds :... |
def moveTo ( self , vector ) :
"""Moves the turtle to the new position . Orientation is kept as it is .
If the pen is lowered it will also add to the currently drawn polyline .""" | self . _position = vector
if self . isPenDown ( ) :
self . _pointsOfPolyline . append ( self . _position ) |
def persist ( self , storageLevel = StorageLevel . MEMORY_ONLY ) :
"""Set this RDD ' s storage level to persist its values across operations
after the first time it is computed . This can only be used to assign
a new storage level if the RDD does not have a storage level set yet .
If no storage level is speci... | self . is_cached = True
javaStorageLevel = self . ctx . _getJavaStorageLevel ( storageLevel )
self . _jrdd . persist ( javaStorageLevel )
return self |
def _resolve ( self , klass ) :
"""Resolve an instance of the given seeder klass .
: param klass : The Seeder class
: type klass : class""" | resolver = None
if self . _resolver :
resolver = self . _resolver
elif self . _command :
resolver = self . _command . resolver
instance = klass ( )
instance . set_connection_resolver ( resolver )
if self . _command :
instance . set_command ( self . _command )
return instance |
def _find_usage_vpcs ( self ) :
"""find usage for VPCs""" | # overall number of VPCs
vpcs = self . conn . describe_vpcs ( )
self . limits [ 'VPCs' ] . _add_current_usage ( len ( vpcs [ 'Vpcs' ] ) , aws_type = 'AWS::EC2::VPC' ) |
def clean_url ( self ) :
"""Only clean the url params and return self .""" | raw_url = self . request [ 'url' ]
parsed_url = urlparse ( raw_url )
qsl = parse_qsl ( parsed_url . query )
for qs in qsl :
new_url = self . _join_url ( parsed_url , [ i for i in qsl if i is not qs ] )
new_request = deepcopy ( self . request )
new_request [ 'url' ] = new_url
self . _add_task ( 'qsl' , q... |
def update_state ( self ) :
"""Update state with latest info from Wink API .""" | response = self . api_interface . get_device_state ( self , id_override = self . parent_id ( ) , type_override = self . parent_object_type ( ) )
self . _update_state_from_response ( response ) |
def obj_asd ( result , reference , voxelspacing = None , connectivity = 1 ) :
"""Average surface distance between objects .
First correspondences between distinct binary objects in reference and result are
established . Then the average surface distance is only computed between corresponding
objects . Corresp... | sds = list ( )
labelmap1 , labelmap2 , _a , _b , mapping = __distinct_binary_object_correspondences ( result , reference , connectivity )
slicers1 = find_objects ( labelmap1 )
slicers2 = find_objects ( labelmap2 )
for lid2 , lid1 in list ( mapping . items ( ) ) :
window = __combine_windows ( slicers1 [ lid1 - 1 ] ,... |
def forward_message ( self , chat_id , from_chat_id , message_id , disable_notification = None ) :
"""Use this method to forward messages of any kind .
: param disable _ notification :
: param chat _ id : which chat to forward
: param from _ chat _ id : which chat message from
: param message _ id : message... | return types . Message . de_json ( apihelper . forward_message ( self . token , chat_id , from_chat_id , message_id , disable_notification ) ) |
def get_category_aliases_under ( parent_alias = None ) :
"""Returns a list of category aliases under the given parent .
Could be useful to pass to ` ModelWithCategory . enable _ category _ lists _ editor `
in ` additional _ parents _ aliases ` parameter .
: param str | None parent _ alias : Parent alias or No... | return [ ch . alias for ch in get_cache ( ) . get_children_for ( parent_alias , only_with_aliases = True ) ] |
def windowed ( self , size ) -> None :
'''Set the window to windowed mode .''' | width , height = size
self . wnd . windowed ( width , height ) |
def recvProxyData ( self , data ) :
"""Write data to server""" | if self . initialized :
self . sendData ( data )
else :
self . queued_data . append ( data ) |
def percent_chance ( self , pct ) :
"""Given a ` ` pct ` ` % chance of something happening right now , decide at
random whether it actually happens , and return ` ` True ` ` or
` ` False ` ` as appropriate .
Values not between 0 and 100 are treated as though they
were 0 or 100 , whichever is nearer .""" | if pct <= 0 :
return False
if pct >= 100 :
return True
return pct / 100 < self . random ( ) |
def add_parser ( self , func = None , name = None , ** kwargs ) :
"""Add parser .
This method makes a new sub command parser . It takes same arguments
as add _ parser ( ) of the action class made by
argparse . ArgumentParser . add _ subparsers .
In addition to , it takes one positional argument ` func ` , w... | if func :
if not func . __doc__ :
raise ValueError ( "No docstrings given in {0}" . format ( func . __name__ ) )
info = _parse_doc ( func . __doc__ )
if _HELP not in kwargs or not kwargs [ _HELP ] :
kwargs [ _HELP ] = info [ "headline" ]
if _DESCRIPTION not in kwargs or not kwargs [ _DES... |
def get ( self , key , mem_map = True ) :
"""Return the samples for the given key and the sampling - rate .
Args :
key ( str ) : The key to read the data from .
mem _ map ( bool ) : If ` ` True ` ` returns the data as
memory - mapped array , otherwise a copy is returned .
Note :
The container has to be ... | self . raise_error_if_not_open ( )
if key in self . _file :
data = self . _file [ key ]
sampling_rate = data . attrs [ SAMPLING_RATE_ATTR ]
if not mem_map :
data = data [ ( ) ]
data = np . float32 ( data ) / MAX_INT16_VALUE
return data , sampling_rate |
def _AlignDecryptedDataOffset ( self , decrypted_data_offset ) :
"""Aligns the encrypted file with the decrypted data offset .
Args :
decrypted _ data _ offset ( int ) : decrypted data offset .""" | self . _file_object . seek ( 0 , os . SEEK_SET )
self . _decrypter = self . _GetDecrypter ( )
self . _decrypted_data = b''
encrypted_data_offset = 0
encrypted_data_size = self . _file_object . get_size ( )
while encrypted_data_offset < encrypted_data_size :
read_count = self . _ReadEncryptedData ( self . _ENCRYPTED... |
def get_series_by_id ( self , series_id ) :
"""Perform lookup for series
: param int series _ id : series id of series
: returns : instance of series
: rtype : object""" | series = trakt . Trakt [ 'search' ] . lookup ( series_id , 'trakt-show' )
if not series :
return None , 'Not Found'
return series , None |
def _get_cert_expiration_time ( headers ) :
"""Get the expiration time for a cert , given the response headers .
Get expiration time from the headers in the result . If we can ' t get
a time from the headers , this returns 0 , indicating that the cert
shouldn ' t be cached .
Args :
headers : A dict contai... | # Check the max age of the cert .
cache_control = headers . get ( 'Cache-Control' , '' )
# http : / / www . w3 . org / Protocols / rfc2616 / rfc2616 - sec4 . html # sec4.2 indicates only
# a comma - separated header is valid , so it should be fine to split this on
# commas .
for entry in cache_control . split ( ',' ) :... |
def client ( self , verifier = None ) :
"""Return the correct client depending on which stage of the OAuth process
we ' re in .""" | # We ' re just starting out and don ' t have neither request nor access
# token . Return the standard client
if not self . _request_token and not self . _access_token :
client = oauth . Client ( self . consumer , timeout = TIMEOUT )
# We ' re one step in , we ' ve got the request token and can add that to
# the cli... |
def add ( self , attachments ) :
"""Add more attachments
: param attachments : list of attachments
: type attachments : list [ str ] or list [ Path ] or str or Path or dict""" | if attachments :
if isinstance ( attachments , ( str , Path ) ) :
attachments = [ attachments ]
if isinstance ( attachments , ( list , tuple , set ) ) : # User provided attachments
attachments_temp = [ self . _attachment_constructor ( attachment , parent = self ) for attachment in attachments ]
... |
def to_json ( self , use_sbo = False ) :
"""Return serialized Statement as a JSON dict .
Parameters
use _ sbo : Optional [ bool ]
If True , SBO annotations are added to each applicable element of
the JSON . Default : False
Returns
json _ dict : dict
The JSON - serialized INDRA Statement .""" | stmt_type = type ( self ) . __name__
# Original comment : For backwards compatibility , could be removed later
all_stmts = [ self ] + self . supports + self . supported_by
for st in all_stmts :
if not hasattr ( st , 'uuid' ) :
st . uuid = '%s' % uuid . uuid4 ( )
json_dict = _o ( type = stmt_type )
json_dict... |
def millis_interval ( start , end ) :
"""start and end are datetime instances""" | diff = end - start
millis = diff . days * 24 * 60 * 60 * 1000
millis += diff . seconds * 1000
millis += diff . microseconds / 1000
return millis |
def update_domain ( self , domainid , data ) :
"""Update a domain""" | return self . api_call ( ENDPOINTS [ 'domains' ] [ 'update' ] , dict ( domainid = domainid ) , body = data ) |
def group_primers ( self , my_list ) :
"""Group elements in list by certain number ' n '""" | new_list = [ ]
n = 2
for i in range ( 0 , len ( my_list ) , n ) :
grouped_primers = my_list [ i : i + n ]
forward_primer = grouped_primers [ 0 ] . split ( " " )
reverse_primer = grouped_primers [ 1 ] . split ( " " )
formatted_primers = ">F_{0}\n{1}" . format ( forward_primer [ 1 ] , forward_primer [ 0 ]... |
def _IN ( self , value ) :
"""Comparison operator for the ' in ' comparison operator .
The Python ' in ' operator cannot be overloaded in the way we want
to , so we define a method . For example : :
Employee . query ( Employee . rank . IN ( [ 4 , 5 , 6 ] ) )
Note that the method is called . _ IN ( ) but may... | if not self . _indexed :
raise datastore_errors . BadFilterError ( 'Cannot query for unindexed property %s' % self . _name )
from . query import FilterNode
# Import late to avoid circular imports .
if not isinstance ( value , ( list , tuple , set , frozenset ) ) :
raise datastore_errors . BadArgumentError ( 'Ex... |
def cfn_viz ( template , parameters = { } , outputs = { } , out = sys . stdout ) :
"""Render dot output for cloudformation . template in json format .""" | known_sg , open_sg = _analyze_sg ( template [ 'Resources' ] )
( graph , edges ) = _extract_graph ( template . get ( 'Description' , '' ) , template [ 'Resources' ] , known_sg , open_sg )
graph [ 'edges' ] . extend ( edges )
_handle_terminals ( template , graph , 'Parameters' , 'source' , parameters )
_handle_terminals ... |
def compute_group_label_positions ( self ) :
"""Computes the x , y positions of the group labels .""" | assert self . group_label_position in [ "beginning" , "middle" , "end" ]
data = [ self . graph . node [ n ] [ self . node_grouping ] for n in self . nodes ]
node_length = len ( data )
groups = items_in_groups ( data )
edge_of_plot = self . plot_radius + self . nodeprops [ "radius" ]
# The 1.02 serves as padding
radius ... |
def unsubscribe ( self , coro ) :
"""Unsubscribe from status updates from the Opentherm Gateway .
Can only be used after connect ( )
@ coro is a coroutine which has been subscribed with subscribe ( )
earlier .
Return True on success , false if not connected or subscribed .""" | if coro in self . _notify :
self . _notify . remove ( coro )
return True
return False |
def set ( constants ) :
"""REACH INTO THE MODULES AND OBJECTS TO SET CONSTANTS .
THINK OF THIS AS PRIMITIVE DEPENDENCY INJECTION FOR MODULES .
USEFUL FOR SETTING DEBUG FLAGS .""" | if not constants :
return
constants = wrap ( constants )
for k , new_value in constants . leaves ( ) :
errors = [ ]
try :
old_value = mo_dots_set_attr ( sys . modules , k , new_value )
continue
except Exception as e :
errors . append ( e )
# ONE MODULE IS MISSING , THE CALLIN... |
def finalize_sv ( samples , config ) :
"""Combine results from multiple sv callers into a single ordered ' sv ' key .""" | by_bam = collections . OrderedDict ( )
for x in samples :
batch = dd . get_batch ( x ) or [ dd . get_sample_name ( x ) ]
try :
by_bam [ x [ "align_bam" ] , tuple ( batch ) ] . append ( x )
except KeyError :
by_bam [ x [ "align_bam" ] , tuple ( batch ) ] = [ x ]
by_batch = collections . Order... |
def dmag ( self , band ) :
"""Difference in magnitudes between fainter and brighter components in band .
: param band :
Photometric bandpass .""" | m1 = self . stars [ '{}_mag_A' . format ( band ) ]
m2 = addmags ( self . stars [ '{}_mag_B' . format ( band ) ] , self . stars [ '{}_mag_C' . format ( band ) ] )
return np . abs ( m2 - m1 ) |
def discover_conf_py_directory ( initial_dir ) :
"""Discover the directory containing the conf . py file .
This function is useful for building stack docs since it will look in
the current working directory and all parents .
Parameters
initial _ dir : ` str `
The inititial directory to search from . In pr... | # Create an absolute Path to work with
initial_dir = pathlib . Path ( initial_dir ) . resolve ( )
# Search upwards until a conf . py is found
try :
return str ( _search_parents ( initial_dir ) )
except FileNotFoundError :
raise |
def draw ( self , value , newline = True , flush = True ) :
"""Draw the progress bar
: type value : int
: param value : Progress value relative to ` ` self . max _ value ` `
: type newline : bool
: param newline : If this is set , a newline will be written after drawing""" | # This is essentially winch - handling without having
# to do winch - handling ; cleanly redrawing on winch is difficult
# and out of the intended scope of this class ; we * can *
# however , adjust the next draw to be proper by re - measuring
# the terminal since the code is mostly written dynamically
# and many attri... |
def samples ( self ) :
"""Yield samples as dictionaries , keyed by dimensions .""" | names = self . series . dimensions
for n , offset in enumerate ( self . series . offsets ) :
dt = datetime . timedelta ( microseconds = offset * 1000 )
d = { "ts" : self . ts + dt }
for name in names :
d [ name ] = getattr ( self . series , name ) [ n ]
yield d |
def _convert_property_type ( value ) :
"""Converts the string value in a boolean , integer or string
: param value : string value
: returns : boolean , integer or string value""" | if value in ( 'true' , 'True' ) :
return True
elif value in ( 'false' , 'False' ) :
return False
elif str ( value ) . startswith ( '{' ) and str ( value ) . endswith ( '}' ) :
return ast . literal_eval ( value )
else :
try :
return int ( value )
except ValueError :
return value |
def atrm ( * args ) :
'''Remove jobs from the queue .
CLI Example :
. . code - block : : bash
salt ' * ' at . atrm < jobid > < jobid > . . < jobid >
salt ' * ' at . atrm all
salt ' * ' at . atrm all [ tag ]''' | # Need to do this here also since we use atq ( )
if not salt . utils . path . which ( 'at' ) :
return '\'at.atrm\' is not available.'
if not args :
return { 'jobs' : { 'removed' : [ ] , 'tag' : None } }
# Convert all to strings
args = salt . utils . data . stringify ( args )
if args [ 0 ] == 'all' :
if len ... |
def reservoir_sample ( stream , num_items , item_parser = lambda x : x ) :
"""samples num _ items from the stream keeping each with equal probability""" | kept = [ ]
for index , item in enumerate ( stream ) :
if index < num_items :
kept . append ( item_parser ( item ) )
else :
r = random . randint ( 0 , index )
if r < num_items :
kept [ r ] = item_parser ( item )
return kept |
def make_fileitem_peinfo_importedmodules_module_importedfunctions_string ( imported_function , condition = 'is' , negate = False , preserve_case = False ) :
"""Create a node for FileItem / PEInfo / ImportedModules / Module / ImportedFunctions / string
: return : A IndicatorItem represented as an Element node""" | document = 'FileItem'
search = 'FileItem/PEInfo/ImportedModules/Module/ImportedFunctions/string'
content_type = 'string'
content = imported_function
ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate , preserve_case = preserve_case )
return ii_node |
def from_sbv ( cls , file ) :
"""Reads captions from a file in YouTube SBV format .""" | parser = SBVParser ( ) . read ( file )
return cls ( file = file , captions = parser . captions ) |
def get_vm_by_name ( content , name , regex = False ) :
'''Get a VM by its name''' | return get_object_by_name ( content , vim . VirtualMachine , name , regex ) |
def set_completed ( self , p_completion_date = date . today ( ) ) :
"""Marks the todo as complete .
Sets the completed flag and sets the completion date to today .""" | if not self . is_completed ( ) :
self . set_priority ( None )
self . fields [ 'completed' ] = True
self . fields [ 'completionDate' ] = p_completion_date
self . src = re . sub ( r'^(\([A-Z]\) )?' , 'x ' + p_completion_date . isoformat ( ) + ' ' , self . src ) |
def shader_string ( body , glsl_version = '450 core' ) :
"""Call this method from a function that defines a literal shader string as the " body " argument .
Dresses up a shader string in three ways :
1 ) Insert # version at the top
2 ) Insert # line number declaration
3 ) un - indents
The line number info... | line_count = len ( body . split ( '\n' ) )
line_number = inspect . currentframe ( ) . f_back . f_lineno + 1 - line_count
return """\
#version %s
%s
""" % ( glsl_version , shader_substring ( body , stack_frame = 2 ) ) |
def print_failure_message ( message ) :
"""Print a message indicating failure in red color to STDERR .
: param message : the message to print
: type message : : class : ` str `""" | try :
import colorama
print ( colorama . Fore . RED + message + colorama . Fore . RESET , file = sys . stderr )
except ImportError :
print ( message , file = sys . stderr ) |
def NoCache ( self , * targets ) :
"""Tags a target so that it will not be cached""" | tlist = [ ]
for t in targets :
tlist . extend ( self . arg2nodes ( t , self . fs . Entry ) )
for t in tlist :
t . set_nocache ( )
return tlist |
def get_institutes_trend_graph_urls ( start , end ) :
"""Get all institute trend graphs .""" | graph_list = [ ]
for institute in Institute . objects . all ( ) :
urls = get_institute_trend_graph_url ( institute , start , end )
urls [ 'institute' ] = institute
graph_list . append ( urls )
return graph_list |
def _check_security_group ( self , name ) :
"""Checks if the security group exists .
: param str name : name of the security group
: return : str - security group id of the security group
: raises : ` SecurityGroupError ` if group does not exist""" | connection = self . _connect ( )
filters = { }
if self . _vpc :
filters = { 'vpc-id' : self . _vpc_id }
security_groups = connection . get_all_security_groups ( filters = filters )
matching_groups = [ group for group in security_groups if name in [ group . name , group . id ] ]
if len ( matching_groups ) == 0 :
... |
def pitch ( ax , ay , az ) :
'''Angle of x - axis relative to ground ( theta )
Args
ax : ndarray
x - axis acceleration values
ay : ndarray
y - axis acceleration values
az : ndarray
z - axis acceleration values
Returns
pitch : ndarray
Pitch angle in radians''' | import numpy
# arctan2 not needed here to cover all quadrants , just for consistency
return numpy . arctan ( ax , numpy . sqrt ( ay ** 2 + az ** 2 ) ) |
def make_oracle ( q0 , q1 , secret_function ) :
"""Gates implementing the secret function f ( x ) .""" | # coverage : ignore
if secret_function [ 0 ] :
yield [ CNOT ( q0 , q1 ) , X ( q1 ) ]
if secret_function [ 1 ] :
yield CNOT ( q0 , q1 ) |
def find ( self , name ) :
"""Returns a dict of collector ' s details if found .
Args :
name ( str ) : name of collector searching for""" | collectors = self . get_collectors ( )
for collector in collectors :
if name . lower ( ) == collector [ 'name' ] . lower ( ) :
self . collector_id = collector [ 'id' ]
return collector
return { 'status' : 'No results found.' } |
def setCurrentValue ( self , value ) :
"""Sets the value for the combobox to the inputed value . If the combobox
is in a checkable state , then the values will be checked , otherwise ,
the value will be selected .
: param value | < int >""" | enum = self . enum ( )
if not enum :
return
if self . isCheckable ( ) :
indexes = [ ]
for i in range ( self . count ( ) ) :
try :
check_value = enum [ nativestring ( self . itemText ( i ) ) ]
except KeyError :
continue
if check_value & value :
inde... |
def ConvBPDN ( * args , ** kwargs ) :
"""A wrapper function that dynamically defines a class derived from
one of the implementations of the Convolutional Constrained MOD
problems , and returns an object instantiated with the provided
parameters . The wrapper is designed to allow the appropriate
object to be... | # Extract method selection argument or set default
method = kwargs . pop ( 'method' , 'admm' )
# Assign base class depending on method selection argument
base = cbpdn_class_label_lookup ( method )
# Nested class with dynamically determined inheritance
class ConvBPDN ( base ) :
def __init__ ( self , * args , ** kwar... |
def _release_line ( c ) :
"""Examine current repo state to determine what type of release to prep .
: returns :
A two - tuple of ` ` ( branch - name , line - type ) ` ` where :
- ` ` branch - name ` ` is the current branch name , e . g . ` ` 1.1 ` ` , ` ` master ` ` ,
` ` gobbledygook ` ` ( or , usually , `... | # TODO : I don ' t _ think _ this technically overlaps with Releases ( because
# that only ever deals with changelog contents , and therefore full release
# version numbers ) but in case it does , move it there sometime .
# TODO : this and similar calls in this module may want to be given an
# explicit pointer - to - g... |
def _encode_time ( self , value ) :
"""Convert datetime to base64 or plaintext string""" | if self . _kp . version >= ( 4 , 0 ) :
diff_seconds = int ( ( self . _datetime_to_utc ( value ) - datetime ( year = 1 , month = 1 , day = 1 , tzinfo = tz . gettz ( 'UTC' ) ) ) . total_seconds ( ) )
return base64 . b64encode ( struct . pack ( '<Q' , diff_seconds ) ) . decode ( 'utf-8' )
else :
return self . ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.