signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _load_nested_libraries ( self , library_path , target_dict ) :
"""Recursively load libraries within path
Adds all libraries specified in a given path and stores them into the provided library dictionary . The library
entries in the dictionary consist only of the path to the library in the file system .
: ... | for library_name in os . listdir ( library_path ) :
library_folder_path , library_name = self . check_clean_path_of_library ( library_path , library_name )
full_library_path = os . path . join ( library_path , library_name )
if os . path . isdir ( full_library_path ) and library_name [ 0 ] != '.' :
... |
def mousePressEvent ( self , event ) :
"""In Auto - parameter selection mode , mouse press over an item emits
` componentSelected `""" | if self . mode == BuildMode :
super ( StimulusView , self ) . mousePressEvent ( event )
else : # select and de - select components
index = self . indexAt ( event . pos ( ) )
if index . isValid ( ) :
self . selectionModel ( ) . select ( index , QtGui . QItemSelectionModel . Toggle )
comp = se... |
def drop_indexes ( quiet = True , stdout = None ) :
"""Discover and drop all indexes .
: type : bool
: return : None""" | results , meta = db . cypher_query ( "CALL db.indexes()" )
pattern = re . compile ( ':(.*)\((.*)\)' )
for index in results :
db . cypher_query ( 'DROP ' + index [ 0 ] )
match = pattern . search ( index [ 0 ] )
stdout . write ( ' - Dropping index on label {0} with property {1}.\n' . format ( match . group ( ... |
def get_base_url ( self , request ) :
"""Creates base url string .
: param request : OGC - type request with specified bounding box , cloud coverage for specific product .
: type request : OgcRequest or GeopediaRequest
: return : base string for url to Sentinel Hub ' s OGC service for this product .
: rtype... | url = self . base_url + request . service_type . value
# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore :
if hasattr ( request , 'data_source' ) and request . data_source . is_uswest_source ( ) :
url = 'https://services-uswest2.sentinel-hub.com/ogc/{}' . format (... |
def get_slot ( self ) :
"""Get the slot position of this pair .""" | corner , edge = self . get_pair ( )
corner_slot , edge_slot = corner . location . replace ( "D" , "" , 1 ) , edge . location
if "U" not in corner_slot and corner_slot not in [ "FR" , "RB" , "BL" , "LF" ] :
corner_slot = [ "FR" , "RB" , "BL" , "LF" ] [ [ "RF" , "BR" , "LB" , "FL" ] . index ( corner_slot ) ]
if "U" n... |
def disable ( self , ids ) :
"""Disable Pool Members Running Script
: param ids : List of ids
: return : None on success
: raise PoolMemberDoesNotExistException
: raise InvalidIdPoolMemberException
: raise ScriptDisablePoolException
: raise NetworkAPIException""" | data = dict ( )
data [ "ids" ] = ids
uri = "api/pools/disable/"
return self . post ( uri , data ) |
def time_conflict ( self , schedule ) :
"""Internal use . Determines when the given time range conflicts with the set of
excluded time ranges .""" | if is_nil ( schedule ) :
return True
for timerange in self . _excluded_times :
if timerange . conflicts_with ( schedule ) :
return False
return True |
def score ( args ) :
"""% prog score main _ results / cached _ data / contigsfasta
Score the current LACHESIS CLM .""" | p = OptionParser ( score . __doc__ )
p . set_cpus ( )
opts , args = p . parse_args ( args )
if len ( args ) != 3 :
sys . exit ( not p . print_help ( ) )
mdir , cdir , contigsfasta = args
orderingfiles = natsorted ( iglob ( mdir , "*.ordering" ) )
sizes = Sizes ( contigsfasta )
contig_names = list ( sizes . iter_nam... |
def _needs_region_update ( out_file , samples ) :
"""Check if we need to update BED file of regions , supporting back compatibility .""" | nblock_files = [ x [ "regions" ] [ "nblock" ] for x in samples if "regions" in x ]
# For older approaches and do not create a new set of analysis
# regions , since the new algorithm will re - do all BAM and variant
# steps with new regions
for nblock_file in nblock_files :
test_old = nblock_file . replace ( "-nbloc... |
def add_sma ( self , periods = 20 , column = None , name = '' , str = None , ** kwargs ) :
"""Add Simple Moving Average ( SMA ) study to QuantFigure . studies
Parameters :
periods : int or list ( int )
Number of periods
column : string
Defines the data column name that contains the
data over which the s... | if not column :
column = self . _d [ 'close' ]
study = { 'kind' : 'sma' , 'name' : name , 'params' : { 'periods' : periods , 'column' : column , 'str' : str } , 'display' : utils . merge_dict ( { 'legendgroup' : False } , kwargs ) }
self . _add_study ( study ) |
def list_channels ( current ) :
"""List channel memberships of current user
. . code - block : : python
# request :
' view ' : ' _ zops _ list _ channels ' ,
# response :
' channels ' : [
{ ' name ' : string , # name of channel
' key ' : key , # key of channel
' unread ' : int , # unread message cou... | current . output = { 'status' : 'OK' , 'code' : 200 , 'channels' : [ ] }
for sbs in current . user . subscriptions . objects . filter ( is_visible = True ) :
try :
current . output [ 'channels' ] . append ( sbs . get_channel_listing ( ) )
except ObjectDoesNotExist : # FIXME : This should not happen ,
... |
def _get_table_width ( table_spec ) :
"""Calculate the width of a table based on its spec .
Args
table _ spec : str
The LaTeX column specification for a table .
Returns
int
The width of a table which uses the specification supplied .""" | # Remove things like { \ bfseries }
cleaner_spec = re . sub ( r'{[^}]*}' , '' , table_spec )
# Remove X [ ] in tabu environments so they dont interfere with column count
cleaner_spec = re . sub ( r'X\[(.*?(.))\]' , r'\2' , cleaner_spec )
spec_counter = Counter ( cleaner_spec )
return sum ( spec_counter [ l ] for l in C... |
def to ( self , unit ) :
"""Convert this velocity to the given AstroPy unit .""" | from astropy . units import au , d
return ( self . au_per_d * au / d ) . to ( unit ) |
def reduce_source_model ( smlt_file , source_ids , remove = True ) :
"""Extract sources from the composite source model""" | found = 0
to_remove = [ ]
for paths in logictree . collect_info ( smlt_file ) . smpaths . values ( ) :
for path in paths :
logging . info ( 'Reading %s' , path )
root = nrml . read ( path )
model = Node ( 'sourceModel' , root [ 0 ] . attrib )
origmodel = root [ 0 ]
if root [ ... |
def get_filelikeobject ( filename : str = None , blob : bytes = None ) -> BinaryIO :
"""Open a file - like object .
Guard the use of this function with ` ` with ` ` .
Args :
filename : for specifying via a filename
blob : for specifying via an in - memory ` ` bytes ` ` object
Returns :
a : class : ` Bin... | if not filename and not blob :
raise ValueError ( "no filename and no blob" )
if filename and blob :
raise ValueError ( "specify either filename or blob" )
if filename :
return open ( filename , 'rb' )
else :
return io . BytesIO ( blob ) |
def get_network ( network_id ) :
"""Get the network with the given id .""" | try :
net = models . Network . query . filter_by ( id = network_id ) . one ( )
except NoResultFound :
return error_response ( error_type = "/network GET: no network found" , status = 403 )
# return the data
return success_response ( field = "network" , data = net . __json__ ( ) , request_type = "network get" ) |
def from_bigquery ( sql ) :
"""Create a Metrics instance from a bigquery query or table .
Returns :
a Metrics instance .
Args :
sql : A BigQuery table name or a query .""" | if isinstance ( sql , bq . Query ) :
sql = sql . _expanded_sql ( )
parts = sql . split ( '.' )
if len ( parts ) == 1 or len ( parts ) > 3 or any ( ' ' in x for x in parts ) :
sql = '(' + sql + ')'
# query , not a table name
else :
sql = '`' + sql + '`'
# table name
metrics = Metrics ( bigquery = sql )
r... |
def has_file_with_suffix ( self , suffixes ) :
"""Finds out if there is a file with one of suffixes in the archive .
Args :
suffixes : list of suffixes or single suffix to look for
Returns :
True if there is at least one file with at least one given suffix
in the archive , False otherwise ( or archive can... | if not isinstance ( suffixes , list ) :
suffixes = [ suffixes ]
if self . handle :
for member in self . handle . getmembers ( ) :
if os . path . splitext ( member . name ) [ 1 ] in suffixes :
return True
else : # hack for . zip files , where directories are not returned
# the... |
def scale ( self , data , unit ) :
"""Scales quantity to obtain dimensionful quantity .
Args :
data ( numpy . array ) : the quantity that should be scaled .
dim ( str ) : the dimension of data as defined in phyvars .
Return :
( float , str ) : scaling factor and unit string .
Other Parameters :
conf .... | if self . par [ 'switches' ] [ 'dimensional_units' ] or not conf . scaling . dimensional or unit == '1' :
return data , ''
scaling = phyvars . SCALES [ unit ] ( self . scales )
factor = conf . scaling . factors . get ( unit , ' ' )
if conf . scaling . time_in_y and unit == 's' :
scaling /= conf . scaling . year... |
def objectprep ( self ) :
"""If the script is being run as part of a pipeline , create and populate the objects for the current analysis""" | for sample in self . metadata :
setattr ( sample , self . analysistype , GenObject ( ) )
# Set the destination folder
sample [ self . analysistype ] . outputdir = os . path . join ( self . path , self . analysistype )
# Make the destination folder
make_path ( sample [ self . analysistype ] . outputd... |
def read_content_types ( archive ) :
"""Read content types .""" | xml_source = archive . read ( ARC_CONTENT_TYPES )
root = fromstring ( xml_source )
contents_root = root . findall ( '{%s}Override' % CONTYPES_NS )
for type in contents_root :
yield type . get ( 'ContentType' ) , type . get ( 'PartName' ) |
def clean_up ( self ) :
'''Clean up child and orphaned processes .''' | if self . tunnel . is_open :
print 'Closing tunnel...'
self . tunnel . close ( )
print 'Done.'
else :
pass |
def trace_on ( full = False ) :
"""Start tracing of the current thread ( and the current thread only ) .""" | if full :
sys . settrace ( _trace_full )
else :
sys . settrace ( _trace ) |
def is_longitudinal ( self ) :
"""Returns
boolean :
longitudinal status of this project""" | return len ( self . events ) > 0 and len ( self . arm_nums ) > 0 and len ( self . arm_names ) > 0 |
def get_scores ( self , * args ) :
'''In this case , parameters a and b aren ' t used , since this information is taken
directly from the corpus categories .
Returns''' | def jelinek_mercer_smoothing ( cat ) :
p_hat_w = self . tdf_ [ cat ] * 1. / self . tdf_ [ cat ] . sum ( )
c_hat_w = ( self . smoothing_lambda_ ) * self . tdf_ . sum ( axis = 1 ) * 1. / self . tdf_ . sum ( ) . sum ( )
return ( 1 - self . smoothing_lambda_ ) * p_hat_w + self . smoothing_lambda_ * c_hat_w
p_w ... |
def replace_namespaced_deployment ( self , name , namespace , body , ** kwargs ) :
"""replace the specified Deployment
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . replace _ namespaced _ deployment ( name ,... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_namespaced_deployment_with_http_info ( name , namespace , body , ** kwargs )
else :
( data ) = self . replace_namespaced_deployment_with_http_info ( name , namespace , body , ** kwargs )
return data |
def _WriteSerializedAttributeContainerList ( self , container_type ) :
"""Writes a serialized attribute container list .
Args :
container _ type ( str ) : attribute container type .""" | if container_type == self . _CONTAINER_TYPE_EVENT :
if not self . _serialized_event_heap . data_size :
return
number_of_attribute_containers = ( self . _serialized_event_heap . number_of_events )
else :
container_list = self . _GetSerializedAttributeContainerList ( container_type )
if not contai... |
def _decode_buffer ( f ) :
"""String types are normal ( byte ) strings
starting with an integer followed by ' : '
which designates the string ’ s length .
Since there ’ s no way to specify the byte type
in bencoded files , we have to guess""" | strlen = int ( _readuntil ( f , _TYPE_SEP ) )
buf = f . read ( strlen )
if not len ( buf ) == strlen :
raise ValueError ( 'string expected to be {} bytes long but the file ended after {} bytes' . format ( strlen , len ( buf ) ) )
try :
return buf . decode ( )
except UnicodeDecodeError :
return buf |
def like ( self , ** kwargs ) :
"""Like the list .
: param kwargs : Extra request options
: type kwargs : : class : ` ~ python : dict `
: return : Boolean to indicate if the request was successful
: rtype : : class : ` ~ python : bool `""" | return self . _client [ 'users/*/lists/*' ] . like ( self . username , self . id , ** kwargs ) |
def strip_prompt ( self , a_string ) :
"""Strip the trailing router prompt from the output .""" | response_list = a_string . split ( self . RESPONSE_RETURN )
new_response_list = [ ]
for line in response_list :
if self . base_prompt not in line :
new_response_list . append ( line )
output = self . RESPONSE_RETURN . join ( new_response_list )
return self . strip_context_items ( output ) |
def p_assignment ( self , p ) :
'assignment : ASSIGN lvalue EQUALS rvalue SEMICOLON' | p [ 0 ] = Assign ( p [ 2 ] , p [ 4 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def _read_header ( self ) :
"""Process the header information ( data model / grid spec )""" | self . _header_pos = self . fp . tell ( )
line = self . fp . readline ( '20sffii' )
modelname , res0 , res1 , halfpolar , center180 = line
self . _attributes . update ( { "modelname" : str ( modelname , 'utf-8' ) . strip ( ) , "halfpolar" : halfpolar , "center180" : center180 , "res" : ( res0 , res1 ) } )
self . __seta... |
def choice ( * es ) :
"""Create a PEG function to match an ordered choice .""" | msg = 'Expected one of: {}' . format ( ', ' . join ( map ( repr , es ) ) )
def match_choice ( s , grm = None , pos = 0 ) :
errs = [ ]
for e in es :
try :
return e ( s , grm , pos )
except PegreError as ex :
errs . append ( ( ex . message , ex . position ) )
if errs :
... |
def _auth_headers ( self ) :
"""Headers required to authenticate a request .
Assumes your ` ` Context ` ` already has a authentication token or
cookie , either provided explicitly or obtained by logging
into the Splunk instance .
: returns : A list of 2 - tuples containing key and value""" | if self . has_cookies ( ) :
return [ ( "Cookie" , _make_cookie_header ( list ( self . get_cookies ( ) . items ( ) ) ) ) ]
elif self . basic and ( self . username and self . password ) :
token = 'Basic %s' % b64encode ( ( "%s:%s" % ( self . username , self . password ) ) . encode ( 'utf-8' ) ) . decode ( 'ascii'... |
def add_item ( self , item ) :
"""Adds an item to the batch .""" | if not isinstance ( item , JsonRpcResponse ) :
raise TypeError ( "Expected JsonRpcResponse but got {} instead" . format ( type ( item ) . __name__ ) )
self . items . append ( item ) |
def get ( self , timeout = None , raise_error = True ) :
"""Args :
timeout ( float ) : timeout for query element , unit seconds
Default 10s
raise _ error ( bool ) : whether to raise error if element not found
Returns :
Element : UI Element
Raises :
WDAElementNotFoundError if raise _ error is True else... | start_time = time . time ( )
if timeout is None :
timeout = self . timeout
while True :
elems = self . find_elements ( )
if len ( elems ) > 0 :
return elems [ 0 ]
if start_time + timeout < time . time ( ) :
break
time . sleep ( 0.01 )
# check alert again
if self . session . alert . e... |
def delete ( self , key , cas = 0 ) :
"""Delete a key / value from server . If key does not exist , it returns True .
: param key : Key ' s name to be deleted
: param cas : CAS of the key
: return : True in case o success and False in case of failure .""" | returns = [ ]
for server in self . servers :
returns . append ( server . delete ( key , cas ) )
return any ( returns ) |
def _validated ( self , data ) :
"""Validate data if any subschema validates it .""" | errors = [ ]
for sub in self . schemas :
try :
return sub ( data )
except NotValid as ex :
errors . extend ( ex . args )
raise NotValid ( ' and ' . join ( errors ) ) |
def saveCurrentNetworkToNdex ( self , body , verbose = None ) :
"""Save current network / collection to NDEx
: param body : Properties required to save current network to NDEx .
: param verbose : print more
: returns : 200 : successful operation ; 404 : Current network does not exist""" | surl = self . ___url
sv = surl . split ( '/' ) [ - 1 ]
surl = surl . rstrip ( sv + '/' )
PARAMS = set_param ( [ 'body' ] , [ body ] )
response = api ( url = surl + '/cyndex2/' + sv + '/networks/current' , PARAMS = PARAMS , method = "POST" , verbose = verbose )
return response |
def mounts ( cls ) :
"""Return tuple of current mount points
: return : tuple of WMountPoint""" | result = [ ]
with open ( cls . __mounts_file__ ) as f :
for mount_record in f :
result . append ( WMountPoint ( mount_record ) )
return tuple ( result ) |
def gen_lt ( self ) :
"""Generate a new LoginTicket and add it to the list of valid LT for the user""" | self . request . session [ 'lt' ] = self . request . session . get ( 'lt' , [ ] ) + [ utils . gen_lt ( ) ]
if len ( self . request . session [ 'lt' ] ) > 100 :
self . request . session [ 'lt' ] = self . request . session [ 'lt' ] [ - 100 : ] |
def get_file_list ( self ) :
"""Retrieve the list of absolute paths to all the files in this data source .
Returns :
List [ str ] List of absolute paths .""" | if os . path . isdir ( self . root_path ) :
return [ os . path . join ( self . root_path , f ) for f in os . listdir ( self . root_path ) if os . path . isfile ( os . path . join ( self . root_path , f ) ) ]
else :
return [ self . root_path ] |
def write ( self , path , wrap_ttl = None , ** kwargs ) :
"""POST / < path >
: param path :
: type path :
: param wrap _ ttl :
: type wrap _ ttl :
: param kwargs :
: type kwargs :
: return :
: rtype :""" | response = self . _adapter . post ( '/v1/{0}' . format ( path ) , json = kwargs , wrap_ttl = wrap_ttl )
if response . status_code == 200 :
return response . json ( ) |
def fit ( self , X , y = None , init = None ) :
"""Computes the position of the points in the embedding space
Parameters
X : array , shape = [ n _ samples , n _ features ] , or [ n _ samples , n _ samples ] \
if dissimilarity = ' precomputed '
Input data .
init : { None or ndarray , shape ( n _ samples , ... | self . fit_transform ( X , init = init )
return self |
def add_tsig ( self , keyname , secret , fudge , id , tsig_error , other_data , request_mac , algorithm = dns . tsig . default_algorithm ) :
"""Add a TSIG signature to the message .
@ param keyname : the TSIG key name
@ type keyname : dns . name . Name object
@ param secret : the secret to use
@ type secret... | self . _set_section ( ADDITIONAL )
before = self . output . tell ( )
s = self . output . getvalue ( )
( tsig_rdata , self . mac , ctx ) = dns . tsig . sign ( s , keyname , secret , int ( time . time ( ) ) , fudge , id , tsig_error , other_data , request_mac , algorithm = algorithm )
keyname . to_wire ( self . output , ... |
def execute_java ( classpath , main , jvm_options = None , args = None , executor = None , workunit_factory = None , workunit_name = None , workunit_labels = None , cwd = None , workunit_log_config = None , distribution = None , create_synthetic_jar = True , synthetic_jar_dir = None , stdin = None ) :
"""Executes t... | runner = _get_runner ( classpath , main , jvm_options , args , executor , cwd , distribution , create_synthetic_jar , synthetic_jar_dir )
workunit_name = workunit_name or main
return execute_runner ( runner , workunit_factory = workunit_factory , workunit_name = workunit_name , workunit_labels = workunit_labels , worku... |
def get_compound_ids ( self ) :
"""Extract the current compound ids in the database . Updates the self . compound _ ids list""" | cursor = self . conn . cursor ( )
cursor . execute ( 'SELECT inchikey_id FROM metab_compound' )
self . conn . commit ( )
for row in cursor :
if not row [ 0 ] in self . compound_ids :
self . compound_ids . append ( row [ 0 ] ) |
def create_user ( self , user_id , roles = None , netmask = None , secret = None , pubkey = None ) :
u"""Create user for the Merchant given in the X - Mcash - Merchant header .
Arguments :
user _ id :
Identifier for the user
roles :
Role
netmask :
Limit user connections by netmask , for example 192.16... | arguments = { 'id' : user_id , 'roles' : roles , 'netmask' : netmask , 'secret' : secret , 'pubkey' : pubkey }
return self . do_req ( 'POST' , self . merchant_api_base_url + '/user/' , arguments ) . json ( ) |
def auto_set_dir ( action = None , name = None ) :
"""Use : func : ` logger . set _ logger _ dir ` to set log directory to
" . / train _ log / { scriptname } : { name } " . " scriptname " is the name of the main python file currently running""" | mod = sys . modules [ '__main__' ]
basename = os . path . basename ( mod . __file__ )
auto_dirname = os . path . join ( 'train_log' , basename [ : basename . rfind ( '.' ) ] )
if name :
auto_dirname += '_%s' % name if os . name == 'nt' else ':%s' % name
set_logger_dir ( auto_dirname , action = action ) |
def variablename ( var ) :
"""Returns the string of a variable name .""" | s = [ tpl [ 0 ] for tpl in itertools . ifilter ( lambda x : var is x [ 1 ] , globals ( ) . items ( ) ) ]
s = s [ 0 ] . upper ( )
return s |
def _R2deriv ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ Rforce
PURPOSE :
evaluate the second radial derivative for this potential
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
the second radial derivative
HISTORY :
2016-05-13 - Writ... | return self . _denom ( R , z ) ** - 1.5 - 3. * R ** 2 * self . _denom ( R , z ) ** - 2.5 |
def save ( self , fname = None , link_copy = False , raiseError = False ) :
"""link _ copy : only works in hfd5 format
save space by creating link when identical arrays are found ,
it may slows down the saving ( 3 or 4 folds ) but saves space
when saving different dataset together ( since it does not duplicat... | if fname is None :
fname = self . filename
assert fname is not None
save ( fname , self , link_copy = link_copy , raiseError = raiseError ) |
def jacobian ( self , maps ) :
"""Returns the Jacobian for transforming mchirp and eta to mass1 and
mass2.""" | mchirp = maps [ parameters . mchirp ]
eta = maps [ parameters . eta ]
m1 = conversions . mass1_from_mchirp_eta ( mchirp , eta )
m2 = conversions . mass2_from_mchirp_eta ( mchirp , eta )
return mchirp * ( m1 - m2 ) / ( m1 + m2 ) ** 3 |
def add ( self , song ) :
"""往播放列表末尾添加一首歌曲""" | if song in self . _songs :
return
self . _songs . append ( song )
logger . debug ( 'Add %s to player playlist' , song ) |
def is_valid ( self , wordid ) -> bool :
"""Ensures < / s > is only generated when the hypothesis is completed .
: param wordid : The wordid to validate .
: return : True if all constraints are already met or the word ID is not the EOS id .""" | return self . finished ( ) or wordid != self . eos_id or ( self . num_needed ( ) == 1 and self . eos_id in self . allowed ( ) ) |
def send ( self , request ) :
"""Send a request to the server and wait for its response .
Args :
request ( Request ) : Reference to a request object that is sent to the server .
Returns :
Response : The response from the server to the request .""" | self . _connection . connection . rpush ( self . _request_key , pickle . dumps ( request ) )
resp_key = '{}:{}' . format ( SIGNAL_REDIS_PREFIX , request . uid )
while True :
if self . _connection . polling_time > 0.0 :
sleep ( self . _connection . polling_time )
response_data = self . _connection . conn... |
def stats ( self ) :
'''Returns the final high level stats from the Ansible run
Example :
{ ' dark ' : { } , ' failures ' : { } , ' skipped ' : { } , ' ok ' : { u ' localhost ' : 2 } , ' processed ' : { u ' localhost ' : 1 } }''' | last_event = list ( filter ( lambda x : 'event' in x and x [ 'event' ] == 'playbook_on_stats' , self . events ) )
if not last_event :
return None
last_event = last_event [ 0 ] [ 'event_data' ]
return dict ( skipped = last_event [ 'skipped' ] , ok = last_event [ 'ok' ] , dark = last_event [ 'dark' ] , failures = las... |
def get_url ( self , action , obj = None , domain = True ) :
"""Returns an RFC3987 IRI for a HTML representation of the given object , action .
If domain is true , the current site ' s domain will be added .""" | if not obj :
url = reverse ( 'actstream_detail' , None , ( action . pk , ) )
elif hasattr ( obj , 'get_absolute_url' ) :
url = obj . get_absolute_url ( )
else :
ctype = ContentType . objects . get_for_model ( obj )
url = reverse ( 'actstream_actor' , None , ( ctype . pk , obj . pk ) )
if domain :
re... |
def from_json ( cls , data ) :
"""Create an analysis period from a dictionary .
Args :
data : {
st _ month : An integer between 1-12 for starting month ( default = 1)
st _ day : An integer between 1-31 for starting day ( default = 1 ) .
Note that some months are shorter than 31 days .
st _ hour : An int... | keys = ( 'st_month' , 'st_day' , 'st_hour' , 'end_month' , 'end_day' , 'end_hour' , 'timestep' , 'is_leap_year' )
for key in keys :
if key not in data :
data [ key ] = None
return cls ( data [ 'st_month' ] , data [ 'st_day' ] , data [ 'st_hour' ] , data [ 'end_month' ] , data [ 'end_day' ] , data [ 'end_hou... |
def read_json ( self , params = None ) :
"""Get information about the current entity .
Call : meth : ` read _ raw ` . Check the response status code , decode JSON and
return the decoded JSON as a dict .
: return : A dict . The server ' s response , with all JSON decoded .
: raises : ` ` requests . exception... | response = self . read_raw ( params = params )
response . raise_for_status ( )
return response . json ( ) |
def select_catalogue_events ( self , id0 ) :
'''Orders the events in the catalogue according to an indexing vector .
: param np . ndarray id0:
Pointer array indicating the locations of selected events''' | for key in self . data :
if isinstance ( self . data [ key ] , np . ndarray ) and len ( self . data [ key ] ) > 0 : # Dictionary element is numpy array - use logical indexing
self . data [ key ] = self . data [ key ] [ id0 ]
elif isinstance ( self . data [ key ] , list ) and len ( self . data [ key ] ) ... |
def add_image_info_cb ( self , gshell , channel , iminfo ) :
"""Add entries related to an added image .""" | timestamp = iminfo . time_modified
if timestamp is None : # Not an image we are interested in tracking
return
self . add_entry ( channel . name , iminfo ) |
def create_parser ( ) :
"""Creat a commandline parser for epubcheck
: return Argumentparser :""" | parser = ArgumentParser ( prog = 'epubcheck' , description = "EpubCheck v%s - Validate your ebooks" % __version__ )
# Arguments
parser . add_argument ( 'path' , nargs = '?' , default = getcwd ( ) , help = "Path to EPUB-file or folder for batch validation. " "The current directory will be processed if this argument " "i... |
def get_unique_id ( element ) :
"""Returns a unique id for a given element""" | this_id = make_id ( element )
dup = True
while dup :
if this_id not in ids :
dup = False
ids . append ( this_id )
else :
this_id = make_id ( element )
return ids [ - 1 ] |
def search_cloud_integration_entities ( self , ** kwargs ) : # noqa : E501
"""Search over a customer ' s non - deleted cloud integrations # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread =... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . search_cloud_integration_entities_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . search_cloud_integration_entities_with_http_info ( ** kwargs )
# noqa : E501
return data |
def join ( self , right_table = None , fields = None , condition = None , join_type = 'JOIN' , schema = None , left_table = None , extract_fields = True , prefix_fields = False , field_prefix = None , allow_duplicates = False ) :
"""Joins a table to another table based on a condition and adds fields from the joined... | # self . mark _ dirty ( )
# TODO : fix bug when joining from simple table to model table with no condition
# it assumes left _ table . model
# if there is no left table , assume the query ' s first table
# TODO : add test for auto left table to replace old auto left table
# if left _ table is None and len ( self . tabl... |
def by_id ( self , region , encrypted_summoner_id ) :
"""Get a summoner by summoner ID .
: param string region : The region to execute this request on
: param string encrypted _ summoner _ id : Summoner ID
: returns : SummonerDTO : represents a summoner""" | url , query = SummonerApiV4Urls . by_id ( region = region , encrypted_summoner_id = encrypted_summoner_id )
return self . _raw_request ( self . by_id . __name__ , region , url , query ) |
def _create_regex_pattern_add_optional_spaces_to_word_characters ( word ) :
r"""Add the regex special characters ( \ s * ) to allow optional spaces .
: param word : ( string ) the word to be inserted into a regex pattern .
: return : ( string ) the regex pattern for that word with optional spaces
between all ... | new_word = u""
for ch in word :
if ch . isspace ( ) :
new_word += ch
else :
new_word += ch + r'\s*'
return new_word |
def copy_results ( self , copy_to_dir , rename_model_to = None , force_rerun = False ) :
"""Copy the raw information from I - TASSER modeling to a new folder .
Copies all files in the list _ attrs _ to _ copy .
Args :
copy _ to _ dir ( str ) : Directory to copy the minimal set of results per sequence .
rena... | # Save path to the structure and copy it if specified
if not rename_model_to :
rename_model_to = self . model_to_use
new_model_path = op . join ( copy_to_dir , '{}.pdb' . format ( rename_model_to ) )
if self . structure_path :
if ssbio . utils . force_rerun ( flag = force_rerun , outfile = new_model_path ) : # ... |
def get_referencer ( registry ) :
"""Get the referencer class
: rtype : pyramid _ urireferencer . referencer . AbstractReferencer""" | # Argument might be a config or request
regis = getattr ( registry , 'registry' , None )
if regis is None :
regis = registry
return regis . queryUtility ( IReferencer ) |
def _fix_permissions ( self ) :
"""Because docker run as root we need to fix permission and ownership to allow user to interact
with it from their filesystem and do operation like file delete""" | state = yield from self . _get_container_state ( )
if state == "stopped" or state == "exited" : # We need to restart it to fix permissions
yield from self . manager . query ( "POST" , "containers/{}/start" . format ( self . _cid ) )
for volume in self . _volumes :
log . debug ( "Docker container '{name}' [{imag... |
async def persist_event ( topic , event , pool ) :
"""Track event to prevent duplication of work
and potential loss of event
: param topic : The event topic
: param event : The event object""" | # Event to json
json_event = json . dumps ( event . __dict__ )
# Connect to database or create and connect if non existent
conn = await pool . acquire ( )
# Insert event if not processed
try :
query = """
CREATE TABLE IF NOT EXISTS public."topic_placeholder"
(
id SERIAL PRIMARY... |
def get_formatter_report ( f : logging . Formatter ) -> Optional [ Dict [ str , str ] ] :
"""Returns information on a log formatter , as a dictionary .
For debugging .""" | if f is None :
return None
return { '_fmt' : f . _fmt , 'datefmt' : f . datefmt , '_style' : str ( f . _style ) , } |
def make_nfs_path ( path ) :
"""Make a nfs version of a file path .
This just puts / nfs at the beginning instead of / gpfs""" | if os . path . isabs ( path ) :
fullpath = path
else :
fullpath = os . path . abspath ( path )
if len ( fullpath ) < 6 :
return fullpath
if fullpath [ 0 : 6 ] == '/gpfs/' :
fullpath = fullpath . replace ( '/gpfs/' , '/nfs/' )
return fullpath |
def _read_miraligner ( fn ) :
"""Read ouput of miraligner and create compatible output .""" | reads = defaultdict ( realign )
with open ( fn ) as in_handle :
in_handle . next ( )
for line in in_handle :
cols = line . strip ( ) . split ( "\t" )
iso = isomir ( )
query_name , seq = cols [ 1 ] , cols [ 0 ]
chrom , reference_start = cols [ - 2 ] , cols [ 3 ]
iso . mirn... |
def fetch_by_client_id ( self , client_id ) :
"""Retrieves a client by its identifier .
: param client _ id : The identifier of a client .
: return : An instance of : class : ` oauth2 . datatype . Client ` .
: raises : : class : ` oauth2 . error . ClientError ` if no client could be
retrieved .""" | grants = None
redirect_uris = None
response_types = None
client_data = self . fetchone ( self . fetch_client_query , client_id )
if client_data is None :
raise ClientNotFoundError
grant_data = self . fetchall ( self . fetch_grants_query , client_data [ 0 ] )
if grant_data :
grants = [ ]
for grant in grant_d... |
def Element ( self , elem , ** params ) :
"""Ensure that the input element is immutable by the transformation . Returns a single element .""" | res = self . __call__ ( deepcopy ( elem ) , ** params )
if len ( res ) > 0 :
return res [ 0 ]
else :
return None |
async def load_cache ( self , archive : bool = False ) -> int :
"""Load caches and archive enough to go offline and be able to verify proof
on content marked of interest in configuration .
Return timestamp ( epoch seconds ) of cache load event , also used as subdirectory
for cache archives .
: param archive... | LOGGER . debug ( 'Verifier.load_cache >>> archive: %s' , archive )
rv = int ( time ( ) )
for s_id in self . cfg . get ( 'archive-on-close' , { } ) . get ( 'schema_id' , { } ) :
with SCHEMA_CACHE . lock :
await self . get_schema ( s_id )
for cd_id in self . cfg . get ( 'archive-on-close' , { } ) . get ( 'cre... |
def listdir_nohidden ( path ) :
"""List not hidden files or directories under path""" | for f in os . listdir ( path ) :
if isinstance ( f , str ) :
f = unicode ( f , "utf-8" )
if not f . startswith ( '.' ) :
yield f |
def on_enter_specimen ( self , event ) :
"""upon enter on the specimen box it makes that specimen the current
specimen""" | new_specimen = self . specimens_box . GetValue ( )
if new_specimen not in self . specimens :
self . user_warning ( "%s is not a valid specimen with measurement data, aborting" % ( new_specimen ) )
self . specimens_box . SetValue ( self . s )
return
self . select_specimen ( new_specimen )
if self . ie_open :... |
def coarse_grain ( self , user_sets ) :
r"""Coarse - grains the flux onto user - defined sets .
Parameters
user _ sets : list of int - iterables
sets of states that shall be distinguished in the coarse - grained flux .
Returns
( sets , tpt ) : ( list of int - iterables , tpt - object )
sets contains the... | # coarse - grain sets
( tpt_sets , Aindexes , Bindexes ) = self . _compute_coarse_sets ( user_sets )
nnew = len ( tpt_sets )
# coarse - grain fluxHere we should branch between sparse and dense implementations , but currently there is only a
F_coarse = tptapi . coarsegrain ( self . _gross_flux , tpt_sets )
Fnet_coarse =... |
def show ( self , wildcard = '*' ) :
'''show parameters''' | k = sorted ( self . keys ( ) )
for p in k :
if fnmatch . fnmatch ( str ( p ) . upper ( ) , wildcard . upper ( ) ) :
print ( "%-16.16s %f" % ( str ( p ) , self . get ( p ) ) ) |
def v2 ( self ) :
""": returns : Version v2 of chat
: rtype : twilio . rest . chat . v2 . V2""" | if self . _v2 is None :
self . _v2 = V2 ( self )
return self . _v2 |
def _ParseStorageMediaImageOptions ( self , options ) :
"""Parses the storage media image options .
Args :
options ( argparse . Namespace ) : command line arguments .
Raises :
BadConfigOption : if the options are invalid .""" | self . _partitions = getattr ( options , 'partitions' , None )
if self . _partitions :
try :
self . _ParseVolumeIdentifiersString ( self . _partitions , prefix = 'p' )
except ValueError :
raise errors . BadConfigOption ( 'Unsupported partitions' )
self . _volumes = getattr ( options , 'volumes' ... |
def get_draft ( self , layer_id , expand = [ ] ) :
"""Get the current draft version of a layer .
: raises NotFound : if there is no draft version .""" | target_url = self . client . get_url ( 'VERSION' , 'GET' , 'draft' , { 'layer_id' : layer_id } )
return self . _get ( target_url , expand = expand ) |
def modprobe ( state , host , name , present = True , force = False ) :
'''Load / unload kernel modules .
+ name : name of the module to manage
+ present : whether the module should be loaded or not
+ force : whether to force any add / remove modules''' | modules = host . fact . kernel_modules
is_present = name in modules
args = ''
if force :
args = ' -f'
# Module is loaded and we don ' t want it ?
if not present and is_present :
yield 'modprobe{0} -r {1}' . format ( args , name )
# Module isn ' t loaded and we want it ?
elif present and not is_present :
yie... |
def add_transform ( self , key , xslt ) :
"""Add or update a transform .
@ param key : Transform key to use when executing transformations
@ param xslt : Text or file name of an xslt transform""" | self . _remove_converter ( key )
self . _xsltLibrary [ key ] = xslt
self . _add_converter ( key ) |
def wnexpd ( left , right , window ) :
"""Expand each of the intervals of a double precision window .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / wnexpd _ c . html
: param left : Amount subtracted from each left endpoint .
: type left : float
: param right : Amount added ... | assert isinstance ( window , stypes . SpiceCell )
assert window . dtype == 1
left = ctypes . c_double ( left )
right = ctypes . c_double ( right )
libspice . wnexpd_c ( left , right , ctypes . byref ( window ) )
return window |
def save_config ( self , cmd = "write mem" , confirm = False , confirm_response = "" ) :
"""Saves Config""" | return super ( CiscoAsaSSH , self ) . save_config ( cmd = cmd , confirm = confirm , confirm_response = confirm_response ) |
def wiki_update ( self , page_id , title = None , body = None , other_names = None , is_locked = None , is_deleted = None ) :
"""Action to lets you update a wiki page ( Requires login ) ( UNTESTED ) .
Parameters :
page _ id ( int ) : Whre page _ id is the wiki page id .
title ( str ) : Page title .
body ( s... | params = { 'wiki_page[title]' : title , 'wiki_page[body]' : body , 'wiki_page[other_names]' : other_names }
return self . _get ( 'wiki_pages/{0}.json' . format ( page_id ) , params , method = 'PUT' , auth = True ) |
def check_scan_process ( self , scan_id ) :
"""Check the scan ' s process , and terminate the scan if not alive .""" | scan_process = self . scan_processes [ scan_id ]
progress = self . get_scan_progress ( scan_id )
if progress < 100 and not scan_process . is_alive ( ) :
self . set_scan_status ( scan_id , ScanStatus . STOPPED )
self . add_scan_error ( scan_id , name = "" , host = "" , value = "Scan process failure." )
logge... |
def get_colr ( txt , argd ) :
"""Return a Colr instance based on user args .""" | fore = parse_colr_arg ( get_name_arg ( argd , '--fore' , 'FORE' , default = None ) , rgb_mode = argd [ '--truecolor' ] , )
back = parse_colr_arg ( get_name_arg ( argd , '--back' , 'BACK' , default = None ) , rgb_mode = argd [ '--truecolor' ] , )
style = get_name_arg ( argd , '--style' , 'STYLE' , default = None )
if ar... |
def gumbel_softmax ( x , z_size , mode , softmax_k = 0 , temperature_warmup_steps = 150000 , summary = True , name = None ) :
"""Gumbel softmax discretization bottleneck .
Args :
x : Input to the discretization bottleneck .
z _ size : Number of bits , where discrete codes range from 1 to 2 * * z _ size .
mo... | with tf . variable_scope ( name , default_name = "gumbel_softmax" ) :
m = tf . layers . dense ( x , 2 ** z_size , name = "mask" )
if softmax_k > 0 :
m , kl = top_k_softmax ( m , softmax_k )
return m , m , 1.0 - tf . reduce_mean ( kl )
logsm = tf . nn . log_softmax ( m )
# Gumbel - softma... |
def session ( self ) :
"""This is what you should use to make requests . It sill authenticate for you .
: return : requests . sessions . Session""" | if not self . _session :
self . _session = requests . Session ( )
self . _session . headers . update ( dict ( Authorization = 'Bearer {0}' . format ( self . token ) ) )
return self . _session |
def get_method ( self , name , arg_types = ( ) ) :
"""searches for the method matching the name and having argument type
descriptors matching those in arg _ types .
Parameters
arg _ types : sequence of strings
each string is a parameter type , in the non - pretty format .
Returns
method : ` JavaMemberIn... | # ensure any lists or iterables are converted to tuple for
# comparison against get _ arg _ type _ descriptors ( )
arg_types = tuple ( arg_types )
for m in self . get_methods_by_name ( name ) :
if ( ( ( not m . is_bridge ( ) ) and m . get_arg_type_descriptors ( ) == arg_types ) ) :
return m
return None |
def write_pbm ( matrix , version , out , scale = 1 , border = None , plain = False ) :
"""Serializes the matrix as ` PBM < http : / / netpbm . sourceforge . net / doc / pbm . html > ` _
image .
: param matrix : The matrix to serialize .
: param int version : The ( Micro ) QR code version
: param out : Filen... | row_iter = matrix_iter ( matrix , version , scale , border )
width , height = get_symbol_size ( version , scale = scale , border = border )
with writable ( out , 'wb' ) as f :
write = f . write
write ( '{0}\n' '# Created by {1}\n' '{2} {3}\n' . format ( ( 'P4' if not plain else 'P1' ) , CREATOR , width , height... |
def plot_parallel ( data , var_names = None , coords = None , figsize = None , textsize = None , legend = True , colornd = "k" , colord = "C1" , shadend = 0.025 , ax = None , norm_method = None , ) :
"""Plot parallel coordinates plot showing posterior points with and without divergences .
Described by https : / /... | if coords is None :
coords = { }
# Get diverging draws and combine chains
divergent_data = convert_to_dataset ( data , group = "sample_stats" )
_ , diverging_mask = xarray_to_ndarray ( divergent_data , var_names = ( "diverging" , ) , combined = True )
diverging_mask = np . squeeze ( diverging_mask )
# Get posterior... |
def infer_enum_class ( node ) :
"""Specific inference for enums .""" | for basename in node . basenames : # TODO : doesn ' t handle subclasses yet . This implementation
# is a hack to support enums .
if basename not in ENUM_BASE_NAMES :
continue
if node . root ( ) . name == "enum" : # Skip if the class is directly from enum module .
break
for local , values in ... |
def OnDestroy ( self , event ) :
"""Called on panel destruction .""" | # deregister observers
if hasattr ( self , 'cardmonitor' ) :
self . cardmonitor . deleteObserver ( self . cardtreecardobserver )
if hasattr ( self , 'readermonitor' ) :
self . readermonitor . deleteObserver ( self . readertreereaderobserver )
self . cardmonitor . deleteObserver ( self . readertreecardobserv... |
def _is_active_model ( cls , model ) :
"""Check is model app name is in list of INSTALLED _ APPS""" | # We need to use such tricky way to check because of inconsistent apps names :
# some apps are included in format " < module _ name > . < app _ name > " like " waldur _ core . openstack "
# other apps are included in format " < app _ name > " like " nodecondcutor _ sugarcrm "
return ( '.' . join ( model . __module__ . ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.