signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _set_serial_console ( self ) :
"""Configures the first serial port to allow a serial console connection .""" | pipe_name = self . _get_pipe_name ( )
serial_port = { "serial0.present" : "TRUE" , "serial0.filetype" : "pipe" , "serial0.filename" : pipe_name , "serial0.pipe.endpoint" : "server" , "serial0.startconnected" : "TRUE" }
self . _vmx_pairs . update ( serial_port ) |
def get_night_light_brightness ( self ) :
"""Return the brightness ( 0-255 ) of the night light .""" | if not self . camera_extended_properties :
return None
night_light = self . camera_extended_properties . get ( 'nightLight' )
if not night_light :
return None
return night_light . get ( 'brightness' ) |
def _add_to_transfer_queue ( self , src_ase , dst_ase ) : # type : ( SyncCopy , blobxfer . models . azure . StorageEntity ,
# blobxfer . models . azure . StorageEntity ) - > None
"""Add remote file to download queue
: param SyncCopy self : this
: param blobxfer . models . azure . StorageEntity src _ ase : src a... | # prepare remote file for download
# if remote file is a block blob , need to retrieve block list
if ( src_ase . mode == dst_ase . mode == blobxfer . models . azure . StorageModes . Block ) :
bl = blobxfer . operations . azure . blob . block . get_committed_block_list ( src_ase )
else :
bl = None
# TODO future ... |
def getgrouploansurl ( idgroup , * args , ** kwargs ) :
"""Request Group loans URL .
How to use it ? By default MambuLoan uses getloansurl as the urlfunc .
Override that behaviour by sending getgrouploansurl ( this function )
as the urlfunc to the constructor of MambuLoans ( note the final ' s ' )
and voila... | getparams = [ ]
if kwargs :
try :
if kwargs [ "fullDetails" ] == True :
getparams . append ( "fullDetails=true" )
else :
getparams . append ( "fullDetails=false" )
except Exception as ex :
pass
try :
getparams . append ( "accountState=%s" % kwargs [ "a... |
def fromhexstring ( cls , hexstring ) :
"""Construct BitMap from hex string""" | bitstring = format ( int ( hexstring , 16 ) , "0" + str ( len ( hexstring ) / 4 ) + "b" )
return cls . fromstring ( bitstring ) |
def is_https ( request_data ) :
"""Checks if https or http .
: param request _ data : The request as a dict
: type : dict
: return : False if https is not active
: rtype : boolean""" | is_https = 'https' in request_data and request_data [ 'https' ] != 'off'
is_https = is_https or ( 'server_port' in request_data and str ( request_data [ 'server_port' ] ) == '443' )
return is_https |
def list_pubs ( self , buf ) :
"""SSH v2 public keys are serialized and returned .""" | assert not buf . read ( )
keys = self . conn . parse_public_keys ( )
code = util . pack ( 'B' , msg_code ( 'SSH2_AGENT_IDENTITIES_ANSWER' ) )
num = util . pack ( 'L' , len ( keys ) )
log . debug ( 'available keys: %s' , [ k [ 'name' ] for k in keys ] )
for i , k in enumerate ( keys ) :
log . debug ( '%2d) %s' , i +... |
def cutL_seq ( seq , cutL , max_palindrome ) :
"""Cut genomic sequence from the left .
Parameters
seq : str
Nucleotide sequence to be cut from the right
cutL : int
cutL - max _ palindrome = how many nucleotides to cut from the left .
Negative cutL implies complementary palindromic insertions .
max _ p... | complement_dict = { 'A' : 'T' , 'C' : 'G' , 'G' : 'C' , 'T' : 'A' }
# can include lower case if wanted
if cutL < max_palindrome :
seq = '' . join ( [ complement_dict [ nt ] for nt in seq [ : max_palindrome - cutL ] ] [ : : - 1 ] ) + seq
# reverse complement palindrome insertions
else :
seq = seq [ cutL - ma... |
def getcolslice ( self , blc , trc , inc = [ ] , startrow = 0 , nrow = - 1 , rowincr = 1 ) :
"""Get a slice from a table column holding arrays .
( see : func : ` table . getcolslice ` )""" | return self . _table . getcolslice ( self . _column , blc , trc , inc , startrow , nrow , rowincr ) |
def listdir ( self , dirname ) :
"""Returns a list of entries contained within a directory .""" | client = boto3 . client ( "s3" )
bucket , path = self . bucket_and_path ( dirname )
p = client . get_paginator ( "list_objects" )
if not path . endswith ( "/" ) :
path += "/"
# This will now only retrieve subdir content
keys = [ ]
for r in p . paginate ( Bucket = bucket , Prefix = path , Delimiter = "/" ) :
... |
def is_iterable ( obj ) :
"""Are we being asked to look up a list of things , instead of a single thing ?
We check for the ` _ _ iter _ _ ` attribute so that this can cover types that
don ' t have to be known by this module , such as NumPy arrays .
Strings , however , should be considered as atomic values to ... | return ( hasattr ( obj , "__iter__" ) and not isinstance ( obj , str ) and not isinstance ( obj , tuple ) ) |
def _get_cluster_dict ( cluster_name , cluster_ref ) :
'''Returns a cluster dict representation from
a vim . ClusterComputeResource object .
cluster _ name
Name of the cluster
cluster _ ref
Reference to the cluster''' | log . trace ( 'Building a dictionary representation of cluster \'%s\'' , cluster_name )
props = salt . utils . vmware . get_properties_of_managed_object ( cluster_ref , properties = [ 'configurationEx' ] )
res = { 'ha' : { 'enabled' : props [ 'configurationEx' ] . dasConfig . enabled } , 'drs' : { 'enabled' : props [ '... |
def files ( self ) -> List [ str ] :
"""Obtain the list of the files ( excluding . git directory ) .
: return : List [ str ] , the list of the files""" | _all = [ ]
for path , _ , files in os . walk ( str ( self . path ) ) :
if '.git' in path :
continue
for name in files :
_all . append ( os . path . join ( path , name ) )
return _all |
def unget_used_services ( self , bundle ) :
"""Cleans up all service usages of the given bundle .
: param bundle : Bundle to be cleaned up""" | # Pop used references
try :
imported_refs = list ( self . __bundle_imports . pop ( bundle ) )
except KeyError : # Nothing to do
return
for svc_ref in imported_refs : # Remove usage marker
svc_ref . unused_by ( bundle )
if svc_ref . is_prototype ( ) : # Get factory information and clean up the service fr... |
def weld_merge_join ( arrays_self , weld_types_self , arrays_other , weld_types_other , how , is_on_sorted , is_on_unique , readable_text ) :
"""Applies merge - join on the arrays returning indices from each to keep in the resulting
Parameters
arrays _ self : list of ( numpy . ndarray or WeldObject )
Columns ... | assert is_on_unique
weld_obj_vec_of_struct_self = weld_arrays_to_vec_of_struct ( arrays_self , weld_types_self )
weld_obj_vec_of_struct_other = weld_arrays_to_vec_of_struct ( arrays_other , weld_types_other )
weld_obj_join = _weld_merge_join ( weld_obj_vec_of_struct_self , weld_obj_vec_of_struct_other , len ( arrays_se... |
def collapse ( self ) :
"""Collapse the collection items into a single element ( list )
: return : A new Collection instance with collapsed items
: rtype : Collection""" | results = [ ]
items = self . items
for values in items :
if isinstance ( values , BaseCollection ) :
values = values . all ( )
results += values
return self . __class__ ( results ) |
def create_csi_driver ( self , body , ** kwargs ) :
"""create a CSIDriver
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . create _ csi _ driver ( body , async _ req = True )
> > > result = thread . get ( )
... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_csi_driver_with_http_info ( body , ** kwargs )
else :
( data ) = self . create_csi_driver_with_http_info ( body , ** kwargs )
return data |
def flds_firstsort ( d ) :
'''Perform a lexsort and return the sort indices and shape as a tuple .''' | shape = [ len ( np . unique ( d [ l ] ) ) for l in [ 'xs' , 'ys' , 'zs' ] ] ;
si = np . lexsort ( ( d [ 'z' ] , d [ 'y' ] , d [ 'x' ] ) ) ;
return si , shape ; |
def delete_zip_codes_geo_zone_by_id ( cls , zip_codes_geo_zone_id , ** kwargs ) :
"""Delete ZipCodesGeoZone
Delete an instance of ZipCodesGeoZone by its ID .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . delete ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _delete_zip_codes_geo_zone_by_id_with_http_info ( zip_codes_geo_zone_id , ** kwargs )
else :
( data ) = cls . _delete_zip_codes_geo_zone_by_id_with_http_info ( zip_codes_geo_zone_id , ** kwargs )
return data |
def Crawl ( self , seed , seedClient = None , jobClient = None , rounds = 1 , index = True ) :
"""Launch a crawl using the given seed
: param seed : Type ( Seed or SeedList ) - used for crawl
: param seedClient : if a SeedList is given , the SeedClient to upload , if None a default will be created
: param job... | if seedClient is None :
seedClient = self . Seeds ( )
if jobClient is None :
jobClient = self . Jobs ( )
if type ( seed ) != Seed :
seed = seedClient . create ( jobClient . crawlId + '_seeds' , seed )
return CrawlClient ( self . server , seed , jobClient , rounds , index ) |
def timestamp_after_timestamp ( self , timestamp = None , seconds = 0 , minutes = 0 , hours = 0 , days = 0 ) :
"""给定时间戳 , 计算该时间戳之后多少秒 、 分钟 、 小时 、 天的时间戳 ( 本地时间 )""" | # 1 . 默认时间戳为当前时间
timestamp = self . get_current_timestamp ( ) if timestamp is None else timestamp
# 2 . 先转换为datetime
d1 = datetime . datetime . fromtimestamp ( timestamp )
# 3 . 根据相关时间得到datetime对象并相加给定时间戳的时间
d2 = d1 + datetime . timedelta ( seconds = int ( seconds ) , minutes = int ( minutes ) , hours = int ( hours ) ,... |
def update_oath_hotp_c ( self , entry , new_c ) :
"""Update the OATH - HOTP counter value for ` entry ' in the database .
Use SQL statement to ensure we only ever increase the counter .""" | key = entry . data [ "key" ]
c = self . conn . cursor ( )
c . execute ( "UPDATE oath SET oath_c = ? WHERE key = ? AND ? > oath_c" , ( new_c , key , new_c , ) )
self . conn . commit ( )
return c . rowcount == 1 |
def job ( request ) :
"""View for a single job .""" | job_id = request . GET . get ( "job_id" )
recent_jobs = JobRecord . objects . order_by ( "-start_time" ) [ 0 : 100 ]
recent_trials = TrialRecord . objects . filter ( job_id = job_id ) . order_by ( "-start_time" )
trial_records = [ ]
for recent_trial in recent_trials :
trial_records . append ( get_trial_info ( recen... |
def parse_method_results ( self , results_file , met ) :
"""Parse the output of a AMYLPRED2 result file .""" | result = str ( open ( results_file ) . read ( ) )
ind_s = str . find ( result , 'HITS' )
ind_e = str . find ( result , '**NOTE' )
tmp = result [ ind_s + 10 : ind_e ] . strip ( " " )
hits_resid = [ ]
method = None
if ":" in tmp :
method = tmp . split ( ":" ) [ 0 ]
hits = tmp . split ( ":" ) [ 1 ]
if "-" in h... |
def update_webhook_metadata ( self , policy , webhook , metadata ) :
"""Adds the given metadata dict to the existing metadata for the specified
webhook .""" | return self . manager . update_webhook_metadata ( self , policy , webhook , metadata ) |
def read_url ( url ) :
"""Reads given URL as JSON and returns data as loaded python object .""" | logging . debug ( 'reading {url} ...' . format ( url = url ) )
token = os . environ . get ( "BOKEH_GITHUB_API_TOKEN" )
headers = { }
if token :
headers [ 'Authorization' ] = 'token %s' % token
request = Request ( url , headers = headers )
response = urlopen ( request ) . read ( )
return json . loads ( response . de... |
def wr_xlsx ( self , fout_xlsx , goea_results , ** kws ) :
"""Write a xlsx file .""" | # kws : prt _ if indent itemid2name ( study _ items )
objprt = PrtFmt ( )
prt_flds = kws . get ( 'prt_flds' , self . get_prtflds_default ( goea_results ) )
xlsx_data = MgrNtGOEAs ( goea_results ) . get_goea_nts_prt ( prt_flds , ** kws )
if 'fld2col_widths' not in kws :
kws [ 'fld2col_widths' ] = { f : objprt . defa... |
def _call ( self , x ) :
"""Return the separable sum evaluated in ` ` x ` ` .""" | return sum ( fi ( xi ) for xi , fi in zip ( x , self . functionals ) ) |
def reset_Ac ( self ) :
"""Reset ` ` dae . Ac ` ` sparse matrix for disabled equations
due to hard _ limit and anti _ windup limiters .
: return : None""" | if self . ac_reset is False :
return
mn = self . m + self . n
x = index ( aandb ( self . zxmin , self . zxmax ) , 0. )
y = [ i + self . n for i in index ( aandb ( self . zymin , self . zymax ) , 0. ) ]
xy = list ( x ) + y
eye = spdiag ( [ 1.0 ] * mn )
H = spmatrix ( 1.0 , xy , xy , ( mn , mn ) , 'd' )
# Modifying `... |
def B4PS ( self ) :
'''判斷是否為四大賣點''' | return self . ckPlusGLI and ( self . S1 or self . S2 or self . S3 or self . S4 ) |
def execute_hook ( self , event_name ) :
"""Execute shell commands related to current event _ name""" | hook = self . settings . hooks . get_string ( '{!s}' . format ( event_name ) )
if hook is not None and hook != "" :
hook = hook . split ( )
try :
subprocess . Popen ( hook )
except OSError as oserr :
if oserr . errno == 8 :
log . error ( "Hook execution failed! Check shebang at f... |
def find_cell_content ( self , lines ) :
"""Parse cell till its end and set content , lines _ to _ next _ cell .
Return the position of next cell start""" | cell_end_marker , next_cell_start , explicit_eoc = self . find_cell_end ( lines )
# Metadata to dict
if self . start_code_re . match ( lines [ 0 ] ) or self . alternative_start_code_re . match ( lines [ 0 ] ) :
cell_start = 1
else :
cell_start = 0
# Cell content
source = lines [ cell_start : cell_end_marker ]
s... |
def geturi ( self , key , ** kwargs ) :
"""Gets the setting value as a : class : ` urllib . parse . ParseResult ` .
: rtype : urllib . parse . ParseResult""" | return self . get ( key , cast_func = urlparse , ** kwargs ) |
def swap_yaml_string ( file_path , swaps ) :
"""Swap a string in a yaml file without touching the existing formatting .""" | original_file = file_to_string ( file_path )
new_file = original_file
changed = False
for item in swaps :
match = re . compile ( r'(?<={0}: )(["\']?)(.*)\1' . format ( item [ 0 ] ) , re . MULTILINE )
new_file = re . sub ( match , item [ 1 ] , new_file )
if new_file != original_file :
changed = True
string_t... |
def find_descendants_by_text_re ( self , parent , re , immediate = False ) :
""": param parent : The parent element into which to search .
: type parent :
: class : ` selenium . webdriver . remote . webelement . WebElement `
or : class : ` str ` . When a string is specified , it
is interpreted as a CSS sele... | def cond ( * _ ) :
return self . driver . execute_script ( """
var parent = arguments[0];
if (typeof parent === "string")
parent = document.querySelector(parent);
var re = new RegExp(arguments[1]);
var ret = [];
var nodes = parent.querySele... |
def _load_old_defaults ( self , old_version ) :
"""Read old defaults""" | old_defaults = cp . ConfigParser ( )
if check_version ( old_version , '3.0.0' , '<=' ) :
path = get_module_source_path ( 'spyder' )
else :
path = osp . dirname ( self . filename ( ) )
path = osp . join ( path , 'defaults' )
old_defaults . read ( osp . join ( path , 'defaults-' + old_version + '.ini' ) )
return ... |
def async_get_ac_state_log ( self , uid , log_id , fields = '*' ) :
"""Get a specific log entry .""" | return ( yield from self . _get ( '/pods/{}/acStates/{}' . format ( uid , log_id ) , fields = fields ) ) |
def _has_fulltext ( cls , uri ) :
"""Enable full text search on the messages if possible and return True .
If the full text search cannot be enabled , then return False .""" | coll = cls . _get_collection ( uri )
with ExceptionTrap ( storage . pymongo . errors . OperationFailure ) as trap :
coll . create_index ( [ ( 'message' , 'text' ) ] , background = True )
return not trap |
def event_html_page_context ( app , pagename , templatename , context , doctree ) :
"""Called when the HTML builder has created a context dictionary to render a template with .
Conditionally adding disqus . js to < head / > if the directive is used in a page .
: param sphinx . application . Sphinx app : Sphinx ... | assert app or pagename or templatename
# Unused , for linting .
if 'script_files' in context and doctree and any ( hasattr ( n , 'disqus_shortname' ) for n in doctree . traverse ( ) ) : # Clone list to prevent leaking into other pages and add disqus . js to this page .
context [ 'script_files' ] = context [ 'script... |
def query ( self , where = "1=1" , out_fields = "*" , timeFilter = None , geometryFilter = None , returnGeometry = True , returnIDsOnly = False , returnCountOnly = False , returnFeatureClass = False , returnDistinctValues = False , returnExtentOnly = False , maxAllowableOffset = None , geometryPrecision = None , outSR ... | params = { "f" : "json" , "where" : where , "outFields" : out_fields , "returnGeometry" : returnGeometry , "returnIdsOnly" : returnIDsOnly , "returnCountOnly" : returnCountOnly , "returnDistinctValues" : returnDistinctValues , "returnExtentOnly" : returnExtentOnly }
if outSR is not None :
params [ 'outSR' ] = outSR... |
def version ( syslog_ng_sbin_dir = None ) :
'''Returns the version of the installed syslog - ng . If syslog _ ng _ sbin _ dir is
specified , it is added to the PATH during the execution of the command
syslog - ng .
CLI Example :
. . code - block : : bash
salt ' * ' syslog _ ng . version
salt ' * ' syslo... | try :
ret = _run_command_in_extended_path ( syslog_ng_sbin_dir , 'syslog-ng' , ( '-V' , ) )
except CommandExecutionError as err :
return _format_return_data ( retcode = - 1 , stderr = six . text_type ( err ) )
if ret [ 'retcode' ] != 0 :
return _format_return_data ( ret [ 'retcode' ] , stderr = ret [ 'stder... |
def _execute_autoprops_on_class ( object_type , # type : Type [ T ]
include = None , # type : Union [ str , Tuple [ str ] ]
exclude = None # type : Union [ str , Tuple [ str ] ]
) :
"""This method will automatically add one getter and one setter for each constructor argument , except for those
overridden using au... | # 0 . first check parameters
validate_include_exclude ( include , exclude )
# 1 . Find the _ _ init _ _ constructor signature and possible pycontracts @ contract
constructor = get_constructor ( object_type , allow_inheritance = True )
s = signature ( constructor )
# option a ) pycontracts
contracts_dict = constructor .... |
def get_user_info ( self , username ) :
""": param username :
: return : a tuple ( realname , email ) if the user can be found , None else""" | info = self . get_users_info ( [ username ] )
return info [ username ] if info is not None else None |
def _create_record ( self , rtype , name , content ) :
"""Connects to Hetzner account , adds a new record to the zone and returns a
boolean , if creation was successful or not . Needed record rtype , name and
content for record to create .""" | with self . _session ( self . domain , self . domain_id ) as ddata : # Validate method parameters
if not rtype or not name or not content :
LOGGER . warning ( 'Hetzner => Record has no rtype|name|content specified' )
return False
# Add record to zone
name = ddata [ 'cname' ] if ddata [ 'cnam... |
def makePartitions ( self ) :
"""Make partitions with gmane help .""" | class NetworkMeasures :
pass
self . nm = nm = NetworkMeasures ( )
nm . degrees = self . network . degree ( )
nm . nodes_ = sorted ( self . network . nodes ( ) , key = lambda x : nm . degrees [ x ] )
nm . degrees_ = [ nm . degrees [ i ] for i in nm . nodes_ ]
nm . edges = self . network . edges ( data = True )
nm . ... |
def print_solution ( solution ) :
"""Prints a solution
Arguments
solution : BaseSolution
Example
[8 , 9 , 10 , 7 ] : 160
[5 , 6 ] : 131
[3 , 4 , 2 ] : 154
Total cost : 445""" | total_cost = 0
for solution in solution . routes ( ) :
cost = solution . length ( )
total_cost = total_cost + cost
print ( '{}: {}' . format ( solution , cost ) )
# print ( ' xxx ' )
print ( 'Total cost: {}' . format ( total_cost ) ) |
def create_ngram_set ( input_list , ngram_value = 2 ) :
"""Extract a set of n - grams from a list of integers .
> > > create _ ngram _ set ( [ 1 , 4 , 9 , 4 , 1 , 4 ] , ngram _ value = 2)
{ ( 4 , 9 ) , ( 4 , 1 ) , ( 1 , 4 ) , ( 9 , 4 ) }
> > > create _ ngram _ set ( [ 1 , 4 , 9 , 4 , 1 , 4 ] , ngram _ value =... | return set ( zip ( * [ input_list [ i : ] for i in range ( ngram_value ) ] ) ) |
def change_svc_snapshot_command ( self , service , snapshot_command ) :
"""Modify host snapshot command
Format of the line that triggers function call : :
CHANGE _ HOST _ SNAPSHOT _ COMMAND ; < host _ name > ; < event _ handler _ command >
: param service : service to modify snapshot command
: type service ... | service . modified_attributes |= DICT_MODATTR [ "MODATTR_EVENT_HANDLER_COMMAND" ] . value
data = { "commands" : self . commands , "call" : snapshot_command }
service . change_snapshot_command ( data )
self . send_an_element ( service . get_update_status_brok ( ) ) |
async def load_blob ( reader , elem_type , params = None , elem = None ) :
"""Loads blob from reader to the element . Returns the loaded blob .
: param reader :
: param elem _ type :
: param params :
: param elem :
: return :""" | ivalue = elem_type . SIZE if elem_type . FIX_SIZE else await load_uvarint ( reader )
fvalue = bytearray ( ivalue )
await reader . areadinto ( fvalue )
if elem is None :
return fvalue
# array by default
elif isinstance ( elem , BlobType ) :
setattr ( elem , elem_type . DATA_ATTR , fvalue )
return elem
else :... |
def parse ( cls , uri ) :
"""Parses uri into a ResourceUri object""" | match = _URI_FORMAT . search ( uri )
return cls ( match . group ( 1 ) , match . group ( 2 ) , match . group ( 3 ) , match . group ( 4 ) ) |
def parse ( self , response ) :
'''根据对 ` ` start _ urls ` ` 中提供链接的请求响应包内容 , 解析生成具体文章链接请求
: param Response response : 由 ` ` Scrapy ` ` 调用并传入的请求响应对象''' | content_raw = response . body . decode ( )
self . logger . debug ( '响应body原始数据:{}' . format ( content_raw ) )
content = json . loads ( content_raw , encoding = 'UTF-8' )
self . logger . debug ( content )
# 文章发布日期
date = datetime . datetime . strptime ( content [ 'date' ] , '%Y%m%d' )
strftime = date . strftime ( "%Y-%m... |
def spin ( compound , theta , around ) :
"""Rotate a compound in place around an arbitrary vector .
Parameters
compound : mb . Compound
The compound being rotated .
theta : float
The angle by which to rotate the compound , in radians .
around : np . ndarray , shape = ( 3 , ) , dtype = float
The axis a... | around = np . asarray ( around ) . reshape ( 3 )
if np . array_equal ( around , np . zeros ( 3 ) ) :
raise ValueError ( 'Cannot spin around a zero vector' )
center_pos = compound . center
translate ( compound , - center_pos )
rotate ( compound , theta , around )
translate ( compound , center_pos ) |
def _log_prior_gradients ( self ) :
"""evaluate the gradients of the priors""" | if self . priors . size == 0 :
return 0.
x = self . param_array
ret = np . zeros ( x . size )
# compute derivate of prior density
[ np . put ( ret , ind , p . lnpdf_grad ( x [ ind ] ) ) for p , ind in self . priors . items ( ) ]
# add in jacobian derivatives if transformed
priored_indexes = np . hstack ( [ i for p ... |
def get_valid_times_for_job_legacy ( self , num_job ) :
"""Get the times for which the job num _ job will be valid , using the method
use in inspiral hipe .""" | # All of this should be integers , so no rounding factors needed .
shift_dur = self . curr_seg [ 0 ] + int ( self . job_time_shift * num_job )
job_valid_seg = self . valid_chunk . shift ( shift_dur )
# If this is the last job , push the end back
if num_job == ( self . num_jobs - 1 ) :
dataPushBack = self . data_len... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'word' ) and self . word is not None :
_dict [ 'word' ] = self . word
if hasattr ( self , 'sounds_like' ) and self . sounds_like is not None :
_dict [ 'sounds_like' ] = self . sounds_like
if hasattr ( self , 'display_as' ) and self . display_as is not None :
_dict [ 'display_... |
def delete_item ( self , tablename , key , expected = None , returns = NONE , return_capacity = None , expect_or = False , ** kwargs ) :
"""Delete an item
This uses the older version of the DynamoDB API .
See also : : meth : ` ~ . delete _ item2 ` .
Parameters
tablename : str
Name of the table to delete f... | key = self . dynamizer . encode_keys ( key )
keywords = { 'ReturnConsumedCapacity' : self . _default_capacity ( return_capacity ) , }
if kwargs :
keywords [ 'Expected' ] = encode_query_kwargs ( self . dynamizer , kwargs )
if len ( keywords [ 'Expected' ] ) > 1 :
keywords [ 'ConditionalOperator' ] = 'OR'... |
def clean_up_dangling_images ( self ) :
"""Clean up all dangling images .""" | cargoes = Image . all ( client = self . _client_session , filters = { 'dangling' : True } )
for id , cargo in six . iteritems ( cargoes ) :
logger . info ( "Removing dangling image: {0}" . format ( id ) )
cargo . delete ( ) |
def lal_spin_evloution_wrapper ( approximant , q , omega0 , chiA0 , chiB0 , dt , spinO , phaseO ) :
"""Inputs :
approximant : ' SpinTaylorT1 / T2 / T4'
q : Mass ratio ( q > = 1)
omega0 : Initial orbital frequency in dimless units .
chiA0 : Dimless spin of BhA at initial freq .
chiB0 : Dimless spin of BhB ... | approxTag = lalsim . GetApproximantFromString ( approximant )
# Total mass in solar masses
M = 100
# This does not affect the returned values as they are
# dimension less
# time step and initial GW freq in SI units
MT = M * MTSUN_SI
deltaT = dt * MT
fStart = omega0 / np . pi / MT
# component masses of the binary
m1_SI ... |
def _initialize ( self ) :
"""Initialize collector worker thread , Log path will be checked first .
Records in DB backend will be cleared .""" | if not os . path . exists ( self . _logdir ) :
raise CollectorError ( "Log directory %s not exists" % self . _logdir )
self . logger . info ( "Collector started, taking %s as parent directory" "for all job logs." % self . _logdir )
# clear old records
JobRecord . objects . filter ( ) . delete ( )
TrialRecord . obje... |
def get_el_amount ( self , element ) :
"""Returns the amount of the element in the reaction .
Args :
element ( Element / Specie ) : Element in the reaction
Returns :
Amount of that element in the reaction .""" | return sum ( [ self . _all_comp [ i ] [ element ] * abs ( self . _coeffs [ i ] ) for i in range ( len ( self . _all_comp ) ) ] ) / 2 |
def json_expand ( json_op ) :
"""For custom _ json ops .""" | if type ( json_op ) == dict and 'json' in json_op :
return update_in ( json_op , [ 'json' ] , safe_json_loads )
return json_op |
def remove_port ( zone , port , permanent = True ) :
'''Remove a specific port from a zone .
. . versionadded : : 2015.8.0
CLI Example :
. . code - block : : bash
salt ' * ' firewalld . remove _ port internal 443 / tcp''' | cmd = '--zone={0} --remove-port={1}' . format ( zone , port )
if permanent :
cmd += ' --permanent'
return __firewall_cmd ( cmd ) |
def rfc2822 ( self ) :
'''a method to report a RFC - 2822 Compliant Date from a labDT object
https : / / tools . ietf . org / html / rfc2822 . html # page - 14
: return : string with RFC - 2822 compliant date time''' | # define format
js_format = '%a, %d %b %Y %H:%M:%S GMT'
utc_time = self . astimezone ( pytz . utc )
return format ( utc_time , js_format ) |
def get_paths ( self , key ) :
"""Same as ` ConfigParser . get _ path ` for a list of paths .
Args :
key : str , the key to lookup the paths with
Returns :
list : The paths .""" | final_paths = [ ]
if key in self . __cli :
paths = self . __cli [ key ] or [ ]
from_conf = False
else :
paths = self . __config . get ( key ) or [ ]
from_conf = True
for path in flatten_list ( paths ) :
final_path = self . __abspath ( path , from_conf )
if final_path :
final_paths . appe... |
def compress_group_index ( group_index , sort = True ) :
"""Group _ index is offsets into cartesian product of all possible labels . This
space can be huge , so this function compresses it , by computing offsets
( comp _ ids ) into the list of unique labels ( obs _ group _ ids ) .""" | size_hint = min ( len ( group_index ) , hashtable . _SIZE_HINT_LIMIT )
table = hashtable . Int64HashTable ( size_hint )
group_index = ensure_int64 ( group_index )
# note , group labels come out ascending ( ie , 1,2,3 etc )
comp_ids , obs_group_ids = table . get_labels_groupby ( group_index )
if sort and len ( obs_group... |
def pprint ( data ) :
"""Returns an indented HTML pretty - print version of JSON .
Take the event _ payload JSON , indent it , order the keys and then
present it as a < code > block . That ' s about as good as we can get
until someone builds a custom syntax function .""" | pretty = json . dumps ( data , sort_keys = True , indent = 4 , separators = ( "," , ": " ) )
html = pretty . replace ( " " , " " ) . replace ( "\n" , "<br>" )
return mark_safe ( "<code>%s</code>" % html ) |
def get_mfa ( self , auth_resp ) :
"""Gets MFA code from user and returns response which includes the client token""" | devices = auth_resp [ 'data' ] [ 'devices' ]
if len ( devices ) == 1 : # If there ' s only one option , don ' t show selection prompt
selection = "0"
x = 1
else :
print ( "Found the following MFA devices" )
x = 0
for device in devices :
print ( "{0}: {1}" . format ( x , device [ 'name' ] ) )... |
def import_categories ( self , category_nodes ) :
"""Import all the categories from ' wp : category ' nodes ,
because categories in ' item ' nodes are not necessarily
all the categories and returning it in a dict for
database optimizations .""" | self . write_out ( self . style . STEP ( '- Importing categories\n' ) )
categories = { }
for category_node in category_nodes :
title = category_node . find ( '{%s}cat_name' % WP_NS ) . text [ : 255 ]
slug = category_node . find ( '{%s}category_nicename' % WP_NS ) . text [ : 255 ]
try :
parent = cate... |
def method_args ( self , context , ** kwargs ) :
"""Collect the set of arguments that should be used by a set of methods
: param context : Which service we ' re working for
: param kwargs : A set of keyword arguments that are added at run - time .
: return : A set of keyword arguments""" | try :
_args = self . conf [ context ] . copy ( )
except KeyError :
_args = kwargs
else :
_args . update ( kwargs )
return _args |
def check_package ( self , package , package_dir ) :
"""Check namespace packages ' _ _ init _ _ for declare _ namespace""" | try :
return self . packages_checked [ package ]
except KeyError :
pass
init_py = orig . build_py . check_package ( self , package , package_dir )
self . packages_checked [ package ] = init_py
if not init_py or not self . distribution . namespace_packages :
return init_py
for pkg in self . distribution . na... |
def serve ( service_brokers : Union [ List [ ServiceBroker ] , ServiceBroker ] , credentials : Union [ List [ BrokerCredentials ] , BrokerCredentials , None ] , logger : logging . Logger = logging . root , port = 5000 , debug = False ) :
"""Starts flask with the given brokers .
You can provide a list or just one ... | from gevent . pywsgi import WSGIServer
from flask import Flask
app = Flask ( __name__ )
app . debug = debug
blueprint = get_blueprint ( service_brokers , credentials , logger )
logger . debug ( "Register openbrokerapi blueprint" )
app . register_blueprint ( blueprint )
logger . info ( "Start Flask on 0.0.0.0:%s" % port... |
def class_in_progress ( stack = None ) :
"""True if currently inside a class definition , else False .""" | if stack is None :
stack = inspect . stack ( )
for frame in stack :
statement_list = frame [ 4 ]
if statement_list is None :
continue
if statement_list [ 0 ] . strip ( ) . startswith ( 'class ' ) :
return True
return False |
def _get_or_insert ( * args , ** kwds ) :
"""Transactionally retrieves an existing entity or creates a new one .
Positional Args :
name : Key name to retrieve or create .
Keyword Args :
namespace : Optional namespace .
app : Optional app ID .
parent : Parent entity key , if any .
context _ options : C... | cls , args = args [ 0 ] , args [ 1 : ]
return cls . _get_or_insert_async ( * args , ** kwds ) . get_result ( ) |
def handle_ConnectionClose ( self , frame ) :
"""AMQP server closed the channel with an error""" | # Notify server we are OK to close .
self . sender . send_CloseOK ( )
exc = ConnectionClosed ( frame . payload . reply_text , frame . payload . reply_code )
self . _close_all ( exc )
# This will not abort transport , it will try to flush remaining data
# asynchronously , as stated in ` asyncio ` docs .
self . protocol ... |
def DeleteInstance ( self , context , ports ) :
"""Destroy Vm Command , will only destroy the vm and will not remove the resource
: param models . QualiDriverModels . ResourceRemoteCommandContext context : the context the command runs on
: param list [ string ] ports : the ports of the connection between the re... | resource_details = self . _parse_remote_model ( context )
# execute command
res = self . command_wrapper . execute_command_with_connection ( context , self . destroy_virtual_machine_command . DeleteInstance , resource_details . vm_uuid , resource_details . fullname )
return set_command_result ( result = res , unpicklab... |
def from_json ( json_str , allow_pickle = False ) :
"""Decodes a JSON object specified in the utool convention
Args :
json _ str ( str ) :
allow _ pickle ( bool ) : ( default = False )
Returns :
object : val
CommandLine :
python - m utool . util _ cache from _ json - - show
Example :
> > > # ENABL... | if six . PY3 :
if isinstance ( json_str , bytes ) :
json_str = json_str . decode ( 'utf-8' )
UtoolJSONEncoder = make_utool_json_encoder ( allow_pickle )
object_hook = UtoolJSONEncoder . _json_object_hook
val = json . loads ( json_str , object_hook = object_hook )
return val |
def _get_top_features ( feature_names , coef , top , x ) :
"""Return a ` ` ( pos , neg ) ` ` tuple . ` ` pos ` ` and ` ` neg ` ` are lists of
` ` ( name , value ) ` ` tuples for features with positive and negative
coefficients .
Parameters :
* ` ` feature _ names ` ` - a vector of feature names ;
* ` ` co... | if isinstance ( top , ( list , tuple ) ) :
num_pos , num_neg = list ( top )
# " list " is just for mypy
pos = _get_top_positive_features ( feature_names , coef , num_pos , x )
neg = _get_top_negative_features ( feature_names , coef , num_neg , x )
else :
pos , neg = _get_top_abs_features ( feature_n... |
def saveDirectory ( alias ) :
"""save a directory to a certain alias / nickname""" | if not settings . platformCompatible ( ) :
return False
dataFile = open ( settings . getDataFile ( ) , "wb" )
currentDirectory = os . path . abspath ( "." )
directory = { alias : currentDirectory }
pickle . dump ( directory , dataFile )
speech . success ( alias + " will now link to " + currentDirectory + "." )
spee... |
def genty_dataprovider ( builder_function ) :
"""Decorator defining that this test gets parameters from the given
build _ function .
: param builder _ function :
A callable that returns parameters that will be passed to the method
decorated by this decorator .
If the builder _ function returns a tuple or ... | datasets = getattr ( builder_function , 'genty_datasets' , { None : ( ) } )
def wrap ( test_method ) : # Save the data providers in the test method . This data will be
# consumed by the @ genty decorator .
if not hasattr ( test_method , 'genty_dataproviders' ) :
test_method . genty_dataproviders = [ ]
t... |
def create_archive ( self , archive_name , authority_name , archive_path , versioned , raise_on_err = True , metadata = None , user_config = None , tags = None , helper = False ) :
'''Create a new data archive
Returns
archive : object
new : py : class : ` ~ datafs . core . data _ archive . DataArchive ` objec... | archive_metadata = self . _create_archive_metadata ( archive_name = archive_name , authority_name = authority_name , archive_path = archive_path , versioned = versioned , raise_on_err = raise_on_err , metadata = metadata , user_config = user_config , tags = tags , helper = helper )
if raise_on_err :
self . _create_... |
def py_to_couch_validate ( key , val ) :
"""Validates the individual parameter key and value .""" | if key not in RESULT_ARG_TYPES :
raise CloudantArgumentError ( 116 , key )
# pylint : disable = unidiomatic - typecheck
# Validate argument values and ensure that a boolean is not passed in
# if an integer is expected
if ( not isinstance ( val , RESULT_ARG_TYPES [ key ] ) or ( type ( val ) is bool and int in RESULT... |
def _responsive_sleep ( self , seconds , wait_log_interval = 0 , wait_reason = '' ) :
"""When there is litte work to do , the queuing thread sleeps a lot .
It can ' t sleep for too long without checking for the quit flag and / or
logging about why it is sleeping .
parameters :
seconds - the number of second... | for x in xrange ( int ( seconds ) ) :
self . quit_check ( )
if wait_log_interval and not x % wait_log_interval :
self . logger . info ( '%s: %dsec of %dsec' , wait_reason , x , seconds )
self . quit_check ( )
time . sleep ( 1.0 ) |
def delete_cache_security_group ( name , region = None , key = None , keyid = None , profile = None ) :
'''Delete a cache security group .
CLI example : :
salt myminion boto _ elasticache . delete _ cache _ security _ group myelasticachesg ' My Cache Security Group ' ''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
deleted = conn . delete_cache_security_group ( name )
if deleted :
log . info ( 'Deleted cache security group %s.' , name )
return True
else :
msg = 'Failed to delete cache security group {0}.' . format ( name )
log . e... |
def _file_name ( self , dtype_out_time , extension = 'nc' ) :
"""Create the name of the aospy file .""" | if dtype_out_time is None :
dtype_out_time = ''
out_lbl = utils . io . data_out_label ( self . intvl_out , dtype_out_time , dtype_vert = self . dtype_out_vert )
in_lbl = utils . io . data_in_label ( self . intvl_in , self . dtype_in_time , self . dtype_in_vert )
start_year = utils . times . infer_year ( self . star... |
def attack_decay ( params , attack , start = 0 , peak = 1 ) :
'''Signal starts at min value , ramps linearly up to max value during the
attack time , than ramps back down to min value over remaining time
: param params : buffer parameters , controls length of signal created
: param attack : attack time , in s... | builder = GenericEnvelope ( params )
builder . set ( start )
builder . linseg ( peak , attack )
if attack < params . length :
builder . linseg ( start , params . length - attack )
return builder . build ( ) |
def setup_queue ( self , queue_name ) :
"""Setup the queue on RabbitMQ by invoking the Queue . Declare RPC
command . When it is complete , the on _ queue _ declareok method will
be invoked by pika .
: param str | unicode queue _ name : The name of the queue to declare .""" | _logger . debug ( 'Declaring queue %s' , queue_name )
self . _channel . queue_declare ( self . on_queue_declareok , queue_name ) |
def load_script ( zap_helper , ** options ) :
"""Load a script from a file .""" | with zap_error_handler ( ) :
if not os . path . isfile ( options [ 'file_path' ] ) :
raise ZAPError ( 'No file found at "{0}", cannot load script.' . format ( options [ 'file_path' ] ) )
if not _is_valid_script_engine ( zap_helper . zap , options [ 'engine' ] ) :
engines = zap_helper . zap . scr... |
def register_listener ( self , listener , interesting , active ) :
"""Register an event listener .
To avoid system overload , the VirtualBox server process checks if passive event
listeners call : py : func : ` IEventSource . get _ event ` frequently enough . In the
current implementation , if more than 500 p... | if not isinstance ( listener , IEventListener ) :
raise TypeError ( "listener can only be an instance of type IEventListener" )
if not isinstance ( interesting , list ) :
raise TypeError ( "interesting can only be an instance of type list" )
for a in interesting [ : 10 ] :
if not isinstance ( a , VBoxEventT... |
def encode_file_header ( boundary , paramname , filesize , filename = None , filetype = None ) :
"""Returns the leading data for a multipart / form - data field that contains
file data .
` ` boundary ` ` is the boundary string used throughout a single request to
separate variables .
` ` paramname ` ` is the... | return MultipartParam ( paramname , filesize = filesize , filename = filename , filetype = filetype ) . encode_hdr ( boundary ) |
def fcoe_fsb_fcoe_fsb_enable ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
fcoe_fsb = ET . SubElement ( config , "fcoe-fsb" , xmlns = "urn:brocade.com:mgmt:brocade-fcoe" )
fcoe_fsb_enable = ET . SubElement ( fcoe_fsb , "fcoe-fsb-enable" )
callback = kwargs . pop ( 'callback' , self . _callback )
return callback ( config ) |
def json_describe ( o , fqdn , descriptor = None ) :
"""Describes the specified object using the directives in the JSON
` descriptor ` , if available .
Args :
o : object to describe .
fqdn ( str ) : fully - qualified domain name of the object .
descriptor ( dict ) : keys are attributes of ` o ` ; values a... | if descriptor is None or not isinstance ( descriptor , dict ) :
return { "fqdn" : fqdn }
else :
result = { "fqdn" : fqdn }
for attr , desc in descriptor . items ( ) :
if attr == "instance" : # For instance methods , we repeatedly call instance methods on
# ` value ` , assuming that the metho... |
def DEFINE_point ( name , default , help ) : # pylint : disable = invalid - name , redefined - builtin
"""Registers a flag whose value parses as a point .""" | flags . DEFINE ( PointParser ( ) , name , default , help ) |
def _recurse_config_to_dict ( t_data ) :
'''helper function to recurse through a vim object and attempt to return all child objects''' | if not isinstance ( t_data , type ( None ) ) :
if isinstance ( t_data , list ) :
t_list = [ ]
for i in t_data :
t_list . append ( _recurse_config_to_dict ( i ) )
return t_list
elif isinstance ( t_data , dict ) :
t_dict = { }
for k , v in six . iteritems ( t_da... |
def send_jsonified ( self , msg , stats = True ) :
"""Send JSON - encoded message
` msg `
JSON encoded string to send
` stats `
If set to True , will update statistics after operation completes""" | msg = bytes_to_str ( msg )
if self . _immediate_flush :
if self . handler and self . handler . active and not self . send_queue : # Send message right away
self . handler . send_pack ( 'a[%s]' % msg )
else :
if self . send_queue :
self . send_queue += ','
self . send_queue +=... |
def exists ( self ) :
"""Test , if this task has been run .""" | try :
self . es . get ( index = self . marker_index , doc_type = self . marker_doc_type , id = self . marker_index_document_id ( ) )
return True
except elasticsearch . NotFoundError :
logger . debug ( 'Marker document not found.' )
except elasticsearch . ElasticsearchException as err :
logger . warn ( e... |
def dump_df ( self , df , version = None , tags = None , ext = None , ** kwargs ) :
"""Dumps an instance of this dataset into a file .
Parameters
df : pandas . DataFrame
The dataframe to dump to file .
version : str , optional
The version of the instance of this dataset .
tags : list of str , optional
... | if ext is None :
ext = self . default_ext
fpath = self . fpath ( version = version , tags = tags , ext = ext )
fmt = SerializationFormat . by_name ( ext )
fmt . serialize ( df , fpath , ** kwargs ) |
def download_user_playlists_by_search ( self , user_name ) :
"""Download user ' s playlists by his / her name .
: params user _ name : user name .""" | try :
user = self . crawler . search_user ( user_name , self . quiet )
except RequestException as exception :
click . echo ( exception )
else :
self . download_user_playlists_by_id ( user . user_id ) |
def replacebranch1 ( idf , loop , branchname , listofcomponents_tuples , fluid = None , debugsave = False ) :
"""do I even use this ? . . . . yup ! I do""" | if fluid is None :
fluid = ''
listofcomponents_tuples = _clean_listofcomponents_tuples ( listofcomponents_tuples )
branch = idf . getobject ( 'BRANCH' , branchname )
# args are ( key , name )
listofcomponents = [ ]
for comp_type , comp_name , compnode in listofcomponents_tuples :
comp = getmakeidfobject ( idf ,... |
def get_scrollbar_value_height ( self ) :
"""Return the value span height of the scrollbar""" | vsb = self . editor . verticalScrollBar ( )
return vsb . maximum ( ) - vsb . minimum ( ) + vsb . pageStep ( ) |
def timeit ( func ) :
"""< http : / / www . zopyx . com / blog / a - python - decorator - for - measuring - the - execution - time - of - methods >""" | import time
def timed ( * args , ** kw ) :
ts = time . time ( )
result = func ( * args , ** kw )
te = time . time ( )
msg = "{0}{1} {2:.2f}s" . format ( func . __name__ , args , te - ts )
logging . debug ( msg )
return result
return timed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.