signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _check_dataframe ( dv = None , between = None , within = None , subject = None , effects = None , data = None ) :
"""Check dataframe""" | # Check that data is a dataframe
if not isinstance ( data , pd . DataFrame ) :
raise ValueError ( 'Data must be a pandas dataframe.' )
# Check that both dv and data are provided .
if any ( v is None for v in [ dv , data ] ) :
raise ValueError ( 'DV and data must be specified' )
# Check that dv is a numeric vari... |
def dump_collection ( self ) :
"""Dumps collection into the target system .
This method is called when we ' re initializing the cursor and have no
configs i . e . when we ' re starting for the first time .""" | timestamp = retry_until_ok ( self . get_last_oplog_timestamp )
if timestamp is None :
return None
long_ts = util . bson_ts_to_long ( timestamp )
# Flag if this oplog thread was cancelled during the collection dump .
# Use a list to workaround python scoping .
dump_cancelled = [ False ]
def get_all_ns ( ) :
ns_s... |
def _renorm ( args : Dict [ str , Any ] ) :
"""Renormalizes the state using the norm arg .""" | state = _state_shard ( args )
# If our gate is so bad that we have norm of zero , we have bigger problems .
state /= np . sqrt ( args [ 'norm_squared' ] ) |
def identify_filepath ( arg , real_path = None , show_directory = None , find_source = None , hide_init = None ) :
"""Discover and return the disk file path of the Python module named in
` arg ` by importing the module and returning its ` ` _ _ file _ _ ` ` attribute .
If ` find _ source ` is ` True ` , the nam... | mod = identify_module ( arg )
# raises ModuleNotFound
try :
filename = mod . __file__
except AttributeError :
raise ModuleNotFound ( "module has no '__file__' attribute; is it a " "built-in or C module?" )
if find_source and ( filename . endswith ( '.pyc' ) or filename . endswith ( '.pyo' ) ) :
log . debug ... |
def zip_many_files ( list_of_abspath , dst ) :
"""Add many files to a zip archive .
* * 中文文档 * *
将一系列的文件压缩到一个压缩包中 , 若有重复的文件名 , 在zip中保留所有的副本 。""" | base_dir = os . getcwd ( )
with ZipFile ( dst , "w" ) as f :
for abspath in list_of_abspath :
dirname , basename = os . path . split ( abspath )
os . chdir ( dirname )
f . write ( basename )
os . chdir ( base_dir ) |
def gamm_inc ( a , x ) :
"""Incomple gamma function \ gamma ; computed from NumRec routine gammp .
> > > np . isclose ( gamm _ inc ( 0.5,1 ) , 1.49365)
True
> > > np . isclose ( gamm _ inc ( 1.5,2 ) , 0.6545103)
True
> > > np . isclose ( gamm _ inc ( 2.5,1e - 12 ) , 0)
True""" | assert ( x > 0 and a >= 0 ) , "Invalid arguments in routine gamm_inc: %s,%s" % ( x , a )
if x < ( a + 1.0 ) : # Use the series representation
gam , gln = _gser ( a , x )
else : # Use continued fractions
gamc , gln = _gcf ( a , x )
gam = 1 - gamc
return np . exp ( gln ) * gam |
def read_datafiles ( files , dtype , column ) :
'''Load the datafiles and return cov , mag , phase and fpi phase values .''' | pha = [ ]
pha_fpi = [ ]
for filename , filetype in zip ( files , dtype ) :
if filetype == 'cov' :
cov = load_cov ( filename )
elif filetype == 'mag' :
mag = load_rho ( filename , column )
elif filetype == 'pha' :
pha = load_rho ( filename , 2 )
elif filetype == 'pha_fpi' :
... |
def phisheye_term_list ( self , include_inactive = False , ** kwargs ) :
"""Provides a list of terms that are set up for this account .
This call is not charged against your API usage limit .
NOTE : The terms must be configured in the PhishEye web interface : https : / / research . domaintools . com / phisheye ... | return self . _results ( 'phisheye_term_list' , '/v1/phisheye/term-list' , include_inactive = include_inactive , items_path = ( 'terms' , ) , ** kwargs ) |
def most_cold ( self ) :
"""Returns the * Weather * object in the forecast having the lowest min
temperature . The temperature is retrieved using the
` ` get _ temperature [ ' temp _ min ' ] ` ` call ; was ' temp _ min ' key missing for
every * Weather * instance in the forecast , ` ` None ` ` would be return... | mintemp = 1000.0
# No one would survive that . . .
coldest = None
for weather in self . _forecast . get_weathers ( ) :
d = weather . get_temperature ( )
if 'temp_min' in d :
if d [ 'temp_min' ] < mintemp :
mintemp = d [ 'temp_min' ]
coldest = weather
return coldest |
def get_coords ( data ) :
"""Retrieve coordinates of genes of interest for prioritization .
Can read from CIViC input data or a supplied BED file of chrom , start , end
and gene information .""" | for category , vtypes in [ ( "LOH" , { "LOSS" , "HETEROZYGOSITY" } ) , ( "amplification" , { "AMPLIFICATION" } ) ] :
out = tz . get_in ( [ category , dd . get_genome_build ( data ) ] , _COORDS , { } )
priority_file = dd . get_svprioritize ( data )
if priority_file :
if os . path . basename ( priorit... |
def transform_to ( ext ) :
"""Decorator to create an output filename from an output filename with
the specified extension . Changes the extension , in _ file is transformed
to a new type .
Takes functions like this to decorate :
f ( in _ file , out _ dir = None , out _ file = None ) or ,
f ( in _ file = i... | def decor ( f ) :
@ functools . wraps ( f )
def wrapper ( * args , ** kwargs ) :
out_file = kwargs . get ( "out_file" , None )
if not out_file :
in_path = kwargs . get ( "in_file" , args [ 0 ] )
out_dir = kwargs . get ( "out_dir" , os . path . dirname ( in_path ) )
... |
def _generate_docker_image_version ( layers , runtime ) :
"""Generate the Docker TAG that will be used to create the image
Parameters
layers list ( samcli . commands . local . lib . provider . Layer )
List of the layers
runtime str
Runtime of the image to create
Returns
str
String representing the T... | # Docker has a concept of a TAG on an image . This is plus the REPOSITORY is a way to determine
# a version of the image . We will produced a TAG for a combination of the runtime with the layers
# specified in the template . This will allow reuse of the runtime and layers across different
# functions that are defined .... |
def register_exporter ( name , base_class ) :
"""Register an exporter to use for a : class : ` Part < cqparts . Part > ` ,
: class : ` Assembly < cqparts . Assembly > ` , or both
( with : class : ` Component < cqparts . Component > ` ) .
Registration is necessary to use with
: meth : ` Component . exporter ... | # Verify params
if not isinstance ( name , str ) or ( not name ) :
raise TypeError ( "invalid name: %r" % name )
if not issubclass ( base_class , Component ) :
raise TypeError ( "invalid base_class: %r, must be a %r subclass" % ( base_class , Component ) )
def decorator ( cls ) : # - - - Verify
# Can only be re... |
def get_log_lines ( self , source_id , scan_id ) :
"""Get the log text for a scan object
: rtype : Iterator over log lines .""" | target_url = self . client . get_url ( 'SCAN' , 'GET' , 'log' , { 'source_id' : source_id , 'scan_id' : scan_id } )
r = self . client . request ( 'GET' , target_url , headers = { 'Accept' : 'text/plain' } , stream = True )
return r . iter_lines ( decode_unicode = True ) |
def PKCS_POST_query ( self , req_hook , req_args ) :
'''Generic POST query method''' | # HTTP POST queries require keyManagerTokens and sessionTokens
headers = { 'Content-Type' : 'application/json' , 'sessionToken' : self . __session__ , 'keyManagerToken' : self . __keymngr__ }
# HTTP POST query to keymanager authenticate API
try :
if req_args is None :
response = requests . post ( self . __u... |
def set ( self , key , value ) :
"""Transactional implementation of : func : ` Map . set ( key , value ) < hazelcast . proxy . map . Map . set > `
The object to be set will be accessible only in the current transaction context till the transaction is
committed .
: param key : ( object ) , key of the entry .
... | check_not_none ( key , "key can't be none" )
check_not_none ( value , "value can't be none" )
return self . _encode_invoke ( transactional_map_set_codec , key = self . _to_data ( key ) , value = self . _to_data ( value ) ) |
def equals ( self , rest_object ) :
"""Compare with another object""" | if self . _is_dirty :
return False
if rest_object is None :
return False
if not isinstance ( rest_object , NURESTObject ) :
raise TypeError ( 'The object is not a NURESTObject %s' % rest_object )
if self . rest_name != rest_object . rest_name :
return False
if self . id and rest_object . id :
return... |
def increment ( self , size : int ) :
'''Increment the number of files downloaded .
Args :
size : The size of the file''' | assert size >= 0 , size
self . files += 1
self . size += size
self . bandwidth_meter . feed ( size ) |
def write_err ( self , text ) :
"""Write error text in the terminal without breaking the spinner .""" | stderr = self . stderr
if self . stderr . closed :
stderr = sys . stderr
stderr . write ( decode_output ( u"\r" , target_stream = stderr ) )
stderr . write ( decode_output ( CLEAR_LINE , target_stream = stderr ) )
if text is None :
text = ""
text = decode_output ( u"{0}\n" . format ( text ) , target_stream = st... |
def name ( self ) :
"""A unique name for this scraper .""" | return '' . join ( '_%s' % c if c . isupper ( ) else c for c in self . __class__ . __name__ ) . strip ( '_' ) . lower ( ) |
def putWebhook ( self , hook_id , external_id , url , event_types ) :
"""Update a webhook .""" | path = 'notification/webhook'
payload = { 'id' : hook_id , 'externalId' : external_id , 'url' : url , 'eventTypes' : event_types }
return self . rachio . put ( path , payload ) |
def print_coco_metrics ( self , json_file ) :
"""Args :
json _ file ( str ) : path to the results json file in coco format
Returns :
dict : the evaluation metrics""" | from pycocotools . cocoeval import COCOeval
ret = { }
cocoDt = self . coco . loadRes ( json_file )
cocoEval = COCOeval ( self . coco , cocoDt , 'bbox' )
cocoEval . evaluate ( )
cocoEval . accumulate ( )
cocoEval . summarize ( )
fields = [ 'IoU=0.5:0.95' , 'IoU=0.5' , 'IoU=0.75' , 'small' , 'medium' , 'large' ]
for k in... |
def to_linspace ( self ) :
"""convert from full to linspace""" | if hasattr ( self . shape , '__len__' ) :
raise NotImplementedError ( "can only convert flat Full arrays to linspace" )
return Linspace ( self . fill_value , self . fill_value , self . shape ) |
def scatter_table ( self , x , y , c , s , mark = '*' ) :
"""Add a data series to the plot .
: param x : array containing x - values .
: param y : array containing y - values .
: param c : array containing values for the color of the mark .
: param s : array containing values for the size of the mark .
: ... | # clear the background of the marks
# self . _ clear _ plot _ mark _ background ( x , y , mark , markstyle )
# draw the plot series over the background
options = self . _parse_plot_options ( mark )
s = [ sqrt ( si ) for si in s ]
plot_series = self . _create_plot_tables_object ( x , y , c , s , options )
self . plot_ta... |
async def display_columns_and_rows ( self , database , table , description , rows , link_column = False , truncate_cells = 0 , ) :
"Returns columns , rows for specified table - including fancy foreign key treatment" | table_metadata = self . ds . table_metadata ( database , table )
sortable_columns = await self . sortable_columns_for_table ( database , table , True )
columns = [ { "name" : r [ 0 ] , "sortable" : r [ 0 ] in sortable_columns } for r in description ]
pks = await self . ds . execute_against_connection_in_thread ( databa... |
def get_index_by_name ( self , db_name , tbl_name , index_name ) :
"""Parameters :
- db _ name
- tbl _ name
- index _ name""" | self . send_get_index_by_name ( db_name , tbl_name , index_name )
return self . recv_get_index_by_name ( ) |
def safe_log_error ( self , error : Exception , * info : str ) :
"""Log error failing silently on error""" | self . __do_safe ( lambda : self . logger . error ( error , * info ) ) |
def conf ( self , key ) :
'''get config''' | return self . __conf [ key ] if key in self . __conf else _YunpianConf . YP_CONF . get ( key ) |
def _build_from ( baseip ) :
"""Build URL for description . xml from ip""" | from ipaddress import ip_address
try :
ip_address ( baseip )
except ValueError : # " " " attempt to construct url but the ip format has changed " " "
# logger . warning ( " Format of internalipaddress changed : % s " , baseip )
if 'http' not in baseip [ 0 : 4 ] . lower ( ) :
baseip = urlunsplit ( [ 'htt... |
def _monitor_for_zero_connected_peers ( self ) :
"""Track if we lost connection to all peers .
Give some retries threshold to allow peers that are in the process of connecting or in the queue to be connected to run""" | if len ( self . Peers ) == 0 and len ( self . connection_queue ) == 0 :
if self . peer_zero_count > 2 :
logger . debug ( "Peer count 0 exceeded max retries threshold, restarting..." )
self . Restart ( )
else :
logger . debug ( f"Peer count is 0, allow for retries or queued connections to... |
def cfg_file ( self ) :
"""Return the configuration file for the given repo path""" | default_path = os . path . join ( self . relpath , '.git' , 'config' )
if os . path . exists ( default_path ) :
return default_path
dotgitpath = os . path . join ( self . relpath , '.git' )
cfg_path = None
# with git submodules , . git is a file containing " gitdir : . . . / . . / path "
if os . path . isfile ( dot... |
def send_hid_event ( use_page , usage , down ) :
"""Create a new SEND _ HID _ EVENT _ MESSAGE .""" | message = create ( protobuf . SEND_HID_EVENT_MESSAGE )
event = message . inner ( )
# TODO : This should be generated somehow . I guess it ' s mach AbsoluteTime
# which is tricky to generate . The device does not seem to care much about
# the value though , so hardcode something here .
abstime = binascii . unhexlify ( b... |
def post ( method , hmc , uri , uri_parms , body , logon_required , wait_for_completion ) :
"""Operation : Create Password Rule .""" | assert wait_for_completion is True
# synchronous operation
try :
console = hmc . consoles . lookup_by_oid ( None )
except KeyError :
raise InvalidResourceError ( method , uri )
check_required_fields ( method , uri , body , [ 'name' ] )
new_password_rule = console . password_rules . add ( body )
return { 'elemen... |
def showActiveState ( self , state ) :
"""Shows this view in the active state based on the inputed state settings .
: param state | < bool >""" | return
palette = self . window ( ) . palette ( )
clr = palette . color ( palette . Window )
avg = ( clr . red ( ) + clr . green ( ) + clr . blue ( ) ) / 3
if avg < 180 and state :
clr = clr . lighter ( 105 )
elif not state :
clr = clr . darker ( 105 )
palette . setColor ( palette . Window , clr )
self . setPale... |
def getParams ( options = None ) :
"""return a string containing script parameters .
Parameters are all variables that start with ` ` param _ ` ` .""" | result = [ ]
if options :
members = options . __dict__
for k , v in sorted ( members . items ( ) ) :
result . append ( "# %-40s: %s" % ( k , str ( v ) ) )
else :
vars = inspect . currentframe ( ) . f_back . f_locals
for var in filter ( lambda x : re . match ( "param_" , x ) , vars . keys ( ) ) :... |
def from_json ( cls , json ) :
"""Create new MapreduceSpec from the json , encoded by to _ json .
Args :
json : json representation of MapreduceSpec .
Returns :
an instance of MapreduceSpec with all data deserialized from json .""" | mapreduce_spec = cls ( json [ "name" ] , json [ "mapreduce_id" ] , json [ "mapper_spec" ] , json . get ( "params" ) , json . get ( "hooks_class_name" ) )
return mapreduce_spec |
def parseRtspReply ( self , data ) :
print ( "Parsing Received Rtsp data..." )
"""Parse the RTSP reply from the server .""" | lines = data . split ( '\n' )
seqNum = int ( lines [ 1 ] . split ( ' ' ) [ 1 ] )
# Process only if the server reply ' s sequence number is the same as the request ' s
if seqNum == self . rtspSeq :
session = int ( lines [ 2 ] . split ( ' ' ) [ 1 ] )
# New RTSP session ID
if self . sessionId == 0 :
se... |
def compute_fingerprint ( self , target ) :
"""UnpackedWheels targets need to be re - unpacked if any of its configuration changes or any of
the jars they import have changed .""" | if isinstance ( target , UnpackedWheels ) :
hasher = sha1 ( )
for cache_key in sorted ( req . cache_key ( ) for req in target . all_imported_requirements ) :
hasher . update ( cache_key . encode ( 'utf-8' ) )
hasher . update ( target . payload . fingerprint ( ) . encode ( 'utf-8' ) )
return hash... |
async def sign_url ( self , url , method = HASH ) :
"""Sign an URL with this request ' s auth token""" | token = await self . get_token ( )
if method == self . QUERY :
return patch_qs ( url , { settings . WEBVIEW_TOKEN_KEY : token , } )
elif method == self . HASH :
hash_id = 5
p = list ( urlparse ( url ) )
p [ hash_id ] = quote ( token )
return urlunparse ( p )
else :
raise ValueError ( f'Invalid s... |
def print_catalog ( self , catalog_filter = [ ] ) :
"""Prints out a catalog of all the texts in the corpus . Can be filtered by passing
a list of keys you want present in the texts .
: param : catalog _ filter = If you wish to sort the list , use the keys pnum ,
edition , metadata , transliteration , normaliz... | keys = sorted ( self . catalog . keys ( ) )
if len ( catalog_filter ) > 0 : # pylint : disable = len - as - condition
valid = [ ]
for key in keys :
for f in catalog_filter :
if len ( self . catalog [ key ] [ f ] ) > 0 : # pylint : disable = len - as - condition
valid . append... |
def update_lincs_proteins ( ) :
"""Load the csv of LINCS protein metadata into a dict .
Produces a dict keyed by HMS LINCS protein ids , with the metadata
contained in a dict of row values keyed by the column headers extracted
from the csv .""" | url = 'http://lincs.hms.harvard.edu/db/proteins/'
prot_data = load_lincs_csv ( url )
prot_dict = { d [ 'HMS LINCS ID' ] : d . copy ( ) for d in prot_data }
assert len ( prot_dict ) == len ( prot_data ) , "We lost data."
fname = os . path . join ( path , 'lincs_proteins.json' )
with open ( fname , 'w' ) as fh :
json... |
def require_python ( minimum ) :
"""Require at least a minimum Python version .
The version number is expressed in terms of ` sys . hexversion ` . E . g . to
require a minimum of Python 2.6 , use : :
> > > require _ python ( 0x206000f0)
: param minimum : Minimum Python version supported .
: type minimum :... | if sys . hexversion < minimum :
hversion = hex ( minimum ) [ 2 : ]
if len ( hversion ) % 2 != 0 :
hversion = '0' + hversion
split = list ( hversion )
parts = [ ]
while split :
parts . append ( int ( '' . join ( ( split . pop ( 0 ) , split . pop ( 0 ) ) ) , 16 ) )
major , minor , ... |
def toggle_play_pause ( self ) :
"""Toggle play pause media player .""" | # Use Play / Pause button only for sources which support NETAUDIO
if ( self . _state == STATE_PLAYING and self . _input_func in self . _netaudio_func_list ) :
return self . _pause ( )
elif self . _input_func in self . _netaudio_func_list :
return self . _play ( ) |
def exclude_matches ( self , matches ) :
"""Filter any matches that match an exclude pattern .
: param matches : a list of possible completions""" | for match in matches :
for exclude_pattern in self . exclude_patterns :
if re . match ( exclude_pattern , match ) is not None :
break
else :
yield match |
def getGridByCard ( self , gssha_card_name ) :
"""Returns GDALGrid object of GSSHA grid
Paramters :
gssha _ card _ name ( str ) : Name of GSSHA project card for grid .
Returns :
GDALGrid""" | with tmp_chdir ( self . project_directory ) :
if gssha_card_name not in ( self . INPUT_MAPS + self . WMS_DATASETS ) :
raise ValueError ( "Card {0} not found in valid grid cards ..." . format ( gssha_card_name ) )
gssha_grid_card = self . getCard ( gssha_card_name )
if gssha_grid_card is None :
... |
def recursepath ( path , reverse = False ) : # type : ( Text , bool ) - > List [ Text ]
"""Get intermediate paths from the root to the given path .
Arguments :
path ( str ) : A PyFilesystem path
reverse ( bool ) : Reverses the order of the paths
( default ` False ` ) .
Returns :
list : A list of paths .... | if path in "/" :
return [ "/" ]
path = abspath ( normpath ( path ) ) + "/"
paths = [ "/" ]
find = path . find
append = paths . append
pos = 1
len_path = len ( path )
while pos < len_path :
pos = find ( "/" , pos )
append ( path [ : pos ] )
pos += 1
if reverse :
return paths [ : : - 1 ]
return paths |
def fromlineno ( self ) :
"""The first line that this node appears on in the source code .
: type : int or None""" | lineno = super ( Arguments , self ) . fromlineno
return max ( lineno , self . parent . fromlineno or 0 ) |
def create_or_update_issue ( self , title , body , culprit , labels , ** kwargs ) :
'''Creates or comments on existing issue in the store .
: params title : title for the issue
: params body : body , the content of the issue
: params culprit : string used to identify the cause of the issue ,
also used for a... | issues = self . search ( q = culprit , labels = labels )
self . time_delta = kwargs . pop ( 'time_delta' )
self . max_comments = kwargs . pop ( 'max_comments' )
if issues :
latest_issue = issues . pop ( 0 )
return self . handle_issue_comment ( issue = latest_issue , title = title , body = body , ** kwargs )
els... |
def validate_json ( data , validator ) :
"""Validate data against a given JSON schema ( see https : / / json - schema . org ) .
data : JSON - serializable data to validate .
validator ( jsonschema . DraftXValidator ) : The validator .
RETURNS ( list ) : A list of error messages , if available .""" | errors = [ ]
for err in sorted ( validator . iter_errors ( data ) , key = lambda e : e . path ) :
if err . path :
err_path = "[{}]" . format ( " -> " . join ( [ str ( p ) for p in err . path ] ) )
else :
err_path = ""
msg = err . message + " " + err_path
if err . context : # Error has su... |
def attach_socket ( self , container , params = None , ws = False ) :
"""Like ` ` attach ` ` , but returns the underlying socket - like object for the
HTTP request .
Args :
container ( str ) : The container to attach to .
params ( dict ) : Dictionary of request parameters ( e . g . ` ` stdout ` ` ,
` ` st... | if params is None :
params = { 'stdout' : 1 , 'stderr' : 1 , 'stream' : 1 }
if 'detachKeys' not in params and 'detachKeys' in self . _general_configs :
params [ 'detachKeys' ] = self . _general_configs [ 'detachKeys' ]
if ws :
return self . _attach_websocket ( container , params )
headers = { 'Connection' :... |
def allows_recursion ( self ) :
"""Return True iff we can recurse into the url ' s content .""" | log . debug ( LOG_CHECK , "checking recursion of %r ..." , self . url )
if not self . valid :
log . debug ( LOG_CHECK , "... no, invalid." )
return False
if not self . can_get_content ( ) :
log . debug ( LOG_CHECK , "... no, cannot get content." )
return False
if not self . allows_simple_recursion ( ) :... |
def delete ( self ) :
"""Deletes the selected items .""" | urls = self . selected_urls ( )
rep = QtWidgets . QMessageBox . question ( self . tree_view , _ ( 'Confirm delete' ) , _ ( 'Are you sure about deleting the selected files/directories?' ) , QtWidgets . QMessageBox . Yes | QtWidgets . QMessageBox . No , QtWidgets . QMessageBox . Yes )
if rep == QtWidgets . QMessageBox . ... |
def file_source_hunks ( self , filename ) :
"""Like ` CoberturaDiff . file _ source ` , but returns a list of line hunks of
the lines that have changed for the given file ` filename ` . An empty
list means that the file has no lines that have a change in coverage
status .""" | lines = self . file_source ( filename )
hunks = hunkify_lines ( lines )
return hunks |
def get_user ( self ) :
"""Retrieves information about the user currently using the api .
: return : a python dictionary with either the result of the search or an error from TheTVDB .""" | return self . parse_raw_response ( requests_util . run_request ( 'get' , self . API_BASE_URL + '/user' , headers = self . __get_header_with_auth ( ) ) ) |
def add_command ( self , cmd_name , * args ) :
"""Add command to action .""" | self . __commands . append ( Command ( cmd_name , args ) ) |
def get_all ( ) :
'''. . versionadded : : 2014.7.0
Return all available boot services
CLI Example :
. . code - block : : bash
salt ' * ' service . get _ all''' | services = [ ]
if not os . path . isdir ( '/etc/rc.d' ) :
return services
for service in os . listdir ( '/etc/rc.d' ) : # this will remove rc . subr and all non executable files
if available ( service ) :
services . append ( service )
return sorted ( services ) |
def find_ent_space_price ( package , category , size , tier_level ) :
"""Find the space price for the given category , size , and tier
: param package : The Enterprise ( Endurance ) product package
: param category : The category of space ( endurance , replication , snapshot )
: param size : The size for whic... | if category == 'snapshot' :
category_code = 'storage_snapshot_space'
elif category == 'replication' :
category_code = 'performance_storage_replication'
else : # category = = ' endurance '
category_code = 'performance_storage_space'
level = ENDURANCE_TIERS . get ( tier_level )
for item in package [ 'items' ]... |
def get_witness ( self , work , siglum , text_class = WitnessText ) :
"""Returns a ` WitnessText ` representing the file associated with
` work ` and ` siglum ` .
Combined , ` work ` and ` siglum ` form the basis of a filename for
retrieving the text .
: param work : name of work
: type work : ` str `
:... | filename = os . path . join ( work , siglum + '.txt' )
self . _logger . debug ( 'Creating WitnessText object from {}' . format ( filename ) )
with open ( os . path . join ( self . _path , filename ) , encoding = 'utf-8' ) as fh :
content = fh . read ( )
return text_class ( work , siglum , content , self . _tokenize... |
def generateSensorimotorSequence ( self , sequenceLength ) :
"""Generate sensorimotor sequences of length sequenceLength .
@ param sequenceLength ( int )
Length of the sensorimotor sequence .
@ return ( tuple ) Contains :
sensorySequence ( list )
Encoded sensory input for whole sequence .
motorSequence ... | motorSequence = [ ]
sensorySequence = [ ]
sensorimotorSequence = [ ]
currentEyeLoc = self . nupicRandomChoice ( self . spatialConfig )
for i in xrange ( sequenceLength ) :
currentSensoryInput = self . spatialMap [ tuple ( currentEyeLoc ) ]
nextEyeLoc , currentEyeV = self . getNextEyeLocation ( currentEyeLoc )
... |
def monitor ( result_queue , broker = None ) :
"""Gets finished tasks from the result queue and saves them to Django
: type result _ queue : multiprocessing . Queue""" | if not broker :
broker = get_broker ( )
name = current_process ( ) . name
logger . info ( _ ( "{} monitoring at {}" ) . format ( name , current_process ( ) . pid ) )
for task in iter ( result_queue . get , 'STOP' ) : # save the result
if task . get ( 'cached' , False ) :
save_cached ( task , broker )
... |
def increment ( version , major = False , minor = False , patch = True ) :
"""Increment a semantic version
: param version : str of the version to increment
: param major : bool specifying major level version increment
: param minor : bool specifying minor level version increment
: param patch : bool specif... | version = semantic_version . Version ( version )
if major :
version . major += 1
version . minor = 0
version . patch = 0
elif minor :
version . minor += 1
version . patch = 0
elif patch :
version . patch += 1
return str ( version ) |
def set_render_wrapper ( func ) :
"""Set an optional wrapper function that is called around the generated
HTML markup on displacy . render . This can be used to allow integration into
other platforms , similar to Jupyter Notebooks that require functions to be
called around the HTML . It can also be used to im... | global RENDER_WRAPPER
if not hasattr ( func , "__call__" ) :
raise ValueError ( Errors . E110 . format ( obj = type ( func ) ) )
RENDER_WRAPPER = func |
def knob_subgroup ( self , cutoff = 7.0 ) :
"""KnobGroup where all KnobsIntoHoles have max _ kh _ distance < = cutoff .""" | if cutoff > self . cutoff :
raise ValueError ( "cutoff supplied ({0}) cannot be greater than self.cutoff ({1})" . format ( cutoff , self . cutoff ) )
return KnobGroup ( monomers = [ x for x in self . get_monomers ( ) if x . max_kh_distance <= cutoff ] , ampal_parent = self . ampal_parent ) |
def give_consent ( ) :
"""Serves up the consent in the popup window .""" | if not ( 'hitId' in request . args and 'assignmentId' in request . args and 'workerId' in request . args ) :
raise ExperimentError ( 'hit_assign_worker_id_not_set_in_consent' )
hit_id = request . args [ 'hitId' ]
assignment_id = request . args [ 'assignmentId' ]
worker_id = request . args [ 'workerId' ]
mode = requ... |
def load_config ( path = None ) :
"""Load a Python or JSON config file .""" | if not path or not op . exists ( path ) :
return Config ( )
path = op . realpath ( path )
dirpath , filename = op . split ( path )
file_ext = op . splitext ( path ) [ 1 ]
logger . debug ( "Load config file `%s`." , path )
if file_ext == '.py' :
config = PyFileConfigLoader ( filename , dirpath , log = logger ) .... |
def get_method_name ( method ) :
"""Returns given method name .
: param method : Method to retrieve the name .
: type method : object
: return : Method name .
: rtype : unicode""" | name = get_object_name ( method )
if name . startswith ( "__" ) and not name . endswith ( "__" ) :
name = "_{0}{1}" . format ( get_object_name ( method . im_class ) , name )
return name |
def attach ( self , filt , view = None ) :
"""Attach a Filter to this visual
Each filter modifies the appearance or behavior of the visual .
Parameters
filt : object
The filter to attach .
view : instance of VisualView | None
The view to use .""" | if view is None :
self . _vshare . filters . append ( filt )
for view in self . _vshare . views . keys ( ) :
filt . _attach ( view )
else :
view . _filters . append ( filt )
filt . _attach ( view ) |
def restore_from_snapshot ( self , volume_id , snapshot_id ) :
"""Restores a specific volume from a snapshot
: param integer volume _ id : The id of the volume
: param integer snapshot _ id : The id of the restore point
: return : Returns whether succesfully restored or not""" | return self . client . call ( 'Network_Storage' , 'restoreFromSnapshot' , snapshot_id , id = volume_id ) |
async def discover ( self , timeout = None ) : # TODO : better name ?
"""Discover sentinels and all monitored services within given timeout .
If no sentinels discovered within timeout : TimeoutError is raised .
If some sentinels were discovered but not all — it is ok .
If not all monitored services ( masters ... | # TODO : check not closed
# TODO : discovery must be done with some customizable timeout .
if timeout is None :
timeout = self . discover_timeout
tasks = [ ]
pools = [ ]
for addr in self . _sentinels : # iterate over unordered set
tasks . append ( self . _connect_sentinel ( addr , timeout , pools ) )
done , pen... |
def is_enabled ( self , cls ) :
"""Return whether the given component class is enabled .""" | if cls not in self . enabled :
self . enabled [ cls ] = self . is_component_enabled ( cls )
return self . enabled [ cls ] |
def to_pypsa ( network , mode , timesteps ) :
"""Translate graph based grid representation to PyPSA Network
For details from a user perspective see API documentation of
: meth : ` ~ . grid . network . EDisGo . analyze ` of the API class
: class : ` ~ . grid . network . EDisGo ` .
Translating eDisGo ' s grid... | # check if timesteps is array - like , otherwise convert to list ( necessary
# to obtain a dataframe when using . loc in time series functions )
if not hasattr ( timesteps , "__len__" ) :
timesteps = [ timesteps ]
# get topology and time series data
if mode is None :
mv_components = mv_to_pypsa ( network )
... |
def _naive_concordance_summary_statistics ( event_times , predicted_event_times , event_observed ) :
"""Fallback , simpler method to compute concordance .
Assumes the data has been verified by lifelines . utils . concordance _ index first .""" | num_pairs = 0.0
num_correct = 0.0
num_tied = 0.0
for a , time_a in enumerate ( event_times ) :
pred_a = predicted_event_times [ a ]
event_a = event_observed [ a ]
# Don ' t want to double count
for b in range ( a + 1 , len ( event_times ) ) :
time_b = event_times [ b ]
pred_b = predicted... |
def _netbsd_brshow ( br = None ) :
'''Internal , returns bridges and enslaved interfaces ( NetBSD - brconfig )''' | brconfig = _tool_path ( 'brconfig' )
if br :
cmd = '{0} {1}' . format ( brconfig , br )
else :
cmd = '{0} -a' . format ( brconfig )
brs = { }
start_int = False
for line in __salt__ [ 'cmd.run' ] ( cmd , python_shell = False ) . splitlines ( ) :
if line . startswith ( 'bridge' ) :
start_int = False
... |
def percent_initiated_interactions ( records , user ) :
"""The percentage of calls initiated by the user .""" | if len ( records ) == 0 :
return 0
initiated = sum ( 1 for r in records if r . direction == 'out' )
return initiated / len ( records ) |
def _sum ( X , xmask = None , xconst = None , Y = None , ymask = None , yconst = None , symmetric = False , remove_mean = False , weights = None ) :
r"""Computes the column sums and centered column sums .
If symmetric = False , the sums will be determined as
. . math :
sx & = & \ frac { 1 } { 2 } \ sum _ t x ... | T = X . shape [ 0 ]
# Check if weights are given :
if weights is not None :
X = weights [ : , None ] * X
if Y is not None :
Y = weights [ : , None ] * Y
# compute raw sums on variable data
sx_raw = X . sum ( axis = 0 )
# this is the mean before subtracting it .
sy_raw = 0
if Y is not None :
sy_raw =... |
def get_nodes ( self , request ) :
"""This method is used to build the menu tree .""" | nodes = [ ]
for shiny_app in ShinyApp . objects . all ( ) :
node = NavigationNode ( shiny_app . name , reverse ( 'cms_shiny:shiny_detail' , args = ( shiny_app . slug , ) ) , shiny_app . slug )
nodes . append ( node )
return nodes |
def _fromJSON ( cls , jsonobject ) :
"""Generates a new instance of : class : ` maspy . core . Smi ` from a decoded
JSON object ( as generated by : func : ` maspy . core . Smi . _ reprJSON ( ) ` ) .
: param jsonobject : decoded JSON object
: returns : a new instance of : class : ` Smi `""" | newInstance = cls ( None , None )
attribDict = { }
attribDict [ 'id' ] = jsonobject [ 0 ]
attribDict [ 'specfile' ] = jsonobject [ 1 ]
attribDict [ 'attributes' ] = jsonobject [ 2 ]
attribDict [ 'params' ] = [ tuple ( param ) for param in jsonobject [ 3 ] ]
attribDict [ 'scanListParams' ] = [ tuple ( param ) for param ... |
def get_equivalent_kpoints ( self , index ) :
"""Returns the list of kpoint indices equivalent ( meaning they are the
same frac coords ) to the given one .
Args :
index : the kpoint index
Returns :
a list of equivalent indices
TODO : now it uses the label we might want to use coordinates instead
( in ... | # if the kpoint has no label it can " t have a repetition along the band
# structure line object
if self . kpoints [ index ] . label is None :
return [ index ]
list_index_kpoints = [ ]
for i in range ( len ( self . kpoints ) ) :
if self . kpoints [ i ] . label == self . kpoints [ index ] . label :
list_... |
def create_application_configuration ( self , name , properties , description = None ) :
"""Create an application configuration .
Args :
name ( str , optional ) : Only return application configurations containing property * * name * * that matches ` name ` . ` name ` can be a
. . versionadded 1.12""" | if not hasattr ( self , 'applicationConfigurations' ) :
raise NotImplementedError ( )
cv = ApplicationConfiguration . _props ( name , properties , description )
res = self . rest_client . session . post ( self . applicationConfigurations , headers = { 'Accept' : 'application/json' } , json = cv )
_handle_http_error... |
def get_term_by_year_and_quarter ( year , quarter ) :
"""Returns a uw _ sws . models . Term object ,
for the passed year and quarter .""" | url = "{}/{},{}.json" . format ( term_res_url_prefix , year , quarter . lower ( ) )
return _json_to_term_model ( get_resource ( url ) ) |
def SLIT_MICHELSON ( x , g ) :
"""Instrumental ( slit ) function .
B ( x ) = 2 / γ * sin ( 2pi * x / γ ) / ( 2pi * x / γ ) if x ! = 0 else 1,
where 1 / γ is the maximum optical path difference .""" | y = zeros ( len ( x ) )
index_zero = x == 0
index_nonzero = ~ index_zero
dk_ = 2 * pi / g
x_ = dk_ * x [ index_nonzero ]
y [ index_zero ] = 1
y [ index_nonzero ] = 2 / g * sin ( x_ ) / x_
return y |
def available ( self ) :
"""True if any of the supported modules from ` ` packages ` ` is available for use .
: return : True if any modules from ` ` packages ` ` exist
: rtype : bool""" | for module_name in self . packages :
if importlib . util . find_spec ( module_name ) :
return True
return False |
def _enforce_bounds ( self , x ) :
"""" Enforce the bounds on x if only infinitesimal violations occurs""" | assert len ( x ) == len ( self . bounds )
x_enforced = [ ]
for x_i , ( lb , ub ) in zip ( x , self . bounds ) :
if x_i < lb :
if x_i > lb - ( ub - lb ) / 1e10 :
x_enforced . append ( lb )
else :
x_enforced . append ( x_i )
elif x_i > ub :
if x_i < ub + ( ub - lb )... |
def set_theme ( self , theme = None ) :
"""Check that the terminal supports the provided theme , and applies
the theme to the terminal if possible .
If the terminal doesn ' t support the theme , this falls back to the
default theme . The default theme only requires 8 colors so it
should be compatible with a... | terminal_colors = curses . COLORS if curses . has_colors ( ) else 0
default_theme = Theme ( use_color = bool ( terminal_colors ) )
if theme is None :
theme = default_theme
elif theme . required_color_pairs > curses . COLOR_PAIRS :
_logger . warning ( 'Theme `%s` requires %s color pairs, but $TERM=%s only ' 'sup... |
def directory_files ( path ) :
"""Yield directory file names .""" | for entry in os . scandir ( path ) :
if not entry . name . startswith ( '.' ) and entry . is_file ( ) :
yield entry . name |
def read_config_file ( self , file_name ) :
"""Reads a CWR grammar config file .
: param file _ name : name of the text file
: return : the file ' s contents""" | with open ( os . path . join ( self . __path ( ) , os . path . basename ( file_name ) ) , 'rt' ) as file_config :
return self . _parser . parseString ( file_config . read ( ) ) |
def find_disulfide_bridges ( self , threshold = 3.0 ) :
"""Run Biopython ' s search _ ss _ bonds to find potential disulfide bridges for each chain and store in ChainProp .
Will add a list of tuple pairs into the annotations field , looks like this : :
[ ( ( ' ' , 79 , ' ' ) , ( ' ' , 110 , ' ' ) ) ,
( ( ' ' ... | if self . structure :
parsed = self . structure
else :
parsed = self . parse_structure ( )
if not parsed :
log . error ( '{}: unable to open structure to find S-S bridges' . format ( self . id ) )
return
disulfide_bridges = ssbio . protein . structure . properties . residues . search_ss_bonds ( parsed .... |
def hexify ( message ) :
'''Print out printable characters , but others in hex''' | import string
hexified = [ ]
for char in message :
if ( char in '\n\r \t' ) or ( char not in string . printable ) :
hexified . append ( '\\x%02x' % ord ( char ) )
else :
hexified . append ( char )
return '' . join ( hexified ) |
def find_log_files ( self , sp_key , filecontents = True , filehandles = False ) :
"""Return matches log files of interest .
: param sp _ key : Search pattern key specified in config
: param filehandles : Set to true to return a file handle instead of slurped file contents
: return : Yields a dict with filena... | # Pick up path filters if specified .
# Allows modules to be called multiple times with different sets of files
path_filters = getattr ( self , 'mod_cust_config' , { } ) . get ( 'path_filters' )
path_filters_exclude = getattr ( self , 'mod_cust_config' , { } ) . get ( 'path_filters_exclude' )
# Old , depreciated syntax... |
def leader_get ( attribute = None ) :
"""Juju leader get value ( s )""" | cmd = [ 'leader-get' , '--format=json' ] + [ attribute or '-' ]
return json . loads ( subprocess . check_output ( cmd ) . decode ( 'UTF-8' ) ) |
def from_url ( cls , url , ** kwargs ) :
"""Create a client from a url .""" | url = urllib3 . util . parse_url ( url )
if url . host :
kwargs . setdefault ( 'host' , url . host )
if url . port :
kwargs . setdefault ( 'port' , url . port )
if url . scheme == 'https' :
kwargs . setdefault ( 'connection_class' , urllib3 . HTTPSConnectionPool )
return cls ( ** kwargs ) |
def organisation_group_id ( self ) :
"""str : Organisation Group ID""" | self . _validate ( )
self . _validate_for_organisation_group_id ( )
parts = [ ]
parts . append ( self . election_type )
if self . subtype :
parts . append ( self . subtype )
parts . append ( self . organisation )
parts . append ( self . date )
return "." . join ( parts ) |
def eventFilter ( self , obj , event ) :
"""Reimplemented to hide on certain key presses and on text edit focus
changes .""" | if obj == self . _text_edit :
etype = event . type ( )
if etype == QEvent . KeyPress :
key = event . key ( )
cursor = self . _text_edit . textCursor ( )
prev_char = self . _text_edit . get_character ( cursor . position ( ) , offset = - 1 )
if key in ( Qt . Key_Enter , Qt . Key_Re... |
def get_distance_matrix ( x ) :
"""Get distance matrix given a matrix . Used in testing .""" | square = nd . sum ( x ** 2.0 , axis = 1 , keepdims = True )
distance_square = square + square . transpose ( ) - ( 2.0 * nd . dot ( x , x . transpose ( ) ) )
return nd . sqrt ( distance_square ) |
def get_by_enclosures ( self , enclosure_urls ) :
"""Get bitlove data for a list of enclosure URLs""" | # prepare URLs
enclosure_urls = map ( str . strip , enclosure_urls )
enclosure_urls = filter ( None , enclosure_urls )
return BitloveResponse ( self . opener , enclosure_urls ) |
def release ( path , repository ) :
"""Create a new release upgrade recipe , for developers .""" | upgrader = InvenioUpgrader ( )
logger = upgrader . get_logger ( )
try :
endpoints = upgrader . find_endpoints ( )
if not endpoints :
logger . error ( "No upgrades found." )
click . Abort ( )
depends_on = [ ]
for repo , upgrades in endpoints . items ( ) :
depends_on . extend ( upg... |
def monitored ( name , group = None , salt_name = True , salt_params = True , agent_version = 1 , ** params ) :
'''Device is monitored with Server Density .
name
Device name in Server Density .
salt _ name
If ` ` True ` ` ( default ) , takes the name from the ` ` id ` ` grain . If
` ` False ` ` , the prov... | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
params_from_salt = _get_salt_params ( )
if salt_name :
name = params_from_salt . pop ( 'name' )
ret [ 'name' ] = name
else :
params_from_salt . pop ( 'name' )
if group :
params [ 'group' ] = group
if agent_version != 2 : # Anyt... |
def textx_isinstance ( obj , obj_cls ) :
"""This function determines , if a textx object is an instance of a
textx class .
Args :
obj : the object to be analyzed
obj _ cls : the class to be checked
Returns :
True if obj is an instance of obj _ cls .""" | if isinstance ( obj , obj_cls ) :
return True
if hasattr ( obj_cls , "_tx_fqn" ) and hasattr ( obj , "_tx_fqn" ) :
if obj_cls . _tx_fqn == obj . _tx_fqn :
return True
if hasattr ( obj_cls , "_tx_inh_by" ) :
for cls in obj_cls . _tx_inh_by :
if ( textx_isinstance ( obj , cls ) ) :
... |
def show ( dataset_uri , overlay_name ) :
"""Show the content of a specific overlay .""" | dataset = dtoolcore . DataSet . from_uri ( dataset_uri )
try :
overlay = dataset . get_overlay ( overlay_name )
except : # NOQA
click . secho ( "No such overlay: {}" . format ( overlay_name ) , fg = "red" , err = True )
sys . exit ( 11 )
formatted_json = json . dumps ( overlay , indent = 2 )
colorful_json =... |
def _get_bandfilenames ( self ) :
"""Get the MODIS rsr filenames""" | path = self . path
for band in MODIS_BAND_NAMES :
bnum = int ( band )
LOG . debug ( "Band = %s" , str ( band ) )
if self . platform_name == 'EOS-Terra' :
filename = os . path . join ( path , "rsr.{0:d}.inb.final" . format ( bnum ) )
else :
if bnum in [ 5 , 6 , 7 ] + range ( 20 , 37 ) :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.