signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def shortcut ( * names ) :
"""Add an shortcut ( alias ) to a decorated function , but not to class methods !
Use aliased / alias decorators for class members !
Calling the shortcut ( alias ) will call the decorated function . The shortcut name will be appended
to the module ' s _ _ all _ _ variable and the sh... | def wrap ( f ) :
globals_ = f . __globals__
for name in names :
globals_ [ name ] = f
if '__all__' in globals_ and name not in globals_ [ '__all__' ] :
globals_ [ '__all__' ] . append ( name )
return f
return wrap |
def _spherical_kmeans_single_lloyd ( X , n_clusters , sample_weight = None , max_iter = 300 , init = "k-means++" , verbose = False , x_squared_norms = None , random_state = None , tol = 1e-4 , precompute_distances = True , ) :
"""Modified from sklearn . cluster . k _ means _ . k _ means _ single _ lloyd .""" | random_state = check_random_state ( random_state )
sample_weight = _check_sample_weight ( X , sample_weight )
best_labels , best_inertia , best_centers = None , None , None
# init
centers = _init_centroids ( X , n_clusters , init , random_state = random_state , x_squared_norms = x_squared_norms )
if verbose :
print... |
def prepend ( cls , d , s , filter = Filter ( ) ) :
"""Prepend schema object ' s from B { s } ource list to
the B { d } estination list while applying the filter .
@ param d : The destination list .
@ type d : list
@ param s : The source list .
@ type s : list
@ param filter : A filter that allows items... | i = 0
for x in s :
if x in filter :
d . insert ( i , x )
i += 1 |
def hard_filter_pipeline ( job , uuid , vcf_id , config ) :
"""Runs GATK Hard Filtering on a Genomic VCF file and uploads the results .
0 : Start 0 - - > 1 - - > 3 - - > 5 - - > 6
1 : Select SNPs | |
2 : Select INDELs + - > 2 - - > 4 +
3 : Apply SNP Filter
4 : Apply INDEL Filter
5 : Merge SNP and INDEL ... | job . fileStore . logToMaster ( 'Running Hard Filter on {}' . format ( uuid ) )
# Get the total size of the genome reference
genome_ref_size = config . genome_fasta . size + config . genome_fai . size + config . genome_dict . size
# The SelectVariants disk requirement depends on the input VCF , the genome reference fil... |
def fetch_gist ( gist_id , filename = None ) :
"""Fetch a gist and return the contents as a string .""" | import requests
url = gist_url ( gist_id , filename )
response = requests . get ( url )
if response . status_code != 200 :
raise Exception ( 'Got a bad status looking up gist.' )
body = response . text
if not body :
raise Exception ( 'Unable to get the gist contents.' )
return body |
def rotate ( self , deg , ** kwargs ) :
"""Rotates the image clockwise around its center . Returns the
instance . Supports the following optional keyword arguments :
expand - Expand the output image to fit rotation""" | opts = Image . _normalize_options ( kwargs )
if deg == "auto" :
if self . _orig_format == "JPEG" :
try :
exif = self . img . _getexif ( ) or dict ( )
deg = _orientation_to_rotation . get ( exif . get ( 274 , 0 ) , 0 )
except Exception :
logger . warn ( 'unable to ... |
def parse_yaml ( self , y ) :
'''Parse a YAML speficication of a message sending object into this
object .''' | self . _targets = [ ]
if 'targets' in y :
for t in y [ 'targets' ] :
if 'waitTime' in t [ 'condition' ] :
new_target = WaitTime ( )
elif 'preceding' in t [ 'condition' ] :
new_target = Preceding ( )
else :
new_target = Condition ( )
new_target . pa... |
def _set_client_interface ( self , v , load = False ) :
"""Setter method for client _ interface , mapped from YANG variable / cluster / client / client _ interface ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ client _ interface is considered as a privat... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = client_interface . client_interface , is_container = 'container' , presence = False , yang_name = "client-interface" , rest_name = "client-interface" , parent = self , path_helper = self . _path_helper , extmethods = self . _... |
def update_user_auth_stat ( self , user , success = True ) :
"""Update authentication successful to user .
: param user :
The authenticated user model
: param success :
Default to true , if false increments fail _ login _ count on user model""" | if not user . login_count :
user . login_count = 0
if not user . fail_login_count :
user . fail_login_count = 0
if success :
user . login_count += 1
user . fail_login_count = 0
else :
user . fail_login_count += 1
user . last_login = datetime . datetime . now ( )
self . update_user ( user ) |
def load_template_source ( template_name , template_dirs = None ) :
"""Template loader that loads templates from a ZIP file .""" | template_zipfiles = getattr ( settings , "TEMPLATE_ZIP_FILES" , [ ] )
# Try each ZIP file in TEMPLATE _ ZIP _ FILES .
for fname in template_zipfiles :
try :
z = zipfile . ZipFile ( fname )
source = z . read ( template_name )
except ( IOError , KeyError ) :
continue
z . close ( )
... |
def stop_replace ( self , accountID , orderID , ** kwargs ) :
"""Shortcut to replace a pending Stop Order in an Account
Args :
accountID : The ID of the Account
orderID : The ID of the Stop Order to replace
kwargs : The arguments to create a StopOrderRequest
Returns :
v20 . response . Response containin... | return self . replace ( accountID , orderID , order = StopOrderRequest ( ** kwargs ) ) |
def get_DB_references ( self ) :
'''" The DBREF record provides cross - reference links between PDB sequences ( what appears in SEQRES record ) and
a corresponding database sequence . " - http : / / www . wwpdb . org / documentation / format33 / sect3 . html # DBREF''' | _database_names = { 'GB' : 'GenBank' , 'PDB' : 'Protein Data Bank' , 'UNP' : 'UNIPROT' , 'NORINE' : 'Norine' , 'TREMBL' : 'UNIPROT' , }
DBref = { }
for l in self . parsed_lines [ "DBREF " ] : # [ l for l in self . lines if l . startswith ( ' DBREF ' ) ]
pdb_id = l [ 7 : 11 ]
chain_id = l [ 12 ]
seqBegin = i... |
def _set_interface_dynamic_bypass_primary_path ( self , v , load = False ) :
"""Setter method for interface _ dynamic _ bypass _ primary _ path , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / mpls _ interface / interface _ dynamic _ bypass / mpls _ interface _ dynamic _ bypass _... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_dict = { 'length' : [ u'1..64' ] } ) , is_leaf = True , yang_name = "interface-dynamic-bypass-primary-path" , rest_name = "primary-path" , parent = self , path_helper = ... |
def verify_authentication_data ( self , key ) :
'''Verify the current authentication data based on the current key - id and
the given key .''' | correct_authentication_data = self . calculate_authentication_data ( key )
return self . authentication_data == correct_authentication_data |
def to_aws_format ( tags ) :
"""Convert the Ray node name tag to the AWS - specific ' Name ' tag .""" | if TAG_RAY_NODE_NAME in tags :
tags [ "Name" ] = tags [ TAG_RAY_NODE_NAME ]
del tags [ TAG_RAY_NODE_NAME ]
return tags |
def load_plugins ( self , args = None ) :
"""Load all plugins in the ' plugins ' folder .""" | for item in os . listdir ( plugins_path ) :
if ( item . startswith ( self . header ) and item . endswith ( ".py" ) and item != ( self . header + "plugin.py" ) ) : # Load the plugin
self . _load_plugin ( os . path . basename ( item ) , args = args , config = self . config )
# Log plugins list
logger . debug ... |
def response_from_prediction ( self , y_pred , single = True ) :
"""Turns a model ' s prediction in * y _ pred * into a JSON
response .""" | result = y_pred . tolist ( )
if single :
result = result [ 0 ]
response = { 'metadata' : get_metadata ( ) , 'result' : result , }
return make_ujson_response ( response , status_code = 200 ) |
def filterItems ( self , terms , caseSensitive = False ) :
"""Filters the items in this tree based on the inputed text .
: param terms | < str > | | { < str > datatype : [ < str > opt , . . ] }
caseSensitive | < bool >""" | # create a dictionary of options
if type ( terms ) != dict :
terms = { '*' : nativestring ( terms ) }
# validate the " all search "
if '*' in terms and type ( terms [ '*' ] ) != list :
sterms = nativestring ( terms [ '*' ] )
if not sterms . strip ( ) :
terms . pop ( '*' )
else :
dtype_ma... |
def exclusively ( f ) :
"""Decorate a function to make it thread - safe by serializing invocations
using a per - instance lock .""" | @ wraps ( f )
def exclusively_f ( self , * a , ** kw ) :
with self . _lock :
return f ( self , * a , ** kw )
return exclusively_f |
def from_json ( self , fname ) :
'''Read contents of a CSV containing a list of servers .''' | with open ( fname , 'rt' ) as fp :
for row in json . load ( fp ) :
nn = ServerInfo . from_dict ( row )
self [ str ( nn ) ] = nn |
def default_database ( ctx : click . Context , _param : Parameter , value : Optional [ str ] ) :
"""Try to guess a reasonable database name by looking at the repository path""" | if value :
return value
if ctx . params [ "repository" ] :
return os . path . join ( ctx . params [ "repository" ] , DB . DEFAULT_DB_FILE )
raise click . BadParameter ( "Could not guess a database location" ) |
def mkdirs ( remote_dir , use_sudo = False ) :
"""Wrapper around mkdir - pv
Returns a list of directories created""" | func = use_sudo and sudo or run
result = func ( ' ' . join ( [ 'mkdir -pv' , remote_dir ] ) ) . split ( '\n' )
# extract dir list from [ " mkdir : created directory ` example . com / some / dir ' " ]
if result [ 0 ] :
result = [ dir . split ( ' ' ) [ 3 ] [ 1 : - 1 ] for dir in result if dir ]
return result |
def auto_connect ( self , port : int or str = 5555 ) -> None :
'''Connect to a device via TCP / IP automatically .''' | host = self . get_ip_addr ( )
self . tcpip ( port )
self . connect ( host , port )
print ( 'Now you can unplug the USB cable, and control your device via WLAN.' ) |
def _read_name_text ( self , bufr , platform_id , encoding_id , strings_offset , name_str_offset , length ) :
"""Return the unicode name string at * name _ str _ offset * or | None | if
decoding its format is not supported .""" | raw_name = self . _raw_name_string ( bufr , strings_offset , name_str_offset , length )
return self . _decode_name ( raw_name , platform_id , encoding_id ) |
def get_quotation_kline ( self , symbol , period , limit = None , _async = False ) :
"""获取etf净值
: param symbol : etf名称
: param period : K线类型
: param limit : 获取数量
: param _ async :
: return :""" | params = { }
path = '/quotation/market/history/kline'
params [ 'symbol' ] = symbol
params [ 'period' ] = period
if limit :
params [ 'limit' ] = limit
return api_key_get ( params , path , _async = _async ) |
def next ( self ) :
"""( internal ) returns the next result from the iterator if the piper is
started .""" | if self . piper . imap is imap and self . piper . started is False :
raise StopIteration
else :
return self . iterator . next ( ) |
def create_search ( pretty , ** kw ) :
'''Create a saved search''' | req = search_req_from_opts ( ** kw )
cl = clientv1 ( )
echo_json_response ( call_and_wrap ( cl . create_search , req ) , pretty ) |
def _load_ipa_data ( self , ipa_data_path ) :
"""Loads and returns the { symbol : name } dictionary stored in the
data / ipa . tsv file .""" | ipa = { }
try :
with open ( ipa_data_path , newline = '' ) as f :
reader = csv . reader ( f , delimiter = '\t' )
for line in reader :
if len ( line ) != 2 :
continue
if line [ 0 ] in ipa :
raise IPADataError ( 'Bad IPA data file' )
... |
def from_timestamp ( timestamp , tz = UTC # type : Union [ int , float ] # type : Union [ str , _ Timezone ]
) : # type : ( . . . ) - > DateTime
"""Create a DateTime instance from a timestamp .""" | dt = _datetime . datetime . utcfromtimestamp ( timestamp )
dt = datetime ( dt . year , dt . month , dt . day , dt . hour , dt . minute , dt . second , dt . microsecond )
if tz is not UTC or tz != "UTC" :
dt = dt . in_timezone ( tz )
return dt |
def pbkdf2_bin ( data , salt , iterations = 1000 , keylen = 24 , hashfunc = None ) :
"""Returns a binary digest for the PBKDF2 hash algorithm of ` data `
with the given ` salt ` . It iterates ` iterations ` time and produces a
key of ` keylen ` bytes . By default SHA - 1 is used as hash function ,
a different... | hashfunc = hashfunc or hashlib . sha1
mac = hmac . new ( bytes_ ( data ) , None , hashfunc )
def _pseudorandom ( x , mac = mac ) :
h = mac . copy ( )
h . update ( bytes_ ( x ) )
if not PY2 :
return [ x for x in h . digest ( ) ]
else :
return map ( ord , h . digest ( ) )
buf = [ ]
for blo... |
def weather_history_at_id ( self , id , start = None , end = None ) :
"""Queries the OWM Weather API for weather history for the specified city ID .
A list of * Weather * objects is returned . It is possible to query for
weather history in a closed time period , whose boundaries can be passed
as optional para... | assert type ( id ) is int , "'id' must be an int"
if id < 0 :
raise ValueError ( "'id' value must be greater than 0" )
params = { 'id' : id , 'lang' : self . _language }
if start is None and end is None :
pass
elif start is not None and end is not None :
unix_start = timeformatutils . to_UNIXtime ( start )
... |
def create_user ( post_data ) :
'''Create the user .
The code used if ` False ` .
11 : standsfor invalid username .
21 : standsfor invalide E - mail .
91 : standsfor unkown reson .''' | out_dic = { 'success' : False , 'code' : '00' }
if not tools . check_username_valid ( post_data [ 'user_name' ] ) :
out_dic [ 'code' ] = '11'
return out_dic
if not tools . check_email_valid ( post_data [ 'user_email' ] ) :
out_dic [ 'code' ] = '21'
return out_dic
try :
TabMember . create ( uid = too... |
def get_thread ( self , thread_id , update_if_cached = True , raise_404 = False ) :
"""Get a thread from 4chan via 4chan API .
Args :
thread _ id ( int ) : Thread ID
update _ if _ cached ( bool ) : Whether the thread should be updated if it ' s already in our cache
raise _ 404 ( bool ) : Raise an Exception ... | # see if already cached
cached_thread = self . _thread_cache . get ( thread_id )
if cached_thread :
if update_if_cached :
cached_thread . update ( )
return cached_thread
res = self . _requests_session . get ( self . _url . thread_api_url ( thread_id = thread_id ) )
# check if thread exists
if raise_404 ... |
def write_header_to_log ( self , sysinfo ) :
"""This method writes information about benchmark and system into txt _ file .""" | runSetName = None
run_sets = [ runSet for runSet in self . benchmark . run_sets if runSet . should_be_executed ( ) ]
if len ( run_sets ) == 1 : # in case there is only a single run set to to execute , we can use its name
runSetName = run_sets [ 0 ] . name
columnWidth = 25
simpleLine = "-" * ( 60 ) + "\n\n"
def form... |
async def _thread_coro ( self , * args ) :
"""Coroutine called by MapAsync . It ' s wrapping the call of
run _ in _ executor to run the synchronous function as thread""" | return await self . _loop . run_in_executor ( self . _executor , self . _function , * args ) |
def ones ( n , d = None ) :
"""Creates a TT - vector of all ones""" | c = _vector . vector ( )
if d is None :
c . n = _np . array ( n , dtype = _np . int32 )
c . d = c . n . size
else :
c . n = _np . array ( [ n ] * d , dtype = _np . int32 )
c . d = d
c . r = _np . ones ( ( c . d + 1 , ) , dtype = _np . int32 )
c . get_ps ( )
c . core = _np . ones ( c . ps [ c . d ] - 1 )... |
def _is_exposed ( minion ) :
'''Check if the minion is exposed , based on the whitelist and blacklist''' | return salt . utils . stringutils . check_whitelist_blacklist ( minion , whitelist = __opts__ [ 'minionfs_whitelist' ] , blacklist = __opts__ [ 'minionfs_blacklist' ] ) |
def _optimize_fit ( self , obj_type = None , ** kwargs ) :
"""This function fits models using Maximum Likelihood or Penalized Maximum Likelihood""" | preopt_search = kwargs . get ( 'preopt_search' , True )
# If user supplied
if obj_type == self . neg_loglik :
method = 'MLE'
else :
method = 'PML'
# Starting values - check to see if model has preoptimize method , if not , simply use default starting values
if preopt_search is True :
try :
phi = sel... |
def _rewrite_where ( self , q ) :
"""Rewrite field names inside WHERE tree .""" | if isinstance ( q , Lookup ) :
self . _rewrite_col ( q . lhs )
if isinstance ( q , Node ) :
for child in q . children :
self . _rewrite_where ( child ) |
def read_job ( self , job_id , checkout = False ) :
"""Reads head and reads the tree into index ,
and checkout the work - tree when checkout = True .
This does not fetch the job from the actual server . It needs to be in the local git already .""" | self . job_id = job_id
commit = self . get_head_commit ( )
self . logger . debug ( 'Job ref points to ' + commit )
self . command_exec ( [ 'read-tree' , self . ref_head ] )
if checkout :
self . logger . debug ( 'Working directory in ' + self . work_tree )
# make sure we have checked out all files we have added ... |
def visit_sequence ( self , node , sequence ) :
"""A parsed Sequence looks like [ term node , OneOrMore node of
` ` another _ term ` ` s ] . Flatten it out .""" | term , other_terms = sequence
return Sequence ( term , * other_terms ) |
def index_map ( data ) :
"""Index demo map function .""" | ( entry , text_fn ) = data
text = text_fn ( )
logging . debug ( "Got %s" , entry . filename )
for s in split_into_sentences ( text ) :
for w in split_into_words ( s . lower ( ) ) :
yield ( w , entry . filename ) |
def centroid_sources ( data , xpos , ypos , box_size = 11 , footprint = None , error = None , mask = None , centroid_func = centroid_com ) :
"""Calculate the centroid of sources at the defined positions .
A cutout image centered on each input position will be used to
calculate the centroid position . The cutout... | xpos = np . atleast_1d ( xpos )
ypos = np . atleast_1d ( ypos )
if xpos . ndim != 1 :
raise ValueError ( 'xpos must be a 1D array.' )
if ypos . ndim != 1 :
raise ValueError ( 'ypos must be a 1D array.' )
if footprint is None :
if box_size is None :
raise ValueError ( 'box_size or footprint must be d... |
def should_retry_on_error ( self , error ) :
"""rules for retry
: param error :
ProtocolException that returns from Server""" | if self . is_streaming_request : # not retry for streaming request
return False
retry_flag = self . headers . get ( 're' , retry . DEFAULT )
if retry_flag == retry . NEVER :
return False
if isinstance ( error , StreamClosedError ) :
return True
if error . code in [ ErrorCode . bad_request , ErrorCode . canc... |
def shutdown_rd ( self ) :
"""Send a shutdown signal for reading - you may no longer read from this
socket .""" | if self . _sock_send is not None :
self . sock . close ( )
else :
return self . shutdown ( socket . SHUT_RD ) |
def import_from_json ( filename_or_fobj , encoding = "utf-8" , * args , ** kwargs ) :
"""Import a JSON file or file - like object into a ` rows . Table ` .
If a file - like object is provided it MUST be open in text ( non - binary ) mode
on Python 3 and could be open in both binary or text mode on Python 2.""" | source = Source . from_file ( filename_or_fobj , mode = "rb" , plugin_name = "json" , encoding = encoding )
json_obj = json . load ( source . fobj , encoding = source . encoding )
field_names = list ( json_obj [ 0 ] . keys ( ) )
table_rows = [ [ item [ key ] for key in field_names ] for item in json_obj ]
meta = { "imp... |
def delete_device_enrollment ( self , id , ** kwargs ) : # noqa : E501
"""Delete an enrollment by ID . # noqa : E501
To free a device from your account you can delete the enrollment claim . To bypass the device ownership , you need to delete the enrollment and do a factory reset for the device . For more informat... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . delete_device_enrollment_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . delete_device_enrollment_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def run ( self , timeout = None , ** kwargs ) :
"""Run a command in a separated thread and wait timeout seconds .
kwargs are keyword arguments passed to Popen .
Return : self""" | from subprocess import Popen , PIPE
def target ( ** kw ) :
try : # print ( ' Thread started ' )
self . process = Popen ( self . command , ** kw )
self . output , self . error = self . process . communicate ( )
self . retcode = self . process . returncode
# print ( ' Thread stopped ' ... |
def date_time_this_month ( self , before_now = True , after_now = False , tzinfo = None ) :
"""Gets a DateTime object for the current month .
: param before _ now : include days in current month before today
: param after _ now : include days in current month after today
: param tzinfo : timezone , instance o... | now = datetime . now ( tzinfo )
this_month_start = now . replace ( day = 1 , hour = 0 , minute = 0 , second = 0 , microsecond = 0 )
next_month_start = this_month_start + relativedelta . relativedelta ( months = 1 )
if before_now and after_now :
return self . date_time_between_dates ( this_month_start , next_month_s... |
def stage_http_response2 ( self , payload ) :
"""Log complete http response , including response1 and payload""" | # required because http code uses sending all None to reset
# parameters . We ignore that
if not self . _http_response_version and not payload :
return
if self . enabled and self . http_detail_level is not None and self . httplogger . isEnabledFor ( logging . DEBUG ) :
if self . _http_response_headers :
... |
def p_declassign_element ( self , p ) :
'declassign _ element : ID EQUALS rvalue' | assign = Assign ( Lvalue ( Identifier ( p [ 1 ] , lineno = p . lineno ( 1 ) ) , lineno = p . lineno ( 1 ) ) , p [ 3 ] , lineno = p . lineno ( 1 ) )
p [ 0 ] = ( p [ 1 ] , assign )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def weibull ( target , seeds , shape , scale , loc ) :
r"""Produces values from a Weibull distribution given a set of random numbers .
Parameters
target : OpenPNM Object
The object which this model is associated with . This controls the
length of the calculated array , and also provides access to other
ne... | seeds = target [ seeds ]
value = spts . weibull_min . ppf ( q = seeds , c = shape , scale = scale , loc = loc )
return value |
def set_start ( self , time , pass_to_command_line = True ) :
"""Set the GPS start time of the analysis node by setting a - - gps - start - time
option to the node when it is executed .
@ param time : GPS start time of job .
@ bool pass _ to _ command _ line : add gps - start - time as variable option .""" | if pass_to_command_line :
self . add_var_opt ( 'gps-start-time' , time )
self . __start = time
self . __data_start = time |
def heatmapf ( func , scale = 10 , boundary = True , cmap = None , ax = None , scientific = False , style = 'triangular' , colorbar = True , permutation = None , vmin = None , vmax = None , cbarlabel = None , cb_kwargs = None ) :
"""Computes func on heatmap partition coordinates and plots heatmap . In other
words... | # Apply the function to a simplex partition
data = dict ( )
for i , j , k in simplex_iterator ( scale = scale , boundary = boundary ) :
data [ ( i , j ) ] = func ( normalize ( [ i , j , k ] ) )
# Pass everything to the heatmapper
ax = heatmap ( data , scale , cmap = cmap , ax = ax , style = style , scientific = sci... |
def write ( self , value ) : # type : ( int ) - > None
"""Write a raw byte to the LCD .""" | # Get current position
row , col = self . _cursor_pos
# Write byte if changed
try :
if self . _content [ row ] [ col ] != value :
self . _send_data ( value )
self . _content [ row ] [ col ] = value
# Update content cache
unchanged = False
else :
unchanged = True
except In... |
def serve ( config ) :
"""Serves ( runs ) the vodka application""" | cfg = vodka . config . Config ( read = config )
vodka . run ( cfg , cfg ) |
def _send_string_clipboard ( self , string : str , paste_command : model . SendMode ) :
"""Use the clipboard to send a string .""" | backup = self . clipboard . text
# Keep a backup of current content , to restore the original afterwards .
if backup is None :
logger . warning ( "Tried to backup the X clipboard content, but got None instead of a string." )
self . clipboard . text = string
try :
self . mediator . send_string ( paste_command . ... |
def add ( self , p_src ) :
"""Given a todo string , parse it and put it to the end of the list .""" | todos = self . add_list ( [ p_src ] )
return todos [ 0 ] if len ( todos ) else None |
def webserver_list ( ) :
"""list of webserver packages""" | p = set ( get_packages ( ) )
w = set ( [ 'apache2' , 'gunicorn' , 'uwsgi' , 'nginx' ] )
installed = p & w
return list ( installed ) |
def _inv_key ( list_keys , valid_keys ) :
"""Brief
A sub - function of _ filter _ keywords function .
Description
Function used for identification when a list of keywords contains invalid keywords not present
in the valid list .
Parameters
list _ keys : list
List of keywords that must be verified , i ... | inv_keys = [ ]
bool_out = True
for i in list_keys :
if i not in valid_keys :
bool_out = False
inv_keys . append ( i )
return bool_out , inv_keys |
def fingerprint ( dirnames , prefix = None , previous = [ ] ) : # pylint : disable = dangerous - default - value
"""Returns a list of paths available from * dirname * . When previous
is specified , returns a list of additional files only .
Example :
[ { " Key " : " abc . txt " ,
" LastModified " : " Mon , 0... | results = [ ]
for dirname in dirnames :
for filename in os . listdir ( dirname ) :
fullpath = os . path . join ( dirname , filename )
if os . path . isdir ( fullpath ) :
results += fingerprint ( [ fullpath ] , prefix = filename , previous = previous )
else :
fullname ... |
def sighash_single ( self , index , script = None , prevout_value = None , anyone_can_pay = False ) :
'''Tx , int , byte - like , byte - like , bool - > bytearray
Sighashes suck
Generates the hash to be signed with SIGHASH _ SINGLE
https : / / en . bitcoin . it / wiki / OP _ CHECKSIG # Procedure _ for _ Hasht... | if index >= len ( self . tx_outs ) :
raise NotImplementedError ( 'I refuse to implement the SIGHASH_SINGLE bug.' )
if riemann . network . FORKID is not None :
return self . _sighash_forkid ( index = index , script = script , prevout_value = prevout_value , sighash_type = shared . SIGHASH_SINGLE , anyone_can_pay... |
def receiveVolumeInfo ( self , paths ) :
"""Return Context Manager for a file - like ( stream ) object to store volume info .""" | path = self . selectReceivePath ( paths )
path = path + Store . theInfoExtension
if Store . skipDryRun ( logger , self . dryrun ) ( "receive info to %s" , path ) :
return None
return open ( path , "w" ) |
def keys ( self ) :
"""Returns a : class : ` GramGenerator ` that produces only keys .""" | return GramGenerator ( self . path , self . elem , keys = True , ignore_hash = self . ignore_hash ) |
def handshake_headers ( self ) :
"""List of headers appropriate for the upgrade
handshake .""" | headers = [ ( 'Host' , self . host ) , ( 'Connection' , 'Upgrade' ) , ( 'Upgrade' , 'WebSocket' ) , ( 'Sec-WebSocket-Key' , self . key . decode ( 'utf-8' ) ) , # Origin is proxyed from the downstream server , don ' t set it twice
# ( ' Origin ' , self . url ) ,
( 'Sec-WebSocket-Version' , str ( max ( WS_VERSION ) ) ) ]... |
def load_buffer_one_to_five ( self , out_buffer ) :
"""Loads first program buffer ( 0x93 ) with everything but
first three bytes and checksum""" | struct . pack_into ( b"< 2B" , out_buffer , 3 , self . _program_type , len ( self . _prog_steps ) )
offset = 5
for ind , step in enumerate ( self . partial_steps_data ( 0 ) ) :
struct . pack_into ( b"< 2H" , out_buffer , offset + ind * 4 , step [ 0 ] , step [ 1 ] ) |
def is_working_day ( self , day , extra_working_days = None , extra_holidays = None ) :
"""Return True if it ' s a working day .
In addition to the regular holidays , you can add exceptions .
By providing ` ` extra _ working _ days ` ` , you ' ll state that these dates
* * are * * working days .
By providin... | day = cleaned_date ( day )
if extra_working_days :
extra_working_days = tuple ( map ( cleaned_date , extra_working_days ) )
if extra_holidays :
extra_holidays = tuple ( map ( cleaned_date , extra_holidays ) )
# Extra lists exceptions
if extra_working_days and day in extra_working_days :
return True
# Regula... |
def set_rule_name ( self , rule_name ) :
"""Add the matched centralized sampling rule name
if a segment is sampled because of that rule .
This method should be only used by the recorder .""" | if not self . aws . get ( 'xray' , None ) :
self . aws [ 'xray' ] = { }
self . aws [ 'xray' ] [ 'sampling_rule_name' ] = rule_name |
def convert ( model , feature_names , target ) :
"""Convert a Nu - Support Vector Classification ( NuSVC ) model to the protobuf spec .
Parameters
model : NuSVC
A trained NuSVC encoder model .
feature _ names : [ str ] , optional ( default = None )
Name of the input columns .
target : str , optional ( d... | if not ( _HAS_SKLEARN ) :
raise RuntimeError ( 'scikit-learn not found. scikit-learn conversion API is disabled.' )
_sklearn_util . check_expected_type ( model , _NuSVC )
return _SVC . convert ( model , feature_names , target ) |
def _ensure_folder_path ( self , filebase_path ) :
"""Creates the directory for the path given , recursively creating
parent directories when needed""" | folders = filebase_path . split ( '/' )
parent = { "id" : "root" }
for folder in folders :
file_list = self . drive . ListFile ( { 'q' : "'{}' in parents and trashed=false and title = '{}'" . format ( parent [ 'id' ] , folder ) } ) . GetList ( )
if not len ( file_list ) :
f = self . drive . CreateFile (... |
def lock ( self , name , ttl = None , lock_id = None ) :
"""Create a named : py : class : ` Lock ` instance . The lock implements
an API similar to the standard library ' s ` ` threading . Lock ` ` ,
and can also be used as a context manager or decorator .
: param str name : The name of the lock .
: param i... | return Lock ( self , name , ttl , lock_id ) |
def set ( self , key , value ) :
"""Add an item to the cache
Args :
key : item key
value : the value associated with this key""" | self . _check_limit ( )
_expire = time . time ( ) + self . _timeout if self . _timeout else None
self . _store [ key ] = ( value , _expire ) |
def post_deploy_assume_role ( assume_role_config , context ) :
"""Revert to previous credentials , if necessary .""" | if isinstance ( assume_role_config , dict ) :
if assume_role_config . get ( 'post_deploy_env_revert' ) :
context . restore_existing_iam_env_vars ( ) |
def tie_prop_to_class ( prop , cls_name ) :
"""reads through the prop attributes and filters them for the associated
class and returns a dictionary for meta _ class _ _ prepare _ _
args :
prop : class object to read
cls _ name : the name of the class to tie the porperty to""" | attr_list = [ attr for attr in dir ( prop ) if type ( attr , Uri ) ]
prop_defs = kwargs . pop ( 'prop_defs' )
prop_name = kwargs . pop ( 'prop_name' )
cls_name = kwargs . pop ( 'cls_name' )
if cls_name == 'RdfClassBase' :
return { }
doc_string = make_doc_string ( name , prop_defs , bases , None )
new_def = prepare_... |
def append_transformation ( self , transformation , extend_collection = False , clear_redo = True ) :
"""Appends a transformation to all TransformedStructures .
Args :
transformation : Transformation to append
extend _ collection : Whether to use more than one output structure
from one - to - many transform... | if self . ncores and transformation . use_multiprocessing :
p = Pool ( self . ncores )
# need to condense arguments into single tuple to use map
z = map ( lambda x : ( x , transformation , extend_collection , clear_redo ) , self . transformed_structures )
new_tstructs = p . map ( _apply_transformation ,... |
def percentage ( value : str ) -> float :
"""` ` argparse ` ` argument type that checks that its value is a percentage ( in
the sense of a float in the range [ 0 , 100 ] ) .""" | try :
fvalue = float ( value )
assert 0 <= fvalue <= 100
except ( AssertionError , TypeError , ValueError ) :
raise ArgumentTypeError ( "{!r} is an invalid percentage value" . format ( value ) )
return fvalue |
def _create_filter ( self , server_id , source_namespace , query , query_language , owned , filter_id , name ) :
"""Create a : term : ` dynamic indication filter ` instance in the Interop
namespace of a WBEM server and return that instance .
In order to catch any changes the server applies , the instance is
r... | # Validate server _ id
server = self . _get_server ( server_id )
this_host = getfqdn ( )
ownership = "owned" if owned else "permanent"
filter_path = CIMInstanceName ( FILTER_CLASSNAME , namespace = server . interop_ns )
filter_inst = CIMInstance ( FILTER_CLASSNAME )
filter_inst . path = filter_path
filter_inst [ 'Creat... |
def replace_find_selection ( self , focus_replace_text = False ) :
"""Replace and find in the current selection""" | if self . editor is not None :
replace_text = to_text_string ( self . replace_text . currentText ( ) )
search_text = to_text_string ( self . search_text . currentText ( ) )
case = self . case_button . isChecked ( )
words = self . words_button . isChecked ( )
re_flags = re . MULTILINE if case else re... |
def error ( message , code = 'ERROR' ) :
"""Display Error .
Method prints the error message , message being given
as an input .
Arguments :
message { string } - - The message to be displayed .""" | now = datetime . now ( ) . strftime ( '%Y-%m-%d %H:%M:%S' )
output = now + ' [' + torn . plugins . colors . FAIL + code + torn . plugins . colors . ENDC + '] \t' + message
print ( output ) |
def participation_coef_sign ( W , ci ) :
'''Participation coefficient is a measure of diversity of intermodular
connections of individual nodes .
Parameters
W : NxN np . ndarray
undirected connection matrix with positive and negative weights
ci : Nx1 np . ndarray
community affiliation vector
Returns
... | _ , ci = np . unique ( ci , return_inverse = True )
ci += 1
n = len ( W )
# number of vertices
def pcoef ( W_ ) :
S = np . sum ( W_ , axis = 1 )
# strength
# neighbor community affil .
Gc = np . dot ( np . logical_not ( W_ == 0 ) , np . diag ( ci ) )
Sc2 = np . zeros ( ( n , ) )
for i in range (... |
def getClass ( self , id = None , uri = None , match = None ) :
"""get the saved - class with given ID or via other methods . . .
Note : it tries to guess what is being passed . .
In [ 1 ] : g . getClass ( uri = ' http : / / www . w3 . org / 2000/01 / rdf - schema # Resource ' )
Out [ 1 ] : < Class * http : /... | if not id and not uri and not match :
return None
if type ( id ) == type ( "string" ) :
uri = id
id = None
if not uri . startswith ( "http://" ) :
match = uri
uri = None
if match :
if type ( match ) != type ( "string" ) :
return [ ]
res = [ ]
if ":" in match : # qname... |
def createGenderPlot ( bfile , intensities , problematic_samples , format , out_prefix ) :
"""Creates the gender plot .
: param bfile : the prefix of the input binary file .
: param intensities : the file containing the intensities .
: param problematic _ samples : the file containing the problematic samples ... | gender_plot_options = [ "--bfile" , bfile , "--intensities" , intensities , "--sex-problems" , problematic_samples , "--format" , format , "--out" , out_prefix ]
try :
gender_plot . main ( gender_plot_options )
except gender_plot . ProgramError as e :
msg = "gender plot: {}" . format ( e )
raise ProgramErro... |
def size_r_img_inches ( width , height ) :
"""Compute the width and height for an R image for display in IPython
Neight width nor height can be null but should be integer pixel values > 0.
Returns a tuple of ( width , height ) that should be used by ggsave in R to
produce an appropriately sized jpeg / png / p... | # both width and height are given
aspect_ratio = height / ( 1.0 * width )
return R_IMAGE_SIZE , round ( aspect_ratio * R_IMAGE_SIZE , 2 ) |
def _node_to_model ( tree_or_item , package , parent = None , lucent_id = TRANSLUCENT_BINDER_ID ) :
"""Given a tree , parse to a set of models""" | if 'contents' in tree_or_item : # It is a binder .
tree = tree_or_item
# Grab the package metadata , so we have required license info
metadata = package . metadata . copy ( )
if tree [ 'id' ] == lucent_id :
metadata [ 'title' ] = tree [ 'title' ]
binder = TranslucentBinder ( metadata = m... |
def subspace_index ( self , little_endian_bits_int : int ) -> Tuple [ Union [ slice , int , 'ellipsis' ] , ... ] :
"""An index for the subspace where the target axes equal a value .
Args :
little _ endian _ bits _ int : The desired value of the qubits at the
targeted ` axes ` , packed into an integer . The le... | return linalg . slice_for_qubits_equal_to ( self . axes , little_endian_bits_int ) |
def _set_af_vpnv4_neighbor ( self , v , load = False ) :
"""Setter method for af _ vpnv4 _ neighbor , mapped from YANG variable / routing _ system / router / router _ bgp / address _ family / vpnv4 / vpnv4 _ unicast / af _ vpnv4 _ neighbor _ address _ holder / af _ vpnv4 _ neighbor ( list )
If this variable is re... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "af_vpnv4_neighbor_address" , af_vpnv4_neighbor . af_vpnv4_neighbor , yang_name = "af-vpnv4-neighbor" , rest_name = "neighbor" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self... |
def normalize ( value , unit ) :
"""Converts the value so that it belongs to some expected range .
Returns the new value and new unit .
E . g :
> > > normalize ( 1024 , ' KB ' )
(1 , ' MB ' )
> > > normalize ( 90 , ' min ' )
(1.5 , ' hr ' )
> > > normalize ( 1.0 , ' object ' )
(1 , ' object ' )""" | if value < 0 :
raise ValueError ( 'Negative value: %s %s.' % ( value , unit ) )
if unit in functions . get_keys ( INFORMATION_UNITS ) :
return _normalize_information ( value , unit )
elif unit in TIME_UNITS :
return _normalize_time ( value , unit )
else : # Unknown unit , just return it
return functions... |
def md5_digest ( instr ) :
'''Generate an md5 hash of a given string .''' | return salt . utils . stringutils . to_unicode ( hashlib . md5 ( salt . utils . stringutils . to_bytes ( instr ) ) . hexdigest ( ) ) |
def decode_coords ( ds , gridfile = None ) :
"""Sets the coordinates and bounds in a dataset
This static method sets those coordinates and bounds that are marked
marked in the netCDF attributes as coordinates in : attr : ` ds ` ( without
deleting them from the variable attributes because this information is
... | def add_attrs ( obj ) :
if 'coordinates' in obj . attrs :
extra_coords . update ( obj . attrs [ 'coordinates' ] . split ( ) )
obj . encoding [ 'coordinates' ] = obj . attrs . pop ( 'coordinates' )
if 'bounds' in obj . attrs :
extra_coords . add ( obj . attrs [ 'bounds' ] )
if gridfile is... |
def _log_likelihood_per_sample ( X , means , covars ) :
"""Theta = ( theta _ 1 , theta _ 2 , . . . theta _ M )
Likelihood of mixture parameters given data : L ( Theta | X ) = product _ i P ( x _ i | Theta )
log likelihood : log L ( Theta | X ) = sum _ i log ( P ( x _ i | Theta ) )
and note that p ( x _ i | Th... | logden = _log_multivariate_density ( X , means , covars )
logden_max = logden . max ( axis = 1 )
log_likelihood = np . log ( np . sum ( np . exp ( logden . T - logden_max ) + Epsilon , axis = 0 ) )
log_likelihood += logden_max
post_proba = np . exp ( logden - log_likelihood [ : , np . newaxis ] )
return ( log_likelihoo... |
def deployment_cancel ( name , resource_group , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Cancel a deployment if in ' Accepted ' or ' Running ' state .
: param name : The name of the deployment to cancel .
: param resource _ group : The resource group name assigned to the
deployment .
CLI Example :
... | resconn = __utils__ [ 'azurearm.get_client' ] ( 'resource' , ** kwargs )
try :
resconn . deployments . cancel ( deployment_name = name , resource_group_name = resource_group )
result = { 'result' : True }
except CloudError as exc :
__utils__ [ 'azurearm.log_cloud_error' ] ( 'resource' , str ( exc ) , ** kwa... |
def get ( ) :
"""Return the list of Processing Blocks known to SDP .""" | LOG . debug ( 'GET Processing Block list' )
_url = get_root_url ( )
# Get list of Processing block Ids
block_ids = sorted ( DB . get_processing_block_ids ( ) )
LOG . debug ( 'Processing Block IDs: %s' , block_ids )
# Construct response object
response = dict ( num_processing_blocks = len ( block_ids ) , processing_bloc... |
def generate_report ( out_dir , latex_summaries , nb_markers , nb_samples , options ) :
"""Generates the report .
: param out _ dir : the output directory .
: param latex _ summaries : the list of LaTeX summaries .
: param nb _ markers : the final number of markers .
: param nb _ samples : the final number ... | # Getting the graphic paths file
graphic_paths_fn = None
if os . path . isfile ( os . path . join ( out_dir , "graphic_paths.txt" ) ) :
graphic_paths_fn = os . path . join ( out_dir , "graphic_paths.txt" )
# We create the automatic report
report_name = os . path . join ( out_dir , "merged_report.tex" )
auto_report ... |
def _generate_subscribe_headers ( self ) :
"""generate the subscribe stub headers based on the supplied config
: return : i""" | headers = [ ]
headers . append ( ( 'predix-zone-id' , self . eventhub_client . zone_id ) )
token = self . eventhub_client . service . _get_bearer_token ( )
headers . append ( ( 'subscribername' , self . _config . subscriber_name ) )
headers . append ( ( 'authorization' , token [ ( token . index ( ' ' ) + 1 ) : ] ) )
if... |
def format_active_subjects ( request ) :
"""Create a string listing active subjects for this connection , suitable for
appending to authentication error messages .""" | decorated_subject_list = [ request . primary_subject_str + ' (primary)' ]
for subject in request . all_subjects_set :
if subject != request . primary_subject_str :
decorated_subject_list . append ( subject )
return ', ' . join ( decorated_subject_list ) |
def _setting ( self , key , default ) :
"""Return the setting , checking config , then the appropriate
environment variable , falling back to the default , caching the
results .
: param str key : The key to get
: param any default : The default value if not set
: return : str""" | if key not in self . _settings :
value = self . _settings_in . get ( key , os . environ . get ( 'STATSD_{}' . format ( key ) . upper ( ) , default ) )
self . _settings [ key ] = value
return self . _settings [ key ] |
def check_platforms ( platforms ) :
"""Checks if the platforms have a valid platform code""" | if len ( platforms ) > 0 :
return all ( platform in PLATFORM_IDS for platform in platforms )
return True |
def report_html ( ) :
"""cr - html
Usage : cr - html < session - file >
Print an HTML formatted report of test results .""" | arguments = docopt . docopt ( report_html . __doc__ , version = 'cr-rate 1.0' )
with use_db ( arguments [ '<session-file>' ] , WorkDB . Mode . open ) as db :
doc = _generate_html_report ( db )
print ( doc . getvalue ( ) ) |
def xgroup_delconsumer ( self , stream , group_name , consumer_name ) :
"""Delete a specific consumer from a group""" | fut = self . execute ( b'XGROUP' , b'DELCONSUMER' , stream , group_name , consumer_name )
return wait_convert ( fut , int ) |
def get_form ( self , step = None , data = None , files = None ) :
"""Instanciate the form for the current step
FormAdminView from xadmin expects form to be at self . form _ obj""" | self . form_obj = super ( FormWizardAdminView , self ) . get_form ( step = step , data = data , files = files )
return self . form_obj |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.