signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def doestr2tabstr ( astr , kword ) :
"""doestr2tabstr""" | alist = astr . split ( '..' )
del astr
# strip junk put . . back
for num in range ( 0 , len ( alist ) ) :
alist [ num ] = alist [ num ] . strip ( )
alist [ num ] = alist [ num ] + os . linesep + '..' + os . linesep
alist . pop ( )
lblock = [ ]
for num in range ( 0 , len ( alist ) ) :
linels = alist [ num ] ... |
def makeHttpRequest ( method , url , payload , headers , retries = MAX_RETRIES , session = None ) :
"""Make an HTTP request and retry it until success , return request""" | retry = - 1
response = None
while retry < retries :
retry += 1
# if this isn ' t the first retry then we sleep
if retry > 0 :
snooze = float ( retry * retry ) / 10.0
log . info ( 'Sleeping %0.2f seconds for exponential backoff' , snooze )
time . sleep ( snooze )
# Seek payload to... |
def _get_tr ( cls , df ) :
"""True Range of the trading
tr = max [ ( high - low ) , abs ( high - close _ prev ) , abs ( low - close _ prev ) ]
: param df : data
: return : None""" | prev_close = df [ 'close_-1_s' ]
high = df [ 'high' ]
low = df [ 'low' ]
c1 = high - low
c2 = np . abs ( high - prev_close )
c3 = np . abs ( low - prev_close )
df [ 'tr' ] = np . max ( ( c1 , c2 , c3 ) , axis = 0 ) |
def send ( self , to , language = None , ** data ) :
"""This is the method to be called""" | self . data = data
self . get_context_data ( )
if app_settings [ 'SEND_EMAILS' ] :
try :
if language :
mail . send ( to , template = self . template , context = self . context_data , language = language )
else :
mail . send ( to , template = self . template , context = self .... |
def set ( self , key , func , * args , ** kwargs ) :
"""Return key ' s value if it exists , otherwise call given function .
: param key : The key to lookup / set .
: param func : A function to use if the key doesn ' t exist .
All other arguments and keyword arguments are passed to * func * .""" | if key in self :
return self [ key ]
self [ key ] = value = func ( * args , ** kwargs )
return value |
def byte_to_bitstring ( byte ) :
"""Convert one byte to a list of bits""" | assert 0 <= byte <= 0xff
bits = [ int ( x ) for x in list ( bin ( byte + 0x100 ) [ 3 : ] ) ]
return bits |
def install_string ( self ) :
"""Add every missing file to the install string shown to the user
in an error message .""" | args = [ "--reference-name" , self . reference_name , "--annotation-name" , self . annotation_name ]
if self . annotation_version :
args . extend ( [ "--annotation-version" , str ( self . annotation_version ) ] )
if self . requires_gtf :
args . append ( "--gtf" )
args . append ( "\"%s\"" % self . _gtf_path_... |
def set_bind ( self ) :
"""Sets key bindings - - we need this more than once""" | RangedInt . set_bind ( self )
self . unbind ( '<Next>' )
self . unbind ( '<Prior>' )
self . bind ( '<Next>' , lambda e : self . set ( self . _min ( ) ) )
self . bind ( '<Prior>' , lambda e : self . set ( self . _max ( ) ) ) |
def unlock_kinetis_read_until_ack ( jlink , address ) :
"""Polls the device until the request is acknowledged .
Sends a read request to the connected device to read the register at the
given ' address ' . Polls indefinitely until either the request is ACK ' d or
the request ends in a fault .
Args :
jlink ... | request = swd . ReadRequest ( address , ap = True )
response = None
while True :
response = request . send ( jlink )
if response . ack ( ) :
break
elif response . wait ( ) :
continue
raise KinetisException ( 'Read exited with status: %s' , response . status )
return response |
def verify_x509_cert_chain ( cert_chain , ca_pem_file = None , ca_path = None ) :
"""Look at certs in the cert chain and add them to the store one by one .
Return the cert at the end of the chain . That is the cert to be used by the caller for verifying .
From https : / / www . w3 . org / TR / xmldsig - core2 /... | from OpenSSL import SSL
context = SSL . Context ( SSL . TLSv1_METHOD )
if ca_pem_file is None and ca_path is None :
import certifi
ca_pem_file = certifi . where ( )
context . load_verify_locations ( ensure_bytes ( ca_pem_file , none_ok = True ) , capath = ca_path )
store = context . get_cert_store ( )
certs = l... |
def update_with ( self , ** query ) :
"""secure update , mass assignment protected""" | for k , v in self . _filter_attrs ( query ) . items ( ) :
setattr ( self , k , v )
return self . save ( ) |
def from_json ( cls , data ) :
"""Create a Wind Condition from a dictionary .
Args :
data = {
" wind _ speed " : float ,
" wind _ direction " : float ,
" rain " : bool ,
" snow _ on _ ground " : bool }""" | # Check required and optional keys
optional_keys = { 'wind_direction' : 0 , 'rain' : False , 'snow_on_ground' : False }
assert 'wind_speed' in data , 'Required key "wind_speed" is missing!'
for key , val in optional_keys . items ( ) :
if key not in data :
data [ key ] = val
return cls ( data [ 'wind_speed' ... |
def _get_server ( self ) :
"""Get server to use for request .
Also process inactive server list , re - add them after given interval .""" | with self . _lock :
inactive_server_count = len ( self . _inactive_servers )
for i in range ( inactive_server_count ) :
try :
ts , server , message = heapq . heappop ( self . _inactive_servers )
except IndexError :
pass
else :
if ( ts + self . retry_in... |
def othertype ( self , othertype ) :
"""Set the ` ` OTHERTYPE ` ` attribute value .""" | if othertype is not None :
self . _el . set ( 'TYPE' , 'OTHER' )
self . _el . set ( 'OTHERTYPE' , othertype ) |
def _pdf ( self , phi ) :
"""Evaluate the _ unnormalized _ flow PDF .""" | pdf = np . inner ( self . _vn , np . cos ( np . outer ( phi , self . _n ) ) )
pdf *= 2.
pdf += 1.
return pdf |
def get_method_sig ( method ) :
"""Given a function , it returns a string that pretty much looks how the
function signature would be written in python .
: param method : a python method
: return : A string similar describing the pythong method signature .
eg : " my _ method ( first _ argArg , second _ arg =... | # The return value of ArgSpec is a bit weird , as the list of arguments and
# list of defaults are returned in separate array .
# eg : ArgSpec ( args = [ ' first _ arg ' , ' second _ arg ' , ' third _ arg ' ] ,
# varargs = None , keywords = None , defaults = ( 42 , ' something ' ) )
argspec = inspect . getargspec ( met... |
def save_data ( self , trigger_id , ** data ) :
"""let ' s save the data
: param trigger _ id : trigger ID from which to save data
: param data : the data to check to be used and save
: type trigger _ id : int
: type data : dict
: return : the status of the save statement
: rtype : boolean""" | if self . token :
title = self . set_title ( data )
body = self . set_content ( data )
# get the details of this trigger
trigger = Github . objects . get ( trigger_id = trigger_id )
# check if it remains more than 1 access
# then we can create an issue
limit = self . gh . ratelimit_remaining... |
def get_environ ( self ) :
"""Return a new environ dict targeting the given wsgi . version .""" | req = self . req
env_10 = super ( Gateway_u0 , self ) . get_environ ( )
env = dict ( map ( self . _decode_key , env_10 . items ( ) ) )
# Request - URI
enc = env . setdefault ( six . u ( 'wsgi.url_encoding' ) , six . u ( 'utf-8' ) )
try :
env [ 'PATH_INFO' ] = req . path . decode ( enc )
env [ 'QUERY_STRING' ] =... |
def reset ( self ) :
"""Sets initial conditions for the experiment .""" | self . stepid = 0
for task , agent in zip ( self . tasks , self . agents ) :
task . reset ( )
agent . module . reset ( )
agent . history . reset ( ) |
def inverted_level_order ( self ) -> Iterator [ "BSP" ] :
"""Iterate over this BSP ' s hierarchy in inverse level order .
. . versionadded : : 8.3""" | levels = [ ]
# type : List [ List [ ' BSP ' ] ]
next = [ self ]
# type : List [ ' BSP ' ]
while next :
levels . append ( next )
level = next
# type : List [ ' BSP ' ]
next = [ ]
for node in level :
next . extend ( node . children )
while levels :
yield from levels . pop ( ) |
def hover_pixmap ( self , value ) :
"""Setter for * * self . _ _ hover _ pixmap * * attribute .
: param value : Attribute value .
: type value : QPixmap""" | if value is not None :
assert type ( value ) is QPixmap , "'{0}' attribute: '{1}' type is not 'QPixmap'!" . format ( "hover_pixmap" , value )
self . __hover_pixmap = value |
def disable ( name , runas = None ) :
'''Disable a launchd service . Raises an error if the service fails to be
disabled
: param str name : Service label , file name , or full path
: param str runas : User to run launchctl commands
: return : ` ` True ` ` if successful or if the service is already disabled ... | # Get the service target . enable requires a full < service - target >
service_target = _get_domain_target ( name , service_target = True ) [ 0 ]
# disable the service : will raise an error if it fails
return launchctl ( 'disable' , service_target , runas = runas ) |
def filter_by_gene_expression ( self , gene_expression_dict , min_expression_value = 0.0 ) :
"""Filters effects to those which have an associated gene whose
expression value in the gene _ expression _ dict argument is greater
than min _ expression _ value .
Parameters
gene _ expression _ dict : dict
Dicti... | return self . filter_above_threshold ( key_fn = lambda effect : effect . gene_id , value_dict = gene_expression_dict , threshold = min_expression_value ) |
def readObject ( self ) :
"""Reads an object from the stream .""" | ref = self . readInteger ( False )
if ref & REFERENCE_BIT == 0 :
obj = self . context . getObject ( ref >> 1 )
if obj is None :
raise pyamf . ReferenceError ( 'Unknown reference %d' % ( ref >> 1 , ) )
if self . use_proxies is True :
obj = self . readProxy ( obj )
return obj
ref >>= 1
cla... |
def show ( self ) :
"""Show the hidden spinner .""" | thr_is_alive = self . _spin_thread and self . _spin_thread . is_alive ( )
if thr_is_alive and self . _hide_spin . is_set ( ) : # clear the hidden spinner flag
self . _hide_spin . clear ( )
# clear the current line so the spinner is not appended to it
sys . stdout . write ( "\r" )
self . _clear_line ( ) |
def optimize ( self , timeSeries , forecastingMethods = None , startingPercentage = 0.0 , endPercentage = 100.0 ) :
"""Runs the optimization of the given TimeSeries .
: param TimeSeries timeSeries : TimeSeries instance that requires an optimized forecast .
: param list forecastingMethods : List of forecastingMe... | if forecastingMethods is None or len ( forecastingMethods ) == 0 :
raise ValueError ( "forecastingMethods cannot be empty." )
self . _startingPercentage = startingPercentage
self . _endPercentage = endPercentage
results = [ ]
for forecastingMethod in forecastingMethods :
results . append ( [ forecastingMethod ]... |
def _nemo_accpars ( self , vo , ro ) :
"""NAME :
_ nemo _ accpars
PURPOSE :
return the accpars potential parameters for use of this potential with NEMO
INPUT :
vo - velocity unit in km / s
ro - length unit in kpc
OUTPUT :
accpars string
HISTORY :
2018-09-14 - Written - Bovy ( UofT )""" | GM = self . _amp * vo ** 2. * ro / 2.
return "0,1,%s,%s,0" % ( GM , self . a * ro ) |
def afni_wf ( name = 'AFNISkullStripWorkflow' , unifize = False , n4_nthreads = 1 ) :
"""Skull - stripping workflow
Originally derived from the ` codebase of the
QAP < https : / / github . com / preprocessed - connectomes - project / quality - assessment - protocol / blob / master / qap / anatomical _ preproc .... | workflow = pe . Workflow ( name = name )
inputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'in_file' ] ) , name = 'inputnode' )
outputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'bias_corrected' , 'out_file' , 'out_mask' , 'bias_image' ] ) , name = 'outputnode' )
inu_n4 = pe . Node ( ants . N4Bia... |
def mount ( nbd , root = None ) :
'''Pass in the nbd connection device location , mount all partitions and return
a dict of mount points
CLI Example :
. . code - block : : bash
salt ' * ' qemu _ nbd . mount / dev / nbd0''' | __salt__ [ 'cmd.run' ] ( 'partprobe {0}' . format ( nbd ) , python_shell = False , )
ret = { }
if root is None :
root = os . path . join ( tempfile . gettempdir ( ) , 'nbd' , os . path . basename ( nbd ) )
for part in glob . glob ( '{0}p*' . format ( nbd ) ) :
m_pt = os . path . join ( root , os . path . basena... |
def limitsChanged ( self , param , limits ) :
"""Called when the parameter ' s limits have changed""" | ParameterItem . limitsChanged ( self , param , limits )
t = self . param . opts [ 'type' ]
if t == 'int' or t == 'float' :
self . widget . setOpts ( bounds = limits )
else :
return |
def ssh_invite ( ctx , code_length , user , ** kwargs ) :
"""Add a public - key to a ~ / . ssh / authorized _ keys file""" | for name , value in kwargs . items ( ) :
setattr ( ctx . obj , name , value )
from . import cmd_ssh
ctx . obj . code_length = code_length
ctx . obj . ssh_user = user
return go ( cmd_ssh . invite , ctx . obj ) |
def get_messages ( self ) :
"""returns all messages in this thread as dict mapping all contained
messages to their direct responses .
: rtype : dict mapping : class : ` ~ alot . db . message . Message ` to a list of
: class : ` ~ alot . db . message . Message ` .""" | if not self . _messages : # if not already cached
query = self . _dbman . query ( 'thread:' + self . _id )
thread = next ( query . search_threads ( ) )
def accumulate ( acc , msg ) :
M = Message ( self . _dbman , msg , thread = self )
acc [ M ] = [ ]
r = msg . get_replies ( )
... |
def __watch_file_system ( self ) :
"""Watches the file system for paths that have been changed or invalidated on disk .""" | for path , data in self . __paths . items ( ) :
stored_modified_time , is_file = data
try :
if not foundations . common . path_exists ( path ) :
LOGGER . warning ( "!> {0} | '{1}' path has been invalidated and will be unregistered!" . format ( self . __class__ . __name__ , path ) )
... |
def delete_all ( self ) :
"""Delete all record in the table / collection of this object .
* * 中文文档 * *
删除表中的所有记录""" | for record in self . find ( using_name = False , data_only = True ) :
res = self . delete_one ( record [ "id" ] ) |
def put_results ( self ) :
"""Put results to scheduler , used by poller or reactionner when they are
in active mode ( passive = False )
This function is not intended for external use . Let the poller and reactionner
manage all this stuff by themselves ; )
: param from : poller / reactionner identification
... | res = cherrypy . request . json
who_sent = res [ 'from' ]
results = res [ 'results' ]
results = unserialize ( results , no_load = True )
if results :
logger . debug ( "Got some results: %d results from %s" , len ( results ) , who_sent )
else :
logger . debug ( "-> no results" )
for result in results :
logge... |
def log_cef ( name , severity = logging . INFO , env = None , username = 'none' , signature = None , ** kwargs ) :
"""Wraps cef logging function so we don ' t need to pass in the config
dictionary every time . See bug 707060 . ` ` env ` ` can be either a request
object or just the request . META dictionary .""" | cef_logger = commonware . log . getLogger ( 'cef' )
c = { 'product' : settings . CEF_PRODUCT , 'vendor' : settings . CEF_VENDOR , 'version' : settings . CEF_VERSION , 'device_version' : settings . CEF_DEVICE_VERSION }
# The CEF library looks for some things in the env object like
# REQUEST _ METHOD and any REMOTE _ ADD... |
def compound_crossspec ( a_data , tbin , Df = None , pointProcess = False ) :
"""Calculate cross spectra of compound signals .
a _ data is a list of datasets ( a _ data = [ data1 , data2 , . . . ] ) .
For each dataset in a _ data , the compound signal is calculated
and the crossspectra between these compound ... | a_mdata = [ ]
for data in a_data :
a_mdata . append ( np . sum ( data , axis = 0 ) )
# calculate compound signals
return crossspec ( np . array ( a_mdata ) , tbin , Df , units = False , pointProcess = pointProcess ) |
def convert ( model , feature_names , target ) :
"""Convert a boosted tree model to protobuf format .
Parameters
decision _ tree : RandomForestRegressor
A trained scikit - learn tree model .
feature _ names : [ str ]
Name of the input columns .
target : str
Name of the output column .
Returns
mode... | if not ( _HAS_SKLEARN ) :
raise RuntimeError ( 'scikit-learn not found. scikit-learn conversion API is disabled.' )
_sklearn_util . check_expected_type ( model , _ensemble . RandomForestRegressor )
def is_rf_model ( m ) :
if len ( m . estimators_ ) == 0 :
return False
if hasattr ( m , 'estimators_' ... |
def postcode ( self ) :
"""Replaces all question mark ( ' ? ' ) occurrences with a random letter
from postal _ code _ formats then passes result to
numerify to insert numbers""" | temp = re . sub ( r'\?' , lambda x : self . postal_code_letter ( ) , self . random_element ( self . postal_code_formats ) )
return self . numerify ( temp ) |
def build ( self , lv2_uri ) :
"""Returns a new : class : ` . Lv2Effect ` by the valid lv2 _ uri
: param string lv2 _ uri :
: return Lv2Effect : Effect created""" | try :
plugin = self . _plugins [ lv2_uri ]
except KeyError :
raise Lv2EffectBuilderError ( "Lv2EffectBuilder not contains metadata information about the plugin '{}'. \n" "Try re-scan the installed plugins using the reload method::\n" " >>> lv2_effect_builder.reload(lv2_effect_builder.lv2_plugins_data())" . fo... |
def kelvin_to_rgb ( kelvin ) :
"""Convert a color temperature given in kelvin to an approximate RGB value .
: param kelvin : Color temp in K
: return : Tuple of ( r , g , b ) , equivalent color for the temperature""" | temp = kelvin / 100.0
# Calculate Red :
if temp <= 66 :
red = 255
else :
red = 329.698727446 * ( ( temp - 60 ) ** - 0.1332047592 )
# Calculate Green :
if temp <= 66 :
green = 99.4708025861 * math . log ( temp ) - 161.1195681661
else :
green = 288.1221695283 * ( ( temp - 60 ) ** - 0.0755148492 )
# Calcul... |
def create_from_row ( cls , table_row ) :
"""Create a ` JobDetails ` from an ` astropy . table . row . Row `""" | kwargs = { }
for key in table_row . colnames :
kwargs [ key ] = table_row [ key ]
infile_refs = kwargs . pop ( 'infile_refs' )
outfile_refs = kwargs . pop ( 'outfile_refs' )
rmfile_refs = kwargs . pop ( 'rmfile_refs' )
intfile_refs = kwargs . pop ( 'intfile_refs' )
kwargs [ 'infile_ids' ] = np . arange ( infile_ref... |
def present ( name , passwd , database = "admin" , user = None , password = None , host = "localhost" , port = 27017 , authdb = None , roles = None ) :
'''Ensure that the user is present with the specified properties
name
The name of the user to manage
passwd
The password of the user to manage
user
Mong... | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'User {0} is already present' . format ( name ) }
# setup default empty roles if not provided to preserve previous API interface
if roles is None :
roles = [ ]
# Check for valid port
try :
port = int ( port )
except TypeError :
ret [ 'r... |
def __dog_started ( self ) :
"""Prepare watchdog for scheduled task starting
: return : None""" | if self . __task is not None :
raise RuntimeError ( 'Unable to start task. In order to start a new task - at first stop it' )
self . __task = self . record ( ) . task ( )
if isinstance ( self . __task , WScheduleTask ) is False :
task_class = self . __task . __class__ . __qualname__
raise RuntimeError ( 'Un... |
def insert ( self , i , tag1 , tag2 , cmd = "prevtag" , x = None , y = None ) :
"""Inserts a new rule that updates words with tag1 to tag2,
given constraints x and y , e . g . , Context . append ( " TO < NN " , " VB " )""" | if " < " in tag1 and not x and not y :
tag1 , x = tag1 . split ( " < " ) ;
cmd = "prevtag"
if " > " in tag1 and not x and not y :
x , tag1 = tag1 . split ( " > " ) ;
cmd = "nexttag"
lazylist . insert ( self , i , [ tag1 , tag2 , cmd , x or "" , y or "" ] ) |
def post ( self ) :
"""Create bucket .""" | with db . session . begin_nested ( ) :
bucket = Bucket . create ( storage_class = current_app . config [ 'FILES_REST_DEFAULT_STORAGE_CLASS' ] , )
db . session . commit ( )
return self . make_response ( data = bucket , context = { 'class' : Bucket , } ) |
def stop_all_periodic_tasks ( self , remove_tasks = True ) :
"""Stop sending any messages that were started using bus . send _ periodic
: param bool remove _ tasks :
Stop tracking the stopped tasks .""" | for task in self . _periodic_tasks :
task . stop ( remove_task = remove_tasks ) |
def cric__lasso ( ) :
"""Lasso Regression""" | model = sklearn . linear_model . LogisticRegression ( penalty = "l1" , C = 0.002 )
# we want to explain the raw probability outputs of the trees
model . predict = lambda X : model . predict_proba ( X ) [ : , 1 ]
return model |
def get_points ( self ) :
"""Returns a ketama compatible list of ( position , nodename ) tuples .""" | return [ ( k , self . runtime . _ring [ k ] ) for k in self . runtime . _keys ] |
def drop ( self , index = None , columns = None ) :
"""Remove row data for target index and columns .
Args :
index : Target index to drop .
columns : Target columns to drop .
Returns :
A new QueryCompiler .""" | if self . _is_transposed :
return self . transpose ( ) . drop ( index = columns , columns = index ) . transpose ( )
if index is None :
new_data = self . data
new_index = self . index
else :
def delitem ( df , internal_indices = [ ] ) :
return df . drop ( index = df . index [ internal_indices ] )... |
def NTU_from_P_G ( P1 , R1 , Ntp , optimal = True ) :
r'''Returns the number of transfer units of a TEMA G type heat exchanger
with a specified ( for side 1 ) thermal effectiveness ` P1 ` , heat capacity
ratio ` R1 ` , the number of tube passes ` Ntp ` , and for the two - pass case
whether or not the inlets a... | NTU_min = 1E-11
function = temperature_effectiveness_TEMA_G
if Ntp == 1 or ( Ntp == 2 and optimal ) :
NTU_max = 1E4
# We could fit a curve to determine the NTU where the floating point
# does not allow NTU to increase though , but that would be another
# binary bisection process , different from the cur... |
def create_new_example ( foo = '' , a = '' , b = '' ) :
"""Factory method for example entities .
: rtype : Example""" | return Example . __create__ ( foo = foo , a = a , b = b ) |
def to_dict ( self , remove_nones = False ) :
"""Creates a dictionary representation of the object .
: param remove _ nones : Whether ` ` None ` ` values should be filtered out of the dictionary . Defaults to ` ` False ` ` .
: return : A dictionary representation of the report .""" | if remove_nones :
report_dict = super ( ) . to_dict ( remove_nones = True )
else :
report_dict = { 'title' : self . title , 'reportBody' : self . body , 'timeBegan' : self . time_began , 'externalUrl' : self . external_url , 'distributionType' : self . _get_distribution_type ( ) , 'externalTrackingId' : self . ... |
def make_prefetchitem_applicationfilename ( application_filename , condition = 'is' , negate = False , preserve_case = False ) :
"""Create a node for PrefetchItem / ApplicationFileName
: return : A IndicatorItem represented as an Element node""" | document = 'PrefetchItem'
search = 'PrefetchItem/ApplicationFileName'
content_type = 'string'
content = application_filename
ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate , preserve_case = preserve_case )
return ii_node |
def count ( self , q ) :
"""Shorthand for counting the results of a specific query .
# # Arguments
* ` q ` ( str ) : The query to count . This will be executed as :
` " SELECT COUNT ( * ) % s " % q ` .
# # Returns
* ` count ` ( int ) : The resulting count .""" | q = "SELECT COUNT(*) %s" % q
return int ( self . quick ( q ) . split ( "\n" ) [ 1 ] ) |
def set_title ( self , title = None ) :
"""Sets the editor title .
: param title : Editor title .
: type title : unicode
: return : Method success .
: rtype : bool""" | if not title : # TODO : https : / / bugreports . qt - project . org / browse / QTBUG - 27084
# titleTemplate = self . is _ modified ( ) and " { 0 } * " or " { 0 } "
# title = titleTemplate . format ( self . get _ file _ short _ name ( ) )
title = self . get_file_short_name ( )
LOGGER . debug ( "> Setting editor tit... |
def from_file ( path ) :
"""Return a ` ` Config ` ` instance by reading a configuration file .""" | with open ( path ) as stream :
obj = yaml . safe_load ( stream )
Config . lint ( obj )
return Config ( config_dict = obj ) |
def spec_from_json_dict ( json_dict # type : Dict [ str , Any ]
) : # type : ( . . . ) - > FieldSpec
"""Turns a dictionary into the appropriate object .
: param dict json _ dict : A dictionary with properties .
: returns : An initialised instance of the appropriate FieldSpec
subclass .""" | if 'ignored' in json_dict :
return Ignore ( json_dict [ 'identifier' ] )
type_str = json_dict [ 'format' ] [ 'type' ]
spec_type = cast ( FieldSpec , FIELD_TYPE_MAP [ type_str ] )
return spec_type . from_json_dict ( json_dict ) |
def _create_ip_report ( self ) :
'''this will take the obfuscated ip and hostname databases and output csv files''' | try :
ip_report_name = os . path . join ( self . report_dir , "%s-ip.csv" % self . session )
self . logger . con_out ( 'Creating IP Report - %s' , ip_report_name )
ip_report = open ( ip_report_name , 'wt' )
ip_report . write ( 'Obfuscated IP,Original IP\n' )
for k , v in self . ip_db . items ( ) :
... |
def _parse_example_spec ( self ) :
"""Returns a ` tf . Example ` parsing spec as dict .""" | height , width = image_util . get_expected_image_size ( self . module_spec )
input_shape = [ height , width , 3 ]
return { self . key : tf_v1 . FixedLenFeature ( input_shape , tf . float32 ) } |
def tiltFactor ( self , midpointdepth = None , printAvAngle = False ) :
'''get tilt factor from inverse distance law
https : / / en . wikipedia . org / wiki / Inverse - square _ law''' | # TODO : can also be only def . with FOV , rot , tilt
beta2 = self . viewAngle ( midpointdepth = midpointdepth )
try :
angles , vals = getattr ( emissivity_vs_angle , self . opts [ 'material' ] ) ( )
except AttributeError :
raise AttributeError ( "material[%s] is not in list of know materials: %s" % ( self . op... |
def maxlevel ( lst ) :
"""Return maximum nesting depth""" | maxlev = 0
def f ( lst , level ) :
nonlocal maxlev
if isinstance ( lst , list ) :
level += 1
maxlev = max ( level , maxlev )
for item in lst :
f ( item , level )
f ( lst , 0 )
return maxlev |
def get_file_object ( filename , mode = "r" ) :
"""Context manager for a file object . If filename is present , this is the
same as with open ( filename , mode ) : . . .
If filename is not present , then the file object returned is either
sys . stdin or sys . stdout depending on the mode .
: filename : the ... | if filename is None :
if mode . startswith ( "r" ) :
yield sys . stdin
else :
yield sys . stdout
else :
with open ( filename , mode ) as fobj :
yield fobj |
def get_initials ( pinyin , strict ) :
"""获取单个拼音中的声母 .
: param pinyin : 单个拼音
: type pinyin : unicode
: param strict : 是否严格遵照 《 汉语拼音方案 》 来处理声母和韵母
: return : 声母
: rtype : unicode""" | if strict :
_initials = _INITIALS
else :
_initials = _INITIALS_NOT_STRICT
for i in _initials :
if pinyin . startswith ( i ) :
return i
return '' |
def get_form_language ( self , request , obj = None ) :
"""Return the current language for the currently displayed object fields .""" | if obj is not None :
return obj . get_current_language ( )
else :
return self . _language ( request ) |
def check_refresh ( self , data , ret ) :
'''Check to see if the modules for this state instance need to be updated ,
only update if the state is a file or a package and if it changed
something . If the file function is managed check to see if the file is a
possible module type , e . g . a python , pyx , or .... | _reload_modules = False
if data . get ( 'reload_grains' , False ) :
log . debug ( 'Refreshing grains...' )
self . opts [ 'grains' ] = salt . loader . grains ( self . opts )
_reload_modules = True
if data . get ( 'reload_pillar' , False ) :
log . debug ( 'Refreshing pillar...' )
self . opts [ 'pillar... |
def _write_cron_lines ( user , lines ) :
'''Takes a list of lines to be committed to a user ' s crontab and writes it''' | lines = [ salt . utils . stringutils . to_str ( _l ) for _l in lines ]
path = salt . utils . files . mkstemp ( )
if _check_instance_uid_match ( user ) or __grains__ . get ( 'os_family' ) in ( 'Solaris' , 'AIX' ) : # In some cases crontab command should be executed as user rather than root
with salt . utils . files ... |
def unicode_string ( string ) :
"""Make sure string is unicode , try to default with utf8 , or base64 if failed .
can been decode by ` decode _ unicode _ string `""" | if isinstance ( string , six . text_type ) :
return string
try :
return string . decode ( "utf8" )
except UnicodeDecodeError :
return '[BASE64-DATA]' + base64 . b64encode ( string ) + '[/BASE64-DATA]' |
def delete_webhook ( self , scaling_group , policy , webhook ) :
"""Deletes the specified webhook from the specified policy .""" | uri = "/%s/%s/policies/%s/webhooks/%s" % ( self . uri_base , utils . get_id ( scaling_group ) , utils . get_id ( policy ) , utils . get_id ( webhook ) )
resp , resp_body = self . api . method_delete ( uri )
return None |
def ParseOptions ( cls , options , configuration_object ) :
"""Parses and validates options .
Args :
options ( argparse . Namespace ) : parser options .
configuration _ object ( CLITool ) : object to be configured by the argument
helper .
Raises :
BadConfigObject : when the configuration object is of th... | if not isinstance ( configuration_object , tools . CLITool ) :
raise errors . BadConfigObject ( 'Configuration object is not an instance of CLITool' )
artifacts_path = getattr ( options , 'artifact_definitions_path' , None )
data_location = getattr ( configuration_object , '_data_location' , None )
if ( ( not artif... |
def _process_image_file ( fobj , session , filename ) :
"""Process image files from the dataset .""" | # We need to read the image files and convert them to JPEG , since some files
# actually contain GIF , PNG or BMP data ( despite having a . jpg extension ) and
# some encoding options that will make TF crash in general .
image = _decode_image ( fobj , session , filename = filename )
return _encode_jpeg ( image ) |
def qvalues1 ( PV , m = None , pi = 1.0 ) :
"""estimate q vlaues from a list of Pvalues
this algorihm is taken from Storey , significance testing for genomic . . .
m : number of tests , ( if not len ( PV ) ) , pi : fraction of expected true null ( 1.0 is a conservative estimate )
@ param PV : pvalues
@ para... | S = PV . shape
PV = PV . flatten ( )
if m is None :
m = len ( PV ) * 1.0
else :
m *= 1.0
lPV = len ( PV )
# 1 . sort pvalues
PV = PV . squeeze ( )
IPV = PV . argsort ( )
PV = PV [ IPV ]
# 2 . estimate lambda
if pi is None :
lrange = sp . linspace ( 0.05 , 0.95 , max ( lPV / 100.0 , 10 ) )
pil = sp . dou... |
def is_connected ( self , attempts = 3 ) :
"""Try to reconnect if neccessary .
: param attempts : The amount of tries to reconnect if neccessary .
: type attempts : ` ` int ` `""" | if self . gce is None :
while attempts > 0 :
self . logger . info ( "Attempting to connect ..." )
try :
self . connect ( )
except ComputeEngineManagerException :
attempts -= 1
continue
self . logger . info ( "Connection established." )
retu... |
def text ( self ) :
"""Get the raw text for the response""" | try :
return self . _text
except AttributeError :
if IS_PYTHON_3 :
encoding = self . _response . headers . get_content_charset ( "utf-8" )
else :
encoding = self . _response . headers . getparam ( "charset" )
self . _text = self . _response . read ( ) . decode ( encoding or "utf-8" )
ret... |
def fetch_mga_scores ( mga_vec , codon_pos , default_mga = None ) :
"""Get MGAEntropy scores from pre - computed scores in array .
Parameters
mga _ vec : np . array
numpy vector containing MGA Entropy conservation scores for residues
codon _ pos : list of int
position of codon in protein sequence
defaul... | # keep only positions in range of MGAEntropy scores
len_mga = len ( mga_vec )
good_codon_pos = [ p for p in codon_pos if p < len_mga ]
# get MGAEntropy scores
if good_codon_pos :
mga_ent_scores = mga_vec [ good_codon_pos ]
else :
mga_ent_scores = None
return mga_ent_scores |
def _round_to_next_multiple ( n , m ) :
"""Round up the the next multiple .
: param n : The number to round up .
: param m : The multiple .
: return : The rounded number""" | return n if n % m == 0 else n + m - n % m |
def username_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
username = ET . SubElement ( config , "username" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" )
name = ET . SubElement ( username , "name" )
name . text = kwargs . pop ( 'name' )
callback = kwargs . pop ( 'callback' , self . _callback )
return callback ( config ) |
def save_config ( ** kwargs ) :
"""Save configuration keys to vispy config file
Parameters
* * kwargs : keyword arguments
Key / value pairs to save to the config file .""" | if kwargs == { } :
kwargs = config . _config
current_config = _load_config ( )
current_config . update ( ** kwargs )
# write to disk
fname = _get_config_fname ( )
if fname is None :
raise RuntimeError ( 'config filename could not be determined' )
if not op . isdir ( op . dirname ( fname ) ) :
os . mkdir ( o... |
def is_valid ( self ) :
"""Return True if tile is available in tile pyramid .""" | if not all ( [ isinstance ( self . zoom , int ) , self . zoom >= 0 , isinstance ( self . row , int ) , self . row >= 0 , isinstance ( self . col , int ) , self . col >= 0 ] ) :
raise TypeError ( "zoom, col and row must be integers >= 0" )
cols = self . tile_pyramid . matrix_width ( self . zoom )
rows = self . tile_... |
def get_env ( key : str , default : Any = None , clean : Callable [ [ str ] , Any ] = lambda v : v ) :
'''Retrieves a configuration value from the environment variables .
The given * key * is uppercased and prefixed by ` ` " BACKEND _ " ` ` and then
` ` " SORNA _ " ` ` if the former does not exist .
: param k... | key = key . upper ( )
v = os . environ . get ( 'BACKEND_' + key )
if v is None :
v = os . environ . get ( 'SORNA_' + key )
if v is None :
if default is None :
raise KeyError ( key )
v = default
return clean ( v ) |
def set_from_json ( self , obj , json , models = None , setter = None ) :
'''Sets the value of this property from a JSON value .
This method first
Args :
obj ( HasProps ) :
json ( JSON - dict ) :
models ( seq [ Model ] , optional ) :
setter ( ClientSession or ServerSession or None , optional ) :
This ... | return super ( BasicPropertyDescriptor , self ) . set_from_json ( obj , self . property . from_json ( json , models ) , models , setter ) |
def _get_translated_queryset ( self , meta = None ) :
"""Return the queryset that points to the translated model .
If there is a prefetch , it can be read from this queryset .""" | # Get via self . TRANSLATIONS _ FIELD . get ( . . ) so it also uses the prefetch / select _ related cache .
if meta is None :
meta = self . _parler_meta . root
accessor = getattr ( self , meta . rel_name )
# RelatedManager
return accessor . get_queryset ( ) |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : CredentialListContext for this CredentialListInstance
: rtype : twilio . rest . api . v2010 . account . sip . credential _... | if self . _context is None :
self . _context = CredentialListContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , sid = self . _solution [ 'sid' ] , )
return self . _context |
def _get_userdir ( user = None ) :
"""Returns the user dir or None""" | if user is not None and not isinstance ( user , fsnative ) :
raise TypeError
if is_win :
if "HOME" in environ :
path = environ [ "HOME" ]
elif "USERPROFILE" in environ :
path = environ [ "USERPROFILE" ]
elif "HOMEPATH" in environ and "HOMEDRIVE" in environ :
path = os . path . jo... |
def is_message_handler ( type_ , from_ , cb ) :
"""Return true if ` cb ` has been decorated with : func : ` message _ handler ` for the
given ` type _ ` and ` from _ ` .""" | try :
handlers = aioxmpp . service . get_magic_attr ( cb )
except AttributeError :
return False
return aioxmpp . service . HandlerSpec ( ( _apply_message_handler , ( type_ , from_ ) ) , require_deps = ( SimpleMessageDispatcher , ) ) in handlers |
def _querystring ( self ) :
"""Additional keyword arguments""" | kw = { "studyoid" : self . studyoid }
if self . location_oid is not None :
kw [ "locationoid" ] = self . location_oid
return kw |
def reset ( self , params , repetition ) :
"""Called at the beginning of each experiment and each repetition""" | pprint . pprint ( params )
self . initialize ( params , repetition )
# Load CIFAR dataset
dataDir = params . get ( 'dataDir' , 'data' )
self . transform_train = transforms . Compose ( [ transforms . RandomCrop ( 32 , padding = 4 ) , transforms . RandomHorizontalFlip ( ) , transforms . ToTensor ( ) , transforms . Normal... |
def return_features_base ( dbpath , set_object , names ) :
"""Generic function which returns a list of extracted features from the database
Parameters
dbpath : string , path to SQLite database file
set _ object : object ( either TestSet or TrainSet ) which is stored in the database
names : list of strings ,... | engine = create_engine ( 'sqlite:////' + dbpath )
session_cl = sessionmaker ( bind = engine )
session = session_cl ( )
return_list = [ ]
if names == 'all' :
for i in session . query ( set_object ) . order_by ( set_object . id ) :
row_list = [ ]
for feature in i . features :
row_list . ap... |
def remove_key ( self , store_key ) :
"""Remove key from the index .
: param store _ key : The key for the document in the store
: type store _ key : str""" | if store_key in self . _undefined_keys :
del self . _undefined_keys [ store_key ]
if store_key in self . _reverse_index :
for value in self . _reverse_index [ store_key ] :
self . _index [ value ] . remove ( store_key )
del self . _reverse_index [ store_key ] |
def do_tag ( self , args : argparse . Namespace ) :
"""create an html tag""" | # The Namespace always includes the Statement object created when parsing the command line
statement = args . __statement__
self . poutput ( "The command line you ran was: {}" . format ( statement . command_and_args ) )
self . poutput ( "It generated this tag:" )
self . poutput ( '<{0}>{1}</{0}>' . format ( args . tag ... |
def _findUniqueMappingValues ( mapping ) :
"""Find mapping entries that are unique for one key ( value length of 1 ) .
. . Note :
This function can be used to find unique proteins by providing a
peptide to protein mapping .
: param mapping : dict , for each key contains a set of entries
: returns : a set ... | uniqueMappingValues = set ( )
for entries in viewvalues ( mapping ) :
if len ( entries ) == 1 :
uniqueMappingValues . update ( entries )
return uniqueMappingValues |
def add_repo_key ( path = None , text = None , keyserver = None , keyid = None , saltenv = 'base' ) :
'''. . versionadded : : 2017.7.0
Add a repo key using ` ` apt - key add ` ` .
: param str path : The path of the key file to import .
: param str text : The key data to import , in string form .
: param str... | cmd = [ 'apt-key' ]
kwargs = { }
current_repo_keys = get_repo_keys ( )
if path :
cached_source_path = __salt__ [ 'cp.cache_file' ] ( path , saltenv )
if not cached_source_path :
log . error ( 'Unable to get cached copy of file: %s' , path )
return False
cmd . extend ( [ 'add' , cached_source... |
def for_me ( conditions , myself ) :
"""Am I among the intended audiences""" | if not conditions . audience_restriction : # No audience restriction
return True
for restriction in conditions . audience_restriction :
if not restriction . audience :
continue
for audience in restriction . audience :
if audience . text . strip ( ) == myself :
return True
... |
def _check_series_convert_timestamps_internal ( s , timezone ) :
"""Convert a tz - naive timestamp in the specified timezone or local timezone to UTC normalized for
Spark internal storage
: param s : a pandas . Series
: param timezone : the timezone to convert . if None then use local timezone
: return pand... | from pyspark . sql . utils import require_minimum_pandas_version
require_minimum_pandas_version ( )
from pandas . api . types import is_datetime64_dtype , is_datetime64tz_dtype
# TODO : handle nested timestamps , such as ArrayType ( TimestampType ( ) ) ?
if is_datetime64_dtype ( s . dtype ) : # When tz _ localize a tz ... |
def select ( self , key , where = None , start = None , stop = None , columns = None , iterator = False , chunksize = None , auto_close = False , ** kwargs ) :
"""Retrieve pandas object stored in file , optionally based on where
criteria
Parameters
key : object
where : list of Term ( or convertible ) object... | group = self . get_node ( key )
if group is None :
raise KeyError ( 'No object named {key} in the file' . format ( key = key ) )
# create the storer and axes
where = _ensure_term ( where , scope_level = 1 )
s = self . _create_storer ( group )
s . infer_axes ( )
# function to call on iteration
def func ( _start , _s... |
def from_code_array ( self ) :
"""Replaces everything in pys _ file from code _ array""" | for key in self . _section2writer :
self . pys_file . write ( key )
self . _section2writer [ key ] ( )
try :
if self . pys_file . aborted :
break
except AttributeError : # pys _ file is not opened via fileio . BZAopen
pass
if config [ "font_save_enabled" ] : # Clean up fonts ... |
def tuples2ids ( tuples , ids ) :
"""Update ` ids ` according to ` tuples ` , e . g . ( 3 , 0 , X ) , ( 4 , 0 , X ) . . .""" | for value in tuples :
if value [ 0 ] == 6 and value [ 2 ] :
ids = value [ 2 ]
elif value [ 0 ] == 5 :
ids [ : ] = [ ]
elif value [ 0 ] == 4 and value [ 1 ] and value [ 1 ] not in ids :
ids . append ( value [ 1 ] )
elif value [ 0 ] == 3 and value [ 1 ] and value [ 1 ] in ids :
... |
def area ( p ) :
"""Area of a polygone
: param p : list of the points taken in any orientation ,
p [ 0 ] can differ from p [ - 1]
: returns : area
: complexity : linear""" | A = 0
for i in range ( len ( p ) ) :
A += p [ i - 1 ] [ 0 ] * p [ i ] [ 1 ] - p [ i ] [ 0 ] * p [ i - 1 ] [ 1 ]
return A / 2. |
def are_equal ( self , sp1 , sp2 ) :
"""True if there is some overlap in composition between the species
Args :
sp1 : First species . A dict of { specie / element : amt } as per the
definition in Site and PeriodicSite .
sp2 : Second species . A dict of { specie / element : amt } as per the
definition in S... | set1 = set ( sp1 . elements )
set2 = set ( sp2 . elements )
return set1 . issubset ( set2 ) or set2 . issubset ( set1 ) |
def check_metadata_link ( self , ds ) :
'''Checks if metadata link is formed in a rational manner
: param netCDF4 . Dataset ds : An open netCDF dataset''' | if not hasattr ( ds , u'metadata_link' ) :
return
msgs = [ ]
meta_link = getattr ( ds , 'metadata_link' )
if 'http' not in meta_link :
msgs . append ( 'Metadata URL should include http:// or https://' )
valid_link = ( len ( msgs ) == 0 )
return Result ( BaseCheck . LOW , valid_link , 'metadata_link_valid' , msg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.