signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def fail_unknown_dialect ( compiler : "SQLCompiler" , task : str ) -> None :
"""Raise : exc : ` NotImplementedError ` in relation to a dialect for which a
function hasn ' t been implemented ( with a helpful error message ) .""" | raise NotImplementedError ( "Don't know how to {task} on dialect {dialect!r}. " "(Check also: if you printed the SQL before it was bound to an " "engine, you will be trying to use a dialect like StrSQLCompiler, " "which could be a reason for failure.)" . format ( task = task , dialect = compiler . dialect ) ) |
def spacing ( self , spacing ) :
"""Set the spacing in each axial direction . Pass a length three tuple of
floats""" | dx , dy , dz = spacing [ 0 ] , spacing [ 1 ] , spacing [ 2 ]
self . SetSpacing ( dx , dy , dz )
self . Modified ( ) |
def _currentResponse ( self , debugInfo ) :
"""Pull the current response off the queue .""" | bd = b'' . join ( self . _bufferedData )
self . _bufferedData = [ ]
return AssuanResponse ( bd , debugInfo ) |
def stream_to_handler ( self , request_handler ) :
"""Write the contents of this file to a
: class : ` tornado . web . RequestHandler ` . This method calls
: meth : ` ~ tornado . web . RequestHandler . flush ` on
the RequestHandler , so ensure all headers have already been set .
For a more complete example ... | written = 0
while written < self . length : # Reading chunk _ size at a time minimizes buffering .
f = self . _framework . yieldable ( self . read ( self . chunk_size ) )
yield f
chunk = f . result ( )
# write ( ) simply appends the output to a list ; flush ( ) sends it
# over the network and minimi... |
def _glyph_for_monomer_pattern ( self , pattern ) :
"""Add glyph for a PySB MonomerPattern .""" | pattern . matches_key = lambda : str ( pattern )
agent_id = self . _make_agent_id ( pattern )
# Handle sources and sinks
if pattern . monomer . name in ( '__source' , '__sink' ) :
return None
# Handle molecules
glyph = emaker . glyph ( emaker . label ( text = pattern . monomer . name ) , emaker . bbox ( ** self . m... |
def pickle_encode ( session_dict ) :
"Returns the given session dictionary pickled and encoded as a string ." | pickled = pickle . dumps ( session_dict , pickle . HIGHEST_PROTOCOL )
return base64 . encodestring ( pickled + get_query_hash ( pickled ) . encode ( ) ) |
def _filepath ( self , name ) :
"""File path to ` name ` morphology file .""" | if self . file_ext is None :
candidates = glob . glob ( os . path . join ( self . directory , name + ".*" ) )
try :
return next ( filter ( _is_morphology_file , candidates ) )
except StopIteration :
raise NeuroMError ( "Can not find morphology file for '%s' " % name )
else :
return os . ... |
def _assign_values_to_unbound_vars ( unbound_vars , unbound_var_values ) :
"""Assigns values to the vars and raises ValueError if one is missing .""" | context = { }
for key , value in six . iteritems ( unbound_var_values ) :
if key not in unbound_vars :
raise ValueError ( 'unexpected key: %s. Legal values are: %s' % ( key , list ( six . iterkeys ( unbound_vars ) ) ) )
context [ unbound_vars [ key ] ] = value
unspecified = [ ]
for unbound_var in six . ... |
def _check_ver_range ( self , version , ver_range ) :
"""Check if version is included in ver _ range""" | lower , upper , lower_inc , upper_inc = ver_range
# If the range extends over everything , we automatically match
if lower is None and upper is None :
return True
if lower is not None :
if lower_inc and version < lower :
return False
elif not lower_inc and version <= lower :
return False
if ... |
def _check_kraus_ops ( n , kraus_ops ) :
"""Verify that the Kraus operators are of the correct shape and satisfy the correct normalization .
: param int n : Number of qubits
: param list | tuple kraus _ ops : The Kraus operators as numpy . ndarrays .""" | for k in kraus_ops :
if not np . shape ( k ) == ( 2 ** n , 2 ** n ) :
raise ValueError ( "Kraus operators for {0} qubits must have shape {1}x{1}: {2}" . format ( n , 2 ** n , k ) )
kdk_sum = sum ( np . transpose ( k ) . conjugate ( ) . dot ( k ) for k in kraus_ops )
if not np . allclose ( kdk_sum , np . eye... |
async def wait_until_serving ( self ) -> None :
"""Await until the ` ` Endpoint ` ` is ready to receive events .""" | await asyncio . gather ( self . _receiving_loop_running . wait ( ) , self . _internal_loop_running . wait ( ) , loop = self . event_loop ) |
def option_chooser ( options , attr = None ) :
"""Given an iterable , enumerate its contents for a user to choose from .
If the optional ` attr ` is not None , that attribute in each iterated
object will be printed .
This function will exit the program if the user chooses the escape option .""" | for num , option in enumerate ( options ) :
if attr :
print ( "%s: %s" % ( num , getattr ( option , attr ) ) )
else :
print ( "%s: %s" % ( num , option ) )
# Add an escape option
escape_opt = num + 1
print ( "%s: I want to exit!" % escape_opt )
choice = six . moves . input ( "Selection: " )
try ... |
def subfield_conflicts ( conflicts : List [ Conflict ] , response_name : str , node1 : FieldNode , node2 : FieldNode ) -> Optional [ Conflict ] :
"""Check whether there are conflicts between sub - fields .
Given a series of Conflicts which occurred between two sub - fields , generate a single
Conflict .""" | if conflicts :
return ( ( response_name , [ conflict [ 0 ] for conflict in conflicts ] ) , list ( chain ( [ node1 ] , * [ conflict [ 1 ] for conflict in conflicts ] ) ) , list ( chain ( [ node2 ] , * [ conflict [ 2 ] for conflict in conflicts ] ) ) , )
return None |
def make_arousals ( events , time , s_freq ) :
"""Create dict for each arousal , based on events of time points .
Parameters
events : ndarray ( dtype = ' int ' )
N x 5 matrix with start , end samples
data : ndarray ( dtype = ' float ' )
vector with the data
time : ndarray ( dtype = ' float ' )
vector ... | arousals = [ ]
for ev in events :
one_ar = { 'start' : time [ ev [ 0 ] ] , 'end' : time [ ev [ 1 ] - 1 ] , 'dur' : ( ev [ 1 ] - ev [ 0 ] ) / s_freq , }
arousals . append ( one_ar )
return arousals |
def common_items ( df ) :
"""Returns the itens that are common in all the segments ,
in the format | idSegmento | id planilhaItens | .""" | percentage = 0.1
return ( df . groupby ( [ 'idSegmento' , 'idPlanilhaItens' ] ) . count ( ) . rename ( columns = { 'PRONAC' : 'itemOccurrences' } ) . sort_values ( 'itemOccurrences' , ascending = False ) . reset_index ( [ 'idSegmento' , 'idPlanilhaItens' ] ) . groupby ( 'idSegmento' ) . apply ( lambda x : x [ None : ma... |
def _check_message_valid ( msg ) :
"""Check packet length valid and that checksum is good .""" | try :
if int ( msg [ : 2 ] , 16 ) != ( len ( msg ) - 2 ) :
raise ValueError ( "Elk message length incorrect" )
_check_checksum ( msg )
except IndexError :
raise ValueError ( "Elk message length incorrect" ) |
def modify_metadata ( self , metadata , target = None , append = None , append_list = None , priority = None , access_key = None , secret_key = None , debug = None , request_kwargs = None ) :
"""Modify the metadata of an existing item on Archive . org .
Note : The Metadata Write API does not yet comply with the
... | append = False if append is None else append
access_key = self . session . access_key if not access_key else access_key
secret_key = self . session . secret_key if not secret_key else secret_key
debug = False if debug is None else debug
request_kwargs = { } if not request_kwargs else request_kwargs
url = '{protocol}//a... |
def patch_make ( self , a , b = None , c = None ) :
"""Compute a list of patches to turn text1 into text2.
Use diffs if provided , otherwise compute it ourselves .
There are four ways to call this function , depending on what data is
available to the caller :
Method 1:
a = text1 , b = text2
Method 2:
... | text1 = None
diffs = None
if isinstance ( a , str ) and isinstance ( b , str ) and c is None : # Method 1 : text1 , text2
# Compute diffs from text1 and text2.
text1 = a
diffs = self . diff_main ( text1 , b , True )
if len ( diffs ) > 2 :
self . diff_cleanupSemantic ( diffs )
self . diff_cle... |
def del_flowspec_local ( flowspec_family , route_dist , rules ) :
"""Deletes / withdraws Flow Specification route from VRF identified
by * route _ dist * .""" | try :
tm = CORE_MANAGER . get_core_service ( ) . table_manager
tm . update_flowspec_vrf_table ( flowspec_family = flowspec_family , route_dist = route_dist , rules = rules , is_withdraw = True )
# Send success response .
return [ { FLOWSPEC_FAMILY : flowspec_family , ROUTE_DISTINGUISHER : route_dist , F... |
def _parse_pattern ( self , element ) :
"""Parse the trigger pattern
: param element : The XML Element object
: type element : etree . _ Element""" | # If this is a raw regular expression , compile it and immediately return
self . _log . info ( 'Parsing Trigger Pattern: ' + element . text )
self . pattern_words , self . pattern_len = self . count_words ( element . text )
self . _log . debug ( 'Pattern contains {wc} words with a total length of {cc}' . format ( wc = ... |
def check_file_ids ( self , rawfiles , cellpyfile ) :
"""Check the stats for the files ( raw - data and cellpy hdf5 ) .
This function checks if the hdf5 file and the res - files have the same
timestamps etc to find out if we need to bother to load . res - files .
Args :
cellpyfile ( str ) : filename of the ... | txt = "checking file ids - using '%s'" % self . filestatuschecker
self . logger . info ( txt )
ids_cellpy_file = self . _check_cellpy_file ( cellpyfile )
self . logger . debug ( f"cellpyfile ids: {ids_cellpy_file}" )
if not ids_cellpy_file : # self . logger . debug ( " hdf5 file does not exist - needs updating " )
... |
def intersects_circle ( self , pt , radius ) :
"""Does the circle intersect with this rect ?""" | # How this works : http : / / stackoverflow . com / a / 402010
rect_corner = self . size / 2
# relative to the rect center
circle_center = ( pt - self . center ) . abs ( )
# relative to the rect center
# Is the circle far from the rect ?
if ( circle_center . x > rect_corner . x + radius or circle_center . y > rect_corn... |
def offset ( self , num_to_skip ) :
"""Skip to an offset in a query with this collection as parent .
See
: meth : ` ~ . firestore _ v1beta1 . query . Query . offset ` for
more information on this method .
Args :
num _ to _ skip ( int ) : The number of results to skip at the beginning
of query results . ... | query = query_mod . Query ( self )
return query . offset ( num_to_skip ) |
def align_bam ( in_bam , ref_file , names , align_dir , data ) :
"""Perform direct alignment of an input BAM file with BWA using pipes .
This avoids disk IO by piping between processes :
- samtools sort of input BAM to queryname
- bedtools conversion to interleaved FASTQ
- bwa - mem alignment
- samtools c... | config = data [ "config" ]
out_file = os . path . join ( align_dir , "{0}-sort.bam" . format ( names [ "lane" ] ) )
samtools = config_utils . get_program ( "samtools" , config )
bedtools = config_utils . get_program ( "bedtools" , config )
resources = config_utils . get_resources ( "samtools" , config )
num_cores = con... |
def get_eids ( rup_array , samples_by_grp , num_rlzs_by_grp ) :
""": param rup _ array : a composite array with fields serial , n _ occ and grp _ id
: param samples _ by _ grp : a dictionary grp _ id - > samples
: param num _ rlzs _ by _ grp : a dictionary grp _ id - > num _ rlzs""" | all_eids = [ ]
for rup in rup_array :
grp_id = rup [ 'grp_id' ]
samples = samples_by_grp [ grp_id ]
num_rlzs = num_rlzs_by_grp [ grp_id ]
num_events = rup [ 'n_occ' ] if samples > 1 else rup [ 'n_occ' ] * num_rlzs
eids = TWO32 * U64 ( rup [ 'serial' ] ) + numpy . arange ( num_events , dtype = U64 )
... |
def _set_vlan_add ( self , v , load = False ) :
"""Setter method for vlan _ add , mapped from YANG variable / routing _ system / evpn _ config / evpn / evpn _ instance / vlan / vlan _ add ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ vlan _ add is consid... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = vlan_add . vlan_add , is_container = 'container' , presence = False , yang_name = "vlan-add" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , ext... |
def StartAFF4Flow ( args = None , runner_args = None , parent_flow = None , sync = True , token = None , ** kwargs ) :
"""The main factory function for creating and executing a new flow .
Args :
args : An arg protocol buffer which is an instance of the required flow ' s
args _ type class attribute .
runner ... | # Build the runner args from the keywords .
if runner_args is None :
runner_args = rdf_flow_runner . FlowRunnerArgs ( )
FilterArgsFromSemanticProtobuf ( runner_args , kwargs )
# Is the required flow a known flow ?
try :
flow_cls = registry . AFF4FlowRegistry . FlowClassByName ( runner_args . flow_name )
except ... |
def set_mysql ( host , user , password , db , charset ) :
"""Set the SQLAlchemy connection string with MySQL settings""" | manager . database . set_mysql_connection ( host = host , user = user , password = password , db = db , charset = charset ) |
def _redundancy_routers_for_floatingip ( self , context , router_id , redundancy_router_ids = None , ha_settings_db = None ) :
"""To be called in update _ floatingip ( ) to get the
redundant router ids .""" | if ha_settings_db is None :
ha_settings_db = self . _get_ha_settings_by_router_id ( context , router_id )
if ha_settings_db is None :
return
e_context = context . elevated ( )
router_ids = [ ]
for r_id in ( redundancy_router_ids or self . _get_redundancy_router_ids ( e_context , router_id ) ) :
router_ids .... |
def mchirp_sampler_lnm ( ** kwargs ) :
'''Draw chirp mass samples for uniform - in - log model
Parameters
* * kwargs : string
Keyword arguments as model parameters and number of samples
Returns
mchirp - astro : array
The chirp mass samples for the population''' | m1 , m2 = draw_lnm_samples ( ** kwargs )
mchirp_astro = mchirp_from_mass1_mass2 ( m1 , m2 )
return mchirp_astro |
def ws_connect ( message ) :
"""Channels connection setup .
Register the current client on the related Group according to the language""" | prefix , language = message [ 'path' ] . strip ( '/' ) . split ( '/' )
gr = Group ( 'knocker-{0}' . format ( language ) )
gr . add ( message . reply_channel )
message . channel_session [ 'knocker' ] = language
message . reply_channel . send ( { "accept" : True } ) |
def chart_json ( start , end , period , symbol ) :
"""Requests chart data from Poloniex API
Args :
start : Int epoch date to START getting market stats from .
Note that this epoch is FURTHER from the current date .
end : Int epoch date to STOP getting market stats from .
Note that this epoch is CLOSER to ... | url = ( 'https://poloniex.com/public?command' '=returnChartData¤cyPair={0}&start={1}' '&end={2}&period={3}' ) . format ( symbol , start , end , period )
logger . debug ( ' HTTP Request URL:\n{0}' . format ( url ) )
json = requests . get ( url ) . json ( )
logger . debug ( ' JSON:\n{0}' . format ( json ) )
if 'err... |
def commit ( self ) :
"""Commit this change""" | if not self . connection :
import boto
self . connection = boto . connect_route53 ( )
return self . connection . change_rrsets ( self . hosted_zone_id , self . to_xml ( ) ) |
def publish ( config , source = None , template = None , destination = None , jinja_env = None , no_write = False ) :
"""Given a config , performs an end - to - end publishing pipeline and returns the result :
linking - > compiling - > templating - > writing
NOTE : at most one of source and template can be None... | if not isinstance ( config , Config ) :
raise PublishError ( "config must be a Config object, " "but instead was type '{}'" . format ( type ( config ) . __name__ ) )
if source is None and template is None :
raise PublishError ( 'When publishing, source and template cannot both be omitted.' )
variables = config ... |
def new ( cls , message , ** kwargs ) :
"""Create a new PGPMessage object .
: param message : The message to be stored .
: type message : ` ` str ` ` , ` ` unicode ` ` , ` ` bytes ` ` , ` ` bytearray ` `
: returns : : py : obj : ` PGPMessage `
The following optional keyword arguments can be used with : py :... | # TODO : have ' codecs ' above ( in : type encoding : ) link to python documentation page on codecs
cleartext = kwargs . pop ( 'cleartext' , False )
format = kwargs . pop ( 'format' , None )
sensitive = kwargs . pop ( 'sensitive' , False )
compression = kwargs . pop ( 'compression' , CompressionAlgorithm . ZIP )
file =... |
def from_etree ( cls , etree_element ) :
"""creates a ` ` SaltNode ` ` instance from the etree representation of an
< nodes > element from a SaltXMI file .""" | ins = SaltElement . from_etree ( etree_element )
# TODO : this looks dangerous , ask Stackoverflow about it !
ins . __class__ = SaltNode . mro ( ) [ 0 ]
# convert SaltElement into SaltNode
ins . layers = get_layer_ids ( etree_element )
ins . features = get_annotations ( etree_element )
return ins |
def delete_unique_identity ( db , uuid ) :
"""Remove a unique identity from the registry .
Function that removes from the registry , the unique identity
that matches with uuid . Data related to this identity will be
also removed .
It checks first whether the unique identity is already on the registry .
Wh... | with db . connect ( ) as session :
uidentity = find_unique_identity ( session , uuid )
if not uidentity :
raise NotFoundError ( entity = uuid )
delete_unique_identity_db ( session , uidentity ) |
def is_error_of_type ( exc , ref_type ) :
"""Helper function to determine if some exception is of some type , by also looking at its declared _ _ cause _ _
: param exc :
: param ref _ type :
: return :""" | if isinstance ( exc , ref_type ) :
return True
elif hasattr ( exc , '__cause__' ) and exc . __cause__ is not None :
return is_error_of_type ( exc . __cause__ , ref_type ) |
def displayName ( date , options = None , format = '%b %d, %Y' ) :
"""Returns the display name for the inputted date , given the list of options .
: param date | < datetime . date >
options | < projex . dates . Names >
format | < str >
: return < str >""" | # map from Qt information
if type ( date ) . __name__ in ( 'QDate' , 'QDateTime' , 'QTime' ) :
date = date . toPython ( )
if isinstance ( date , datetime . datetime ) :
time = ' @ ' + date . strftime ( '%I:%M%p' ) . strip ( '0M' ) . lower ( )
date = date . date ( )
else :
time = ''
today = datetime . da... |
def add_site_list ( dir_list ) :
"""Add a list of pseudo site - packages to : data : ` python : sys . path ` .
This centers the list on ` ` sys . path ` ` around the current environment .
I . e . if this environment is in the list , then directories before it in the
list will be prepended to ` ` sys . path ` ... | our_site_packages = os . path . abspath ( os . path . join ( sys . prefix , site_package_postfix ) )
dir_list = [ os . path . abspath ( x ) for x in dir_list ]
prepend = SysPathInserter ( 0 )
append = SysPathInserter ( )
try :
our_index = dir_list . index ( our_site_packages )
except ValueError :
our_index = No... |
def account_distance ( A1 , A2 ) :
"""Return the distance between two accounts . Here that is just the
difference in sum ( alpha )
Args :
A1 ( Account ) : The first account .
A2 ( Account ) : The second account
Returns :
float : The distance between the two accounts .""" | return ( sum ( [ action . alpha for action in A1 ] ) - sum ( [ action . alpha for action in A2 ] ) ) |
def _find_xinput ( self ) :
"""Find most recent xinput library .""" | for dll in XINPUT_DLL_NAMES :
try :
self . xinput = getattr ( ctypes . windll , dll )
except OSError :
pass
else : # We found an xinput driver
self . xinput_dll = dll
break
else : # We didn ' t find an xinput library
warn ( "No xinput driver dll found, gamepads not suppor... |
def verify_json ( self , json , user_key , user_id , device_id ) :
"""Verifies a signed key object ' s signature .
The object must have a ' signatures ' key associated with an object of the form
` user _ id : { key _ id : signature } ` .
Args :
json ( dict ) : The JSON object to verify .
user _ key ( str ... | try :
signatures = json . pop ( 'signatures' )
except KeyError :
return False
key_id = 'ed25519:{}' . format ( device_id )
try :
signature_base64 = signatures [ user_id ] [ key_id ]
except KeyError :
json [ 'signatures' ] = signatures
return False
unsigned = json . pop ( 'unsigned' , None )
try :
... |
def deserialize_tag ( stream , header , verifier = None ) :
"""Deserialize the Tag value from a non - framed stream .
: param stream : Source data stream
: type stream : io . BytesIO
: param header : Deserialized header
: type header : aws _ encryption _ sdk . structures . MessageHeader
: param verifier :... | ( data_tag , ) = unpack_values ( format_string = ">{auth_len}s" . format ( auth_len = header . algorithm . auth_len ) , stream = stream , verifier = verifier )
return data_tag |
def merge ( * args , ** kwargs ) :
'''merge ( . . . ) lazily collapses all arguments , which must be python Mapping objects of some kind ,
into a single mapping from left - to - right . The mapping that is returned is a lazy persistent
object that does not request the value of a key from any of the maps provide... | from . table import ( is_itable , ITable )
# figure out the choose - fn
choose_fn = None
if 'choose' in kwargs :
choose_fn = kwargs [ 'choose' ]
if len ( kwargs ) > 1 or ( len ( kwargs ) > 0 and 'choose' not in kwargs ) :
raise ValueError ( 'Unidentified options given to merge: %s' ( kwargs . keys ( ) , ) )
# c... |
def force_symmetric ( self ) :
"""Force a symmetric laminate
The ` B ` terms of the constitutive matrix are set to zero .""" | if self . offset != 0. :
raise RuntimeError ( 'Laminates with offset cannot be forced symmetric!' )
self . B = np . zeros ( ( 3 , 3 ) )
self . ABD [ 0 : 3 , 3 : 6 ] = 0
self . ABD [ 3 : 6 , 0 : 3 ] = 0
self . ABDE [ 0 : 3 , 3 : 6 ] = 0
self . ABDE [ 3 : 6 , 0 : 3 ] = 0 |
def cdfout ( data , file ) :
"""spits out the cdf for data to file""" | f = open ( file , "w" )
data . sort ( )
for j in range ( len ( data ) ) :
y = old_div ( float ( j ) , float ( len ( data ) ) )
out = str ( data [ j ] ) + ' ' + str ( y ) + '\n'
f . write ( out )
f . close ( ) |
def tree_structures_for ( self , prefix , current_oid , parent_oids , prefixes ) :
"""Return the entries for this commit , the entries of the parent commits ,
and the difference between the two ( current _ files - parent _ files )""" | if prefix and prefixes and prefix not in prefixes :
return empty , empty
parent_files = set ( )
for oid in parent_oids :
parent_files . update ( self . entries_in_tree_oid ( prefix , oid ) )
current_files = self . entries_in_tree_oid ( prefix , current_oid )
return ( current_files , parent_files ) , ( current_f... |
def merge_dependency ( self , item , resolve_parent , parents ) :
"""Merge dependencies of element with further dependencies . First parent dependencies are checked , and then
immediate dependencies of the current element should be added to the list , but without duplicating any entries .
: param item : Item . ... | dep = [ ]
for parent_key in parents :
if item == parent_key :
raise CircularDependency ( item , True )
parent_dep = resolve_parent ( parent_key )
if item in parent_dep :
raise CircularDependency ( item )
merge_list ( dep , parent_dep )
merge_list ( dep , parents )
return dep |
def begin_batch ( self ) :
'''Starts the batch operation . Intializes the batch variables
is _ batch :
batch operation flag .
batch _ table :
the table name of the batch operation
batch _ partition _ key :
the PartitionKey of the batch requests .
batch _ row _ keys :
the RowKey list of adding reques... | self . is_batch = True
self . batch_table = ''
self . batch_partition_key = ''
self . batch_row_keys = [ ]
self . batch_requests = [ ] |
def format_date ( format_string , localize = False , key = None ) :
"""A pre - called helper to supply a date format string ahead of time , so that it can apply to each
date or datetime that this column represents . With Django > = 1.5 , the ` ` localize = True ` ` keyword
argument can be given , or else can be... | if localize is not False and localtime is None :
raise Exception ( "Cannot use format_date argument 'localize' with Django < 1.5" )
def helper ( value , * args , ** kwargs ) :
inner_localize = kwargs . get ( 'localize' , localize )
if inner_localize is not False and localtime is None :
raise Excepti... |
def mad ( arr , relative = True ) :
"""Median Absolute Deviation : a " Robust " version of standard deviation .
Indices variabililty of the sample .
https : / / en . wikipedia . org / wiki / Median _ absolute _ deviation""" | with warnings . catch_warnings ( ) :
warnings . simplefilter ( "ignore" )
med = np . nanmedian ( arr , axis = 1 )
mad = np . nanmedian ( np . abs ( arr - med [ : , np . newaxis ] ) , axis = 1 )
if relative :
return mad / med
else :
return mad |
def _normalize_slice ( self , index , pipe = None ) :
"""Given a : obj : ` slice ` * index * , return a 4 - tuple
` ` ( start , stop , step , fowrward ) ` ` . The first three items can be used
with the ` ` range ` ` function to retrieve the values associated with the
slice ; the last item indicates the direct... | if index . step == 0 :
raise ValueError
pipe = self . redis if pipe is None else pipe
len_self = self . __len__ ( pipe )
step = index . step or 1
forward = step > 0
step = abs ( step )
if index . start is None :
start = 0 if forward else len_self - 1
elif index . start < 0 :
start = max ( len_self + index .... |
def stringify ( type_name , value , ** opts ) :
"""Generate a string representation of the data in ` ` value ` ` .
Based on the converter specified by ` ` type _ name ` ` . This is
guaranteed to yield a form which can easily be parsed by ` ` cast ( ) ` ` .""" | type_name , opts = _field_options ( type_name , opts )
return converter ( type_name ) . stringify ( value , ** opts ) |
def determine_result ( self , returncode , returnsignal , output , isTimeout ) :
"""Parse the output of the tool and extract the verification result .
This method always needs to be overridden .
If the tool gave a result , this method needs to return one of the
benchexec . result . RESULT _ * strings .
Othe... | join_output = '\n' . join ( output )
if isTimeout :
return 'TIMEOUT'
if returncode == 2 :
return 'ERROR - Pre-run'
if join_output is None :
return 'ERROR - no output'
elif 'Safe.' in join_output :
return result . RESULT_TRUE_PROP
elif 'Error state' in join_output :
return result . RESULT_FALSE_REACH... |
def exchange_code ( self , code , redirect_uri ) :
"""Exchanges code for token / s""" | token = requests . post ( GOOGLE_OAUTH2_TOKEN_URL , data = dict ( code = code , redirect_uri = redirect_uri , grant_type = 'authorization_code' , client_id = self . client_id , client_secret = self . client_secret , ) ) . json ( )
if not token or token . get ( 'error' ) :
abort ( 400 )
return token |
def _is_numeric ( self , values ) :
"""Check to be sure values are numbers before doing numerical operations .""" | if len ( values ) > 0 :
assert isinstance ( values [ 0 ] , ( float , int ) ) , "values must be numbers to perform math operations. Got {}" . format ( type ( values [ 0 ] ) )
return True |
async def _process_access_form ( self , html : str ) -> ( str , str ) :
"""Parsing page with access rights
: param html : html page
: return : url and html from redirected page""" | # Parse page
p = AccessPageParser ( )
p . feed ( html )
p . close ( )
form_url = p . url
form_data = dict ( p . inputs )
# Send request
url , html = await self . driver . post_text ( form_url , form_data )
return url , html |
def exception_class ( self , exception ) :
"""Return a name representing the class of an exception .""" | cls = type ( exception )
if cls . __module__ == 'exceptions' : # Built - in exception .
return cls . __name__
return "%s.%s" % ( cls . __module__ , cls . __name__ ) |
def replace_namespaced_pod_disruption_budget_status ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""replace _ namespaced _ pod _ disruption _ budget _ status # noqa : E501
replace status of the specified PodDisruptionBudget # noqa : E501
This method makes a synchronous HTTP request by default ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_namespaced_pod_disruption_budget_status_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . replace_namespaced_pod_disruption_budget_status_with_http_info ( name , nam... |
def nack_message ( self , delivery_tag , ** kwargs ) :
"""Negative acknowledge a message
: param int delivery _ tag : The deliver tag from the Basic . Deliver frame""" | logger . info ( 'Nacking message' , delivery_tag = delivery_tag , ** kwargs )
self . _channel . basic_nack ( delivery_tag ) |
def batchInsert ( self , itemType , itemAttributes , dataRows ) :
"""Create multiple items in the store without loading
corresponding Python objects into memory .
the items ' C { stored } callback will not be called .
Example : :
myData = [ ( 37 , u " Fred " , u " Wichita " ) ,
(28 , u " Jim " , u " Fresn... | class FakeItem :
pass
_NEEDS_DEFAULT = object ( )
# token for lookup failure
fakeOSelf = FakeItem ( )
fakeOSelf . store = self
sql = itemType . _baseInsertSQL ( self )
indices = { }
schema = [ attr for ( name , attr ) in itemType . getSchema ( ) ]
for i , attr in enumerate ( itemAttributes ) :
indices [ attr ] ... |
def get_relation_count_query ( self , query , parent ) :
"""Add the constraints for a relationship count query .
: type query : Builder
: type parent : Builder
: rtype : Builder""" | query . select ( QueryExpression ( "COUNT(*)" ) )
key = self . wrap ( self . get_qualified_parent_key_name ( ) )
return query . where ( self . get_has_compare_key ( ) , "=" , QueryExpression ( key ) ) |
def Close ( self , abort = False ) :
"""Closes the queue .
Args :
abort ( Optional [ bool ] ) : whether the Close is the result of an abort
condition . If True , queue contents may be lost .
Raises :
QueueAlreadyClosed : if the queue is not started , or has already been
closed .
RuntimeError : if clos... | if not self . _closed_event or not self . _terminate_event :
raise RuntimeError ( 'Missing closed or terminate event.' )
if not abort and self . _closed_event . is_set ( ) :
raise errors . QueueAlreadyClosed ( )
self . _closed_event . set ( )
if abort :
if not self . _closed_event . is_set ( ) :
log... |
def do_ultracache ( parser , token ) :
"""Based on Django ' s default cache template tag""" | nodelist = parser . parse ( ( "endultracache" , ) )
parser . delete_first_token ( )
tokens = token . split_contents ( )
if len ( tokens ) < 3 :
raise TemplateSyntaxError ( "" % r" tag requires at least 2 arguments." % tokens [ 0 ] )
return UltraCacheNode ( nodelist , parser . compile_filter ( tokens [ 1 ] ) , token... |
def eeg_microstates ( gfp , n_microstates = 4 , clustering_method = "kmeans" , n_jobs = 1 , n_init = 25 , occurence_rejection_treshold = 0.05 , max_refitting = 5 , clustering_metrics = True , good_fit_treshold = 0 , feature_reduction_method = "PCA" , n_features = 32 , nonlinearity = True , verbose = True ) :
"""Run... | # if isinstance ( gfp , str ) :
# results = load _ object ( filename = gfp )
# else :
# results = gfp
if verbose is True :
print ( """
STARTING MICROSTATES ANALYSIS...
# ===================================
Infering microstates pattern from all data points...
# ---------------------------------------... |
def add_data ( t , msg , msg_types , vars , fields , field_types , position_field_type ) :
'''add some data''' | mtype = msg . get_type ( )
if mtype not in msg_types :
return
for i in range ( 0 , len ( fields ) ) :
if mtype not in field_types [ i ] :
continue
f = fields [ i ]
v = mavutil . evaluate_expression ( f , vars )
if v is None :
continue
# Check if we have position or state informat... |
def get_perm_model ( ) :
"""Returns the Perm model that is active in this project .""" | try :
return django_apps . get_model ( settings . PERM_MODEL , require_ready = False )
except ValueError :
raise ImproperlyConfigured ( "PERM_MODEL must be of the form 'app_label.model_name'" )
except LookupError :
raise ImproperlyConfigured ( "PERM_MODEL refers to model '{}' that has not been installed" . ... |
def subnet_absent ( name = None , subnet_id = None , region = None , key = None , keyid = None , profile = None ) :
'''Ensure subnet with passed properties is absent .
name
Name of the subnet .
region
Region to connect to .
key
Secret key to be used .
keyid
Access key to be used .
profile
A dict... | ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
r = __salt__ [ 'boto_vpc.get_resource_id' ] ( 'subnet' , name = name , region = region , key = key , keyid = keyid , profile = profile )
if 'error' in r :
ret [ 'result' ] = False
ret [ 'comment' ] = 'Failed to delete subnet: {0}.' . f... |
def _compress ( operation , data , ctx ) :
"""Takes message data , compresses it , and adds an OP _ COMPRESSED header .""" | compressed = ctx . compress ( data )
request_id = _randint ( )
header = _pack_compression_header ( _COMPRESSION_HEADER_SIZE + len ( compressed ) , # Total message length
request_id , # Request id
0 , # responseTo
2012 , # operation id
operation , # original operation id
len ( data ) , # uncompressed message length
ctx ... |
def sort_by_length_usearch61 ( seq_path , output_dir = "." , minlen = 64 , remove_usearch_logs = False , HALT_EXEC = False , output_fna_filepath = None , log_name = "length_sorted.log" ) :
"""usearch61 application call to sort fasta file by length .
seq _ path : fasta filepath to be clustered with usearch61
out... | if not output_fna_filepath :
_ , output_fna_filepath = mkstemp ( prefix = 'length_sorted' , suffix = '.fna' )
log_filepath = join ( output_dir , log_name )
params = { '--minseqlength' : minlen , '--sortbylength' : seq_path , '--output' : output_fna_filepath }
if not remove_usearch_logs :
params [ '--log' ] = lo... |
def get_registered_loggers ( hide_children = False , hide_reusables = False ) :
"""Find the names of all loggers currently registered
: param hide _ children : only return top level logger names
: param hide _ reusables : hide the reusables loggers
: return : list of logger names""" | return [ logger for logger in logging . Logger . manager . loggerDict . keys ( ) if not ( hide_reusables and "reusables" in logger ) and not ( hide_children and "." in logger ) ] |
def add_object_to_scope ( self , obj ) :
"""Add an object to the appropriate scope block .
Args :
obj : JSSObject to add to scope . Accepted subclasses are :
Computer
ComputerGroup
Building
Department
Raises :
TypeError if invalid obj type is provided .""" | if isinstance ( obj , Computer ) :
self . add_object_to_path ( obj , "scope/computers" )
elif isinstance ( obj , ComputerGroup ) :
self . add_object_to_path ( obj , "scope/computer_groups" )
elif isinstance ( obj , Building ) :
self . add_object_to_path ( obj , "scope/buildings" )
elif isinstance ( obj , De... |
def scheduleTask ( self , * args , ** kwargs ) :
"""Schedule Defined Task
scheduleTask will schedule a task to be executed , even if it has
unresolved dependencies . A task would otherwise only be scheduled if
its dependencies were resolved .
This is useful if you have defined a task that depends on itself ... | return self . _makeApiCall ( self . funcinfo [ "scheduleTask" ] , * args , ** kwargs ) |
def dimension_values ( self , dimension , expanded = True , flat = True ) :
"""Return the values along the requested dimension .
Applies to the main object in the AdjointLayout .
Args :
dimension : The dimension to return values for
expanded ( bool , optional ) : Whether to expand values
Whether to return... | dimension = self . get_dimension ( dimension , strict = True ) . name
return self . main . dimension_values ( dimension , expanded , flat ) |
def plot_scores ( self , motifs , name = True , max_len = 50 ) :
"""Create motif scores boxplot of different clusters .
Motifs can be specified as either motif or factor names .
The motif scores will be scaled and plotted as z - scores .
Parameters
motifs : iterable or str
List of motif or factor names . ... | if self . input . shape [ 1 ] != 1 :
raise ValueError ( "Can't make a categorical plot with real-valued data" )
if type ( "" ) == type ( motifs ) :
motifs = [ motifs ]
plot_motifs = [ ]
for motif in motifs :
if motif in self . motifs :
plot_motifs . append ( motif )
else :
for m in self ... |
def get_lxc_version ( ) :
"""Asks the current host what version of LXC it has . Returns it as a
string . If LXC is not installed , raises subprocess . CalledProcessError""" | runner = functools . partial ( subprocess . check_output , stderr = subprocess . STDOUT , universal_newlines = True , )
# Old LXC had an lxc - version executable , and prefixed its result with
# " lxc version : "
try :
result = runner ( [ 'lxc-version' ] ) . rstrip ( )
return parse_version ( result . replace ( ... |
def get_binary_path ( executable , logging_level = 'INFO' ) :
"""Gets the software name and returns the path of the binary .""" | if sys . platform == 'win32' :
if executable == 'start' :
return executable
executable = executable + '.exe'
if executable in os . listdir ( '.' ) :
binary = os . path . join ( os . getcwd ( ) , executable )
else :
binary = next ( ( os . path . join ( path , executable ) for path... |
def get_image_upload_to ( self , filename ) :
"""Returns the path to upload a new associated image to .""" | dummy , ext = os . path . splitext ( filename )
return os . path . join ( machina_settings . FORUM_IMAGE_UPLOAD_TO , '{id}{ext}' . format ( id = str ( uuid . uuid4 ( ) ) . replace ( '-' , '' ) , ext = ext ) , ) |
def labels ( ) :
"""Path to labels file""" | datapath = path . join ( path . dirname ( path . realpath ( __file__ ) ) , path . pardir )
datapath = path . join ( datapath , '../gzoo_data' , 'train_solution.csv' )
return path . normpath ( datapath ) |
def computeVoronoiDiagram ( points ) :
"""Takes a list of point objects ( which must have x and y fields ) .
Returns a 3 - tuple of :
(1 ) a list of 2 - tuples , which are the x , y coordinates of the
Voronoi diagram vertices
(2 ) a list of 3 - tuples ( a , b , c ) which are the equations of the
lines in ... | siteList = SiteList ( points )
context = Context ( )
voronoi ( siteList , context )
return ( context . vertices , context . edges , context . polygons ) |
def verify_id ( ctx , param , app ) :
"""Verify the experiment id .""" | if app is None :
raise TypeError ( "Select an experiment using the --app parameter." )
elif app [ 0 : 5 ] == "dlgr-" :
raise ValueError ( "The --app parameter requires the full " "UUID beginning with {}-..." . format ( app [ 5 : 13 ] ) )
return app |
def displayMakewcsWarningBox ( display = True , parent = None ) :
"""Displays a warning box for the ' makewcs ' parameter .""" | if sys . version_info [ 0 ] >= 3 :
from tkinter . messagebox import showwarning
else :
from tkMessageBox import showwarning
ans = { 'yes' : True , 'no' : False }
if ans [ display ] :
msg = 'Setting "updatewcs=yes" will result ' + 'in all input WCS values to be recomputed ' + 'using the original distortion m... |
def get_default_config_help ( self ) :
"""Returns the help text for the configuration options for this handler""" | config = super ( MultiGraphitePickleHandler , self ) . get_default_config_help ( )
config . update ( { 'host' : 'Hostname, Hostname, Hostname' , 'port' : 'Port' , 'proto' : 'udp or tcp' , 'timeout' : '' , 'batch' : 'How many to store before sending to the graphite server' , 'max_backlog_multiplier' : 'how many batches ... |
def rank_centrality ( n_items , data , alpha = 0.0 ) :
"""Compute the Rank Centrality estimate of model parameters .
This function implements Negahban et al . ' s Rank Centrality algorithm
[ NOS12 ] _ . The algorithm is similar to : func : ` ~ choix . ilsr _ pairwise ` , but
considers the * ratio * of wins fo... | _ , chain = _init_lsr ( n_items , alpha , None )
for winner , loser in data :
chain [ loser , winner ] += 1.0
# Transform the counts into ratios .
idx = chain > 0
# Indices ( i , j ) of non - zero entries .
chain [ idx ] = chain [ idx ] / ( chain + chain . T ) [ idx ]
# Finalize the Markov chain by adding the self ... |
def model_g2master_g ( model_params : Sequence [ Tensor ] , master_params : Sequence [ Tensor ] , flat_master : bool = False ) -> None :
"Copy the ` model _ params ` gradients to ` master _ params ` for the optimizer step ." | if flat_master :
for model_group , master_group in zip ( model_params , master_params ) :
if len ( master_group ) != 0 :
if master_group [ 0 ] . grad is None :
master_group [ 0 ] . grad = master_group [ 0 ] . data . new ( * master_group [ 0 ] . data . size ( ) )
maste... |
def metrolyrics ( song ) :
"""Returns the lyrics found in metrolyrics for the specified mp3 file or an
empty string if not found .""" | translate = { URLESCAPE : '' , ' ' : '-' }
title = song . title . lower ( )
title = normalize ( title , translate )
title = re . sub ( r'\-{2,}' , '-' , title )
artist = song . artist . lower ( )
artist = normalize ( artist , translate )
artist = re . sub ( r'\-{2,}' , '-' , artist )
url = 'http://www.metrolyrics.com/{... |
def _lint ( self ) :
"""Run linter in a subprocess .""" | command = self . _get_command ( )
process = subprocess . run ( command , stdout = subprocess . PIPE , # nosec
stderr = subprocess . PIPE )
LOG . info ( 'Finished %s' , ' ' . join ( command ) )
stdout , stderr = self . _get_output_lines ( process )
return self . _linter . parse ( stdout ) , self . _parse_stderr ( stderr... |
def parent ( self , parent ) :
"""Parents
: param parent : Parent to set for the object
: type parent : Collection
: return :""" | self . _parent = parent
self . graph . add ( ( self . asNode ( ) , RDF_NAMESPACES . CAPITAINS . parent , parent . asNode ( ) ) )
parent . _add_member ( self ) |
def series64bitto32bit ( s ) :
"""Convert a Pandas series from 64 bit types to 32 bit types to save
memory or disk space .
Parameters
s : The series to convert
Returns
The converted series""" | if s . dtype == np . float64 :
return s . astype ( 'float32' )
elif s . dtype == np . int64 :
return s . astype ( 'int32' )
return s |
def randomize_nick ( cls , base , suffix_length = 3 ) :
"""Generates a pseudo - random nickname .
: param base : prefix to use for the generated nickname .
: type base : unicode
: param suffix _ length : amount of digits to append to ` base `
: type suffix _ length : int
: return : generated nickname .
... | suffix = u'' . join ( choice ( u'0123456789' ) for _ in range ( suffix_length ) )
return u'{0}{1}' . format ( base , suffix ) |
def validate_v2_endpoint_data ( self , endpoints , admin_port , internal_port , public_port , expected ) :
"""Validate endpoint data .
Validate actual endpoint data vs expected endpoint data . The ports
are used to find the matching endpoint .""" | self . log . debug ( 'Validating endpoint data...' )
self . log . debug ( 'actual: {}' . format ( repr ( endpoints ) ) )
found = False
for ep in endpoints :
self . log . debug ( 'endpoint: {}' . format ( repr ( ep ) ) )
if ( admin_port in ep . adminurl and internal_port in ep . internalurl and public_port in ep... |
def atc ( jobid ) :
'''Print the at ( 1 ) script that will run for the passed job
id . This is mostly for debugging so the output will
just be text .
CLI Example :
. . code - block : : bash
salt ' * ' at . atc < jobid >''' | atjob_file = '/var/spool/cron/atjobs/{job}' . format ( job = jobid )
if __salt__ [ 'file.file_exists' ] ( atjob_file ) :
with salt . utils . files . fopen ( atjob_file , 'r' ) as rfh :
return '' . join ( [ salt . utils . stringutils . to_unicode ( x ) for x in rfh . readlines ( ) ] )
else :
return { 'er... |
def dpd_to_int ( dpd ) :
"""Convert DPD encodined value to int ( 0-999)
dpd : DPD encoded value . 10bit unsigned int""" | b = [ None ] * 10
b [ 9 ] = 1 if dpd & 0b1000000000 else 0
b [ 8 ] = 1 if dpd & 0b0100000000 else 0
b [ 7 ] = 1 if dpd & 0b0010000000 else 0
b [ 6 ] = 1 if dpd & 0b0001000000 else 0
b [ 5 ] = 1 if dpd & 0b0000100000 else 0
b [ 4 ] = 1 if dpd & 0b0000010000 else 0
b [ 3 ] = 1 if dpd & 0b0000001000 else 0
b [ 2 ] = 1 if ... |
def event_id ( name , encode_types ) :
"""Return the event id .
Defined as :
` keccak ( EVENT _ NAME + " ( " + EVENT _ ARGS . map ( canonical _ type _ of ) . join ( " , " ) + " ) " ) `
Where ` canonical _ type _ of ` is a function that simply returns the canonical
type of a given argument , e . g . for uint... | event_types = [ _canonical_type ( type_ ) for type_ in encode_types ]
event_signature = '{event_name}({canonical_types})' . format ( event_name = name , canonical_types = ',' . join ( event_types ) , )
return big_endian_to_int ( utils . sha3 ( event_signature ) ) |
def _set_cluster ( self , v , load = False ) :
"""Setter method for cluster , mapped from YANG variable / cluster ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ cluster is considered as a private
method . Backends looking to populate this variable should
d... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "cluster_name cluster_id" , cluster . cluster , yang_name = "cluster" , rest_name = "cluster" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'cl... |
def objects ( self , cls = None ) :
"""Return an iterater over all objects in this directory which are
instances of ` cls ` . By default , iterate over all objects ( ` cls = None ` ) .
Parameters
cls : a class , optional ( default = None )
If a class is specified , only iterate over objects that are
insta... | objs = ( asrootpy ( x . ReadObj ( ) , warn = False ) for x in self . GetListOfKeys ( ) )
if cls is not None :
objs = ( obj for obj in objs if isinstance ( obj , cls ) )
return objs |
def filter_top_level ( stmts_in , ** kwargs ) :
"""Filter to statements that are at the top - level of the hierarchy .
Here top - level statements correspond to most specific ones .
Parameters
stmts _ in : list [ indra . statements . Statement ]
A list of statements to filter .
save : Optional [ str ]
T... | logger . info ( 'Filtering %d statements for top-level...' % len ( stmts_in ) )
stmts_out = [ st for st in stmts_in if not st . supports ]
logger . info ( '%d statements after filter...' % len ( stmts_out ) )
dump_pkl = kwargs . get ( 'save' )
if dump_pkl :
dump_statements ( stmts_out , dump_pkl )
return stmts_out |
def _py24_25_compat ( self ) :
"""Python 2.4/2.5 have grave difficulties with threads / fork . We
mandatorily quiesce all running threads during fork using a
monkey - patch there .""" | if sys . version_info < ( 2 , 6 ) : # import _ module ( ) is used to avoid dep scanner .
os_fork = import_module ( 'mitogen.os_fork' )
mitogen . os_fork . _notice_broker_or_pool ( self ) |
def sync_mounts ( self , active_mounts , resources , vault_client ) :
"""Synchronizes mount points . Removes things before
adding new .""" | # Create a resource set that is only explicit mounts
# and sort so removals are first
mounts = [ x for x in resources if isinstance ( x , ( Mount , AWS ) ) ]
s_resources = sorted ( mounts , key = absent_sort )
# Iterate over explicit mounts only
for resource in s_resources :
active_mounts = self . actually_mount ( ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.