signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def parse ( cls , gvid , exception = True ) :
"""Parse a string value into the geoid of this class .
: param gvid : String value to parse .
: param exception : If true ( default ) raise an eception on parse erorrs . If False , return a
' null ' geoid .
: return :""" | if gvid == 'invalid' :
return cls . get_class ( 'null' ) ( 0 )
if not bool ( gvid ) :
return None
if not isinstance ( gvid , six . string_types ) :
raise TypeError ( "Can't parse; not a string. Got a '{}' " . format ( type ( gvid ) ) )
try :
if not cls . sl : # Civick and ACS include the SL , so can cal... |
def base_concrete_modeladmin ( self ) :
"""The class inheriting directly from ContentModelAdmin .""" | candidates = [ self . __class__ ]
while candidates :
candidate = candidates . pop ( )
if ContentTypedAdmin in candidate . __bases__ :
return candidate
candidates . extend ( candidate . __bases__ )
raise Exception ( "Can't find base concrete ModelAdmin class." ) |
async def on_shutdown ( self ) :
"""Cleans up any outstanding subscriptions .""" | await self . _unregister_subscriptions ( )
self . _accepting = False
for ( ws , _ ) in self . _subscribers :
await ws . close ( code = aiohttp . WSCloseCode . GOING_AWAY , message = 'Server shutdown' ) |
def get_cases ( self , skip_ws = False ) :
"""Returns a list of 2 - tuples ( condition , value ) .
If an ELSE exists condition is None .""" | CONDITION = 1
VALUE = 2
ret = [ ]
mode = CONDITION
for token in self . tokens : # Set mode from the current statement
if token . match ( T . Keyword , 'CASE' ) :
continue
elif skip_ws and token . ttype in T . Whitespace :
continue
elif token . match ( T . Keyword , 'WHEN' ) :
ret . a... |
def thunder_decorator ( func ) :
"""Decorator for functions so they could get as input a thunder . Images / thunder . Series object ,
while they are expecting an rdd . Also will return the data from rdd to the appropriate type
Assumes only one input object of type Images / Series , and up to one output object o... | @ wraps ( func )
def dec ( * args , ** kwargs ) : # find Images / Series object in args
result = None
args = list ( args )
image_args = list ( map ( lambda x : isinstance ( x , td . images . Images ) , args ) )
series_args = list ( map ( lambda x : isinstance ( x , td . series . Series ) , args ) )
... |
def get_nx_graph ( ea ) :
"""Convert an IDA flowchart to a NetworkX graph .""" | nx_graph = networkx . DiGraph ( )
func = idaapi . get_func ( ea )
flowchart = FlowChart ( func )
for block in flowchart : # Make sure all nodes are added ( including edge - less nodes )
nx_graph . add_node ( block . startEA )
for pred in block . preds ( ) :
nx_graph . add_edge ( pred . startEA , block .... |
def mouse_out ( self ) :
"""Performs a mouse out the element .
Currently works only on Chrome driver .""" | self . scroll_to ( )
ActionChains ( self . parent . driver ) . move_by_offset ( 0 , 0 ) . click ( ) . perform ( ) |
def main ( args ) :
'''register _ retinotopy . main ( args ) can be given a list of arguments , such as sys . argv [ 1 : ] ; these
arguments may include any options and must include at least one subject id . All subjects whose
ids are given are registered to a retinotopy model , and the resulting registration ,... | m = register_retinotopy_plan ( args = args )
# force completion
files = m [ 'files' ]
if len ( files ) > 0 :
return 0
else :
print ( 'Error: No files exported.' , file = sys . stderr )
return 1 |
def validate_params_match ( method , parameters ) :
"""Validates that the given parameters are exactly the method ' s declared parameters .
: param method : The method to be called
: type method : function
: param parameters : The parameters to use in the call
: type parameters : dict [ str , object ] | lis... | argspec = inspect . getargspec ( method )
# pylint : disable = deprecated - method
default_length = len ( argspec . defaults ) if argspec . defaults is not None else 0
if isinstance ( parameters , list ) :
if len ( parameters ) > len ( argspec . args ) and argspec . varargs is None :
raise InvalidParamsErro... |
def _parse_extra_features ( node , NHX_string ) :
"""Reads node ' s extra data form its NHX string . NHX uses this
format : [ & & NHX : prop1 = value1 : prop2 = value2]""" | NHX_string = NHX_string . replace ( "[&&NHX:" , "" )
NHX_string = NHX_string . replace ( "]" , "" )
for field in NHX_string . split ( ":" ) :
try :
pname , pvalue = field . split ( "=" )
except ValueError as e :
raise NewickError ( 'Invalid NHX format %s' % field )
node . add_feature ( pname... |
def list_blobs ( kwargs = None , storage_conn = None , call = None ) :
'''. . versionadded : : 2015.8.0
List blobs associated with the container
CLI Example :
. . code - block : : bash
salt - cloud - f list _ blobs my - azure container = mycontainer
container :
The name of the storage container
prefix... | if call != 'function' :
raise SaltCloudSystemExit ( 'The list_blobs function must be called with -f or --function.' )
if kwargs is None :
kwargs = { }
if 'container' not in kwargs :
raise SaltCloudSystemExit ( 'An storage container name must be specified as "container"' )
if not storage_conn :
storage_c... |
def HashFilePath ( self , path , byte_count ) :
"""Updates underlying hashers with file on a given path .
Args :
path : A path to the file that is going to be fed to the hashers .
byte _ count : A maximum numbers of bytes that are going to be processed .""" | with open ( path , "rb" ) as fd :
self . HashFile ( fd , byte_count ) |
def get_cat_model ( model ) :
"""Return a class from a string or class""" | try :
if isinstance ( model , string_types ) :
model_class = apps . get_model ( * model . split ( "." ) )
elif issubclass ( model , CategoryBase ) :
model_class = model
if model_class is None :
raise TypeError
except TypeError :
raise TemplateSyntaxError ( "Unknown model submitte... |
def tabulate ( self , n = None , headers = ( ) , tablefmt = "simple" , floatfmt = "g" , numalign = "decimal" , stralign = "left" , missingval = "" ) :
"""Return pretty string table of first n rows of sequence or everything if n is None . See
https : / / bitbucket . org / astanin / python - tabulate for details on... | self . cache ( )
length = self . len ( )
if length == 0 or not is_tabulatable ( self [ 0 ] ) :
return None
if n is None or n >= length :
rows = self . list ( )
message = ''
else :
rows = self . take ( n ) . list ( )
if tablefmt == 'simple' :
message = '\nShowing {} of {} rows' . format ( n ,... |
def add_or_update_record ( self , dst_ase , src_block_list , offset , chunk_size , total_chunks , completed_chunks , completed ) : # type : ( SyncCopyResumeManager ,
# blobxfer . models . azure . StorageEntity , list , int , int , int ,
# int , bool ) - > None
"""Add or update a resume record
: param SyncCopyResu... | key = blobxfer . operations . resume . _BaseResumeManager . generate_record_key ( dst_ase )
with self . datalock ( ) :
sc = self . get_record ( dst_ase , key = key , lock = False )
if sc is None :
sc = blobxfer . models . resume . SyncCopy ( length = dst_ase . _size , src_block_list = src_block_list , o... |
def itemData ( self , item , column , role = Qt . DisplayRole ) :
"""Returns the data stored under the given role for the item . O
The column parameter may be used to differentiate behavior per column .
The default implementation does nothing . Descendants should typically override this
function instead of da... | if role == Qt . DecorationRole :
if column == self . COL_DECORATION :
return item . decoration
elif role == Qt . FontRole :
return item . font
elif role == Qt . ForegroundRole :
return item . foregroundBrush
elif role == Qt . BackgroundRole :
return item . backgroundBrush
elif role == Qt . SizeH... |
def _build_mesh ( self , mesh_method , ** kwargs ) :
"""this function takes mesh _ method and kwargs that came from the generic Body . intialize _ mesh and returns
the grid . . . intialize mesh then takes care of filling columns and rescaling to the correct units , etc""" | # need the sma to scale between Roche and real units
sma = kwargs . get ( 'sma' , self . sma )
# Rsol ( same units as coordinates )
mesh_args = self . instantaneous_mesh_args
if mesh_method == 'marching' : # TODO : do this during mesh initialization only and then keep delta fixed in time ? ?
ntriangles = kwargs . g... |
def error ( self , buf , newline = True ) :
"""Similar to ` write ` , except it writes buffer to error stream .
If coloring enabled , adds error coloring .
` buf `
Data buffer to write .
` newline `
Append newline character to buffer before writing .""" | buf = buf or ''
if self . _colored :
buf = self . ESCAPE_RED + buf + self . ESCAPE_CLEAR
if newline :
buf += os . linesep
try :
self . _error . write ( buf )
if hasattr ( self . _error , 'flush' ) :
self . _error . flush ( )
except IOError as exc :
if exc . errno != errno . EPIPE : # silence... |
def paste ( ** kwargs ) :
"""Returns system clipboard contents .""" | clip . OpenClipboard ( )
d = clip . GetClipboardData ( win32con . CF_UNICODETEXT )
clip . CloseClipboard ( )
return d |
def get_pending_bios_settings ( self , only_allowed_settings = True ) :
"""Get current BIOS settings .
: param : only _ allowed _ settings : True when only allowed BIOS settings
are to be returned . If False , All the BIOS settings supported
by iLO are returned .
: return : a dictionary of pending BIOS sett... | headers , bios_uri , bios_settings = self . _check_bios_resource ( )
try :
settings_config_uri = bios_settings [ 'links' ] [ 'Settings' ] [ 'href' ]
except KeyError :
msg = ( "Settings resource not found. Couldn't get pending BIOS " "Settings." )
raise exception . IloCommandNotSupportedError ( msg )
status ... |
def stats ( self , request ) :
'''Get stats for the provided request .
: param request dict : A search request that also contains the ' interval '
property .
: returns : : py : class : ` planet . api . models . JSON `
: raises planet . api . exceptions . APIException : On API error .''' | # work - around for API bug
request = _patch_stats_request ( request )
body = json . dumps ( request )
return self . dispatcher . response ( models . Request ( self . _url ( 'data/v1/stats' ) , self . auth , body_type = models . JSON , data = body , method = 'POST' ) ) . get_body ( ) |
def prune ( self , whole = False , keys = [ ] , names = [ ] , filters = [ ] ) :
"""Filter tree nodes based on given criteria""" | for node in self . climb ( whole ) : # Select only nodes with key content
if not all ( [ key in node . data for key in keys ] ) :
continue
# Select nodes with name matching regular expression
if names and not any ( [ re . search ( name , node . name ) for name in names ] ) :
continue
# A... |
def acctradinginfo_query ( self , order_type , code , price , order_id = None , adjust_limit = 0 , trd_env = TrdEnv . REAL , acc_id = 0 , acc_index = 0 ) :
"""查询账户下最大可买卖数量
: param order _ type : 订单类型 , 参见OrderType
: param code : 证券代码 , 例如 ' HK . 00700'
: param price : 报价 , 3位精度
: param order _ id : 订单号 。 如果... | ret , msg = self . _check_trd_env ( trd_env )
if ret != RET_OK :
return ret , msg
ret , msg , acc_id = self . _check_acc_id_and_acc_index ( trd_env , acc_id , acc_index )
if ret != RET_OK :
return ret , msg
ret , content = self . _split_stock_code ( code )
if ret != RET_OK :
return ret , content
market_str ... |
def syncView ( self , recursive = False ) :
"""Syncs the information from this item to the view .""" | # update the view widget
gantt = self . ganttWidget ( )
tree = self . treeWidget ( )
if not gantt :
return
vwidget = gantt . viewWidget ( )
scene = vwidget . scene ( )
cell_w = gantt . cellWidth ( )
tree_offset_y = tree . header ( ) . height ( ) + 1
tree_offset_y += tree . verticalScrollBar ( ) . value ( )
# collec... |
def render_message ( self ) :
"""渲染消息
: return : 渲染后的消息""" | message = None
if self . title :
message = '标题:{0}' . format ( self . title )
if self . message_time :
message = '{0}\n时间:{1}' . format ( message , self . time )
if message :
message = '{0}\n内容:{1}' . format ( message , self . content )
else :
message = self . content
return message |
def __getIp6Address ( self , addressType ) :
"""get specific type of IPv6 address configured on OpenThread _ WpanCtl
Args :
addressType : the specific type of IPv6 address
link local : link local unicast IPv6 address that ' s within one - hop scope
global : global unicast IPv6 address
rloc : mesh local un... | addrType = [ 'link local' , 'global' , 'rloc' , 'mesh EID' ]
addrs = [ ]
globalAddr = [ ]
linkLocal64Addr = ''
rlocAddr = ''
meshEIDAddr = ''
addrs = self . __sendCommand ( WPANCTL_CMD + 'getprop -v IPv6:AllAddresses' )
for ip6AddrItem in addrs :
if re . match ( '\[|\]' , ip6AddrItem ) :
continue
if re ... |
def update_with_diff ( self , identifier , new_instance ) :
"""Update an existing model with a new one .
: raises ` ModelNotFoundError ` if there is no existing model""" | with self . flushing ( ) :
instance = self . retrieve ( identifier )
before = Version ( instance )
self . merge ( instance , new_instance )
instance . updated_at = instance . new_timestamp ( )
after = Version ( instance )
return instance , before - after |
def _get_datapoints ( self , params ) :
"""Will make a direct REST call with the given json body payload to
get datapoints .""" | url = self . query_uri + '/v1/datapoints'
return self . service . _get ( url , params = params ) |
def tr ( self , args , color = None ) :
"""Method to print ASCII patterns to terminal""" | width = self . _term_size ( ) [ 1 ]
if not args :
if color is not None :
print ( self . _echo ( "#" * width , color ) )
else :
print ( self . _echo ( "#" * width , "green" ) )
else :
for each_symbol in args :
chars = len ( each_symbol )
number_chars = width // chars
i... |
def _log_future_exception ( future , logger ) :
"""Log any exception raised by future .""" | if not future . done ( ) :
return
try :
future . result ( )
except : # pylint : disable = bare - except ; This is a background logging helper
logger . warning ( "Exception in ignored future: %s" , future , exc_info = True ) |
def make_app ( ) :
"""Helper function that creates a plnt app .""" | from plnt import Plnt
database_uri = os . environ . get ( "PLNT_DATABASE_URI" )
app = Plnt ( database_uri or "sqlite:////tmp/plnt.db" )
app . bind_to_context ( )
return app |
def fetch_option_taskfileinfos ( self , typ , element ) :
"""Fetch the options for possible files to load , replace etc for the given element .
Thiss will call : meth : ` ReftypeInterface . fetch _ option _ taskfileinfos ` .
: param typ : the typ of options . E . g . Asset , Alembic , Camera etc
: type typ : ... | inter = self . get_typ_interface ( typ )
return inter . fetch_option_taskfileinfos ( element ) |
def diff ( name_a , name_b = None , ** kwargs ) :
'''Display the difference between a snapshot of a given filesystem and
another snapshot of that filesystem from a later time or the current
contents of the filesystem .
name _ a : string
name of snapshot
name _ b : string
( optional ) name of snapshot or... | # # Configure command
# NOTE : initialize the defaults
flags = [ '-H' ]
target = [ ]
# NOTE : set extra config from kwargs
if kwargs . get ( 'show_changetime' , True ) :
flags . append ( '-t' )
if kwargs . get ( 'show_indication' , True ) :
flags . append ( '-F' )
# NOTE : update target
target . append ( name_a... |
def _validate_number_of_layers ( self , number_of_layers ) :
"""Makes sure that the specified number of layers to squash
is a valid number""" | # Only positive numbers are correct
if number_of_layers <= 0 :
raise SquashError ( "Number of layers to squash cannot be less or equal 0, provided: %s" % number_of_layers )
# Do not squash if provided number of layer to squash is bigger
# than number of actual layers in the image
if number_of_layers > len ( self . ... |
def _round ( self , ** kwargs ) :
"""Subclasses may override this method .""" | mathInfo = self . _toMathInfo ( guidelines = False )
mathInfo = mathInfo . round ( )
self . _fromMathInfo ( mathInfo , guidelines = False ) |
def sinkhorn2 ( a , b , M , reg , method = 'sinkhorn' , numItermax = 1000 , stopThr = 1e-9 , verbose = False , log = False , ** kwargs ) :
u"""Solve the entropic regularization optimal transport problem and return the loss
The function solves the following optimization problem :
. . math : :
W = \ min _ \ gam... | if method . lower ( ) == 'sinkhorn' :
def sink ( ) :
return sinkhorn_knopp ( a , b , M , reg , numItermax = numItermax , stopThr = stopThr , verbose = verbose , log = log , ** kwargs )
elif method . lower ( ) == 'sinkhorn_stabilized' :
def sink ( ) :
return sinkhorn_stabilized ( a , b , M , reg ... |
def flatten ( iterables ) :
"""Flatten an iterable , except for string elements .""" | for it in iterables :
if isinstance ( it , str ) :
yield it
else :
for element in it :
yield element |
def _generate_shape ( word : str ) -> str :
"""Recreate shape from a token input by user
Args :
word : str
Returns : str""" | def counting_stars ( w ) -> List [ int ] :
count = [ 1 ]
for i in range ( 1 , len ( w ) ) :
if w [ i - 1 ] == w [ i ] :
count [ - 1 ] += 1
else :
count . append ( 1 )
return count
shape = ""
p = 0
for c in counting_stars ( word ) :
if c > 4 :
shape += word... |
def _compute_distance_fast ( self ) :
"""Calls edit _ distance , and asserts that if we already have values for
matches and distance , that they match .""" | d , m = edit_distance ( self . seq1 , self . seq2 , action_function = self . action_function , test = self . test )
if self . dist :
assert d == self . dist
if self . _matches :
assert m == self . _matches
self . dist = d
self . _matches = m |
def info ( self , remote_path ) :
"""Gets information about resource on WebDAV .
More information you can find by link http : / / webdav . org / specs / rfc4918 . html # METHOD _ PROPFIND
: param remote _ path : the path to remote resource .
: return : a dictionary of information attributes and them values wi... | urn = Urn ( remote_path )
if not self . check ( urn . path ( ) ) and not self . check ( Urn ( remote_path , directory = True ) . path ( ) ) :
raise RemoteResourceNotFound ( remote_path )
response = self . execute_request ( action = 'info' , path = urn . quote ( ) )
path = self . get_full_path ( urn )
return WebDavX... |
async def shutdown ( self , connmark = - 1 ) :
'''Can call without delegate''' | if connmark is None :
connmark = self . connmark
self . scheduler . emergesend ( ConnectionControlEvent ( self , ConnectionControlEvent . SHUTDOWN , True , connmark ) ) |
def export ( self , filename , fmt = "DER" ) :
"""Export certificate in ' fmt ' format ( DER or PEM ) to file ' filename '""" | f = open ( filename , "wb" )
if fmt == "DER" :
f . write ( self . der )
elif fmt == "PEM" :
f . write ( self . pem )
f . close ( ) |
def parent_images ( self ) :
""": return : list of parent images - - one image per each stage ' s FROM instruction""" | parents = [ ]
for instr in self . structure :
if instr [ 'instruction' ] != 'FROM' :
continue
image , _ = image_from ( instr [ 'value' ] )
if image is not None :
parents . append ( image )
return parents |
def ensure_hexadecimal_string ( self , value , command = None ) :
"""Make sure the given value is a hexadecimal string .
: param value : The value to check ( a string ) .
: param command : The command that produced the value ( a string or : data : ` None ` ) .
: returns : The validated hexadecimal string .
... | if not HEX_PATTERN . match ( value ) :
msg = "Expected a hexadecimal string, got '%s' instead!"
if command :
msg += " ('%s' gave unexpected output)"
msg %= ( value , command )
else :
msg %= value
raise ValueError ( msg )
return value |
def from_dict ( d ) :
"""Transform the dict to a response object and return the response .""" | warnings_ = d . get ( 'warnings' , [ ] )
query = d . get ( 'query' ) or None
if query :
query = Person . from_dict ( query )
person = d . get ( 'person' ) or None
if person :
person = Person . from_dict ( person )
records = d . get ( 'records' )
if records :
records = [ Record . from_dict ( record ) for rec... |
def content ( self , file_relpath ) :
"""Returns the content for file at path . Raises exception if path is ignored .
Raises exception if path is ignored .""" | if self . isignored ( file_relpath ) :
self . _raise_access_ignored ( file_relpath )
return self . _content_raw ( file_relpath ) |
def reconstitute_path ( drive , folders ) :
"""Reverts a tuple from ` get _ path _ components ` into a path .
: param drive : A drive ( eg ' c : ' ) . Only applicable for NT systems
: param folders : A list of folder names
: return : A path comprising the drive and list of folder names . The path terminate
... | reconstituted = os . path . join ( drive , os . path . sep , * folders )
return reconstituted |
def confirm_destructive_query ( queries ) :
"""Check if the query is destructive and prompts the user to confirm .
Returns :
* None if the query is non - destructive or we can ' t prompt the user .
* True if the query is destructive and the user wants to proceed .
* False if the query is destructive and the... | prompt_text = ( "You're about to run a destructive command.\n" "Do you want to proceed? (y/n)" )
if is_destructive ( queries ) and sys . stdin . isatty ( ) :
return prompt ( prompt_text , type = bool ) |
def _ParseLogonApplications ( self , parser_mediator , registry_key ) :
"""Parses the registered logon applications .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
registry _ key ( dfwinreg . WinRegistryKey ) : Windows ... | for application in self . _LOGON_APPLICATIONS :
command_value = registry_key . GetValueByName ( application )
if not command_value :
continue
values_dict = { 'Application' : application , 'Command' : command_value . GetDataAsObject ( ) , 'Trigger' : 'Logon' }
event_data = windows_events . Window... |
def setup ( app ) :
"""Configure setup for Sphinx extension .
: param app : Sphinx application context .""" | app . add_config_value ( 'sphinxmark_enable' , False , 'html' )
app . add_config_value ( 'sphinxmark_div' , 'default' , 'html' )
app . add_config_value ( 'sphinxmark_border' , None , 'html' )
app . add_config_value ( 'sphinxmark_repeat' , True , 'html' )
app . add_config_value ( 'sphinxmark_fixed' , False , 'html' )
ap... |
async def change_presence ( self , * , activity = None , status = None , afk = False , shard_id = None ) :
"""| coro |
Changes the client ' s presence .
The activity parameter is a : class : ` Activity ` object ( not a string ) that represents
the activity being done currently . This could also be the slimmed... | if status is None :
status = 'online'
status_enum = Status . online
elif status is Status . offline :
status = 'invisible'
status_enum = Status . offline
else :
status_enum = status
status = str ( status )
if shard_id is None :
for shard in self . shards . values ( ) :
await shard . ... |
def storage_record2pairwise_info ( storec : StorageRecord ) -> PairwiseInfo :
"""Given indy - sdk non _ secrets implementation of pairwise storage record dict , return corresponding PairwiseInfo .
: param storec : ( non - secret ) storage record to convert to PairwiseInfo
: return : PairwiseInfo on record DIDs ... | return PairwiseInfo ( storec . id , # = their did
storec . value , # = their verkey
storec . tags [ '~my_did' ] , storec . tags [ '~my_verkey' ] , { tag [ tag . startswith ( '~' ) : ] : storec . tags [ tag ] for tag in ( storec . tags or { } ) # strip any leading ' ~ '
} ) |
def CloseCHM ( self ) :
'''Closes the CHM archive .
This function will close the CHM file , if it is open . All variables
are also reset .''' | if self . filename is not None :
chmlib . chm_close ( self . file )
self . file = None
self . filename = ''
self . title = ""
self . home = "/"
self . index = None
self . topics = None
self . encoding = None |
def _resolve_readme ( self , path = None , silent = False ) :
"""Returns the path if it ' s a file ; otherwise , looks for a compatible
README file in the directory specified by path .
If path is None , the current working directory is used .
If silent is set , the default relative filename will be returned
... | # Default to current working directory
if path is None :
path = '.'
# Normalize the path
path = os . path . normpath ( path )
# Resolve README file if path is a directory
if os . path . isdir ( path ) :
return self . _find_file ( path , silent )
# Return path if file exists or if silent
if silent or os . path .... |
def add_filter ( self , methods = None , endpoints = None ) :
"""Adds a filter .
: param methods : The HTTP methods to be filtered .
: param endpoints : The endpoints to be filtered .
: return Filter : The filter added .""" | if not methods and not endpoints :
raise ValueError ( 'Filter cannot be added with no criteria.' )
filter = TraceFilter ( methods , endpoints )
self . filters . append ( filter )
return filter |
def trmm ( L , B , alpha = 1.0 , trans = 'N' , nrhs = None , offsetB = 0 , ldB = None ) :
r"""Multiplication with sparse triangular matrix . Computes
. . math : :
B & : = \ alpha L B \ text { if trans is ' N ' } \ \
B & : = \ alpha L ^ T B \ text { if trans is ' T ' }
where : math : ` L ` is a : py : class ... | assert isinstance ( L , cspmatrix ) and L . is_factor is True , "L must be a cspmatrix factor"
assert isinstance ( B , matrix ) , "B must be a matrix"
if ldB is None :
ldB = B . size [ 0 ]
if nrhs is None :
nrhs = B . size [ 1 ]
assert trans in [ 'N' , 'T' ]
n = L . symb . n
snpost = L . symb . snpost
snptr = L... |
def _validate_min_version ( min_version ) :
"""Validates the extension version matches the requested version .
Args :
min _ version : Minimum version passed as a query param when establishing the
connection .
Returns :
An ExtensionVersionResult indicating validation status . If there is a
problem , the ... | if min_version is not None :
try :
parsed_min_version = version . StrictVersion ( min_version )
except ValueError :
return ExtensionVersionResult ( error_reason = ExtensionValidationError . UNPARSEABLE_REQUESTED_VERSION , requested_extension_version = min_version )
if parsed_min_version > HA... |
def multi_exposure_analysis_question_extractor ( impact_report , component_metadata ) :
"""Extracting analysis question from the impact layer .
: param impact _ report : the impact report that acts as a proxy to fetch
all the data that extractor needed
: type impact _ report : safe . report . impact _ report ... | context = { }
extra_args = component_metadata . extra_args
multi_exposure = impact_report . multi_exposure_impact_function
provenance = multi_exposure . provenance
header = resolve_from_dictionary ( extra_args , 'header' )
analysis_questions = [ ]
analysis_question = provenance [ 'analysis_question' ]
analysis_question... |
def install_templates ( srcroot , destroot , prefix = '' , excludes = None , includes = None , path_prefix = None ) : # pylint : disable = too - many - arguments , too - many - statements
"""Expand link to compiled assets all templates in * srcroot *
and its subdirectories .""" | # pylint : disable = too - many - locals
if excludes is None :
excludes = [ ]
if includes is None :
includes = [ ]
if not os . path . exists ( os . path . join ( prefix , destroot ) ) :
os . makedirs ( os . path . join ( prefix , destroot ) )
for pathname in os . listdir ( os . path . join ( srcroot , prefi... |
def euler_trans_matrix ( etheta , elongan , eincl ) :
"""Get the transformation matrix R to translate / rotate a mesh according to
euler angles .
The matrix is
R ( long , incl , theta ) =
Rz ( pi ) . Rz ( long ) . Rx ( incl ) . Rz ( theta )
Rz ( long ) . Rx ( - incl ) . Rz ( theta ) . Rz ( pi )
where
... | s1 = sin ( eincl ) ;
c1 = cos ( eincl ) ;
s2 = sin ( elongan ) ;
c2 = cos ( elongan ) ;
s3 = sin ( etheta ) ;
c3 = cos ( etheta ) ;
c1s3 = c1 * s3 ;
c1c3 = c1 * c3 ;
return np . array ( [ [ - c2 * c3 + s2 * c1s3 , c2 * s3 + s2 * c1c3 , - s2 * s1 ] , [ - s2 * c3 - c2 * c1s3 , s2 * s3 - c2 * c1c3 , c2 * s1 ] , [ s1 * s3 ... |
def name_usage ( key = None , name = None , data = 'all' , language = None , datasetKey = None , uuid = None , sourceId = None , rank = None , shortname = None , limit = 100 , offset = None , ** kwargs ) :
'''Lookup details for specific names in all taxonomies in GBIF .
: param key : [ fixnum ] A GBIF key for a t... | args = { 'language' : language , 'name' : name , 'datasetKey' : datasetKey , 'rank' : rank , 'sourceId' : sourceId , 'limit' : limit , 'offset' : offset }
data_choices = [ 'all' , 'verbatim' , 'name' , 'parents' , 'children' , 'related' , 'synonyms' , 'descriptions' , 'distributions' , 'media' , 'references' , 'species... |
def _normalize_coerce ( self , mapping , schema ) :
"""{ ' oneof ' : [
{ ' type ' : ' callable ' } ,
{ ' type ' : ' list ' ,
' schema ' : { ' oneof ' : [ { ' type ' : ' callable ' } ,
{ ' type ' : ' string ' } ] } } ,
{ ' type ' : ' string ' }""" | error = errors . COERCION_FAILED
for field in mapping :
if field in schema and 'coerce' in schema [ field ] :
mapping [ field ] = self . __normalize_coerce ( schema [ field ] [ 'coerce' ] , field , mapping [ field ] , schema [ field ] . get ( 'nullable' , False ) , error )
elif isinstance ( self . allow... |
def download_binaries ( package_dir = False ) :
"""Download all binaries for the current platform
Parameters
package _ dir : bool
If set to ` True ` , the binaries will be downloaded to the
` resources ` directory of the qpsphere package instead of
to the users application data directory . Note that this ... | # bhfield
# make sure the binary is available on the system
paths = _bhfield . fetch . get_binaries ( )
if package_dir : # Copy the binaries to the ` resources ` directory
# of qpsphere .
pdir = RESCR_PATH
outpaths = [ ]
for pp in paths :
target = pdir / pp . name
if not target . exists ( ) ... |
def meta_changed_notify_after ( self , state_machine_m , _ , info ) :
"""Handle notification about the change of a state ' s meta data
The meta data of the affected state ( s ) are read and the view updated accordingly .
: param StateMachineModel state _ machine _ m : Always the state machine model belonging to... | meta_signal_message = info [ 'arg' ]
if meta_signal_message . origin == "graphical_editor_gaphas" : # Ignore changes caused by ourself
return
if meta_signal_message . origin == "load_meta_data" : # Meta data can ' t be applied , as the view has not yet
return
# been created
notification = meta_signal_messag... |
def _send_kex_init ( self ) :
"""announce to the other side that we ' d like to negotiate keys , and what
kind of key negotiation we support .""" | self . clear_to_send_lock . acquire ( )
try :
self . clear_to_send . clear ( )
finally :
self . clear_to_send_lock . release ( )
self . in_kex = True
if self . server_mode :
if ( self . _modulus_pack is None ) and ( 'diffie-hellman-group-exchange-sha1' in self . _preferred_kex ) : # can ' t do group - excha... |
def get_sns_subscriptions ( app_name , env , region ) :
"""List SNS lambda subscriptions .
Returns :
list : List of Lambda subscribed SNS ARNs .""" | session = boto3 . Session ( profile_name = env , region_name = region )
sns_client = session . client ( 'sns' )
lambda_alias_arn = get_lambda_alias_arn ( app = app_name , account = env , region = region )
lambda_subscriptions = [ ]
subscriptions = sns_client . list_subscriptions ( )
for subscription in subscriptions [ ... |
def get_feature_by_query ( self , ** kwargs ) :
"""Retrieve an enumerated sequence feature
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please define a ` callback ` function
to be invoked when receiving the response .
> > > def callback _ function ( respon... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . get_feature_by_query_with_http_info ( ** kwargs )
else :
( data ) = self . get_feature_by_query_with_http_info ( ** kwargs )
return data |
def product ( self , * bases ) :
"""Compute the tensor product with another basis .
: param bases : One or more additional bases to form the product with .
: return ( OperatorBasis ) : The tensor product basis as an OperatorBasis object .""" | if len ( bases ) > 1 :
basis_rest = bases [ 0 ] . product ( * bases [ 1 : ] )
else :
assert len ( bases ) == 1
basis_rest = bases [ 0 ]
labels_ops = [ ( b1l + b2l , qt . tensor ( b1 , b2 ) ) for ( b1l , b1 ) , ( b2l , b2 ) in itertools . product ( self , basis_rest ) ]
return OperatorBasis ( labels_ops ) |
def _generate_current_command ( self ) :
'''Returns a constructed GCode string that contains this driver ' s
axis - current settings , plus a small delay to wait for those settings
to take effect .''' | values = [ '{}{}' . format ( axis , value ) for axis , value in sorted ( self . current . items ( ) ) ]
current_cmd = '{} {}' . format ( GCODES [ 'SET_CURRENT' ] , ' ' . join ( values ) )
command = '{currents} {code}P{seconds}' . format ( currents = current_cmd , code = GCODES [ 'DWELL' ] , seconds = CURRENT_CHANGE_DEL... |
def _storage_init ( self ) :
"""Ensure that storage is initialized .""" | if not self . _storage . initialized :
self . _storage . init ( self . _module . _py3_wrapper , self . _is_python_2 ) |
def fill_parentidid2obj_r1 ( self , id2obj_user , child_obj ) :
"""Fill id2obj _ user with all parent / relationship key item IDs and their objects .""" | for higher_obj in self . _getobjs_higher ( child_obj ) :
if higher_obj . item_id not in id2obj_user :
id2obj_user [ higher_obj . item_id ] = higher_obj
self . fill_parentidid2obj_r1 ( id2obj_user , higher_obj ) |
def append_from_list ( self , content , fill_title = False ) :
"""Appends rows created from the data contained in the provided
list of tuples of strings . The first tuple of the list can be
set as table title .
Args :
content ( list ) : list of tuples of strings . Each tuple is a row .
fill _ title ( bool... | row_index = 0
for row in content :
tr = TableRow ( )
column_index = 0
for item in row :
if row_index == 0 and fill_title :
ti = TableTitle ( item )
else :
ti = TableItem ( item )
tr . append ( ti , str ( column_index ) )
column_index = column_index + 1... |
def getTotalPrice ( self ) :
"""Compute total price including VAT""" | price = self . getPrice ( )
vat = self . getVAT ( )
price = price and price or 0
vat = vat and vat or 0
return float ( price ) + ( float ( price ) * float ( vat ) ) / 100 |
def xross_listener ( http_method = None , ** xross_attrs ) :
"""Instructs xross to handle AJAX calls right from the moment it is called .
This should be placed in a view decorated with ` @ xross _ view ( ) ` .
: param str http _ method : GET or POST . To be used as a source of data for xross .
: param dict xr... | handler = currentframe ( ) . f_back . f_locals [ 'request' ] . _xross_handler
handler . set_attrs ( ** xross_attrs )
if http_method is not None :
handler . http_method = http_method
handler . dispatch ( ) |
def get_port_profile_for_intf_output_interface_interface_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_port_profile_for_intf = ET . Element ( "get_port_profile_for_intf" )
config = get_port_profile_for_intf
output = ET . SubElement ( get_port_profile_for_intf , "output" )
interface = ET . SubElement ( output , "interface" )
interface_type = ET . SubElement ( interface , "interface-... |
def get_iss ( self , key ) :
"""Get the Issuer ID
: param key : Key to the information in the state database
: return : The issuer ID""" | _state = self . get_state ( key )
if not _state :
raise KeyError ( key )
return _state [ 'iss' ] |
def after ( self , value ) :
"""Sets the operator type to Query . Op . After and sets the value to
the amount that this query should be lower than . This is functionally
the same as doing the lessThan operation , but is useful for visual
queries for things like dates .
: param value | < variant >
: return... | newq = self . copy ( )
newq . setOp ( Query . Op . After )
newq . setValue ( value )
return newq |
def huge_words_and_punctuation_challenge ( ) :
"Yay , undocumneted . Mostly used to test Issue 39 - http : / / code . google . com / p / django - simple - captcha / issues / detail ? id = 39" | fd = open ( settings . CAPTCHA_WORDS_DICTIONARY , 'rb' )
l = fd . readlines ( )
fd . close ( )
word = ''
while True :
word1 = random . choice ( l ) . strip ( )
word2 = random . choice ( l ) . strip ( )
punct = random . choice ( settings . CAPTCHA_PUNCTUATION )
word = '%s%s%s' % ( word1 , punct , word2 )... |
def backup ( path , password_file = None ) :
"""Replaces the contents of a file with its decrypted counterpart , storing the
original encrypted version and a hash of the file contents for later
retrieval .""" | vault = VaultLib ( get_vault_password ( password_file ) )
with open ( path , 'r' ) as f :
encrypted_data = f . read ( )
# Normally we ' d just try and catch the exception , but the
# exception raised here is not very specific ( just
# ` AnsibleError ` ) , so this feels safer to avoid suppressing
# o... |
def send_single_image ( self , sender , receiver , media_id ) :
"""发送单聊图片消息
: param sender : 发送人
: param receiver : 接收人成员 ID
: param media _ id : 图片媒体文件id , 可以调用上传素材文件接口获取
: return : 返回的 JSON 数据包""" | return self . send_image ( sender , 'single' , receiver , media_id ) |
def update ( tgt , tgt_type = 'glob' , clear = False , mine_functions = None ) :
'''. . versionadded : : 2017.7.0
Update the mine data on a certain group of minions .
tgt
Which minions to target for the execution .
tgt _ type : ` ` glob ` `
The type of ` ` tgt ` ` .
clear : ` ` False ` `
Boolean flag ... | ret = __salt__ [ 'salt.execute' ] ( tgt , 'mine.update' , tgt_type = tgt_type , clear = clear , mine_functions = mine_functions )
return ret |
def docgraph2freqt ( docgraph , root = None , include_pos = False , escape_func = FREQT_ESCAPE_FUNC ) :
"""convert a docgraph into a FREQT string .""" | if root is None :
return u"\n" . join ( sentence2freqt ( docgraph , sentence , include_pos = include_pos , escape_func = escape_func ) for sentence in docgraph . sentences )
else :
return sentence2freqt ( docgraph , root , include_pos = include_pos , escape_func = escape_func ) |
def _max ( self ) :
"""Getter for the maximum series value""" | return ( self . range [ 1 ] if ( self . range and self . range [ 1 ] is not None ) else ( max ( self . _values ) if self . _values else None ) ) |
def relative_path ( sub_directory = '' , function_index = 1 ) :
"""This will return the file relative to this python script
: param subd _ irectory : str of the relative path
: param function _ index : int of the number of function calls to go back
: return : str of the full path""" | frm = inspect . currentframe ( )
for i in range ( function_index ) :
frm = frm . f_back
if frm . f_code . co_name == 'run_code' :
frm = frm . f_back
if not isinstance ( sub_directory , list ) :
sub_directory = sub_directory . replace ( '\\' , '/' ) . split ( '/' )
path = os . path . split ( frm . f_code . c... |
def get_console_width ( ) -> int :
"""A small utility function for getting the current console window ' s width .
: return : The current console window ' s width .""" | # Assigning the value once , as frequent call to this function
# causes a major slow down ( ImportErrors + isinstance ) .
global _IN_QT
if _IN_QT is None :
_IN_QT = _in_qtconsole ( )
try :
if _IN_QT : # QTConsole determines and handles the max line length by itself .
width = sys . maxsize
else :
... |
def getRandomSequence ( length = 500 ) :
"""Generates a random name and sequence .""" | fastaHeader = ""
for i in xrange ( int ( random . random ( ) * 100 ) ) :
fastaHeader = fastaHeader + random . choice ( [ 'A' , 'C' , '0' , '9' , ' ' , '\t' ] )
return ( fastaHeader , "" . join ( [ random . choice ( [ 'A' , 'C' , 'T' , 'G' , 'A' , 'C' , 'T' , 'G' , 'A' , 'C' , 'T' , 'G' , 'A' , 'C' , 'T' , 'G' , 'A'... |
def construct_item_args ( self , domain_event ) :
"""Constructs attributes of a sequenced item from the given domain event .""" | # Get the sequence ID .
sequence_id = domain_event . __dict__ [ self . sequence_id_attr_name ]
# Get the position in the sequence .
position = getattr ( domain_event , self . position_attr_name , None )
# Get topic and data .
topic , state = self . get_item_topic_and_state ( domain_event . __class__ , domain_event . __... |
def _archive_single_dir ( archive ) :
"""Check if all members of the archive are in a single top - level directory
: param archive :
An archive from _ open _ archive ( )
: return :
None if not a single top level directory in archive , otherwise a
unicode string of the top level directory name""" | common_root = None
for info in _list_archive_members ( archive ) :
fn = _info_name ( info )
if fn in set ( [ '.' , '/' ] ) :
continue
sep = None
if '/' in fn :
sep = '/'
elif '\\' in fn :
sep = '\\'
if sep is None :
root_dir = fn
else :
root_dir , _ = ... |
def update_port_statuses_cfg ( self , context , port_ids , status ) :
"""Update the operational statuses of a list of router ports .
This is called by the Cisco cfg agent to update the status of a list
of ports .
: param context : contains user information
: param port _ ids : list of ids of all the ports f... | self . _l3plugin . update_router_port_statuses ( context , port_ids , status ) |
def _TemplateNamesToFiles ( self , template_str ) :
"""Parses a string of templates into a list of file handles .""" | template_list = template_str . split ( ":" )
template_files = [ ]
try :
for tmplt in template_list :
template_files . append ( open ( os . path . join ( self . template_dir , tmplt ) , "r" ) )
except : # noqa
for tmplt in template_files :
tmplt . close ( )
raise
return template_files |
def _overwrite_special_dates ( midnight_utcs , opens_or_closes , special_opens_or_closes ) :
"""Overwrite dates in open _ or _ closes with corresponding dates in
special _ opens _ or _ closes , using midnight _ utcs for alignment .""" | # Short circuit when nothing to apply .
if not len ( special_opens_or_closes ) :
return
len_m , len_oc = len ( midnight_utcs ) , len ( opens_or_closes )
if len_m != len_oc :
raise ValueError ( "Found misaligned dates while building calendar.\n" "Expected midnight_utcs to be the same length as open_or_closes,\n"... |
def best_trial_tid ( self , rank = 0 ) :
"""Get tid of the best trial
rank = 0 means the best model
rank = 1 means second best""" | candidates = [ t for t in self . trials if t [ 'result' ] [ 'status' ] == STATUS_OK ]
if len ( candidates ) == 0 :
return None
losses = [ float ( t [ 'result' ] [ 'loss' ] ) for t in candidates ]
assert not np . any ( np . isnan ( losses ) )
lid = np . where ( np . argsort ( losses ) . argsort ( ) == rank ) [ 0 ] [... |
def delta ( self , local = False ) :
"""Returns the number of days of difference""" | ( s , e ) = self . get ( local )
return e - s |
def validate_cidr ( s ) :
"""Validate a CIDR notation ip address .
The string is considered a valid CIDR address if it consists of a valid
IPv6 address in hextet format followed by a forward slash ( / ) and a bit
mask length ( 0-128 ) .
> > > validate _ cidr ( ' : : / 128 ' )
True
> > > validate _ cidr ... | if _CIDR_RE . match ( s ) :
ip , mask = s . split ( '/' )
if validate_ip ( ip ) :
if int ( mask ) > 128 :
return False
else :
return False
return True
return False |
def register_sub ( self , o ) :
"""Register argument a suboption for ` self ` .""" | if o . subopt in self . subopt_map :
raise OptionConflictError ( "conflicting suboption handlers for `%s'" % o . subopt , o )
self . subopt_map [ o . subopt ] = o |
def format_args ( options ) :
"""Convert hash / key options into arguments list""" | args = list ( )
for key , value in options . items ( ) : # convert foo _ bar key into - - foo - bar option
key = key . replace ( '_' , '-' )
if value is True : # key : True
# - - key
args . append ( '--{key}' . format ( key = key ) )
elif is_sequence ( value ) : # key : [ ' foo ' , ' bar ' ]
... |
def delete ( self , req , driver ) :
"""Delete a network
Delete a specific netowrk with id on special cloud
with :
: Param req
: Type object Request""" | response = driver . delete_network ( req . params , id )
data = { 'action' : "delete" , 'controller' : "network" , 'id' : id , 'cloud' : req . environ [ 'calplus.cloud' ] , 'response' : response }
return data |
def _logfile_sigterm_handler ( * _ ) : # type : ( . . . ) - > None
"""Handle exit signals and write out a log file .
Raises :
SystemExit : Contains the signal as the return code .""" | logging . error ( 'Received SIGTERM.' )
write_logfile ( )
print ( 'Received signal. Please see the log file for more information.' , file = sys . stderr )
sys . exit ( signal ) |
def CacheStorage_requestEntries ( self , cacheId , skipCount , pageSize ) :
"""Function path : CacheStorage . requestEntries
Domain : CacheStorage
Method name : requestEntries
Parameters :
Required arguments :
' cacheId ' ( type : CacheId ) - > ID of cache to get entries from .
' skipCount ' ( type : in... | assert isinstance ( skipCount , ( int , ) ) , "Argument 'skipCount' must be of type '['int']'. Received type: '%s'" % type ( skipCount )
assert isinstance ( pageSize , ( int , ) ) , "Argument 'pageSize' must be of type '['int']'. Received type: '%s'" % type ( pageSize )
subdom_funcs = self . synchronous_command ( 'Cach... |
def _split_source_page ( self , path ) :
"""Split the source file texts by triple - dashed lines .
shit code""" | with codecs . open ( path , "rb" , "utf-8" ) as fd :
textlist = fd . readlines ( )
metadata_notation = "---\n"
if textlist [ 0 ] != metadata_notation :
logging . error ( "{} first line must be triple-dashed!" . format ( path ) )
sys . exit ( 1 )
metadata_textlist = [ ]
metadata_end_flag = False
idx = 1
max_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.