signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _build_first_tree ( self ) :
"""Build the first tree with n - 1 variable .""" | # Prim ' s algorithm
neg_tau = - 1.0 * abs ( self . tau_matrix )
X = { 0 }
while len ( X ) != self . n_nodes :
adj_set = set ( )
for x in X :
for k in range ( self . n_nodes ) :
if k not in X and k != x :
adj_set . add ( ( x , k ) )
# find edge with maximum
edge = sor... |
def _list_vlans_by_name ( self , name ) :
"""Returns a list of IDs of VLANs which match the given VLAN name .
: param string name : a VLAN name
: returns : List of matching IDs""" | results = self . list_vlans ( name = name , mask = 'id' )
return [ result [ 'id' ] for result in results ] |
def get_iex_dividends ( start = None , ** kwargs ) :
"""MOVED to iexfinance . refdata . get _ iex _ dividends""" | import warnings
warnings . warn ( WNG_MSG % ( "get_iex_dividends" , "refdata.get_iex_dividends" ) )
return Dividends ( start = start , ** kwargs ) . fetch ( ) |
def expect_column_values_to_be_dateutil_parseable ( self , column , mostly = None , result_format = None , include_config = False , catch_exceptions = None , meta = None ) :
"""Expect column entries to be parseable using dateutil .
expect _ column _ values _ to _ be _ dateutil _ parseable is a : func : ` column _... | raise NotImplementedError |
def run_with_pmids ( model_path , pmids ) :
"""Run with given list of PMIDs .""" | from indra . tools . machine . machine import run_with_pmids_helper
run_with_pmids_helper ( model_path , pmids ) |
def sizeof_fmt ( num ) :
"""Turn number of bytes into human - readable str .
Parameters
num : int
The number of bytes .
Returns
size : str
The size in human - readable format .""" | units = [ 'bytes' , 'kB' , 'MB' , 'GB' , 'TB' , 'PB' ]
decimals = [ 0 , 0 , 1 , 2 , 2 , 2 ]
if num > 1 :
exponent = min ( int ( log ( num , 1024 ) ) , len ( units ) - 1 )
quotient = float ( num ) / 1024 ** exponent
unit = units [ exponent ]
num_decimals = decimals [ exponent ]
format_string = '{0:.%... |
def static_data ( fn ) :
"""Static file handler . This functions accesses all static files in ` ` static ` `
directory .""" | file_path = os . path . normpath ( fn )
full_path = os . path . join ( STATIC_PATH , file_path )
if not os . path . exists ( full_path ) :
abort ( 404 , "Soubor '%s' neexistuje!" % fn )
return static_file ( file_path , STATIC_PATH ) |
def enq ( self , task ) :
"""Enqueues a fetch task to the pool of workers . This will raise
a RuntimeError if the pool is stopped or in the process of
stopping .
: param task : the Task object
: type task : Task or PutTask""" | if not self . _stop . is_set ( ) :
self . _inq . put ( task )
else :
raise RuntimeError ( "Attempted to enqueue an operation while " "multi pool was shutdown!" ) |
def next ( self ) :
"""Send signal to resume playback at the paused offset""" | self . _response [ 'shouldEndSession' ] = True
self . _response [ 'action' ] [ 'audio' ] [ 'interface' ] = 'next'
self . _response [ 'action' ] [ 'audio' ] [ 'sources' ] = [ ]
return self |
def wait ( self , timeout = None ) :
"""Waits for the client to stop its loop""" | self . __stopped . wait ( timeout )
return self . __stopped . is_set ( ) |
def get_network_instances ( self , name = "" ) :
"""get _ network _ instances implementation for EOS .""" | output = self . _show_vrf ( )
vrfs = { }
all_vrf_interfaces = { }
for vrf in output :
if ( vrf . get ( "route_distinguisher" , "" ) == "<not set>" or vrf . get ( "route_distinguisher" , "" ) == "None" ) :
vrf [ "route_distinguisher" ] = ""
else :
vrf [ "route_distinguisher" ] = py23_compat . tex... |
def in_hours ( self , office = None , when = None ) :
"""Finds if it is business hours in the given office .
: param office : Office ID to look up , or None to check if any office is in business hours .
: type office : str or None
: param datetime . datetime when : When to check the office is open , or None f... | if when == None :
when = datetime . now ( tz = utc )
if office == None :
for office in self . offices . itervalues ( ) :
if office . in_hours ( when ) :
return True
return False
else : # check specific office
return self . offices [ office ] . in_hours ( when ) |
def save_report ( self , name , address = True ) :
"""Save Compare report in . comp ( flat file format ) .
: param name : filename
: type name : str
: param address : flag for address return
: type address : bool
: return : saving Status as dict { " Status " : bool , " Message " : str }""" | try :
message = None
file = open ( name + ".comp" , "w" )
report = compare_report_print ( self . sorted , self . scores , self . best_name )
file . write ( report )
file . close ( )
if address :
message = os . path . join ( os . getcwd ( ) , name + ".comp" )
return { "Status" : True ... |
def to_bool ( self , value ) :
"""Converts a sheet string value to a boolean value .
Needed because of utf - 8 conversions""" | try :
value = value . lower ( )
except :
pass
try :
value = value . encode ( 'utf-8' )
except :
pass
try :
value = int ( value )
except :
pass
if value in ( 'true' , 1 ) :
return True
else :
return False |
def get_orthogonal_selection ( self , selection , out = None , fields = None ) :
"""Retrieve data by making a selection for each dimension of the array . For
example , if an array has 2 dimensions , allows selecting specific rows and / or
columns . The selection for each dimension can be either an integer ( ind... | # refresh metadata
if not self . _cache_metadata :
self . _load_metadata ( )
# check args
check_fields ( fields , self . _dtype )
# setup indexer
indexer = OrthogonalIndexer ( selection , self )
return self . _get_selection ( indexer = indexer , out = out , fields = fields ) |
def update_firmware ( node ) :
"""Performs SUM based firmware update on the node .
This method performs SUM firmware update by mounting the
SPP ISO on the node . It performs firmware update on all or
some of the firmware components .
: param node : A node object of type dict .
: returns : Operation Status... | sum_update_iso = node [ 'clean_step' ] [ 'args' ] . get ( 'url' )
# Validates the http image reference for SUM update ISO .
try :
utils . validate_href ( sum_update_iso )
except exception . ImageRefValidationFailed as e :
raise exception . SUMOperationError ( reason = e )
# Ejects the CDROM device in the iLO an... |
def text_pb ( tag , data , description = None ) :
"""Create a text tf . Summary protobuf .
Arguments :
tag : String tag for the summary .
data : A Python bytestring ( of type bytes ) , a Unicode string , or a numpy data
array of those types .
description : Optional long - form description for this summary... | try :
tensor = tensor_util . make_tensor_proto ( data , dtype = np . object )
except TypeError as e :
raise TypeError ( 'tensor must be of type string' , e )
summary_metadata = metadata . create_summary_metadata ( display_name = None , description = description )
summary = summary_pb2 . Summary ( )
summary . va... |
def additions_install ( ** kwargs ) :
'''Install VirtualBox Guest Additions . Uses the CD , connected by VirtualBox .
To connect VirtualBox Guest Additions via VirtualBox graphical interface
press ' Host + D ' ( ' Host ' is usually ' Right Ctrl ' ) .
See https : / / www . virtualbox . org / manual / ch04 . ht... | with _additions_mounted ( ) as mount_point :
kernel = __grains__ . get ( 'kernel' , '' )
if kernel == 'Linux' :
return _additions_install_linux ( mount_point , ** kwargs ) |
def _ParseTimestamp ( self , parser_mediator , row ) :
"""Provides a timestamp for the given row .
If the Trend Micro log comes from a version that provides a POSIX timestamp ,
use that directly ; it provides the advantages of UTC and of second
precision . Otherwise fall back onto the local - timezone date an... | timestamp = row . get ( 'timestamp' , None )
if timestamp is not None :
try :
timestamp = int ( timestamp , 10 )
except ( ValueError , TypeError ) :
parser_mediator . ProduceExtractionWarning ( 'Unable to parse timestamp value: {0!s}' . format ( timestamp ) )
return dfdatetime_posix_time . P... |
def is_presence_handler ( type_ , from_ , cb ) :
"""Deprecated alias of : func : ` . dispatcher . is _ presence _ handler ` .
. . deprecated : : 0.9""" | import aioxmpp . dispatcher
return aioxmpp . dispatcher . is_presence_handler ( type_ , from_ , cb ) |
def write_bits ( self , * args ) :
'''Write multiple bits in a single byte field . The bits will be written in
little - endian order , but should be supplied in big endian order . Will
raise ValueError when more than 8 arguments are supplied .
write _ bits ( True , False ) = > 0x02''' | # Would be nice to make this a bit smarter
if len ( args ) > 8 :
raise ValueError ( "Can only write 8 bits at a time" )
self . _output_buffer . append ( chr ( reduce ( lambda x , y : xor ( x , args [ y ] << y ) , xrange ( len ( args ) ) , 0 ) ) )
return self |
def RemoveScanNode ( self , path_spec ) :
"""Removes a scan node of a certain path specification .
Args :
path _ spec ( PathSpec ) : path specification .
Returns :
SourceScanNode : parent scan node or None if not available .
Raises :
RuntimeError : if the scan node has sub nodes .""" | scan_node = self . _scan_nodes . get ( path_spec , None )
if not scan_node :
return None
if scan_node . sub_nodes :
raise RuntimeError ( 'Scan node has sub nodes.' )
parent_scan_node = scan_node . parent_node
if parent_scan_node :
parent_scan_node . sub_nodes . remove ( scan_node )
if path_spec == self . _r... |
def can_query_state_for_block ( self , block_identifier : BlockSpecification ) -> bool :
"""Returns if the provided block identifier is safe enough to query chain
state for . If it ' s close to the state pruning blocks then state should
not be queried .
More info : https : / / github . com / raiden - network ... | latest_block_number = self . block_number ( )
preconditions_block = self . web3 . eth . getBlock ( block_identifier )
preconditions_block_number = int ( preconditions_block [ 'number' ] )
difference = latest_block_number - preconditions_block_number
return difference < constants . NO_STATE_QUERY_AFTER_BLOCKS |
def setup_parser ( sub_parsers ) :
"""Sets up the command line parser for the * run * subprogram and adds it to * sub _ parsers * .""" | parser = sub_parsers . add_parser ( "run" , prog = "law run" , description = "Run a task with" " configurable parameters. See http://luigi.rtfd.io/en/stable/running_luigi.html for more" " info." )
parser . add_argument ( "task_family" , help = "a task family registered in the task database file or" " a module and task ... |
def collect_completions ( self , active_parsers , parsed_args , cword_prefix , debug ) :
"""Visits the active parsers and their actions , executes their completers or introspects them to collect their
option strings . Returns the resulting completions as a list of strings .
This method is exposed for overriding... | completions = [ ]
debug ( "all active parsers:" , active_parsers )
active_parser = active_parsers [ - 1 ]
debug ( "active_parser:" , active_parser )
if self . always_complete_options or ( len ( cword_prefix ) > 0 and cword_prefix [ 0 ] in active_parser . prefix_chars ) :
completions += self . _get_option_completion... |
def rollback_savepoint ( self , savepoint ) :
"""Rolls back to the given savepoint .
: param savepoint : the name of the savepoint to rollback to
: raise : pydbal . exception . DBALConnectionError""" | if not self . _platform . is_savepoints_supported ( ) :
raise DBALConnectionError . savepoints_not_supported ( )
self . ensure_connected ( )
self . _platform . rollback_savepoint ( savepoint ) |
def get_pr_checks ( pr : PullRequestDetails ) -> Dict [ str , Any ] :
"""References :
https : / / developer . github . com / v3 / checks / runs / # list - check - runs - for - a - specific - ref""" | url = ( "https://api.github.com/repos/{}/{}/commits/{}/check-runs" "?access_token={}" . format ( pr . repo . organization , pr . repo . name , pr . branch_sha , pr . repo . access_token ) )
response = requests . get ( url , headers = { 'Accept' : 'application/vnd.github.antiope-preview+json' } )
if response . status_co... |
def flush ( self , * args , ** kwgs ) :
"""Before ` RequestHandler . flush ` was called , we got the final _ write _ buffer .
This method will not be called in wsgi mode""" | if settings [ 'LOG_RESPONSE' ] and not self . _status_code == 500 :
log_response ( self )
super ( BaseHandler , self ) . flush ( * args , ** kwgs ) |
def phone_text_subs ( ) :
"""Gets a dictionary of dictionaries that each contain alphabetic number manifestations mapped to their actual
Number value .
Returns :
dictionary of dictionaries containing Strings mapped to Numbers""" | Small = { 'zero' : 0 , 'zer0' : 0 , 'one' : 1 , 'two' : 2 , 'three' : 3 , 'four' : 4 , 'fuor' : 4 , 'five' : 5 , 'fith' : 5 , 'six' : 6 , 'seven' : 7 , 'sven' : 7 , 'eight' : 8 , 'nine' : 9 , 'ten' : 10 , 'eleven' : 11 , 'twelve' : 12 , 'thirteen' : 13 , 'fourteen' : 14 , 'fifteen' : 15 , 'sixteen' : 16 , 'seventeen' :... |
def lru_cache ( maxsize = 128 , key_fn = None ) :
"""Decorator that adds an LRU cache of size maxsize to the decorated function .
maxsize is the number of different keys cache can accomodate .
key _ fn is the function that builds key from args . The default key function
creates a tuple out of args and kwargs ... | def decorator ( fn ) :
cache = LRUCache ( maxsize )
argspec = inspect2 . getfullargspec ( fn )
arg_names = argspec . args [ 1 : ] + argspec . kwonlyargs
# remove self
kwargs_defaults = get_kwargs_defaults ( argspec )
cache_key = key_fn
if cache_key is None :
def cache_key ( args , kw... |
def mfpt ( totflux , pi , qminus ) :
r"""Mean first passage time for reaction A to B .
Parameters
totflux : float
The total flux between reactant and product
pi : ( M , ) ndarray
Stationary distribution
qminus : ( M , ) ndarray
Backward comittor
Returns
tAB : float
The mean first - passage time ... | return dense . tpt . mfpt ( totflux , pi , qminus ) |
def nanvar ( values , axis = None , skipna = True , ddof = 1 , mask = None ) :
"""Compute the variance along given axis while ignoring NaNs
Parameters
values : ndarray
axis : int , optional
skipna : bool , default True
ddof : int , default 1
Delta Degrees of Freedom . The divisor used in calculations is... | values = com . values_from_object ( values )
dtype = values . dtype
if mask is None :
mask = isna ( values )
if is_any_int_dtype ( values ) :
values = values . astype ( 'f8' )
values [ mask ] = np . nan
if is_float_dtype ( values ) :
count , d = _get_counts_nanvar ( mask , axis , ddof , values . dtype )... |
def download_file ( self , file_path , range = None ) :
"""Download a file from Telegram servers""" | headers = { "range" : range } if range else None
url = "{0}/file/bot{1}/{2}" . format ( API_URL , self . api_token , file_path )
return self . session . get ( url , headers = headers , proxy = self . proxy , proxy_auth = self . proxy_auth ) |
def text_to_edtf_date ( text ) :
"""Return EDTF string equivalent of a given natural language date string .
The approach here is to parse the text twice , with different default
dates . Then compare the results to see what differs - the parts that
differ are undefined .""" | if not text :
return
t = text . lower ( )
result = ''
for reject_re in REJECT_RULES :
if re . match ( reject_re , t ) :
return
# matches on ' 1800s ' . Needs to happen before is _ decade .
could_be_century = re . findall ( r'(\d{2}00)s' , t )
# matches on ' 1800s ' and ' 1910s ' . Removes the ' s ' .
# ... |
def save_data ( self ) :
"""Save data""" | title = _ ( "Save profiler result" )
filename , _selfilter = getsavefilename ( self , title , getcwd_or_home ( ) , _ ( "Profiler result" ) + " (*.Result)" )
if filename :
self . datatree . save_data ( filename ) |
def to_capabilities ( self ) :
"""Marshals the IE options to the correct object .""" | caps = self . _caps
opts = self . _options . copy ( )
if len ( self . _arguments ) > 0 :
opts [ self . SWITCHES ] = ' ' . join ( self . _arguments )
if len ( self . _additional ) > 0 :
opts . update ( self . _additional )
if len ( opts ) > 0 :
caps [ Options . KEY ] = opts
return caps |
def getRawReportDescriptor ( self ) :
"""Return a binary string containing the raw HID report descriptor .""" | descriptor = _hidraw_report_descriptor ( )
size = ctypes . c_uint ( )
self . _ioctl ( _HIDIOCGRDESCSIZE , size , True )
descriptor . size = size
self . _ioctl ( _HIDIOCGRDESC , descriptor , True )
return '' . join ( chr ( x ) for x in descriptor . value [ : size . value ] ) |
def format_errors ( self , errors , many ) :
"""Format validation errors as JSON Error objects .""" | if not errors :
return { }
if isinstance ( errors , ( list , tuple ) ) :
return { 'errors' : errors }
formatted_errors = [ ]
if many :
for index , errors in iteritems ( errors ) :
for field_name , field_errors in iteritems ( errors ) :
formatted_errors . extend ( [ self . format_error ( ... |
def _delete_from_hdx ( self , object_type , id_field_name ) : # type : ( str , str ) - > None
"""Helper method to deletes a resource from HDX
Args :
object _ type ( str ) : Description of HDX object type ( for messages )
id _ field _ name ( str ) : Name of field containing HDX object identifier
Returns :
... | if id_field_name not in self . data :
raise HDXError ( 'No %s field (mandatory) in %s!' % ( id_field_name , object_type ) )
self . _save_to_hdx ( 'delete' , id_field_name ) |
def batch_taxids ( list_of_names ) :
"""Opposite of batch _ taxonomy ( ) :
Convert list of Latin names to taxids""" | for name in list_of_names :
handle = Entrez . esearch ( db = 'Taxonomy' , term = name , retmode = "xml" )
records = Entrez . read ( handle )
yield records [ "IdList" ] [ 0 ] |
def get_template ( self ) :
"""读取一个Excel模板 , 将此Excel的所有行读出来 , 并且识别特殊的标记进行记录
: return : 返回读取后的模板 , 结果类似 :
{ ' cols ' : # 各列 , 与subs不会同时生效
' subs ' : [ # 子模板
{ ' cols ' : # 各列 ,
' subs ' : # 子模板
' field ' : # 对应数据中字段名称
' field ' : # 对应数据中字段名称
子模板的判断根据第一列是否为 { { for field } } 来判断 , 结束使用 { { end } }""" | rows = [ ]
stack = [ ]
stack . append ( rows )
# top用来记录当前栈
top = rows
for i in range ( 1 , self . sheet . max_row + 1 ) :
cell = self . sheet . cell ( row = i , column = 1 )
# 是否子模板开始
if ( isinstance ( cell . value , ( str , unicode ) ) and cell . value . startswith ( '{{for ' ) and cell . value . endswith... |
def REV ( self , params ) :
"""REV Ra , Rb
Reverse the byte order in register Rb and store the result in Ra""" | Ra , Rb = self . get_two_parameters ( self . TWO_PARAMETER_COMMA_SEPARATED , params )
self . check_arguments ( low_registers = ( Ra , Rb ) )
def REV_func ( ) :
self . register [ Ra ] = ( ( self . register [ Rb ] & 0xFF000000 ) >> 24 ) | ( ( self . register [ Rb ] & 0x00FF0000 ) >> 8 ) | ( ( self . register [ Rb ] &... |
def set_alpha ( self , alpha ) :
"""Set alpha / last value on all four lighting attributes .""" | self . transparency = alpha
self . diffuse [ 3 ] = alpha
self . ambient [ 3 ] = alpha
self . specular [ 3 ] = alpha
self . emissive [ 3 ] = alpha |
def json_2_injector_gear ( json_obj ) :
"""transform the JSON return by Ariane server to local object
: param json _ obj : the JSON returned by Ariane server
: return : a new InjectorCachedGear""" | LOGGER . debug ( "InjectorCachedGear.json_2_injector_gear" )
return InjectorCachedGear ( gear_id = json_obj [ 'gearId' ] , gear_name = json_obj [ 'gearName' ] , gear_description = json_obj [ 'gearDescription' ] , gear_admin_queue = json_obj [ 'gearAdminQueue' ] , running = json_obj [ 'running' ] ) |
def innerHTML ( self ) -> str :
"""Get innerHTML of the inner node .""" | if self . _inner_element :
return self . _inner_element . innerHTML
return super ( ) . innerHTML |
def get_OS_UUID ( cls , os ) :
"""Validate Storage OS and its UUID .
If the OS is a custom OS UUID , don ' t validate against templates .""" | if os in cls . templates :
return cls . templates [ os ]
uuid_regexp = '^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$'
if re . search ( uuid_regexp , os ) :
return os
raise Exception ( ( "Invalid OS -- valid options are: 'CentOS 6.5', 'CentOS 7.0', " "'Debian 7.8', 'Debian 8.0' ,'Ubuntu 12.04',... |
def template ( self , key ) :
"""Returns the template associated with this scaffold .
: param key | < str >
: return < projex . scaffold . Template > | | None""" | try :
return self . _templates [ key ]
except KeyError :
return Template . Plugins [ key ] |
def escape_header ( val ) :
"""Escapes a value so that it can be used in a mime header""" | if val is None :
return None
try :
return quote ( val , encoding = "ascii" , safe = "/ " )
except ValueError :
return "utf-8''" + quote ( val , encoding = "utf-8" , safe = "/ " ) |
def _read_parquet_columns ( path , columns , num_splits , kwargs ) : # pragma : no cover
"""Use a Ray task to read columns from Parquet into a Pandas DataFrame .
Note : Ray functions are not detected by codecov ( thus pragma : no cover )
Args :
path : The path of the Parquet file .
columns : The list of col... | import pyarrow . parquet as pq
df = pq . read_pandas ( path , columns = columns , ** kwargs ) . to_pandas ( )
# Append the length of the index here to build it externally
return _split_result_for_readers ( 0 , num_splits , df ) + [ len ( df . index ) ] |
def _effective_view_filter ( self ) :
"""Returns the mongodb relationship filter for effective views""" | if self . _effective_view == EFFECTIVE :
now = datetime . datetime . utcnow ( )
return { 'startDate' : { '$$lte' : now } , 'endDate' : { '$$gte' : now } }
return { } |
def alignment ( job , ids , input_args , sample ) :
"""Runs BWA and then Bamsort on the supplied fastqs for this sample
Input1 : Toil Job instance
Input2 : jobstore id dictionary
Input3 : Input arguments dictionary
Input4 : Sample tuple - - contains uuid and urls for the sample""" | uuid , urls = sample
# ids [ ' bam ' ] = job . fileStore . getEmptyFileStoreID ( )
work_dir = job . fileStore . getLocalTempDir ( )
output_dir = input_args [ 'output_dir' ]
key_path = input_args [ 'ssec' ]
cores = multiprocessing . cpu_count ( )
# I / O
return_input_paths ( job , work_dir , ids , 'ref.fa' , 'ref.fa.amb... |
def get_default_for ( prop , value ) :
"""Ensures complex property types have the correct default values""" | prop = prop . strip ( '_' )
# Handle alternate props ( leading underscores )
val = reduce_value ( value )
# Filtering of value happens here
if prop in _COMPLEX_LISTS :
return wrap_value ( val )
elif prop in _COMPLEX_STRUCTS :
return val or { }
else :
return u'' if val is None else val |
def get_project_root ( ) :
"""Get the project root folder as a string .""" | cfg = get_project_configuration ( )
# At this point it can be sure that the configuration file exists
# Now make sure the project structure exists
for dirname in [ "raw-datasets" , "preprocessed" , "feature-files" , "models" , "reports" ] :
directory = os . path . join ( cfg [ 'root' ] , dirname )
if not os . p... |
def run ( self ) :
'''Runs the NIfTI conversion based on internal state .''' | self . _log ( 'About to perform NifTI to %s conversion...\n' % self . _str_outputFileType )
frames = 1
frameStart = 0
frameEnd = 0
sliceStart = 0
sliceEnd = 0
if self . _b_4D :
self . _log ( '4D volume detected.\n' )
frames = self . _Vnp_4DVol . shape [ 3 ]
if self . _b_3D :
self . _log ( '3D volume detecte... |
def _parse_node ( graph , text , condition_node_params , leaf_node_params ) :
"""parse dumped node""" | match = _NODEPAT . match ( text )
if match is not None :
node = match . group ( 1 )
graph . node ( node , label = match . group ( 2 ) , ** condition_node_params )
return node
match = _LEAFPAT . match ( text )
if match is not None :
node = match . group ( 1 )
graph . node ( node , label = match . gro... |
def remove_agent ( self , agent : GUIAgent ) :
"""Removes the given agent .
: param agent : the agent to remove
: return :""" | self . index_manager . free_index ( agent . overall_index )
self . agents . remove ( agent )
self . update_teams_listwidgets ( )
self . overall_config . set_value ( MATCH_CONFIGURATION_HEADER , PARTICIPANT_COUNT_KEY , len ( self . agents ) )
self . overall_config . set_value ( PARTICIPANT_CONFIGURATION_HEADER , PARTICI... |
def write_file ( data , outfilename ) :
"""Write a single file to disk .""" | if not data :
return False
try :
with open ( outfilename , 'w' ) as outfile :
for line in data :
if line :
outfile . write ( line )
return True
except ( OSError , IOError ) as err :
sys . stderr . write ( 'An error occurred while writing {0}:\n{1}' . format ( outfilen... |
def to_int ( x , index = False ) :
"""Formatting series or timeseries columns to int and checking validity .
If ` index = False ` , the function works on the ` pd . Series x ` ; else ,
the function casts the index of ` x ` to int and returns x with a new index .""" | _x = x . index if index else x
cols = list ( map ( int , _x ) )
error = _x [ cols != _x ]
if not error . empty :
raise ValueError ( 'invalid values `{}`' . format ( list ( error ) ) )
if index :
x . index = cols
return x
else :
return _x |
def range_depth ( ranges , size , verbose = True ) :
"""Overlay ranges on [ start , end ] , and summarize the ploidy of the intervals .""" | from jcvi . utils . iter import pairwise
from jcvi . utils . cbook import percentage
# Make endpoints
endpoints = [ ]
for a , b in ranges :
endpoints . append ( ( a , LEFT ) )
endpoints . append ( ( b , RIGHT ) )
endpoints . sort ( )
vstart , vend = min ( endpoints ) [ 0 ] , max ( endpoints ) [ 0 ]
assert 0 <= ... |
def recover ( self , runAsync = False ) :
"""If the shared configuration store for a site is unavailable , a site
in read - only mode will operate in a degraded capacity that allows
access to the ArcGIS Server Administrator Directory . You can recover
a site if the shared configuration store is permanently lo... | url = self . _url + "/recover"
params = { "f" : "json" , "runAsync" : runAsync }
return self . _post ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) |
def range_yearly ( start = None , stop = None , timezone = 'UTC' , count = None ) :
"""This an alternative way to generating sets of Delorean objects with
YEARLY stops""" | return stops ( start = start , stop = stop , freq = YEARLY , timezone = timezone , count = count ) |
def toxml ( self ) :
"""Exports this object into a LEMS XML object""" | return '<With ' + ( ' instance="{0}"' . format ( self . instance ) if self . instance else '' ) + ( ' list="{0}"' . format ( self . list ) if self . list else '' ) + ( ' index="{0}"' . format ( self . index ) if self . index else '' ) + ' as="{1}"/>' . format ( self . instance , self . as_ ) |
def users_getPresence ( self , * , user : str , ** kwargs ) -> SlackResponse :
"""Gets user presence information .
Args :
user ( str ) : User to get presence info on . Defaults to the authed user .
e . g . ' W1234567890'""" | kwargs . update ( { "user" : user } )
return self . api_call ( "users.getPresence" , http_verb = "GET" , params = kwargs ) |
def _next_unit_in_service ( service , placed_in_services ) :
"""Return the unit number where to place a unit placed on a service .
Receive the service name and a dict mapping service names to the current
number of placed units in that service .""" | current = placed_in_services . get ( service )
number = 0 if current is None else current + 1
placed_in_services [ service ] = number
return number |
def _consent_registration ( self , consent_args ) :
"""Register a request at the consent service
: type consent _ args : dict
: rtype : str
: param consent _ args : All necessary parameters for the consent request
: return : Ticket received from the consent service""" | jws = JWS ( json . dumps ( consent_args ) , alg = self . signing_key . alg ) . sign_compact ( [ self . signing_key ] )
request = "{}/creq/{}" . format ( self . api_url , jws )
res = requests . get ( request )
if res . status_code != 200 :
raise UnexpectedResponseError ( "Consent service error: %s %s" , res . status... |
def get_credentials ( ) :
"""Gets valid user credentials from storage .
If nothing has been stored , or if the stored credentials are invalid ,
the OAuth2 flow is completed to obtain the new credentials .
Returns :
Credentials , the obtained credential .""" | home_dir = os . path . expanduser ( '~' )
credential_dir = os . path . join ( home_dir , '.credentials' )
if not os . path . exists ( credential_dir ) :
os . makedirs ( credential_dir )
credential_path = os . path . join ( credential_dir , 'calendar-python-quickstart.json' )
store = Storage ( credential_path )
cred... |
def url_api_version ( self , api_version ) :
"""Return base API url string for the QualysGuard api _ version and server .""" | # Set base url depending on API version .
if api_version == 1 : # QualysGuard API v1 url .
url = "https://%s/msp/" % ( self . server , )
elif api_version == 2 : # QualysGuard API v2 url .
url = "https://%s/" % ( self . server , )
elif api_version == 'was' : # QualysGuard REST v3 API url ( Portal API ) .
url... |
def get_added_obs_importance ( self , obslist_dict = None , base_obslist = None , reset_zero_weight = False ) :
"""get a dataframe fo the posterior uncertainty
as a results of added some observations
Parameters
obslist _ dict : dict
a nested dictionary - list of groups of observations
that are to be treat... | if obslist_dict is not None :
if type ( obslist_dict ) == list :
obslist_dict = dict ( zip ( obslist_dict , obslist_dict ) )
reset = False
if reset_zero_weight is not False :
if not self . obscov . isdiagonal :
raise NotImplementedError ( "cannot reset weights for non-" + "diagonal obscov" )
... |
def main ( cls , args , settings = None , userdata = None ) : # pylint : disable = too - many - branches , too - many - statements
"""Main entry point of this module .""" | # The command - line client uses Service Account authentication .
logger . info ( 'Using Compute Engine credentials from %s' , Focus . info ( args . conf . name ) )
try :
key = json . loads ( args . conf . read ( ) )
except ValueError as msg :
logger . error ( 'Unable to parse %s: %s' , args . conf . name , msg... |
def generate_ctrlpts_weights ( ctrlpts ) :
"""Generates unweighted control points from weighted ones in 1 - D .
This function
# . Takes in 1 - D control points list whose coordinates are organized in ( x * w , y * w , z * w , w ) format
# . Converts the input control points list into ( x , y , z , w ) format ... | # Divide control points by weight
new_ctrlpts = [ ]
for cpt in ctrlpts :
temp = [ float ( pt / cpt [ - 1 ] ) for pt in cpt ]
temp [ - 1 ] = float ( cpt [ - 1 ] )
new_ctrlpts . append ( temp )
return new_ctrlpts |
def registerFilters ( self , ** kwargs ) :
"""Register multiple filters at once .
@ param * * kwargs : Multiple filters are registered using keyword
variables . Each keyword must correspond to a field name
with an optional suffix :
field : Field equal to value or in list of
values .
field _ ic : Field e... | for ( key , patterns ) in kwargs . items ( ) :
if key . endswith ( '_regex' ) :
col = key [ : - len ( '_regex' ) ]
is_regex = True
else :
col = key
is_regex = False
if col . endswith ( '_ic' ) :
col = col [ : - len ( '_ic' ) ]
ignore_case = True
else :
... |
def read_event ( self , check_result ) :
'''Convert the piped check result ( json ) into a global ' event ' dict''' | try :
event = json . loads ( check_result )
event [ 'occurrences' ] = event . get ( 'occurrences' , 1 )
event [ 'check' ] = event . get ( 'check' , { } )
event [ 'client' ] = event . get ( 'client' , { } )
return event
except Exception :
raise ValueError ( 'error reading event: ' + check_result ... |
def htmlentityreplace_errors ( ex ) :
"""An encoding error handler .
This python ` codecs ` _ error handler replaces unencodable
characters with HTML entities , or , if no HTML entity exists for
the character , XML character references .
> > > u ' The cost was \u20ac 12 . ' . encode ( ' latin1 ' , ' htmlent... | if isinstance ( ex , UnicodeEncodeError ) : # Handle encoding errors
bad_text = ex . object [ ex . start : ex . end ]
text = _html_entities_escaper . escape ( bad_text )
return ( compat . text_type ( text ) , ex . end )
raise ex |
def _runParasol ( self , command , autoRetry = True ) :
"""Issues a parasol command using popen to capture the output . If the command fails then it
will try pinging parasol until it gets a response . When it gets a response it will
recursively call the issue parasol command , repeating this pattern for a maxim... | command = list ( concat ( self . parasolCommand , command ) )
while True :
logger . debug ( 'Running %r' , command )
process = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE , bufsize = - 1 )
stdout , stderr = process . communicate ( )
status = process . wait ( )
... |
def serialize_numeric ( self , tag ) :
"""Return the literal representation of a numeric tag .""" | str_func = int . __str__ if isinstance ( tag , int ) else float . __str__
return str_func ( tag ) + tag . suffix |
def update_user_groups ( self , user , claims ) :
"""Updates user group memberships based on the GROUPS _ CLAIM setting .
Args :
user ( django . contrib . auth . models . User ) : User model instance
claims ( dict ) : Claims from the access token""" | if settings . GROUPS_CLAIM is not None : # Update the user ' s group memberships
django_groups = [ group . name for group in user . groups . all ( ) ]
if settings . GROUPS_CLAIM in claims :
claim_groups = claims [ settings . GROUPS_CLAIM ]
if not isinstance ( claim_groups , list ) :
... |
def stop_capture_coordinates ( self ) :
"""Exit the coordinate capture mode .""" | self . extent_dialog . _populate_coordinates ( )
self . extent_dialog . canvas . setMapTool ( self . extent_dialog . previous_map_tool )
self . parent . show ( ) |
def encrypt_to_file ( contents , filename ) :
"""Encrypts ` ` contents ` ` and writes it to ` ` filename ` ` .
` ` contents ` ` should be a bytes string . ` ` filename ` ` should end with
` ` . enc ` ` .
Returns the secret key used for the encryption .
Decrypt the file with : func : ` doctr . travis . decry... | if not filename . endswith ( '.enc' ) :
raise ValueError ( "%s does not end with .enc" % filename )
key = Fernet . generate_key ( )
fer = Fernet ( key )
encrypted_file = fer . encrypt ( contents )
with open ( filename , 'wb' ) as f :
f . write ( encrypted_file )
return key |
def merge_rootnodes ( self , other_docgraph ) :
"""Copy all the metadata from the root node of the other graph into this
one . Then , move all edges belonging to the other root node to this
one . Finally , remove the root node of the other graph from this one .""" | # copy metadata from other graph , cf . # 136
if 'metadata' in other_docgraph . node [ other_docgraph . root ] :
other_meta = other_docgraph . node [ other_docgraph . root ] [ 'metadata' ]
self . node [ self . root ] [ 'metadata' ] . update ( other_meta )
assert not other_docgraph . in_edges ( other_docgraph . ... |
def referenced ( self ) :
"""For a cursor that is a reference , returns a cursor
representing the entity that it references .""" | if not hasattr ( self , '_referenced' ) :
self . _referenced = conf . lib . clang_getCursorReferenced ( self )
return self . _referenced |
def update_slaves ( self ) :
"""Update all ` slave ` | Substituter | objects .
See method | Substituter . update _ masters | for further information .""" | for slave in self . slaves :
slave . _medium2long . update ( self . _medium2long )
slave . update_slaves ( ) |
def create_post ( self , post_type , post_folders , post_subject , post_content , is_announcement = 0 , bypass_email = 0 , anonymous = False ) :
"""Create a post
It seems like if the post has ` < p > ` tags , then it ' s treated as HTML ,
but is treated as text otherwise . You ' ll want to provide ` content `
... | params = { "anonymous" : "yes" if anonymous else "no" , "subject" : post_subject , "content" : post_content , "folders" : post_folders , "type" : post_type , "config" : { "bypass_email" : bypass_email , "is_announcement" : is_announcement } }
return self . _rpc . content_create ( params ) |
def variantAnnotationsGenerator ( self , request ) :
"""Returns a generator over the ( variantAnnotaitons , nextPageToken ) pairs
defined by the specified request .""" | compoundId = datamodel . VariantAnnotationSetCompoundId . parse ( request . variant_annotation_set_id )
dataset = self . getDataRepository ( ) . getDataset ( compoundId . dataset_id )
variantSet = dataset . getVariantSet ( compoundId . variant_set_id )
variantAnnotationSet = variantSet . getVariantAnnotationSet ( reque... |
def sync_files ( self , dataset_key ) :
"""Trigger synchronization process to update all dataset files linked to
source URLs .
: param dataset _ key : Dataset identifier , in the form of owner / id
: type dataset _ key : str
: raises RestApiException : If a server error occurs
Examples
> > > import data... | try :
self . _datasets_api . sync ( * ( parse_dataset_key ( dataset_key ) ) )
except _swagger . rest . ApiException as e :
raise RestApiError ( cause = e ) |
def extract_all_snow_tweets_from_disk_generator ( json_folder_path ) :
"""A generator that returns all SNOW tweets stored in disk .
Input : - json _ file _ path : The path of the folder containing the raw data .
Yields : - tweet : A tweet in python dictionary ( json ) format .""" | # Get a generator with all file paths in the folder
json_file_path_generator = ( json_folder_path + "/" + name for name in os . listdir ( json_folder_path ) )
for path in json_file_path_generator :
for tweet in extract_snow_tweets_from_file_generator ( path ) :
yield tweet |
def index ( self , item ) :
"""Finds the child index of a given item , searchs in added order .""" | index_at = None
for ( i , child ) in enumerate ( self . _children ) :
if child . item == item :
index_at = i
break
if index_at is None :
raise ValueError ( "%s is not contained in any child" % ( item ) )
return index_at |
def mute ( self ) :
"""bool : The speaker ' s mute state .
True if muted , False otherwise .""" | response = self . renderingControl . GetMute ( [ ( 'InstanceID' , 0 ) , ( 'Channel' , 'Master' ) ] )
mute_state = response [ 'CurrentMute' ]
return True if int ( mute_state ) else False |
def system ( self ) :
"""Creates a reference to the System operations for Portal""" | url = self . _url + "/system"
return _System ( url = url , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) |
def extract_paths ( self , paths , * args , ** kwargs ) :
"""Thin method that just uses the provider""" | return self . provider . extract_paths ( paths , * args , ** kwargs ) |
def check_schema_transforms_match ( schema , inverted_features ) :
"""Checks that the transform and schema do not conflict .
Args :
schema : schema list
inverted _ features : inverted _ features dict
Raises :
ValueError if transform cannot be applied given schema type .""" | num_target_transforms = 0
for col_schema in schema :
col_name = col_schema [ 'name' ]
col_type = col_schema [ 'type' ] . lower ( )
# Check each transform and schema are compatible
if col_name in inverted_features :
for transform in inverted_features [ col_name ] :
transform_name = tr... |
def project_name_changed ( self , widget , data = None ) :
"""Function controls whether run button is enabled""" | if widget . get_text ( ) != "" :
self . run_btn . set_sensitive ( True )
else :
self . run_btn . set_sensitive ( False )
self . update_full_label ( ) |
def create ( self , req , parent , name , mode , fi ) :
"""Create and open a file
Valid replies :
reply _ create
reply _ err""" | self . reply_err ( req , errno . ENOSYS ) |
def trace ( line ) :
"""Usage : % trace ( enable | disable ) [ file pattern ] [ output path ]""" | args = line . split ( )
enable = args [ 0 ] in { 'enable' , 'on' }
if not enable :
sys . settrace ( None )
sys . stdout = _ORIGINAL_STDOUT
return
pattern = args [ 1 ] if len ( args ) > 1 else None
sys . stdout = open ( args [ 2 ] , 'a' ) if len ( args ) > 2 else sys . stdout
sys . settrace ( partial ( trace... |
def get_string ( self , recalculate_width = True ) :
"""Get the table as a String .
Parameters
recalculate _ width : bool , optional
If width for each column should be recalculated ( default True ) .
Note that width is always calculated if it wasn ' t set
explicitly when this method is called for the firs... | # Empty table . returning empty string .
if len ( self . _table ) == 0 :
return ''
if self . serialno and self . column_count > 0 :
self . insert_column ( 0 , self . serialno_header , range ( 1 , len ( self ) + 1 ) )
# Should widths of column be recalculated
if recalculate_width or sum ( self . _column_widths )... |
def is_ccw ( points ) :
"""Check if connected planar points are counterclockwise .
Parameters
points : ( n , 2 ) float , connected points on a plane
Returns
ccw : bool , True if points are counterclockwise""" | points = np . asanyarray ( points , dtype = np . float64 )
if ( len ( points . shape ) != 2 or points . shape [ 1 ] != 2 ) :
raise ValueError ( 'CCW is only defined for 2D' )
xd = np . diff ( points [ : , 0 ] )
yd = np . column_stack ( ( points [ : , 1 ] , points [ : , 1 ] ) ) . reshape ( - 1 ) [ 1 : - 1 ] . reshap... |
def thumbnail ( self , value ) :
"""gets / sets the thumbnail
Enter the pathname to the thumbnail image to be used for the item .
The recommended image size is 200 pixels wide by 133 pixels high .
Acceptable image formats are PNG , GIF , and JPEG . The maximum file
size for an image is 1 MB . This is not a ... | if os . path . isfile ( value ) and self . _thumbnail != value :
self . _thumbnail = value
elif value is None :
self . _thumbnail = None |
def _build_gene_disease_model ( self , gene_id , relation_id , disease_id , variant_label , consequence_predicate = None , consequence_id = None , allelic_requirement = None , pmids = None ) :
"""Builds gene variant disease model
: return : None""" | model = Model ( self . graph )
geno = Genotype ( self . graph )
pmids = [ ] if pmids is None else pmids
is_variant = False
variant_or_gene = gene_id
variant_id_string = variant_label
variant_bnode = self . make_id ( variant_id_string , "_" )
if consequence_predicate is not None and consequence_id is not None :
is_v... |
def getBigIndexFromIndices ( self , indices ) :
"""Get the big index from a given set of indices
@ param indices
@ return big index
@ note no checks are performed to ensure that the returned
indices are valid""" | return reduce ( operator . add , [ self . dimProd [ i ] * indices [ i ] for i in range ( self . ndims ) ] , 0 ) |
def mask_raster ( in_raster , mask , out_raster ) :
"""Mask raster data .
Args :
in _ raster : list or one raster
mask : Mask raster data
out _ raster : list or one raster""" | if is_string ( in_raster ) and is_string ( out_raster ) :
in_raster = [ str ( in_raster ) ]
out_raster = [ str ( out_raster ) ]
if len ( in_raster ) != len ( out_raster ) :
raise RuntimeError ( 'input raster and output raster must have the same size.' )
maskr = RasterUtilClass . read_raster ( mask )
rows = ... |
def build_command ( command , parameter_map ) :
"""Build command line ( s ) using the given parameter map .
Even if the passed a single ` command ` , this function will return a list
of shell commands . It is the caller ' s responsibility to concatenate them ,
likely using the semicolon or double ampersands .... | if isinstance ( parameter_map , list ) : # Partially emulate old ( pre - 0.7 ) API for this function .
parameter_map = LegacyParameterMap ( parameter_map )
out_commands = [ ]
for command in listify ( command ) : # Only attempt formatting if the string smells like it should be formatted .
# This allows the user to i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.