signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _ex_type_str ( exobj ) :
"""Return a string corresponding to the exception type .""" | regexp = re . compile ( r"<(?:\bclass\b|\btype\b)\s+'?([\w|\.]+)'?>" )
exc_type = str ( exobj )
if regexp . match ( exc_type ) :
exc_type = regexp . match ( exc_type ) . groups ( ) [ 0 ]
exc_type = exc_type [ 11 : ] if exc_type . startswith ( "exceptions." ) else exc_type
if "." in exc_type :
exc_type = exc... |
def create_namespaced_pod_template ( self , namespace , body , ** kwargs ) : # noqa : E501
"""create _ namespaced _ pod _ template # noqa : E501
create a PodTemplate # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_namespaced_pod_template_with_http_info ( namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . create_namespaced_pod_template_with_http_info ( namespace , body , ** kwargs )
# noqa : E501
... |
def predict ( self , features , verbose = False ) :
"""Probability estimates of each feature
See sklearn ' s SGDClassifier predict and predict _ proba methods .
Args :
features ( : obj : ` list ` of : obj : ` list ` of : obj : ` float ` )
verbose : Boolean , optional . If true returns an array where each
... | probs = self . clf . predict_proba ( features )
if verbose :
labels = self . labels . classes_
res = [ ]
for prob in probs :
vals = { }
for i , val in enumerate ( prob ) :
label = labels [ i ]
vals [ label ] = val
res . append ( vals )
return res
else :
... |
def set_as_defaults ( self ) :
"""Set defaults from the current config""" | self . defaults = [ ]
for section in self . sections ( ) :
secdict = { }
for option , value in self . items ( section , raw = self . raw ) :
secdict [ option ] = value
self . defaults . append ( ( section , secdict ) ) |
def smart_fitting_predicate ( page_width , ribbon_frac , min_nesting_level , max_width , triplestack ) :
"""Lookahead until the last doc at the current indentation level .
Pretty , but not as fast .""" | chars_left = max_width
while chars_left >= 0 :
if not triplestack :
return True
indent , mode , doc = triplestack . pop ( )
if doc is NIL :
continue
elif isinstance ( doc , str ) :
chars_left -= len ( doc )
elif isinstance ( doc , Concat ) : # Recursive call in Strictly Prett... |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) :
"""See : meth : ` superclass method
< . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > `
for spec of input and result values .""" | mean = self . _get_mean ( sites . vs30 , rup . mag , dists . rrup , imt , scale_fac = 0 )
stddevs = self . _get_stddevs ( stddev_types , num_sites = sites . vs30 . size )
return mean , stddevs |
def persist ( self ) :
"""Banana banana""" | os . makedirs ( self . __symbol_folder , exist_ok = True )
os . makedirs ( self . __aliases_folder , exist_ok = True )
os . makedirs ( self . __comments_folder , exist_ok = True )
for name , sym in self . __symbols . items ( ) :
with open ( self . __get_pickle_path ( self . __symbol_folder , name , True ) , 'wb' ) ... |
def et2roc ( et_fo , roc_fo ) :
"""ET to ROC conversion .
Args :
et _ fo ( file ) : File object for the ET file .
roc _ fo ( file ) : File object for the ROC file .
raises : ValueError""" | stats_dicts = [ { "q" : q , "M" : 0 , "w" : 0 , "m" : 0 , "P" : 0 , "U" : 0 , "u" : 0 , "T" : 0 , "t" : 0 , "x" : 0 } for q in range ( rnftools . lavender . MAXIMAL_MAPPING_QUALITY + 1 ) ]
for line in et_fo :
line = line . strip ( )
if line != "" and line [ 0 ] != "#" :
( read_tuple_name , tab , info_ca... |
def execute ( self , eopatch , * , eopatch_folder ) :
"""Saves the EOPatch to disk : ` folder / eopatch _ folder ` .
: param eopatch : EOPatch which will be saved
: type eopatch : EOPatch
: param eopatch _ folder : name of EOPatch folder containing data
: type eopatch _ folder : str
: return : The same EO... | eopatch . save ( os . path . join ( self . folder , eopatch_folder ) , * self . args , ** self . kwargs )
return eopatch |
def _SimpleSizer ( compute_value_size ) :
"""A sizer which uses the function compute _ value _ size to compute the size of
each value . Typically compute _ value _ size is _ VarintSize .""" | def SpecificSizer ( field_number , is_repeated , is_packed ) :
tag_size = _TagSize ( field_number )
if is_packed :
local_VarintSize = _VarintSize
def PackedFieldSize ( value ) :
result = 0
for element in value :
result += compute_value_size ( element )
... |
def surface_constructor ( surface ) :
"""Image for : class ` . Surface ` docstring .""" | if NO_IMAGES :
return
ax = surface . plot ( 256 , with_nodes = True )
line = ax . lines [ 0 ]
nodes = surface . _nodes
add_patch ( ax , nodes [ : , ( 0 , 1 , 2 , 5 ) ] , line . get_color ( ) )
delta = 1.0 / 32.0
ax . text ( nodes [ 0 , 0 ] , nodes [ 1 , 0 ] , r"$v_0$" , fontsize = 20 , verticalalignment = "top" , h... |
def scalefactor ( self , other , qmin = None , qmax = None , Npoints = None ) :
"""Calculate a scaling factor , by which this curve is to be multiplied to best fit the other one .
Inputs :
other : the other curve ( an instance of GeneralCurve or of a subclass of it )
qmin : lower cut - off ( None to determine... | if qmin is None :
qmin = max ( self . q . min ( ) , other . q . min ( ) )
if qmax is None :
xmax = min ( self . q . max ( ) , other . q . max ( ) )
data1 = self . trim ( qmin , qmax )
data2 = other . trim ( qmin , qmax )
if Npoints is None :
Npoints = min ( len ( data1 ) , len ( data2 ) )
commonx = np . lin... |
def alias_absent ( name , index ) :
'''Ensure that the index alias is absent .
name
Name of the index alias to remove
index
Name of the index for the alias''' | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
try :
alias = __salt__ [ 'elasticsearch.alias_get' ] ( aliases = name , indices = index )
if alias and alias . get ( index , { } ) . get ( "aliases" , { } ) . get ( name , None ) is not None :
if __opts__ [ 'test' ] :
... |
def standardize_images ( x ) :
"""Image standardization on batches and videos .""" | with tf . name_scope ( "standardize_images" , values = [ x ] ) :
x_shape = shape_list ( x )
x = to_float ( tf . reshape ( x , [ - 1 ] + x_shape [ - 3 : ] ) )
x_mean = tf . reduce_mean ( x , axis = [ 1 , 2 ] , keepdims = True )
x_variance = tf . reduce_mean ( tf . squared_difference ( x , x_mean ) , axis... |
def _update_indexes_for_mutated_object ( collection , obj ) :
"""If an object is updated , this will simply remove
it and re - add it to the indexes defined on the
collection .""" | for index in _db [ collection ] . indexes . values ( ) :
_remove_from_index ( index , obj )
_add_to_index ( index , obj ) |
def login ( self , template = 'login' ) :
'''This property will return component which will handle login requests .
auth . login ( template = ' login . html ' )''' | def _login ( env , data ) :
form = self . _login_form ( env )
next = env . request . GET . get ( 'next' , '/' )
login_failed = False
if env . request . method == 'POST' :
if form . accept ( env . request . POST ) :
user_identity = self . get_user_identity ( env , ** form . python_dat... |
def push ( self ) :
"""Push built documents to ElasticSearch .""" | self . _refresh_connection ( )
# Check if we need to update mappings as this needs to be done
# before we push anything to the Elasticsearch server .
# This must be done even if the queue is empty , as otherwise ES
# will fail when retrieving data .
if not self . _mapping_created :
logger . debug ( "Pushing mapping... |
def to_xyz ( self , buf = None , sort_index = True , index = False , header = False , float_format = '{:.6f}' . format , overwrite = True ) :
"""Write xyz - file
Args :
buf ( str ) : StringIO - like , optional buffer to write to
sort _ index ( bool ) : If sort _ index is true , the
: class : ` ~ chemcoord .... | if sort_index :
molecule_string = self . sort_index ( ) . to_string ( header = header , index = index , float_format = float_format )
else :
molecule_string = self . to_string ( header = header , index = index , float_format = float_format )
# NOTE the following might be removed in the future
# introduced becau... |
def get_object ( self , setting_name , warn_only_if_overridden = False , accept_deprecated = '' , suppress_warnings = False , warning_stacklevel = 3 ) :
"""Returns a python class , method , or other object referenced by an app
setting where the value is expected to be a valid , absolute Python
import path , def... | self . _warn_if_deprecated_setting_value_requested ( setting_name , warn_only_if_overridden , suppress_warnings , warning_stacklevel )
cache_key = self . _make_cache_key ( setting_name , accept_deprecated )
if cache_key in self . _objects_cache :
return self . _objects_cache [ cache_key ]
raw_value = self . get ( s... |
def isLevel2 ( edtf_candidate ) :
"""Checks to see if the date is level 2 valid""" | if "[" in edtf_candidate or "{" in edtf_candidate :
result = edtf_candidate == level2Expression
elif " " in edtf_candidate :
result = False
else :
result = edtf_candidate == level2Expression
return result |
def render ( self , * , block_span_x : Optional [ int ] = None , block_span_y : Optional [ int ] = None , min_block_width : int = 0 , min_block_height : int = 0 ) -> str :
"""Outputs text containing the diagram .
Args :
block _ span _ x : The width of the diagram in blocks . Set to None to
default to using th... | # Determine desired size of diagram in blocks .
if block_span_x is None :
block_span_x = 1 + max ( max ( x for x , _ in self . _blocks . keys ( ) ) , max ( self . _min_widths . keys ( ) ) , )
if block_span_y is None :
block_span_y = 1 + max ( max ( y for _ , y in self . _blocks . keys ( ) ) , max ( self . _min_... |
def _swallow_next_tc ( self , grid_width , top_tc ) :
"""Extend the horizontal span of this ` w : tc ` element to incorporate the
following ` w : tc ` element in the row and then delete that following
` w : tc ` element . Any content in the following ` w : tc ` element is
appended to the content of * top _ tc... | def raise_on_invalid_swallow ( next_tc ) :
if next_tc is None :
raise InvalidSpanError ( 'not enough grid columns' )
if self . grid_span + next_tc . grid_span > grid_width :
raise InvalidSpanError ( 'span is not rectangular' )
next_tc = self . _next_tc
raise_on_invalid_swallow ( next_tc )
next_t... |
def align_rna ( job , fastqs , univ_options , star_options ) :
"""A wrapper for the entire rna alignment subgraph .
: param list fastqs : The input fastqs for alignment
: param dict univ _ options : Dict of universal options used by almost all tools
: param dict star _ options : Options specific to star
: r... | star = job . wrapJobFn ( run_star , fastqs , univ_options , star_options , cores = star_options [ 'n' ] , memory = PromisedRequirement ( lambda x : int ( 1.85 * x . size ) , star_options [ 'index' ] ) , disk = PromisedRequirement ( star_disk , fastqs , star_options [ 'index' ] ) )
s_and_i = job . wrapJobFn ( sort_and_i... |
def prepare_environment ( params : Params ) :
"""Sets random seeds for reproducible experiments . This may not work as expected
if you use this from within a python project in which you have already imported Pytorch .
If you use the scripts / run _ model . py entry point to training models with this library ,
... | seed = params . pop_int ( "random_seed" , 13370 )
numpy_seed = params . pop_int ( "numpy_seed" , 1337 )
torch_seed = params . pop_int ( "pytorch_seed" , 133 )
if seed is not None :
random . seed ( seed )
if numpy_seed is not None :
numpy . random . seed ( numpy_seed )
if torch_seed is not None :
torch . man... |
def frames ( self ) :
"""Retrieve the next frame from the image directory and convert it to a ColorImage ,
a DepthImage , and an IrImage .
Parameters
skip _ registration : bool
If True , the registration step is skipped .
Returns
: obj : ` tuple ` of : obj : ` ColorImage ` , : obj : ` DepthImage ` , : o... | if not self . _running :
raise RuntimeError ( 'Device pointing to %s not runnning. Cannot read frames' % ( self . _path_to_images ) )
if self . _im_index >= self . _num_images :
raise RuntimeError ( 'Device is out of images' )
# read images
color_filename = os . path . join ( self . _path_to_images , 'color_%d%... |
async def request ( self , request , addr , integrity_key = None , retransmissions = None ) :
"""Execute a STUN transaction and return the response .""" | assert request . transaction_id not in self . transactions
if integrity_key is not None :
request . add_message_integrity ( integrity_key )
request . add_fingerprint ( )
transaction = stun . Transaction ( request , addr , self , retransmissions = retransmissions )
transaction . integrity_key = integrity_key
sel... |
def is_tile_strictly_isolated ( hand_34 , tile_34 ) :
"""Tile is strictly isolated if it doesn ' t have - 2 , - 1 , 0 , + 1 , + 2 neighbors
: param hand _ 34 : array of tiles in 34 tile format
: param tile _ 34 : int
: return : bool""" | hand_34 = copy . copy ( hand_34 )
# we don ' t need to count target tile in the hand
hand_34 [ tile_34 ] -= 1
if hand_34 [ tile_34 ] < 0 :
hand_34 [ tile_34 ] = 0
indices = [ ]
if is_honor ( tile_34 ) :
return hand_34 [ tile_34 ] == 0
else :
simplified = simplify ( tile_34 )
# 1 suit tile
if simplif... |
def filter_tag ( arg ) :
"""Parses a - - filter - tag argument""" | try :
strip_len = len ( 'Key=' )
key , value = arg [ strip_len : ] . split ( ',Value=' , 1 )
return key , value
except :
msg = 'Invalid --filter-tag argument: {}'
raise argparse . ArgumentTypeError ( msg . format ( arg ) ) |
def retrieve ( self ) :
"""Retrieve contact information on ourselves .""" | response = self . request ( E . retrieveResellerRequest ( ) )
return Reseller ( response . data ) |
def UninstallTrump ( RemoveDataTables = True , RemoveOverrides = True , RemoveFailsafes = True ) :
"""This script removes all tables associated with Trump .
It ' s written for PostgreSQL , but should be very easy to adapt to other
databases .""" | ts = [ '_symbols' , '_symbol_validity' , '_symbol_tags' , '_symbol_aliases' , '_feeds' , '_feed_munging' , '_feed_munging_args' , '_feed_sourcing' , '_feed_validity' , '_feed_meta' , '_feed_tags' , '_feed_handle' , '_index_kwargs' , '_indicies' , '_symbol_handle' , '_symboldatadef' ]
if RemoveOverrides :
ts . appen... |
def tokenize_timeperiod ( timeperiod ) :
"""method breaks given timeperiod into 4 parts : ( year , month , day , hour )
for instance : daily 2015031400 - > ( ' 2013 ' , ' 03 ' , ' 14 ' , ' 00 ' )
hourly 2015031413 - > ( ' 2013 ' , ' 03 ' , ' 14 ' , ' 13 ' )
monthly 2015030000 - > ( ' 2013 ' , ' 03 ' , ' 00 ' ... | assert len ( timeperiod ) == 10 , 'timeperiod {0} does not match accepted format YYYYMMDDHH' . format ( timeperiod )
return timeperiod [ : 4 ] , timeperiod [ 4 : 6 ] , timeperiod [ 6 : 8 ] , timeperiod [ 8 : ] , |
def get_hostname_from_dn ( dn ) :
"""This parses the hostname from a dn designator . They look like this :
topology / pod - 1 / node - 101 / sys / phys - [ eth1/6 ] / CDeqptMacsectxpkts5min""" | pod = get_pod_from_dn ( dn )
node = get_node_from_dn ( dn )
if pod and node :
return "pod-{}-node-{}" . format ( pod , node )
else :
return None |
def merge ( self , range2 ) :
"""merge this bed with another bed to make a longer bed . Returns None if on different chromosomes .
keeps the options of this class ( not range2)
: param range2:
: type range2 : GenomicRange
: return : bigger range with both
: rtype : GenomicRange""" | if self . chr != range2 . chr :
return None
o = type ( self ) ( self . chr , min ( self . start , range2 . start ) + self . _start_offset , max ( self . end , range2 . end ) , self . payload , self . dir )
return o |
def subject_id ( self ) :
"""The name of the subject can be in either of
BaseID , NameID or EncryptedID
: return : The identifier if there is one""" | if "subject" in self . message . keys ( ) :
_subj = self . message . subject
if "base_id" in _subj . keys ( ) and _subj . base_id :
return _subj . base_id
elif _subj . name_id :
return _subj . name_id
else :
if "base_id" in self . message . keys ( ) and self . message . base_id :
... |
def _JMS_to_Bern_I ( C , qq ) :
"""From JMS to BernI basis ( = traditional SUSY basis in this case )
for $ \ Delta F = 2 $ operators .
` qq ` should be ' sb ' , ' db ' , ' ds ' or ' cu '""" | if qq in [ 'sb' , 'db' , 'ds' ] :
dd = 'dd'
ij = tuple ( dflav [ q ] for q in qq )
elif qq == 'cu' :
dd = 'uu'
ij = tuple ( uflav [ q ] for q in qq )
else :
raise ValueError ( "not in Bern_I: " . format ( qq ) )
ji = ( ij [ 1 ] , ij [ 0 ] )
d = { '1' + 2 * qq : C [ "V{}LL" . format ( dd ) ] [ ij + i... |
def time ( self ) :
"""Returns time as list [ hh , mm , ss ] .""" | slist = self . toList ( )
if slist [ 0 ] == '-' :
slist [ 1 ] *= - 1
# We must do a trick if we want to
# make negative zeros explicit
if slist [ 1 ] == - 0 :
slist [ 1 ] = - 0.0
return slist [ 1 : ] |
def _parse_fmadm_config ( output ) :
'''Parsbb fmdump / fmadm output''' | result = [ ]
output = output . split ( "\n" )
# extract header
header = [ field for field in output [ 0 ] . lower ( ) . split ( " " ) if field ]
del output [ 0 ]
# parse entries
for entry in output :
entry = [ item for item in entry . split ( " " ) if item ]
entry = entry [ 0 : 3 ] + [ " " . join ( entry [ 3 : ... |
def aes_pad ( s , block_size = 32 , padding = '{' ) :
"""Adds padding to get the correct block sizes for AES encryption
@ s : # str being AES encrypted or decrypted
@ block _ size : the AES block size
@ padding : character to pad with
- > padded # str
from vital . security import aes _ pad
aes _ pad ( "... | return s + ( block_size - len ( s ) % block_size ) * padding |
def synergy_to_datetime ( time_qualifier , timeperiod ) :
"""method receives timeperiod in Synergy format YYYYMMDDHH and convert it to UTC _ naive _ datetime""" | if time_qualifier == QUALIFIER_HOURLY :
date_format = SYNERGY_HOURLY_PATTERN
elif time_qualifier == QUALIFIER_DAILY :
date_format = SYNERGY_DAILY_PATTERN
elif time_qualifier == QUALIFIER_MONTHLY :
date_format = SYNERGY_MONTHLY_PATTERN
elif time_qualifier == QUALIFIER_YEARLY :
date_format = SYNERGY_YEARL... |
async def get_http_proxy ( cls ) -> typing . Optional [ str ] :
"""Proxy for APT and HTTP / HTTPS .
This will be passed onto provisioned nodes to use as a proxy for APT
traffic . MAAS also uses the proxy for downloading boot images . If no
URL is provided , the built - in MAAS proxy will be used .""" | data = await cls . get_config ( "http_proxy" )
return None if data is None or data == "" else data |
def _buildTerms ( self ) :
"""Builds a data structure indexing the terms
longitude by sign and object .""" | termLons = tables . termLons ( tables . EGYPTIAN_TERMS )
res = { }
for ( ID , sign , lon ) in termLons :
try :
res [ sign ] [ ID ] = lon
except KeyError :
res [ sign ] = { }
res [ sign ] [ ID ] = lon
return res |
def ratio ( self , operand ) :
"""Calculate the ratio of this ` Spectrogram ` against a reference
Parameters
operand : ` str ` , ` FrequencySeries ` , ` Quantity `
a ` ~ gwpy . frequencyseries . FrequencySeries ` or
` ~ astropy . units . Quantity ` to weight against , or one of
- ` ` ' mean ' ` ` : weight... | if isinstance ( operand , string_types ) :
if operand == 'mean' :
operand = self . mean ( axis = 0 )
elif operand == 'median' :
operand = self . median ( axis = 0 )
else :
raise ValueError ( "operand %r unrecognised, please give a " "Quantity or one of: 'mean', 'median'" % operand )
... |
def join_channel ( self , partner_address , partner_deposit ) :
"""Will be called , when we were selected as channel partner by another
node . It will fund the channel with up to the partners deposit , but
not more than remaining funds or the initial funding per channel .
If the connection manager has no fund... | # Consider this race condition :
# - Partner opens the channel and starts the deposit .
# - This nodes learns about the new channel , starts ConnectionManager ' s
# retry _ connect , which will start a deposit for this half of the
# channel .
# - This node learns about the partner ' s deposit before its own .
# join _ ... |
def calculate_clock_angle ( inst ) :
"""Calculate IMF clock angle and magnitude of IMF in GSM Y - Z plane
Parameters
inst : pysat . Instrument
Instrument with OMNI HRO data""" | # Calculate clock angle in degrees
clock_angle = np . degrees ( np . arctan2 ( inst [ 'BY_GSM' ] , inst [ 'BZ_GSM' ] ) )
clock_angle [ clock_angle < 0.0 ] += 360.0
inst [ 'clock_angle' ] = pds . Series ( clock_angle , index = inst . data . index )
# Calculate magnitude of IMF in Y - Z plane
inst [ 'BYZ_GSM' ] = pds . S... |
def build_ricecooker_json_tree ( args , options , metadata_provider , json_tree_path ) :
"""Download all categories , subpages , modules , and resources from open . edu .""" | LOGGER . info ( 'Starting to build the ricecooker_json_tree' )
channeldir = args [ 'channeldir' ]
if channeldir . endswith ( os . path . sep ) :
channeldir . rstrip ( os . path . sep )
channelparentdir , channeldirname = os . path . split ( channeldir )
channelparentdir , channeldirname = os . path . split ( channe... |
def as_dict ( self , keep_readonly = True , key_transformer = attribute_transformer ) :
"""Return a dict that can be JSONify using json . dump .
Advanced usage might optionaly use a callback as parameter :
. . code : : python
def my _ key _ transformer ( key , attr _ desc , value ) :
return key
Key is the... | serializer = Serializer ( self . _infer_class_models ( ) )
return serializer . _serialize ( self , key_transformer = key_transformer , keep_readonly = keep_readonly ) |
def _M2_dense ( X , Y , weights = None , diag_only = False ) :
"""2nd moment matrix using dense matrix computations .
This function is encapsulated such that we can make easy modifications of the basic algorithms""" | if weights is not None :
if diag_only :
return np . sum ( weights [ : , None ] * X * Y , axis = 0 )
else :
return np . dot ( ( weights [ : , None ] * X ) . T , Y )
else :
if diag_only :
return np . sum ( X * Y , axis = 0 )
else :
return np . dot ( X . T , Y ) |
def genfromtxt_args_error ( self ) :
"""Passed as keyword arguments to [ ` numpy . genfromtxt ` ] [ 1]
when called by ` scipy _ data _ fitting . Data . load _ error ` .
Even if defined here , the ` usecols ` value will always be reset based
on ` scipy _ data _ fitting . Data . error _ columns ` before being p... | if not hasattr ( self , '_genfromtxt_args_error' ) :
self . _genfromtxt_args_error = self . genfromtxt_args . copy ( )
return self . _genfromtxt_args_error |
def execute_command ( self , * args , ** options ) :
"""Execute a command and return a parsed response""" | pool = self . connection_pool
command_name = args [ 0 ]
for i in _xrange ( self . execution_attempts ) :
connection = pool . get_connection ( command_name , ** options )
try :
connection . send_command ( * args )
res = self . parse_response ( connection , command_name , ** options )
pool... |
def send ( self , task , result , expire = 60 ) :
"""Sends the result back to the producer . This should be called if only you
want to return the result in async manner .
: arg task : : : class : ` ~ retask . task . Task ` object
: arg result : Result data to be send back . Should be in JSON serializable .
... | self . rdb . lpush ( task . urn , json . dumps ( result ) )
self . rdb . expire ( task . urn , expire ) |
def get ( self , index ) :
"""Returns the ` Constant ` at ` index ` , raising a KeyError if it
does not exist .""" | constant = self . _pool [ index ]
if not isinstance ( constant , Constant ) :
constant = _constant_types [ constant [ 0 ] ] ( self , index , * constant [ 1 : ] )
self . _pool [ index ] = constant
return constant |
def memoized ( maxsize = 1024 ) :
"""Momoization decorator for immutable classes and pure functions .""" | cache = SimpleCache ( maxsize = maxsize )
def decorator ( obj ) :
@ wraps ( obj )
def new_callable ( * a , ** kw ) :
def create_new ( ) :
return obj ( * a , ** kw )
key = ( a , tuple ( kw . items ( ) ) )
return cache . get ( key , create_new )
return new_callable
return d... |
def API520_A_g ( m , T , Z , MW , k , P1 , P2 = 101325 , Kd = 0.975 , Kb = 1 , Kc = 1 ) :
r'''Calculates required relief valve area for an API 520 valve passing
a gas or a vapor , at either critical or sub - critical flow .
For critical flow :
. . math : :
A = \ frac { m } { CK _ dP _ 1K _ bK _ c } \ sqrt {... | P1 , P2 = P1 / 1000. , P2 / 1000.
# Pa to Kpa in the standard
m = m * 3600.
# kg / s to kg / hr
if is_critical_flow ( P1 , P2 , k ) :
C = API520_C ( k )
A = m / ( C * Kd * Kb * Kc * P1 ) * ( T * Z / MW ) ** 0.5
else :
F2 = API520_F2 ( k , P1 , P2 )
A = 17.9 * m / ( F2 * Kd * Kc ) * ( T * Z / ( MW * P1 *... |
def is_file_exists ( filename ) : # type : ( AnyStr ) - > bool
"""Check the existence of file path .""" | if filename is None or not os . path . exists ( filename ) or not os . path . isfile ( filename ) :
return False
else :
return True |
def cache_key_prefix ( request ) :
"""Cache key for yacms ' s cache middleware . Adds the current
device and site ID .""" | cache_key = "%s.%s.%s." % ( settings . CACHE_MIDDLEWARE_KEY_PREFIX , current_site_id ( ) , device_from_request ( request ) or "default" , )
return _i18n_cache_key_suffix ( request , cache_key ) |
def create_pipeline ( self ) :
"""Use JSON files to create Pipelines .""" | pipelines = self . settings [ 'pipeline' ] [ 'pipeline_files' ]
self . log . info ( 'Uploading manual Pipelines: %s' , pipelines )
lookup = FileLookup ( git_short = self . generated . gitlab ( ) [ 'main' ] , runway_dir = self . runway_dir )
for json_file in pipelines :
json_dict = lookup . json ( filename = json_fi... |
def list ( self , filter = None , type = None , sort = None , limit = None , page = None ) : # pylint : disable = redefined - builtin
"""Get a list of packages .
: param filter : ( optional ) Filters to apply as a string list .
: param type : ( optional ) ` union ` or ` inter ` as string .
: param sort : ( op... | schema = PackageSchema ( exclude = ( 'testlist' , 'extra_cli_args' , 'agent_id' , 'options' , 'note' ) )
resp = self . service . list ( self . base , filter , type , sort , limit , page )
ps , l = self . service . decode ( schema , resp , many = True , links = True )
return Page ( ps , l ) |
def vibrational_internal_energy ( self , temperature , volume ) :
"""Vibrational internal energy , U _ vib ( V , T ) .
Eq ( 4 ) in doi . org / 10.1016 / j . comphy . 2003.12.001
Args :
temperature ( float ) : temperature in K
volume ( float ) : in Ang ^ 3
Returns :
float : vibrational internal energy in... | y = self . debye_temperature ( volume ) / temperature
return self . kb * self . natoms * temperature * ( 9. / 8. * y + 3 * self . debye_integral ( y ) ) |
def user_portals_picker ( self ) :
"""This function is broken and needs to either be fixed or discarded .
User - Interaction function . Allows user to choose which Portal
to make the active one .""" | # print ( " Getting Portals list . This could take a few seconds . . . " )
portals = self . get_portals_list ( )
done = False
while not done :
opts = [ ( i , p ) for i , p in enumerate ( portals ) ]
# print ( ' ' )
for opt , portal in opts :
print ( "\t{0} - {1}" . format ( opt , portal [ 1 ] ) )
... |
def __get_keys_map ( self , bundleId , languageId , fallback = False ) :
"""Returns key - value pairs for the specified language .
If fallback is ` ` True ` ` , source language value is used if translated
value is not available .""" | return self . __get_language_data ( bundleId = bundleId , languageId = languageId , fallback = fallback ) |
def _updateImage ( self ) :
"""Internal method to render text as an image .""" | # Fill the background of the image
if self . backgroundColor is not None :
self . textImage . fill ( self . backgroundColor )
# Render the text as a single line , and blit it onto the textImage surface
if self . mask is None :
lineSurface = self . font . render ( self . text , True , self . textColor )
else :
... |
def classes ( p : ecore . EPackage ) :
"""Returns classes in package in ordered by number of bases .""" | classes = ( c for c in p . eClassifiers if isinstance ( c , ecore . EClass ) )
return sorted ( classes , key = lambda c : len ( set ( c . eAllSuperTypes ( ) ) ) ) |
def _parseSections ( self , data , imageDosHeader , imageNtHeaders , parse_header_only = False ) :
"""Parses the sections in the memory and returns a list of them""" | sections = [ ]
optional_header_offset = imageDosHeader . header . e_lfanew + 4 + sizeof ( IMAGE_FILE_HEADER )
offset = optional_header_offset + imageNtHeaders . header . FileHeader . SizeOfOptionalHeader
# start reading behind the dos - and ntheaders
image_section_header_size = sizeof ( IMAGE_SECTION_HEADER )
for secti... |
def _parse_topic ( self , element ) :
"""Parse and assign the topic for this trigger
: param element : The XML Element object
: type element : etree . _ Element""" | self . _log . debug ( 'Setting Trigger topic: {topic}' . format ( topic = element . text ) )
super ( Trigger , self ) . _parse_topic ( element ) |
def authenticate_through_netrc ( path = None ) :
"""Return the tuple user / password given a path for the . netrc file .
Raises CredentialsError if no valid netrc file is found .""" | errors = [ ]
netrc_machine = 'coursera-dl'
paths = [ path ] if path else get_config_paths ( "netrc" )
for path in paths :
try :
logging . debug ( 'Trying netrc file %s' , path )
auths = netrc . netrc ( path ) . authenticators ( netrc_machine )
except ( IOError , netrc . NetrcParseError ) as e :
... |
def tomof ( self , indent = 0 , maxline = MAX_MOF_LINE ) :
"""Return a MOF string with the declaration of this CIM method for use in
a CIM class declaration .
The order of parameters and qualifiers is preserved .
Parameters :
indent ( : term : ` integer ` ) : Number of spaces to indent each line of
the re... | mof = [ ]
if self . qualifiers :
mof . append ( _qualifiers_tomof ( self . qualifiers , indent + MOF_INDENT , maxline ) )
mof . append ( _indent_str ( indent ) )
# return _ type is ensured not to be None or reference
mof . append ( moftype ( self . return_type , None ) )
mof . append ( u' ' )
mof . append ( self . ... |
def function_linenumber ( function_index = 1 , function_name = None , width = 5 ) :
"""This will return the line number of the indicated function in the stack
: param width :
: param function _ index : int of how many frames back the program
should look ( 2 will give the parent of the caller )
: param funct... | frm = func_frame ( function_index + 1 , function_name )
if width is None :
return frm . _f_lineno
return str ( frm . f_lineno ) . ljust ( width ) |
def _build_jacobian ( self , Ybus , V , pv , pq , pvpq ) :
"""Returns the Jacobian matrix .""" | pq_col = [ [ i ] for i in pq ]
pvpq_col = [ [ i ] for i in pvpq ]
dS_dVm , dS_dVa = self . case . dSbus_dV ( Ybus , V )
J11 = dS_dVa [ pvpq_col , pvpq ] . real
J12 = dS_dVm [ pvpq_col , pq ] . real
J21 = dS_dVa [ pq_col , pvpq ] . imag
J22 = dS_dVm [ pq_col , pq ] . imag
J = vstack ( [ hstack ( [ J11 , J12 ] ) , hstack... |
def _get_json ( value ) :
"""Convert the given value to a JSON object .""" | if hasattr ( value , 'replace' ) :
value = value . replace ( '\n' , ' ' )
try :
return json . loads ( value )
except json . JSONDecodeError : # Escape double quotes .
if hasattr ( value , 'replace' ) :
value = value . replace ( '"' , '\\"' )
# try putting the value into a string
return json ... |
def read_data_page ( file_obj , schema_helper , page_header , column_metadata , dictionary ) :
"""Read the data page from the given file - like object based upon the parameters .
Metadata in the the schema _ helper , page _ header , column _ metadata , and ( optional ) dictionary
are used for parsing data .
R... | daph = page_header . data_page_header
raw_bytes = _read_page ( file_obj , page_header , column_metadata )
io_obj = io . BytesIO ( raw_bytes )
vals = [ ]
debug_logging = logger . isEnabledFor ( logging . DEBUG )
if debug_logging :
logger . debug ( " definition_level_encoding: %s" , _get_name ( parquet_thrift . Enco... |
def cancel ( self , * args , ** kwargs ) :
"""Manually cancel all tasks assigned to this event loop .""" | # Because remove all futures will trigger ` set _ result ` ,
# we cancel itself first .
super ( ) . cancel ( )
for future in self . traverse ( ) : # All cancelled futures should have callbacks to removed itself
# from this linked list . However , these callbacks are scheduled in
# an event loop , so we could still find... |
def displayable_path ( path , separator = u'; ' ) :
"""Attempts to decode a bytestring path to a unicode object for the
purpose of displaying it to the user . If the ` path ` argument is a
list or a tuple , the elements are joined with ` separator ` .""" | if isinstance ( path , ( list , tuple ) ) :
return separator . join ( displayable_path ( p ) for p in path )
elif isinstance ( path , six . text_type ) :
return path
elif not isinstance ( path , bytes ) : # A non - string object : just get its unicode representation .
return six . text_type ( path )
try :
... |
def names ( args ) :
"""% prog names namelist templatefile
Generate name blocks from the ` namelist ` file . The ` namelist ` file is
tab - delimited that contains > = 4 columns of data . Three columns are mandatory .
First name , middle initial and last name . First row is table header . For the
extra colu... | p = OptionParser ( names . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 2 :
sys . exit ( p . print_help ( ) )
namelist , templatefile = args
# First check the alternative format
if open ( namelist ) . read ( ) [ 0 ] == '[' :
out = parse_names ( namelist )
make_template ( templatefile ,... |
def removeRow ( self , row , parent ) :
"""Remove row from parent
: param row : the row index
: type row : int
: param parent : the parent index
: type parent : : class : ` QtCore . QModelIndex `
: returns : True if row is inserted ; otherwise returns false .
: rtype : bool
: raises : None""" | if parent . isValid ( ) :
parentitem = parent . internalPointer ( )
else :
parentitem = self . _root
self . beginRemoveRows ( parent , row , row )
item = parentitem . childItems [ row ]
item . set_model ( None )
item . _parent = None
del parentitem . childItems [ row ]
self . endRemoveRows ( )
return True |
def module_reload_changed ( key ) :
"""Reload a module if it has changed since we last imported it . This is
necessary if module a imports script b , script b is changed , and then
module c asks to import script b .
: param key : our key used in the WatchList .
: returns : True if reloaded .""" | imp . acquire_lock ( )
try :
modkey = module_sys_modules_key ( key )
if not modkey :
return False
found = None
if modkey :
for second in WatchList :
secmodkey = module_sys_modules_key ( second )
if secmodkey and sys . modules [ modkey ] == sys . modules [ secmodke... |
def Load ( file ) :
"""Loads a model from specified file""" | with open ( file , 'rb' ) as file :
model = dill . load ( file )
return model |
def tensor_product ( a , b , reshape = True ) :
"""compute the tensor protuct of two matrices a and b
if a is ( n , m _ a ) , b is ( n , m _ b ) ,
then the result is
( n , m _ a * m _ b ) if reshape = True .
or
( n , m _ a , m _ b ) otherwise
Parameters
a : array - like of shape ( n , m _ a )
b : ar... | assert a . ndim == 2 , 'matrix a must be 2-dimensional, but found {} dimensions' . format ( a . ndim )
assert b . ndim == 2 , 'matrix b must be 2-dimensional, but found {} dimensions' . format ( b . ndim )
na , ma = a . shape
nb , mb = b . shape
if na != nb :
raise ValueError ( 'both arguments must have the same nu... |
def _compute_C_matrix ( self ) :
"""See Fouss et al . ( 2006 ) and von Luxburg et al . ( 2007 ) .
This is the commute - time matrix . It ' s a squared - euclidian distance
matrix in : math : ` \\ mathbb { R } ^ n ` .""" | self . C = np . repeat ( np . diag ( self . Lp ) [ : , np . newaxis ] , self . Lp . shape [ 0 ] , axis = 1 )
self . C += np . repeat ( np . diag ( self . Lp ) [ np . newaxis , : ] , self . Lp . shape [ 0 ] , axis = 0 )
self . C -= 2 * self . Lp
# the following is much slower
# self . C = np . zeros ( self . Lp . shape ... |
def cimread ( source , packageMap = None , nsURI = None , start_dict = None ) :
"""CIM RDF / XML parser .
@ type source : File - like object or a path to a file .
@ param source : CIM RDF / XML file .
@ type profile : dict
@ param packageMap : Map of class name to PyCIM package name . All CIM
classes are ... | # Start the clock .
t0 = time ( )
# logger . info ( ' # # # # # ' )
logger . info ( 'START of parsing file \"%s\"' , source )
logger_errors_grouped = { }
# A map of uuids to CIM objects to be returned .
d = start_dict if start_dict is not None else { }
# Obtain the namespaces from the input file
namespaces = xmlns ( so... |
def show_result ( resource , verbose = False ) :
"""TODO""" | if resource . uri == surf . ns . EFRBROO [ 'F10_Person' ] :
print ( "\n{} ({})\n" . format ( unicode ( resource ) , resource . get_urn ( ) ) )
works = resource . get_works ( )
print ( "Works by {} ({}):\n" . format ( resource , len ( works ) ) )
[ show_result ( work ) for work in works ]
print ( "\n... |
def get_next_assessment_part_id ( self , assessment_part_id ) :
"""This supports the basic simple sequence case . Can be overriden in a record for other cases""" | if self . has_next_assessment_part ( assessment_part_id ) :
return Id ( self . _my_map [ 'childIds' ] [ self . _my_map [ 'childIds' ] . index ( str ( assessment_part_id ) ) + 1 ] ) |
def make_semver ( version_str ) :
"""Make a semantic version from Python PEP440 version .
Semantic versions does not handle post - releases .""" | v = parse_version ( version_str )
major = v . _version . release [ 0 ]
try :
minor = v . _version . release [ 1 ]
except IndexError :
minor = 0
try :
patch = v . _version . release [ 2 ]
except IndexError :
patch = 0
prerelease = [ ]
if v . _version . pre :
prerelease . append ( '' . join ( str ( x ... |
def transform ( self , df ) :
"""Transform dataframe into a numpy ndarray ( matrix )""" | # Make sure the dataframe columns are the same as the ones passed to fit
assert df . columns . equals ( self . columns_ )
# Convert the dataframe with get _ dummies
df_with_dummies = pd . get_dummies ( df )
# Make sure our columns exactly match what we stored during the fit operation
my_columns = set ( df_with_dummies ... |
def parse_int_arg ( name , default ) :
"""Return a given URL parameter as int or return the default value .""" | return default if request . args . get ( name ) is None else int ( request . args . get ( name ) ) |
def _fetch_disambiguating_assoc ( self ) :
"""For any of the items in the chemical - disease association file that have
ambiguous association types we fetch the disambiguated associations
using the batch query API , and store these in a file . Elsewhere , we can
loop through the file and create the appropriat... | disambig_file = '/' . join ( ( self . rawdir , self . static_files [ 'publications' ] [ 'file' ] ) )
assoc_file = '/' . join ( ( self . rawdir , self . files [ 'chemical_disease_interactions' ] [ 'file' ] ) )
# check if there is a local association file ,
# and download if it ' s dated later than the original intxn fil... |
def _cache_lookup ( word , data_dir , native = False ) :
"""Checks if word is in cache .
Parameters
word : str
Word to check in cache .
data _ dir : pathlib . Path
Cache directory location .
Returns
translation : str or None
Translation of given word .""" | trans_dir = "translations"
if native :
trans_dir += "_native"
logger . debug ( "Cache lookup: %s" , word )
filename = data_dir . joinpath ( trans_dir , "{}.html" . format ( word ) )
if filename . is_file ( ) :
with open ( filename , mode = "r" ) as f :
logger . debug ( "Cache found: %s" , word )
... |
def origination_urls ( self ) :
"""Access the origination _ urls
: returns : twilio . rest . trunking . v1 . trunk . origination _ url . OriginationUrlList
: rtype : twilio . rest . trunking . v1 . trunk . origination _ url . OriginationUrlList""" | if self . _origination_urls is None :
self . _origination_urls = OriginationUrlList ( self . _version , trunk_sid = self . _solution [ 'sid' ] , )
return self . _origination_urls |
def find_consensus ( bases ) :
"""find consensus base based on nucleotide
frequencies""" | nucs = [ 'A' , 'T' , 'G' , 'C' , 'N' ]
total = sum ( [ bases [ nuc ] for nuc in nucs if nuc in bases ] )
# save most common base as consensus ( random nuc if there is a tie )
try :
top = max ( [ bases [ nuc ] for nuc in nucs if nuc in bases ] )
except :
bases [ 'consensus' ] = ( 'N' , 'n/a' )
bases [ 'conse... |
def plot_importance ( booster , ax = None , height = 0.2 , xlim = None , ylim = None , title = 'Feature importance' , xlabel = 'Feature importance' , ylabel = 'Features' , importance_type = 'split' , max_num_features = None , ignore_zero = True , figsize = None , grid = True , precision = None , ** kwargs ) :
"""Pl... | if MATPLOTLIB_INSTALLED :
import matplotlib . pyplot as plt
else :
raise ImportError ( 'You must install matplotlib to plot importance.' )
if isinstance ( booster , LGBMModel ) :
booster = booster . booster_
elif not isinstance ( booster , Booster ) :
raise TypeError ( 'booster must be Booster or LGBMMo... |
def _get_vlan_body_on_trunk_int ( self , nexus_host , vlanid , intf_type , interface , is_native , is_delete , add_mode ) :
"""Prepares an XML snippet for VLAN on a trunk interface .
: param nexus _ host : IP address of Nexus switch
: param vlanid : Vlanid ( s ) to add to interface
: param intf _ type : Strin... | starttime = time . time ( )
LOG . debug ( "NexusDriver get if body config for host %s: " "if_type %s port %s" , nexus_host , intf_type , interface )
if intf_type == "ethernet" :
body_if_type = "l1PhysIf"
path_interface = "phys-[eth" + interface + "]"
else :
body_if_type = "pcAggrIf"
path_interface = "ag... |
def decode_transaction_input ( self , transaction_hash : bytes ) -> Dict :
"""Return inputs of a method call""" | transaction = self . contract . web3 . eth . getTransaction ( transaction_hash , )
return self . contract . decode_function_input ( transaction [ 'input' ] , ) |
def _update_discovery_config ( opts ) :
'''Update discovery config for all instances .
: param opts :
: return :''' | if opts . get ( 'discovery' ) not in ( None , False ) :
if opts [ 'discovery' ] is True :
opts [ 'discovery' ] = { }
discovery_config = { 'attempts' : 3 , 'pause' : 5 , 'port' : 4520 , 'match' : 'any' , 'mapping' : { } , 'multimaster' : False }
for key in opts [ 'discovery' ] :
if key not in... |
def add_margins ( df , vars , margins = True ) :
"""Add margins to a data frame .
All margining variables will be converted to factors .
Parameters
df : dataframe
input data frame
vars : list
a list of 2 lists | tuples vectors giving the
variables in each dimension
margins : bool | list
variable n... | margin_vars = _margins ( vars , margins )
if not margin_vars :
return df
# create margin dataframes
margin_dfs = [ df ]
for vlst in margin_vars [ 1 : ] :
dfx = df . copy ( )
for v in vlst :
dfx . loc [ 0 : , v ] = '(all)'
margin_dfs . append ( dfx )
merged = pd . concat ( margin_dfs , axis = 0 )... |
def frames ( self , most_recent = False ) :
"""Retrieve a new frame from the PhoXi and convert it to a ColorImage ,
a DepthImage , and an IrImage .
Parameters
most _ recent : bool
If true , the OpenCV buffer is emptied for the webcam before reading the most recent frame .
Returns
: obj : ` tuple ` of : ... | if most_recent :
for i in xrange ( 4 ) :
self . _cap . grab ( )
for i in range ( 1 ) :
if self . _adjust_exposure :
try :
command = 'v4l2-ctl -d /dev/video{} -c exposure_auto=1 -c exposure_auto_priority=0 -c exposure_absolute=100 -c saturation=60 -c gain=140' . format ( self . _devic... |
def close ( self ) :
"""Closes the cursor . The cursor is unusable from this point .""" | conn = self . _conn
if conn is not None :
conn = conn ( )
if conn is not None :
if self is conn . _active_cursor :
conn . _active_cursor = conn . _main_cursor
self . _session = None
self . _conn = None |
def label_store ( self ) :
'''Return a thread local : class : ` dossier . label . LabelStore ` client .''' | if self . _label_store is None :
config = global_config ( 'dossier.label' )
if 'kvlayer' in config :
kvl = kvlayer . client ( config = config [ 'kvlayer' ] )
self . _label_store = LabelStore ( kvl )
else :
self . _label_store = self . create ( LabelStore , config = config )
return se... |
def handle_dataframe ( df : pd . DataFrame , entrez_id_name , log2_fold_change_name , adjusted_p_value_name , entrez_delimiter , base_mean = None , ) -> List [ Gene ] :
"""Convert data frame on differential expression values as Gene objects .
: param df : Data frame with columns showing values on differential
e... | logger . info ( "In _handle_df()" )
if base_mean is not None and base_mean in df . columns :
df = df [ pd . notnull ( df [ base_mean ] ) ]
df = df [ pd . notnull ( df [ entrez_id_name ] ) ]
df = df [ pd . notnull ( df [ log2_fold_change_name ] ) ]
df = df [ pd . notnull ( df [ adjusted_p_value_name ] ) ]
# try :
# ... |
def to_df ( self , variables = None , format = 'wide' , fillna = np . nan , ** kwargs ) :
'''Merge variables into a single pandas DataFrame .
Args :
variables ( list ) : Optional list of column names to retain ; if None ,
all variables are returned .
format ( str ) : Whether to return a DataFrame in ' wide ... | if variables is None :
variables = list ( self . variables . keys ( ) )
# Can receive already - selected Variables from sub - classes
if not isinstance ( variables [ 0 ] , BIDSVariable ) :
variables = [ v for v in self . variables . values ( ) if v . name in variables ]
dfs = [ v . to_df ( ** kwargs ) for v in ... |
def readCmd ( cls , cmd ) :
"""run command and return the str format stdout
Args :
cmd : string
Returns :
str : what the command ' s echo""" | args = shlex . split ( cmd )
proc = subprocess . Popen ( args , stdout = subprocess . PIPE )
( proc_stdout , proc_stderr ) = proc . communicate ( input = None )
# proc _ stdin
return proc_stdout . decode ( ) |
def color ( self , c = False ) :
"""Set / get actor ' s color .
If None is passed as input , will use colors from active scalars .
Same as ` c ( ) ` .""" | if c is False :
return np . array ( self . GetProperty ( ) . GetColor ( ) )
elif c is None :
self . GetMapper ( ) . ScalarVisibilityOn ( )
return self
else :
self . GetMapper ( ) . ScalarVisibilityOff ( )
self . GetProperty ( ) . SetColor ( colors . getColor ( c ) )
return self |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.