signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def run ( self , daemon = False ) :
"""Launch the process with the given inputs , by default running in the current interpreter .
: param daemon : boolean , if True , will submit the process instead of running it .""" | from aiida . engine import launch
# If daemon is True , submit the process and return
if daemon :
node = launch . submit ( self . process , ** self . inputs )
echo . echo_info ( 'Submitted {}<{}>' . format ( self . process_name , node . pk ) )
return
# Otherwise we run locally and wait for the process to fi... |
def ParseNotificationcenterRow ( self , parser_mediator , query , row , ** unused_kwargs ) :
"""Parses a message row .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
query ( str ) : query that created the row .
row ( s... | query_hash = hash ( query )
event_data = MacNotificationCenterEventData ( )
event_data . bundle_name = self . _GetRowValue ( query_hash , row , 'bundle_name' )
event_data . presented = self . _GetRowValue ( query_hash , row , 'presented' )
blob = self . _GetRowValue ( query_hash , row , 'dataBlob' )
try :
full_bipl... |
def disconnect ( self ) :
'''Disconnect from the transport . Typically socket . close ( ) . This call is
welcome to raise exceptions , which the Connection will catch .
The transport is encouraged to allow for any pending writes to complete
before closing the socket .''' | if not hasattr ( self , '_sock' ) :
return
# TODO : If there are bytes left on the output , queue the close for
# later .
self . _sock . close_cb = None
self . _sock . close ( ) |
def identify ( self , seconds ) :
"""Identify a robot by flashing the light around the frame button for 10s""" | from time import sleep
for i in range ( seconds ) :
self . turn_off_button_light ( )
sleep ( 0.25 )
self . turn_on_button_light ( )
sleep ( 0.25 ) |
def invoke ( proc , args = None , * , _instance = None , ** kwargs ) :
"""Executes the processor passing given arguments .
: param args : a list of parameters in - - key = value format .""" | if args is None :
args = [ ]
for kwargname in kwargs :
args . append ( '--' + kwargname )
args . append ( '{}' . format ( kwargs [ kwargname ] ) )
parser = proc . invoke_parser ( noexit = ( _instance is not None ) )
opts = parser . parse_args ( args )
kwargs0 = { }
def handle_set ( opts , dataset , kwargs0 ... |
def _respond_commands ( self , update_response ) :
"""Extract commands to bot from update and
act accordingly . For description of commands ,
see HELP _ MESSAGE variable on top of this module .""" | chatfile = self . chatfile
chats = self . chats
exc , upd = update_response . exception ( ) , update_response . result ( ) . body
if exc :
LOGGER . error ( str ( exc ) )
if not upd :
return
data = get_data ( upd , self . bot_ident )
for update_id , chat_id , message_id , command in data :
self . _last_updat... |
def run_code ( self , code , file_name , argv = None ) :
if logger . parent . level <= logging . DEBUG2 : # pragma : no cover
logger . debug2 ( '------------------' )
logger . debug2 ( 'main (gobal) code:' )
handler = logger . parent . handlers [ 0 ]
handler . acquire ( )
dis... | error = None
result = None
try :
logger . debug3 ( 'globals for script: %s' , ayrton . utils . dump_dict ( self . globals ) )
if self . params . trace : # pragma : no cover
sys . settrace ( self . global_tracer )
exec ( code , self . globals , self . locals )
result = self . locals . get ( 'ayrt... |
def bash_echo_metric ( ) :
"""A very basic example that monitors
a number of currently running processes""" | import subprocess
# import random
# more predictable version of the metric
cmd = ( 'set -o pipefail ' ' ; pgrep -f "^bash.*sleep .*from bash: started relay launcher"' ' | wc -l ' )
# less predictable version of the metric
# cmd = ' ps aux | wc - l '
while True :
yield ( int ( subprocess . check_output ( cmd , shell... |
def associate ( self , eip_or_aid , instance_id = '' , network_interface_id = '' , private_ip = '' ) :
"""Associate an EIP with a given instance or network interface . If
the EIP was allocated for a VPC instance , an AllocationId ( aid ) must
be provided instead of a PublicIp .""" | if "." in eip_or_aid : # If an IP is given ( Classic )
return self . call ( "AssociateAddress" , PublicIp = eip_or_aid , InstanceId = instance_id , NetworkInterfaceId = network_interface_id , PrivateIpAddress = private_ip )
else : # If an AID is given ( VPC )
return self . call ( "AssociateAddress" , Allocation... |
def describe_security_groups ( self , xml_bytes ) :
"""Parse the XML returned by the C { DescribeSecurityGroups } function .
@ param xml _ bytes : XML bytes with a C { DescribeSecurityGroupsResponse }
root element .
@ return : A list of L { SecurityGroup } instances .""" | root = XML ( xml_bytes )
result = [ ]
for group_info in root . findall ( "securityGroupInfo/item" ) :
id = group_info . findtext ( "groupId" )
name = group_info . findtext ( "groupName" )
description = group_info . findtext ( "groupDescription" )
owner_id = group_info . findtext ( "ownerId" )
allowe... |
def register ( config , pconn ) :
"""Do registration using basic auth""" | username = config . username
password = config . password
authmethod = config . authmethod
auto_config = config . auto_config
if not username and not password and not auto_config and authmethod == 'BASIC' :
logger . debug ( 'Username and password must be defined in configuration file with BASIC authentication metho... |
def clone_rtcpath_update_rt_as ( path , new_rt_as ) :
"""Clones given RT NLRI ` path ` , and updates it with new RT _ NLRI AS .
Parameters :
- ` path ` : ( Path ) RT _ NLRI path
- ` new _ rt _ as ` : AS value of cloned paths ' RT _ NLRI""" | assert path and new_rt_as
if not path or path . route_family != RF_RTC_UC :
raise ValueError ( 'Expected RT_NLRI path' )
old_nlri = path . nlri
new_rt_nlri = RouteTargetMembershipNLRI ( new_rt_as , old_nlri . route_target )
return RtcPath ( path . source , new_rt_nlri , path . source_version_num , pattrs = path . p... |
def Init ( ) :
"""Run all required startup routines and initialization hooks .""" | global INIT_RAN
if INIT_RAN :
return
# Set up a temporary syslog handler so we have somewhere to log problems
# with ConfigInit ( ) which needs to happen before we can start our create our
# proper logging setup .
syslog_logger = logging . getLogger ( "TempLogger" )
if os . path . exists ( "/dev/log" ) :
handle... |
def uncompress_file ( inputfile , filename ) :
"""Uncompress this file using gzip and change its name .
: param inputfile : File to compress
: type inputfile : ` ` file ` ` like object
: param filename : File ' s name
: type filename : ` ` str ` `
: returns : Tuple with file and new file ' s name
: rtyp... | zipfile = gzip . GzipFile ( fileobj = inputfile , mode = "rb" )
try :
outputfile = create_spooled_temporary_file ( fileobj = zipfile )
finally :
zipfile . close ( )
new_basename = os . path . basename ( filename ) . replace ( '.gz' , '' )
return outputfile , new_basename |
def _get_handling_triplet ( self , node_id ) :
"""_ get _ handling _ triplet ( node _ id ) - > ( handler , value , attrs )""" | handler = self . _get_handler ( node_id )
value = self [ node_id ]
attrs = self . _get_attrs ( node_id )
return handler , value , attrs |
def get_core_api ( ) :
"""Create instance of Core V1 API of kubernetes :
https : / / github . com / kubernetes - client / python / blob / master / kubernetes / docs / CoreV1Api . md
: return : instance of client""" | global core_api
if core_api is None :
config . load_kube_config ( )
if API_KEY is not None : # Configure API key authorization : BearerToken
configuration = client . Configuration ( )
configuration . api_key [ 'authorization' ] = API_KEY
configuration . api_key_prefix [ 'authorization' ]... |
def e ( self , eid ) :
"""Get an Entity""" | ta = datetime . datetime . now ( )
rs = self . rest ( 'GET' , self . uri_db + '-/entity' , data = { 'e' : int ( eid ) } , parse = True )
tb = datetime . datetime . now ( ) - ta
print cl ( '<<< fetched entity %s in %sms' % ( eid , tb . microseconds / 1000.0 ) , 'cyan' )
return rs |
def int_filter ( text ) :
"""Extract integer from text .
* * 中文文档 * *
摘除文本内的整数 。""" | res = list ( )
for char in text :
if char . isdigit ( ) :
res . append ( char )
return int ( "" . join ( res ) ) |
def visit_Call ( self , node ) :
"""Propagate ' debug ' wrapper into inner function calls if needed .
Args :
node ( ast . AST ) : node statement to surround .""" | if self . depth == 0 :
return node
if self . ignore_exceptions is None :
ignore_exceptions = ast . Name ( "None" , ast . Load ( ) )
else :
ignore_exceptions = ast . List ( self . ignore_exceptions , ast . Load ( ) )
catch_exception_type = self . catch_exception if self . catch_exception else "None"
catch_ex... |
def read_iou_stdout ( self ) :
"""Reads the standard output of the IOU process .
Only use when the process has been stopped or has crashed .""" | output = ""
if self . _iou_stdout_file :
try :
with open ( self . _iou_stdout_file , "rb" ) as file :
output = file . read ( ) . decode ( "utf-8" , errors = "replace" )
except OSError as e :
log . warn ( "could not read {}: {}" . format ( self . _iou_stdout_file , e ) )
return output |
def to_dict ( self ) :
"""Returns a simplified dictionary representing the Graph .
Returns :
A dictionary that can easily be serialized to JSON .""" | return { "node" : [ v . to_dict ( ) for v in self . vertices ] , "edge" : [ e . to_dict ( ) for e in self . edges ] } |
def tile ( lt , width = 70 , gap = 1 ) :
"""Pretty print list of items .""" | from jcvi . utils . iter import grouper
max_len = max ( len ( x ) for x in lt ) + gap
items_per_line = max ( width // max_len , 1 )
lt = [ x . rjust ( max_len ) for x in lt ]
g = list ( grouper ( lt , items_per_line , fillvalue = "" ) )
return "\n" . join ( "" . join ( x ) for x in g ) |
def topological_sort ( self ) :
"""Perform a topological sort of the graph .
: return : A tuple , the first element of which is a topologically sorted
list of distributions , and the second element of which is a
list of distributions that cannot be sorted because they have
circular dependencies and so form ... | result = [ ]
# Make a shallow copy of the adjacency list
alist = { }
for k , v in self . adjacency_list . items ( ) :
alist [ k ] = v [ : ]
while True : # See what we can remove in this run
to_remove = [ ]
for k , v in list ( alist . items ( ) ) [ : ] :
if not v :
to_remove . append ( k ... |
def T ( self , ID , sign ) :
"""Returns the term of an object in a sign .""" | lon = self . terms [ sign ] [ ID ]
ID = 'T_%s_%s' % ( ID , sign )
return self . G ( ID , 0 , lon ) |
def _generate_draw_order ( self , node = None ) :
"""Return a list giving the order to draw visuals .
Each node appears twice in the list - - ( node , True ) appears before the
node ' s children are drawn , and ( node , False ) appears after .""" | if node is None :
node = self . _scene
order = [ ( node , True ) ]
children = node . children
children . sort ( key = lambda ch : ch . order )
for ch in children :
order . extend ( self . _generate_draw_order ( ch ) )
order . append ( ( node , False ) )
return order |
def wrap_constant ( self , val ) :
"""Used for wrapping raw inputs such as numbers in Criterions and Operator .
For example , the expression F ( ' abc ' ) + 1 stores the integer part in a ValueWrapper object .
: param val :
Any value .
: return :
Raw string , number , or decimal values will be returned in... | from . queries import QueryBuilder
if isinstance ( val , ( Term , QueryBuilder , Interval ) ) :
return val
if val is None :
return NullValue ( )
if isinstance ( val , list ) :
return Array ( * val )
if isinstance ( val , tuple ) :
return Tuple ( * val )
_ValueWrapper = getattr ( self , '_wrapper_cls' , ... |
def convert_dot ( node , ** kwargs ) :
"""Map MXNet ' s dot operator attributes to onnx ' s
MatMul and Transpose operators based on the values set for
transpose _ a , transpose _ b attributes .""" | name , input_nodes , attrs = get_inputs ( node , kwargs )
input_node_a = input_nodes [ 0 ]
input_node_b = input_nodes [ 1 ]
trans_a_node = None
trans_b_node = None
trans_a = get_boolean_attribute_value ( attrs , "transpose_a" )
trans_b = get_boolean_attribute_value ( attrs , "transpose_b" )
op_name = "transpose" + str ... |
def expandBranch ( self , index = None , expanded = None ) :
"""Expands or collapses the node at the index and all it ' s descendants .
If expanded is True the nodes will be expanded , if False they will be collapsed , and if
expanded is None the expanded attribute of each item is used .
If parentIndex is Non... | configModel = self . model ( )
if index is None : # index = configTreeModel . createIndex ( )
index = QtCore . QModelIndex ( )
if index . isValid ( ) :
if expanded is None :
item = configModel . getItem ( index )
self . setExpanded ( index , item . expanded )
else :
self . setExpande... |
def _sia ( cache_key , subsystem ) :
"""Return the minimal information partition of a subsystem .
Args :
subsystem ( Subsystem ) : The candidate set of nodes .
Returns :
SystemIrreducibilityAnalysis : A nested structure containing all the
data from the intermediate calculations . The top level contains th... | # pylint : disable = unused - argument
log . info ( 'Calculating big-phi data for %s...' , subsystem )
# Check for degenerate cases
# Phi is necessarily zero if the subsystem is :
# - not strongly connected ;
# - empty ;
# - an elementary micro mechanism ( i . e . no nontrivial bipartitions ) .
# So in those cases we i... |
def ReadHuntCounters ( self , hunt_id ) :
"""Reads hunt counters .""" | num_clients = self . CountHuntFlows ( hunt_id )
num_successful_clients = self . CountHuntFlows ( hunt_id , filter_condition = db . HuntFlowsCondition . SUCCEEDED_FLOWS_ONLY )
num_failed_clients = self . CountHuntFlows ( hunt_id , filter_condition = db . HuntFlowsCondition . FAILED_FLOWS_ONLY )
num_clients_with_results ... |
def trigger ( self , source ) :
"""Triggers all actions meant to trigger on the board state from ` source ` .""" | actions = self . evaluate ( source )
if actions :
if not hasattr ( actions , "__iter__" ) :
actions = ( actions , )
source . game . trigger_actions ( source , actions ) |
def decimal_format ( value , TWOPLACES = Decimal ( 100 ) ** - 2 ) :
'Format a decimal . Decimal like to 2 decimal places .' | if not isinstance ( value , Decimal ) :
value = Decimal ( str ( value ) )
return value . quantize ( TWOPLACES ) |
def exception ( self , * args , ** kwargs ) :
"""Delegate a exception call to the underlying logger .""" | return self . _log_kw ( ERROR , args , kwargs , exc_info = True ) |
def parse ( self , expr , simplify = False ) :
"""Return a boolean expression parsed from ` expr ` either a unicode string
or tokens iterable .
Optionally simplify the expression if ` simplify ` is True .
Raise ParseError on errors .
If ` expr ` is a string , the standard ` tokenizer ` is used for tokenizat... | precedence = { self . NOT : 5 , self . AND : 10 , self . OR : 15 , TOKEN_LPAR : 20 }
if isinstance ( expr , basestring ) :
tokenized = self . tokenize ( expr )
else :
tokenized = iter ( expr )
if TRACE_PARSE :
tokenized = list ( tokenized )
print ( 'tokens:' )
map ( print , tokenized )
tokenized... |
def api_info ( self , headers = None ) :
"""Retrieves information provided by the API root endpoint
` ` ' / api / v1 ' ` ` .
Args :
headers ( dict ) : Optional headers to pass to the request .
Returns :
dict : Details of the HTTP API provided by the BigchainDB
server .""" | return self . transport . forward_request ( method = 'GET' , path = self . api_prefix , headers = headers , ) |
def create_hlamphaplot ( plotman , h , v , alpha , options ) :
'''Plot the data of the tomodir in one overview plot .''' | sizex , sizez = getfigsize ( plotman )
# create figure
f , ax = plt . subplots ( 1 , 3 , figsize = ( 3 * sizex , sizez ) )
if options . title is not None :
plt . suptitle ( options . title , fontsize = 18 )
plt . subplots_adjust ( wspace = 1 , top = 0.8 )
cidh = plotman . parman . add_data ( h )
cidv = plotman ... |
def range ( self , start = 0 , end = None , predicate = None , index = None ) :
"""Retrieves a set of Match objects that are available in given range , sorted from start to end .
: param start : the starting index
: type start : int
: param end : the ending index
: type end : int
: param predicate :
: t... | if end is None :
end = self . max_end
else :
end = min ( self . max_end , end )
ret = _BaseMatches . _base ( )
for match in sorted ( self ) :
if match . start < end and match . end > start :
ret . append ( match )
return filter_index ( ret , predicate , index ) |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) :
"""See : meth : ` superclass method
< . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > `
for spec of input and result values .""" | # extracting dictionary of coefficients specific to required
# intensity measure type .
C = self . COEFFS [ imt ]
mean = ( self . _compute_style_of_faulting_term ( rup , C ) + self . _compute_magnitude_scaling ( rup . mag , C ) + self . _compute_distance_scaling ( dists . rjb , C ) + self . _compute_site_term ( sites .... |
def mean ( self ) :
"""Compute a total score for each model over all the tests .
Uses the ` norm _ score ` attribute , since otherwise direct comparison
across different kinds of scores would not be possible .""" | return np . dot ( np . array ( self . norm_scores ) , self . weights ) |
def compare ( self , dn , attr , value ) :
"""Compare the ` ` attr ` ` of the entry ` ` dn ` ` with given ` ` value ` ` .
This is a convenience wrapper for the ldap library ' s ` ` compare ` `
function that returns a boolean value instead of 1 or 0.""" | return self . connection . compare_s ( dn , attr , value ) == 1 |
def generate_results ( cube , q ) :
"""Generate the resulting records for this query , applying pagination .
Values will be returned by their reference .""" | if q . _limit is not None and q . _limit < 1 :
return
rp = cube . engine . execute ( q )
while True :
row = rp . fetchone ( )
if row is None :
return
yield dict ( row . items ( ) ) |
def open_raw_data_file ( filename , mode = "w" , title = "" , scan_parameters = None , socket_address = None ) :
'''Mimics pytables . open _ file ( ) and stores the configuration and run configuration
Returns :
RawDataFile Object
Examples :
with open _ raw _ data _ file ( filename = self . scan _ data _ fil... | return RawDataFile ( filename = filename , mode = mode , title = title , scan_parameters = scan_parameters , socket_address = socket_address ) |
def remove_callback ( self , instance , func ) :
"""Remove a previously - added callback
Parameters
instance
The instance to detach the callback from
func : func
The callback function to remove""" | for cb in [ self . _callbacks , self . _2arg_callbacks ] :
if instance not in cb :
continue
if func in cb [ instance ] :
cb [ instance ] . remove ( func )
return
else :
raise ValueError ( "Callback function not found: %s" % func ) |
def read_solrad ( filename ) :
"""Read NOAA SOLRAD [ 1 ] _ [ 2 ] _ fixed - width file into pandas dataframe .
Parameters
filename : str
filepath or url to read for the fixed - width file .
Returns
data : Dataframe
A dataframe with DatetimeIndex and all of the variables in the
file .
Notes
SOLRAD d... | if 'msn' in filename :
names = MADISON_HEADERS
widths = MADISON_WIDTHS
dtypes = MADISON_DTYPES
else :
names = HEADERS
widths = WIDTHS
dtypes = DTYPES
# read in data
data = pd . read_fwf ( filename , header = None , skiprows = 2 , names = names , widths = widths , na_values = - 9999.9 )
# loop he... |
def _finalize_requires ( self ) :
"""Set ` metadata . python _ requires ` and fix environment markers
in ` install _ requires ` and ` extras _ require ` .""" | if getattr ( self , 'python_requires' , None ) :
self . metadata . python_requires = self . python_requires
if getattr ( self , 'extras_require' , None ) :
for extra in self . extras_require . keys ( ) : # Since this gets called multiple times at points where the
# keys have become ' converted ' extras , en... |
def stop ( self ) :
"""Try to gracefully stop the greenlet synchronously
Stop isn ' t expected to re - raise greenlet _ run exception
( use self . greenlet . get ( ) for that ) ,
but it should raise any stop - time exception""" | if self . _stop_event . ready ( ) :
return
self . _stop_event . set ( )
self . _global_send_event . set ( )
for retrier in self . _address_to_retrier . values ( ) :
if retrier :
retrier . notify ( )
self . _client . set_presence_state ( UserPresence . OFFLINE . value )
self . _client . stop_listener_thr... |
def _discarded_reads1_out_file_name ( self ) :
"""Checks if file name is set for discarded reads1 output .
Returns absolute path .""" | if self . Parameters [ '-3' ] . isOn ( ) :
discarded_reads1 = self . _absolute ( str ( self . Parameters [ '-3' ] . Value ) )
else :
raise ValueError ( "No discarded-reads1 (flag -3) output path specified" )
return discarded_reads1 |
def invalidation_hash ( self ) :
"""Return a hash ( string ) that can be used to determine when the layout
has to be rebuild .""" | # if not self . root :
# return ' < empty - window > '
def _hash_for_split ( split ) :
result = [ ]
for item in split :
if isinstance ( item , ( VSplit , HSplit ) ) :
result . append ( _hash_for_split ( item ) )
elif isinstance ( item , Pane ) :
result . append ( 'p%s' % ... |
def _connect ( self ) :
"""Do not call this directly - call auto _ connect ( ) or connect ( ) ,
which will call _ connect ( ) for you .
Connects to the roaster and creates communication thread .
Raises a RoasterLokkupError exception if the hardware is not found .""" | # the following call raises a RoasterLookupException when the device
# is not found . It is
port = utils . find_device ( '1A86:5523' )
# on some systems , after the device port is added to the device list ,
# it can take up to 20 seconds after USB insertion for
# the port to become available . . . ( ! )
# let ' s put a... |
def mahalanobis ( x , mean , cov ) :
"""Computes the Mahalanobis distance between the state vector x from the
Gaussian ` mean ` with covariance ` cov ` . This can be thought as the number
of standard deviations x is from the mean , i . e . a return value of 3 means
x is 3 std from mean .
Parameters
x : ( ... | x = _validate_vector ( x )
mean = _validate_vector ( mean )
if x . shape != mean . shape :
raise ValueError ( "length of input vectors must be the same" )
y = x - mean
S = np . atleast_2d ( cov )
dist = float ( np . dot ( np . dot ( y . T , inv ( S ) ) , y ) )
return math . sqrt ( dist ) |
def search_proxy_entities ( self , ** kwargs ) : # noqa : E501
"""Search over a customer ' s non - deleted proxies # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . search _ proxy _... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . search_proxy_entities_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . search_proxy_entities_with_http_info ( ** kwargs )
# noqa : E501
return data |
def text ( message : Text , default : Text = "" , validate : Union [ Type [ Validator ] , Callable [ [ Text ] , bool ] , None ] = None , # noqa
qmark : Text = DEFAULT_QUESTION_PREFIX , style : Optional [ Style ] = None , ** kwargs : Any ) -> Question :
"""Prompt the user to enter a free text message .
This questi... | merged_style = merge_styles ( [ DEFAULT_STYLE , style ] )
validator = build_validator ( validate )
def get_prompt_tokens ( ) :
return [ ( "class:qmark" , qmark ) , ( "class:question" , ' {} ' . format ( message ) ) ]
p = PromptSession ( get_prompt_tokens , style = merged_style , validator = validator , ** kwargs )
... |
def _parse_reference ( self , el ) :
"""Return reference ID from href or text content .""" | if '#' in el . get ( 'href' , '' ) :
return [ el . get ( 'href' ) . split ( '#' , 1 ) [ 1 ] ]
elif 'rid' in el . attrib :
return [ el . attrib [ 'rid' ] ]
elif 'idref' in el . attrib :
return [ el . attrib [ 'idref' ] ]
else :
return [ '' . join ( el . itertext ( ) ) . strip ( ) ] |
def images ( self ) :
"""List of images for a response .
When using lookup with RespnoseGroup ' Images ' , you ' ll get a
list of images . Parse them so they are returned in an easily
used list format .
: return :
A list of ` ObjectifiedElement ` images""" | try :
images = [ image for image in self . _safe_get_element ( 'ImageSets.ImageSet' ) ]
except TypeError : # No images in this ResponseGroup
images = [ ]
return images |
def get_election_electoral_votes ( self , election ) :
"""Get all electoral votes for this candidate in an election .""" | candidate_election = CandidateElection . objects . get ( candidate = self , election = election )
return candidate_election . electoral_votes . all ( ) |
def qualify ( self , name ) :
"""Qualify the name as either :
- plain name
- ns prefixed name ( eg : ns0 : Person )
- fully ns qualified name ( eg : { http : / / myns - uri } Person )
@ param name : The name of an object in the schema .
@ type name : str
@ return : A qualifed name .
@ rtype : qname""" | m = self . altp . match ( name )
if m is None :
return qualify ( name , self . wsdl . root , self . wsdl . tns )
else :
return ( m . group ( 4 ) , m . group ( 2 ) ) |
def copy ( self ) :
"""Returns a copy of this ClasspathProducts .
Edits to the copy ' s classpaths or exclude associations will not affect the classpaths or
excludes in the original . The copy is shallow though , so edits to the copy ' s product values
will mutate the original ' s product values . See ` Union... | return ClasspathProducts ( pants_workdir = self . _pants_workdir , classpaths = self . _classpaths . copy ( ) , excludes = self . _excludes . copy ( ) ) |
async def startup ( self , app ) :
"""Initialize a local namespace and setup Jinja2.""" | self . local = slocal ( app . loop )
if self . cfg . configure_jinja2 and 'jinja2' in app . ps :
app . ps . jinja2 . env . add_extension ( 'jinja2.ext.i18n' )
app . ps . jinja2 . env . install_gettext_callables ( lambda x : self . get_translations ( ) . ugettext ( x ) , lambda s , p , n : self . get_translation... |
def dragTo ( x = None , y = None , duration = 0.0 , tween = linear , button = 'left' , pause = None , _pause = True , mouseDownUp = True ) :
"""Performs a mouse drag ( mouse movement while a button is held down ) to a
point on the screen .
The x and y parameters detail where the mouse event happens . If None , ... | _failSafeCheck ( )
x , y = _unpackXY ( x , y )
if mouseDownUp :
mouseDown ( button = button , _pause = False )
_mouseMoveDrag ( 'drag' , x , y , 0 , 0 , duration , tween , button )
if mouseDownUp :
mouseUp ( button = button , _pause = False )
_autoPause ( pause , _pause ) |
def plot_element_profile ( self , element , comp , show_label_index = None , xlim = 5 ) :
"""Draw the element profile plot for a composition varying different
chemical potential of an element .
X value is the negative value of the chemical potential reference to
elemental chemical potential . For example , if... | plt = pretty_plot ( 12 , 8 )
pd = self . _pd
evolution = pd . get_element_profile ( element , comp )
num_atoms = evolution [ 0 ] [ "reaction" ] . reactants [ 0 ] . num_atoms
element_energy = evolution [ 0 ] [ 'chempot' ]
for i , d in enumerate ( evolution ) :
v = - ( d [ "chempot" ] - element_energy )
print ( "... |
def getXRDExpiration ( xrd_element , default = None ) :
"""Return the expiration date of this XRD element , or None if no
expiration was specified .
@ type xrd _ element : ElementTree node
@ param default : The value to use as the expiration if no
expiration was specified in the XRD .
@ rtype : datetime .... | expires_element = xrd_element . find ( expires_tag )
if expires_element is None :
return default
else :
expires_string = expires_element . text
# Will raise ValueError if the string is not the expected format
expires_time = strptime ( expires_string , "%Y-%m-%dT%H:%M:%SZ" )
return datetime ( * expir... |
def search_all ( self , queries , audio_basename = None , case_sensitive = False , subsequence = False , supersequence = False , timing_error = 0.0 , anagram = False , missing_word_tolerance = 0 ) :
"""Returns a dictionary of all results of all of the queries for all of
the audio files .
All the specified param... | search_gen_rest_of_kwargs = { "audio_basename" : audio_basename , "case_sensitive" : case_sensitive , "subsequence" : subsequence , "supersequence" : supersequence , "timing_error" : timing_error , "anagram" : anagram , "missing_word_tolerance" : missing_word_tolerance }
if not isinstance ( queries , ( list , str ) ) :... |
def get_phase ( n_samples , des_mask , asc_mask ) :
'''Get the directional phase sign for each sample in depths
Args
n _ samples : int
Length of output phase array
des _ mask : numpy . ndarray , shape ( n , )
Boolean mask of values where animal is descending
asc _ mask : numpy . ndarray , shape ( n , ) ... | import numpy
phase = numpy . zeros ( n_samples , dtype = int )
phase [ asc_mask ] = 1
phase [ des_mask ] = - 1
return phase |
def what ( self ) :
"""May return a ' postponed ' or ' rescheduled ' string depending what
the start and finish time of the event has been changed to .""" | originalFromDt = dt . datetime . combine ( self . except_date , timeFrom ( self . overrides . time_from ) )
changedFromDt = dt . datetime . combine ( self . date , timeFrom ( self . time_from ) )
originalDaysDelta = dt . timedelta ( days = self . overrides . num_days - 1 )
originalToDt = getAwareDatetime ( self . excep... |
def extend ( self , name , opts , info ) :
'''Extend this type to construct a sub - type .
Args :
name ( str ) : The name of the new sub - type .
opts ( dict ) : The type options for the sub - type .
info ( dict ) : The type info for the sub - type .
Returns :
( synapse . types . Type ) : A new sub - ty... | tifo = self . info . copy ( )
tifo . update ( info )
topt = self . opts . copy ( )
topt . update ( opts )
tobj = self . __class__ ( self . modl , name , tifo , topt )
tobj . subof = self . name
return tobj |
def pretaxonomy_hook ( generator ) :
"""This hook is invoked before the generator ' s . categories property is
filled in . Each article has already been assigned a category
object , but these objects are _ not _ unique per category and so are
not safe to tack metadata onto ( as is ) .
The category metadata ... | category_objects = { }
real_articles = [ ]
for article in generator . articles :
dirname , fname = os . path . split ( article . source_path )
fname , _ = os . path . splitext ( fname )
if fname == 'index' :
category_objects [ dirname ] = make_category ( article , os . path . basename ( dirname ) )
... |
def get_db_mutations ( mut_db_path , gene_list , res_stop_codons ) :
"""This function opens the file resistenss - overview . txt , and reads the
content into a dict of dicts . The dict will contain information about
all known mutations given in the database . This dict is returned .""" | # Open resistens - overview . txt
try :
drugfile = open ( mut_db_path , "r" )
except :
sys . exit ( "Wrong path: %s" % ( mut_db_path ) )
# Initiate variables
known_mutations = dict ( )
drug_genes = dict ( )
known_stop_codon = dict ( )
indelflag = False
stopcodonflag = False
# Go throug mutation file line by lin... |
def ingest ( self , co , classname = None , code_objects = { } , show_asm = None ) :
"""Pick out tokens from an uncompyle6 code object , and transform them ,
returning a list of uncompyle6 Token ' s .
The transformations are made to assist the deparsing grammar .
Specificially :
- various types of LOAD _ CO... | if not show_asm :
show_asm = self . show_asm
bytecode = self . build_instructions ( co )
# show _ asm = ' both '
if show_asm in ( 'both' , 'before' ) :
for instr in bytecode . get_instructions ( co ) :
print ( instr . disassemble ( ) )
# list of tokens / instructions
tokens = [ ]
# " customize " is in t... |
def _decode ( self , data ) :
"""Decode data , if any
Called before passing to stdout / stderr streams""" | if self . encoding :
data = data . decode ( self . encoding , 'replace' )
return data |
def create_configwidget ( self , parent ) :
"""Create configuration dialog box page widget""" | if self . CONFIGWIDGET_CLASS is not None :
configwidget = self . CONFIGWIDGET_CLASS ( self , parent )
configwidget . initialize ( )
return configwidget |
def as_json ( self , ensure_ascii = False ) :
"""Property return key - value json - string from _ _ slots _ _ .""" | return json . dumps ( self . as_dict , ensure_ascii = ensure_ascii ) |
def hover ( self ) :
'''Splattable list of : class : ` ~ bokeh . models . tools . HoverTool ` objects .''' | hovers = [ obj for obj in self . tools if isinstance ( obj , HoverTool ) ]
return _list_attr_splat ( hovers ) |
def add ( self , bounds1 , label1 , bounds2 , label2 , bin3 , label3 , data_label ) :
"""Combines signals from multiple instruments within
given bounds .
Parameters
bounds1 : ( min , max )
Bounds for selecting data on the axis of label1
Data points with label1 in [ min , max ) will be considered .
label... | # TODO Update for 2.7 compatability .
if isinstance ( data_label , str ) :
data_label = [ data_label , ]
elif not isinstance ( data_label , collections . Sequence ) :
raise ValueError ( "Please pass data_label as a string or " "collection of strings." )
# Modeled after pysat . ssnl . median2D
# Make bin boundar... |
def getFeature ( self , compoundId ) :
"""Returns a protocol . Feature object corresponding to a compoundId
: param compoundId : a datamodel . FeatureCompoundId object
: return : a Feature object .
: raises : exceptions . ObjectWithIdNotFoundException if invalid
compoundId is provided .""" | featureId = long ( compoundId . featureId )
with self . _db as dataSource :
featureReturned = dataSource . getFeatureById ( featureId )
if featureReturned is None :
raise exceptions . ObjectWithIdNotFoundException ( compoundId )
else :
gaFeature = self . _gaFeatureForFeatureDbRecord ( featureReturned )
... |
def copy ( self ) :
"""Return a new Block instance with the same attributes .""" | args = [ ]
for arg in self . args :
if isinstance ( arg , Block ) :
arg = arg . copy ( )
elif isinstance ( arg , list ) :
arg = [ b . copy ( ) for b in arg ]
args . append ( arg )
return Block ( self . type , * args ) |
def name ( self ) :
"""Return the name of the node or raise a BadRequest exception
: return str : the name of the field to filter on""" | name = self . filter_ . get ( 'name' )
if name is None :
raise InvalidFilters ( "Can't find name of a filter" )
if '__' in name :
name = name . split ( '__' ) [ 0 ]
if name not in self . schema . _declared_fields :
raise InvalidFilters ( "{} has no attribute {}" . format ( self . schema . __name__ , name ) ... |
def generate_nonce ( ) :
"""Generate nonce number""" | nonce = '' . join ( [ str ( randint ( 0 , 9 ) ) for i in range ( 8 ) ] )
return HMAC ( nonce . encode ( ) , "secret" . encode ( ) , sha1 ) . hexdigest ( ) |
def get_fw ( self , fw_id ) :
"""Return the Firewall given its ID .""" | fw = None
try :
fw = self . neutronclient . show_firewall ( fw_id )
except Exception as exc :
LOG . error ( "Failed to get firewall list for id %(id)s, " "Exc %(exc)s" , { 'id' : fw_id , 'exc' : str ( exc ) } )
return fw |
def Client ( api_version , * args , ** kwargs ) :
"""Return an neutron client .
@ param api _ version : only 2.0 is supported now""" | neutron_client = utils . get_client_class ( API_NAME , api_version , API_VERSIONS , )
return neutron_client ( * args , ** kwargs ) |
def parameters ( self , sequence , value_means , value_ranges , arrangement ) :
"""Relates the individual to be evolved to the full parameter string .
Parameters
sequence : str
Full amino acid sequence for specification object to be
optimized . Must be equal to the number of residues in the
model .
valu... | self . _params [ 'sequence' ] = sequence
self . _params [ 'value_means' ] = value_means
self . _params [ 'value_ranges' ] = value_ranges
self . _params [ 'arrangement' ] = arrangement
if any ( x <= 0 for x in self . _params [ 'value_ranges' ] ) :
raise ValueError ( "range values must be greater than zero" )
self . ... |
def plot_transaction_rate_heterogeneity ( model , suptitle = "Heterogeneity in Transaction Rate" , xlabel = "Transaction Rate" , ylabel = "Density" , suptitle_fontsize = 14 , ** kwargs ) :
"""Plot the estimated gamma distribution of lambda ( customers ' propensities to purchase ) .
Parameters
model : lifetimes ... | from matplotlib import pyplot as plt
r , alpha = model . _unload_params ( "r" , "alpha" )
rate_mean = r / alpha
rate_var = r / alpha ** 2
rv = stats . gamma ( r , scale = 1 / alpha )
lim = rv . ppf ( 0.99 )
x = np . linspace ( 0 , lim , 100 )
fig , ax = plt . subplots ( 1 )
fig . suptitle ( "Heterogeneity in Transactio... |
def mse ( predicted , actual ) :
"""Mean squared error of predictions .
. . versionadded : : 0.5.0
Parameters
predicted : ndarray
Predictions on which to measure error . May
contain a single or multiple column but must
match ` actual ` in shape .
actual : ndarray
Actual values against which to measu... | diff = predicted - actual
return np . average ( diff * diff , axis = 0 ) |
def guess_mime_mimedb ( filename ) :
"""Guess MIME type from given filename .
@ return : tuple ( mime , encoding )""" | mime , encoding = None , None
if mimedb is not None :
mime , encoding = mimedb . guess_type ( filename , strict = False )
if mime not in ArchiveMimetypes and encoding in ArchiveCompressions : # Files like ' t . txt . gz ' are recognized with encoding as format , and
# an unsupported mime - type like ' text / plain ... |
def load_quota ( self , quota , TTL , interval ) :
"""Load new quota with a TTL . If the input is None ,
the reservoir will continue using old quota until it
expires or has a non - None quota / TTL in a future load .""" | if quota is not None :
self . _quota = quota
if TTL is not None :
self . _TTL = TTL
if interval is not None :
self . _report_interval = interval / 10 |
def log ( self , level , msg , * args , ** kwargs ) :
"""Logs a message at a cetain level substituting in the supplied arguments .
This method behaves differently in python and c + + modes .
Args :
level : int , the standard logging level at which to log the message .
msg : str , the text of the message to ... | if level >= logging . FATAL : # Add property to the LogRecord created by this logger .
# This will be used by the ABSLHandler to determine whether it should
# treat CRITICAL / FATAL logs as really FATAL .
extra = kwargs . setdefault ( 'extra' , { } )
extra [ _ABSL_LOG_FATAL ] = True
super ( ABSLLogger , self ) ... |
def __sub_make_request ( self , foc , gpid , callback ) :
"""Make right subscription request depending on whether local or global - used by _ _ sub *""" | # global
if isinstance ( gpid , string_types ) :
gpid = uuid_to_hex ( gpid )
ref = ( foc , gpid )
with self . __sub_add_reference ( ref ) :
req = self . _client . _request_sub_create ( self . __lid , foc , gpid , callback = callback )
# local
elif isinstance ( gpid , Sequence ) and len ( gpid ) == 2... |
def can_use_cached_output ( self , contentitem ) :
"""Tell whether the code should try reading cached output""" | plugin = contentitem . plugin
return appsettings . FLUENT_CONTENTS_CACHE_OUTPUT and plugin . cache_output and contentitem . pk |
def _HasAccessToClient ( self , subject , token ) :
"""Checks if user has access to a client under given URN .""" | client_id , _ = rdfvalue . RDFURN ( subject ) . Split ( 2 )
client_urn = rdf_client . ClientURN ( client_id )
return self . CheckClientAccess ( token , client_urn ) |
def reply ( self , message , text , opts = None ) :
"""Reply to the sender of the provided message with a message containing the provided text .
: param message : the message to reply to
: param text : the text to reply with
: param opts : A dictionary of additional values to add to metadata
: return : None... | metadata = Metadata ( source = self . actor_urn , dest = message [ 'metadata' ] [ 'source' ] ) . __dict__
metadata [ 'opts' ] = opts
message = Message ( text = text , metadata = metadata , should_log = message [ 'should_log' ] ) . __dict__
dest_actor = ActorRegistry . get_by_urn ( message [ 'metadata' ] [ 'dest' ] )
if... |
def _mine_delete ( self , load ) :
'''Allow the minion to delete a specific function from its own mine''' | if 'id' not in load or 'fun' not in load :
return False
if self . opts . get ( 'minion_data_cache' , False ) or self . opts . get ( 'enforce_mine_cache' , False ) :
cbank = 'minions/{0}' . format ( load [ 'id' ] )
ckey = 'mine'
try :
data = self . cache . fetch ( cbank , ckey )
if not is... |
def _get_field_error_dict ( self , field ) :
'''Returns the dict containing the field errors information''' | return { 'name' : field . html_name , 'id' : 'id_{}' . format ( field . html_name ) , # This may be a problem
'errors' : field . errors , } |
def date_to_datetime_tz ( cr , table_name , user_field_name , date_field_name , datetime_field_name ) :
"""Take the related user ' s timezone into account when converting
date field to datetime in a given table .
This function must be call in post migration script .
: param table _ name : Name of the table wh... | cr . execute ( """
SELECT distinct(rp.tz)
FROM %s my_table, res_users ru, res_partner rp
WHERE rp.tz IS NOT NULL
AND my_table.%s=ru.id
AND ru.partner_id=rp.id
""" % ( table_name , user_field_name , ) )
for timezone , in cr . fetchall ( ) :
cr . execute ( "SET ... |
def _build_payload ( self , key , value , metric_type ) :
"""Return the""" | if self . _setting ( 'include_hostname' , True ) :
return self . PAYLOAD_HOSTNAME . format ( self . _prefix , self . _hostname , self . _consumer_name , key , value , metric_type )
return self . PAYLOAD_NO_HOSTNAME . format ( self . _prefix , self . _consumer_name , key , value , metric_type ) |
def from_dict ( cls , d ) :
"""Decode a dictionary , as from : meth : ` to _ dict ` , into an Eds object .""" | makepred , charspan = Pred . surface_or_abstract , Lnk . charspan
top = d . get ( 'top' )
nodes , edges = [ ] , [ ]
for nid , node in d . get ( 'nodes' , { } ) . items ( ) :
props = node . get ( 'properties' , { } )
if 'type' in node :
props [ CVARSORT ] = node [ 'type' ]
if not props :
prop... |
def _restoreResults ( newdir , origdir ) :
"""Move ( not copy ) all files from newdir back to the original directory""" | for fname in glob . glob ( os . path . join ( newdir , '*' ) ) :
shutil . move ( fname , os . path . join ( origdir , os . path . basename ( fname ) ) ) |
def get_last_post_for_model ( cr , uid , ids , model_pool ) :
"""Given a set of ids and a model pool , return a dict of each object ids with
their latest message date as a value .
To be called in post - migration scripts
: param cr : database cursor
: param uid : user id , assumed to be openerp . SUPERUSER ... | if type ( ids ) is not list :
ids = [ ids ]
res = { }
for obj in model_pool . browse ( cr , uid , ids ) :
message_ids = obj . message_ids
if message_ids :
res [ obj . id ] = sorted ( message_ids , key = lambda x : x . date , reverse = True ) [ 0 ] . date
else :
res [ obj . id ] = False
r... |
def register_action ( self , name , ** kwargs ) :
"""Registers given action name , optional arguments like a parent , icon , slot etc . . . can be given .
: param name : Action to register .
: type name : unicode
: param \ * \ * kwargs : Keywords arguments .
: type \ * \ * kwargs : \ * \ *
: return : Acti... | settings = foundations . data_structures . Structure ( ** { "parent" : None , "text" : None , "icon" : None , "icon_text" : None , "checkable" : None , "checked" : None , "status_tip" : None , "whats_this" : None , "tool_tip" : None , "shortcut" : None , "shortcut_context" : None , "slot" : None } )
settings . update (... |
def generate_password_link ( self ) :
"""Generates a link to reset password""" | self . password_link = self . generate_hash ( 50 )
now = datetime . datetime . utcnow ( )
self . password_link_expires = now + datetime . timedelta ( hours = 24 ) |
def put_cors ( Bucket , CORSRules , region = None , key = None , keyid = None , profile = None ) :
'''Given a valid config , update the CORS rules for a bucket .
Returns { updated : true } if CORS was updated and returns
{ updated : False } if CORS was not updated .
CLI Example :
. . code - block : : bash
... | try :
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
if CORSRules is not None and isinstance ( CORSRules , six . string_types ) :
CORSRules = salt . utils . json . loads ( CORSRules )
conn . put_bucket_cors ( Bucket = Bucket , CORSConfiguration = { 'CORSRules' :... |
def buildIcon ( icon ) :
"""Builds an icon from the inputed information .
: param icon | < variant >""" | if icon is None :
return QIcon ( )
if type ( icon ) == buffer :
try :
icon = QIcon ( projexui . generatePixmap ( icon ) )
except :
icon = QIcon ( )
else :
try :
icon = QIcon ( icon )
except :
icon = QIcon ( )
return icon |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.