signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def cmd_velocity ( self , args ) :
'''velocity x - ms y - ms z - ms''' | if ( len ( args ) != 3 ) :
print ( "Usage: velocity x y z (m/s)" )
return
if ( len ( args ) == 3 ) :
x_mps = float ( args [ 0 ] )
y_mps = float ( args [ 1 ] )
z_mps = float ( args [ 2 ] )
# print ( " x : % f , y : % f , z : % f " % ( x _ mps , y _ mps , z _ mps ) )
self . master . mav . set_... |
def detector_50_Cent ( text ) :
"""Determine whether 50 Cent is a topic .""" | keywords = [ "50 Cent" , "rap" , "hip hop" , "Curtis James Jackson III" , "Curtis Jackson" , "Eminem" , "Dre" , "Get Rich or Die Tryin'" , "G-Unit" , "Street King Immortal" , "In da Club" , "Interscope" , ]
num_keywords = sum ( word in text for word in keywords )
return ( "50 Cent" , float ( num_keywords > 2 ) ) |
def ping ( bot , mask , target , args ) :
"""ping / pong
% % ping""" | bot . send ( 'NOTICE %(nick)s :PONG %(nick)s!' % dict ( nick = mask . nick ) ) |
def convert_iris ( directory , output_directory , output_filename = 'iris.hdf5' ) :
"""Convert the Iris dataset to HDF5.
Converts the Iris dataset to an HDF5 dataset compatible with
: class : ` fuel . datasets . Iris ` . The converted dataset is
saved as ' iris . hdf5 ' .
This method assumes the existence o... | classes = { b'Iris-setosa' : 0 , b'Iris-versicolor' : 1 , b'Iris-virginica' : 2 }
data = numpy . loadtxt ( os . path . join ( directory , 'iris.data' ) , converters = { 4 : lambda x : classes [ x ] } , delimiter = ',' )
features = data [ : , : - 1 ] . astype ( 'float32' )
targets = data [ : , - 1 ] . astype ( 'uint8' )... |
def ParseFromHumanReadable ( self , string ) :
"""Parse a human readable string of a byte string .
Args :
string : The string to parse .
Raises :
DecodeError : If the string can not be parsed .""" | if not string :
return None
match = self . REGEX . match ( string . strip ( ) . lower ( ) )
if not match :
raise DecodeError ( "Unknown specification for ByteSize %s" % string )
multiplier = self . DIVIDERS . get ( match . group ( 2 ) )
if not multiplier :
raise DecodeError ( "Invalid multiplier %s" % match... |
def format ( self , record ) :
"""Format a message from a record object .""" | record = ColoredRecord ( record )
record . log_color = self . color ( self . log_colors , record . levelname )
# Set secondary log colors
if self . secondary_log_colors :
for name , log_colors in self . secondary_log_colors . items ( ) :
color = self . color ( log_colors , record . levelname )
setat... |
def get_all_kernels ( self , kernel_ids = None , owners = None ) :
"""Retrieve all the EC2 kernels available on your account .
Constructs a filter to allow the processing to happen server side .
: type kernel _ ids : list
: param kernel _ ids : A list of strings with the image IDs wanted
: type owners : lis... | params = { }
if kernel_ids :
self . build_list_params ( params , kernel_ids , 'ImageId' )
if owners :
self . build_list_params ( params , owners , 'Owner' )
filter = { 'image-type' : 'kernel' }
self . build_filter_params ( params , filter )
return self . get_list ( 'DescribeImages' , params , [ ( 'item' , Image... |
def update ( self , milliseconds ) :
"""Updates all of the objects in our world .""" | self . __sort_up ( )
for obj in self . __up_objects :
obj . update ( milliseconds ) |
def get_channelstate_for ( chain_state : ChainState , payment_network_id : PaymentNetworkID , token_address : TokenAddress , partner_address : Address , ) -> Optional [ NettingChannelState ] :
"""Return the NettingChannelState if it exists , None otherwise .""" | token_network = get_token_network_by_token_address ( chain_state , payment_network_id , token_address , )
channel_state = None
if token_network :
channels = [ token_network . channelidentifiers_to_channels [ channel_id ] for channel_id in token_network . partneraddresses_to_channelidentifiers [ partner_address ] ]
... |
def _encode_datetime ( name , value , dummy0 , dummy1 ) :
"""Encode datetime . datetime .""" | if value . utcoffset ( ) is not None :
value = value - value . utcoffset ( )
millis = int ( calendar . timegm ( value . timetuple ( ) ) * 1000 + value . microsecond / 1000 )
return b"\x09" + name + _PACK_LONG ( millis ) |
def __create_nlinks ( self , data , inds = None , boundary_penalties_fcn = None ) :
"""Compute nlinks grid from data shape information . For boundary penalties
are data ( intensities ) values are used .
ins : Default is None . Used for multiscale GC . This are indexes of
multiscale pixels . Next example shows... | # use the gerneral graph algorithm
# first , we construct the grid graph
start = time . time ( )
if inds is None :
inds = np . arange ( data . size ) . reshape ( data . shape )
# if not self . segparams [ ' use _ boundary _ penalties ' ] and \
# boundary _ penalties _ fcn is None :
if boundary_penalties_fcn is None... |
def confirm ( prompt = None , resp = False ) :
"""Prompts user for confirmation .
: param prompt : String to display to user .
: param resp : Default response value .
: return : Boolean response from user , or default value .""" | if prompt is None :
prompt = 'Confirm'
if resp :
prompt = '%s [%s]|%s: ' % ( prompt , 'y' , 'n' )
else :
prompt = '%s [%s]|%s: ' % ( prompt , 'n' , 'y' )
while True :
ans = raw_input ( prompt )
if not ans :
return resp
if ans not in [ 'y' , 'Y' , 'n' , 'N' ] :
print 'please enter... |
def shuffle ( enable ) :
"""Change shuffle mode of current player .""" | message = command ( protobuf . CommandInfo_pb2 . ChangeShuffleMode )
send_command = message . inner ( )
send_command . options . shuffleMode = 3 if enable else 1
return message |
def subnet_absent ( name , virtual_network , resource_group , connection_auth = None ) :
'''. . versionadded : : 2019.2.0
Ensure a virtual network does not exist in the virtual network .
: param name :
Name of the subnet .
: param virtual _ network :
Name of the existing virtual network containing the sub... | ret = { 'name' : name , 'result' : False , 'comment' : '' , 'changes' : { } }
if not isinstance ( connection_auth , dict ) :
ret [ 'comment' ] = 'Connection information must be specified via connection_auth dictionary!'
return ret
snet = __salt__ [ 'azurearm_network.subnet_get' ] ( name , virtual_network , reso... |
def views_show_many ( self , ids = None , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / views # list - views - by - id" | api_path = "/api/v2/views/show_many.json"
api_query = { }
if "query" in kwargs . keys ( ) :
api_query . update ( kwargs [ "query" ] )
del kwargs [ "query" ]
if ids :
api_query . update ( { "ids" : ids , } )
return self . call ( api_path , query = api_query , ** kwargs ) |
async def i2c_read_data ( self , command ) :
"""This method retrieves the last value read for an i2c device identified by address .
This is a polling implementation and i2c _ read _ request and i2c _ read _ request _ reply may be
a better alternative .
: param command : { " method " : " i2c _ read _ data " , ... | address = int ( command [ 0 ] )
i2c_data = await self . core . i2c_read_data ( address )
reply = json . dumps ( { "method" : "i2c_read_data_reply" , "params" : i2c_data } )
await self . websocket . send ( reply ) |
def get_logins ( self , user_id , start_date = None ) :
"""Gets the login history for a user , default start _ date is 30 days ago
: param int id : User id to get
: param string start _ date : " % m / % d / % Y % H : % M : % s " formatted string .
: returns : list https : / / softlayer . github . io / referen... | if start_date is None :
date_object = datetime . datetime . today ( ) - datetime . timedelta ( days = 30 )
start_date = date_object . strftime ( "%m/%d/%Y 0:0:0" )
date_filter = { 'loginAttempts' : { 'createDate' : { 'operation' : 'greaterThanDate' , 'options' : [ { 'name' : 'date' , 'value' : [ start_date ] } ... |
def _git_config ( cwd , user , password , output_encoding = None ) :
'''Helper to retrieve git config options''' | contextkey = 'git.config.' + cwd
if contextkey not in __context__ :
git_dir = rev_parse ( cwd , opts = [ '--git-dir' ] , user = user , password = password , ignore_retcode = True , output_encoding = output_encoding )
if not os . path . isabs ( git_dir ) :
paths = ( cwd , git_dir , 'config' )
else :
... |
def _graphql_query_waittime ( self , query_hash : str , current_time : float , untracked_queries : bool = False ) -> int :
"""Calculate time needed to wait before GraphQL query can be executed .""" | sliding_window = 660
if query_hash not in self . _graphql_query_timestamps :
self . _graphql_query_timestamps [ query_hash ] = [ ]
self . _graphql_query_timestamps [ query_hash ] = list ( filter ( lambda t : t > current_time - 60 * 60 , self . _graphql_query_timestamps [ query_hash ] ) )
reqs_in_sliding_window = li... |
def long_form_one_format ( jupytext_format , metadata = None , update = None ) :
"""Parse ' sfx . py : percent ' into { ' suffix ' : ' sfx ' , ' extension ' : ' py ' , ' format _ name ' : ' percent ' }""" | if isinstance ( jupytext_format , dict ) :
if update :
jupytext_format . update ( update )
return validate_one_format ( jupytext_format )
if not jupytext_format :
return { }
common_name_to_ext = { 'notebook' : 'ipynb' , 'rmarkdown' : 'Rmd' , 'markdown' : 'md' , 'c++' : 'cpp' }
if jupytext_format . l... |
def raw ( self ) -> str :
"""Return signed raw format string of the Membership instance
: return :""" | return """Version: {0}
Type: Membership
Currency: {1}
Issuer: {2}
Block: {3}
Membership: {4}
UserID: {5}
CertTS: {6}
""" . format ( self . version , self . currency , self . issuer , self . membership_ts , self . membership_type , self . uid , self . identity_ts ) |
def mediation_analysis ( data = None , x = None , m = None , y = None , covar = None , alpha = 0.05 , n_boot = 500 , seed = None , return_dist = False ) :
"""Mediation analysis using a bias - correct non - parametric bootstrap method .
Parameters
data : pd . DataFrame
Dataframe .
x : str
Column name in da... | # Sanity check
assert isinstance ( x , str ) , 'y must be a string.'
assert isinstance ( y , str ) , 'y must be a string.'
assert isinstance ( m , ( list , str ) ) , 'Mediator(s) must be a list or string.'
assert isinstance ( covar , ( type ( None ) , str , list ) )
if isinstance ( m , str ) :
m = [ m ]
n_mediator ... |
def swap_word_order ( source ) :
"""Swap the order of the words in ' source ' bitstring""" | assert len ( source ) % 4 == 0
words = "I" * ( len ( source ) // 4 )
return struct . pack ( words , * reversed ( struct . unpack ( words , source ) ) ) |
def verify_light_chains ( self , threshold = 0.9 ) :
'''Clusters the light chains to identify potentially spurious ( non - lineage )
pairings . Following clustering , all pairs in the largest light chain
cluster are assumed to be correctly paired . For each of those pairs ,
the < verified > attribute is set t... | lseqs = [ l . light for l in self . lights ]
clusters = cluster ( lseqs , threshold = threshold )
clusters . sort ( key = lambda x : x . size , reverse = True )
verified_ids = clusters [ 0 ] . ids
for p in self . lights :
p . verified = True if p . name in verified_ids else False |
def apply ( self , tokens ) :
"""Applies the named entity recognizer to the given list of tokens ,
where each token is a [ word , tag ] list .""" | # Note : we could also scan for patterns , e . g . ,
# " my | his | her name is | was * " = > NNP - PERS .
i = 0
while i < len ( tokens ) :
w = tokens [ i ] [ 0 ] . lower ( )
if RE_ENTITY1 . match ( w ) or RE_ENTITY2 . match ( w ) or RE_ENTITY3 . match ( w ) :
tokens [ i ] [ 1 ] = self . tag
if w in... |
def field_value ( key , label , color , padding ) :
"""Print a specific field ' s stats .""" | if not clr . has_colors and padding > 0 :
padding = 7
if color == "bright gray" or color == "dark gray" :
bright_prefix = ""
else :
bright_prefix = "bright "
field = clr . stringc ( key , "{0}{1}" . format ( bright_prefix , color ) )
field_label = clr . stringc ( label , color )
return "{0:>{1}} {2}" . form... |
def as_widget ( self , widget = None , attrs = None , only_initial = False ) :
"""Renders the field .""" | if not widget :
widget = self . field . widget
if DJANGO_VERSION > ( 1 , 10 ) : # so that we can refer to the field when building the rendering context
widget . _field = self . field
# Make sure that NgWidgetMixin is not already part of the widget ' s bases so it doesn ' t get added twice .
if not isins... |
def LoadFromString ( yaml_doc , product_yaml_key , required_client_values , optional_product_values ) :
"""Loads the data necessary for instantiating a client from file storage .
In addition to the required _ client _ values argument , the yaml file must supply
the keys used to create OAuth2 credentials . It ma... | data = yaml . safe_load ( yaml_doc ) or { }
if 'dfp' in data :
raise googleads . errors . GoogleAdsValueError ( 'Please replace the "dfp" key in the configuration YAML string with' '"ad_manager" to fix this issue.' )
logging_config = data . get ( _LOGGING_KEY )
if logging_config :
logging . config . dictConfig ... |
def _parse_float_vec ( vec ) :
"""Parse a vector of float values representing IBM 8 byte floats into
native 8 byte floats .""" | dtype = np . dtype ( '>u4,>u4' )
vec1 = vec . view ( dtype = dtype )
xport1 = vec1 [ 'f0' ]
xport2 = vec1 [ 'f1' ]
# Start by setting first half of ieee number to first half of IBM
# number sans exponent
ieee1 = xport1 & 0x00ffffff
# The fraction bit to the left of the binary point in the ieee
# format was set and the ... |
def filter_time_frame ( start , delta ) :
"""Filter : class : ` . Line ` objects by their connection time .
: param start : a time expression ( see - s argument on - - help for its format )
to filter log lines that are before this time .
: type start : string
: param delta : a relative time expression ( see... | start_value = start
delta_value = delta
end_value = None
if start_value is not '' :
start_value = _date_str_to_datetime ( start_value )
if delta_value is not '' :
delta_value = _delta_str_to_timedelta ( delta_value )
if start_value is not '' and delta_value is not '' :
end_value = start_value + delta_value
... |
def main ( name , options ) :
"""The main method for this script .
: param name : The name of the VM to create .
: type name : str
: param template _ name : The name of the template to use for creating the VM .
: type template _ name : str""" | server = config . _config_value ( "general" , "server" , options . server )
if server is None :
raise ValueError ( "server must be supplied on command line" " or in configuration file." )
username = config . _config_value ( "general" , "username" , options . username )
if username is None :
raise ValueError ( "... |
def get ( self ) :
"""API endpoint to get the related blocks for a transaction .
Return :
A ` ` list ` ` of ` ` block _ id ` ` s that contain the given transaction . The
list may be filtered when provided a status query parameter :
" valid " , " invalid " , " undecided " .""" | parser = reqparse . RequestParser ( )
parser . add_argument ( 'transaction_id' , type = str , required = True )
args = parser . parse_args ( strict = True )
tx_id = args [ 'transaction_id' ]
pool = current_app . config [ 'bigchain_pool' ]
with pool ( ) as bigchain :
blocks = bigchain . get_block_containing_tx ( tx_... |
def CheckHash ( self , responses ) :
"""Adds the block hash to the file tracker responsible for this vfs URN .""" | index = responses . request_data [ "index" ]
if index not in self . state . pending_files : # This is a blobhash for a file we already failed to read and logged as
# below , check here to avoid logging dups .
return
file_tracker = self . state . pending_files [ index ]
hash_response = responses . First ( )
if not r... |
def geo_haystack ( self , name , bucket_size ) :
"""Create a Haystack index . See :
http : / / www . mongodb . org / display / DOCS / Geospatial + Haystack + Indexing
: param name : Name of the indexed column
: param bucket _ size : Size of the haystack buckets ( see mongo docs )""" | self . components . append ( ( name , 'geoHaystack' ) )
self . __bucket_size = bucket_size
return self |
def unit ( session ) :
"""Run the unit test suite .""" | # Testing multiple version of django
# See https : / / www . djangoproject . com / download / for supported version
django_deps_27 = [ ( 'django==1.8.19' , ) , ( 'django >= 1.11.0, < 2.0.0dev' , ) , ]
if session . virtualenv . interpreter == '2.7' :
[ default ( session , django_dep = django ) for django in django_d... |
def _literal_handling ( self , cursor ) :
"""Parse all literal associated with this cursor .
Literal handling is usually useful only for initialization values .
We can ' t use a shortcut by getting tokens
# init _ value = ' ' . join ( [ t . spelling for t in children [ 0 ] . get _ tokens ( )
# if t . spelli... | # use a shortcut - does not work on unicode var _ decl
# if cursor . kind = = CursorKind . STRING _ LITERAL :
# value = cursor . displayname
# value = self . _ clean _ string _ literal ( cursor , value )
# return value
tokens = list ( cursor . get_tokens ( ) )
log . debug ( 'literal has %d tokens.[ %s ]' , len ( tokens... |
def autohash_decorate ( cls , # type : Type [ T ]
include = None , # type : Union [ str , Tuple [ str ] ]
exclude = None , # type : Union [ str , Tuple [ str ] ]
only_constructor_args = False , # type : bool
only_public_fields = False , # type : bool
) : # type : ( . . . ) - > Type [ T ]
"""To automatically generat... | # first check that we do not conflict with other known decorators
_check_known_decorators ( cls , '@autohash' )
# perform the class mod
_execute_autohash_on_class ( cls , include = include , exclude = exclude , only_constructor_args = only_constructor_args , only_public_fields = only_public_fields )
return cls |
def set_offchain_secret ( state : MediatorTransferState , channelidentifiers_to_channels : ChannelMap , secret : Secret , secrethash : SecretHash , ) -> List [ Event ] :
"""Set the secret to all mediated transfers .""" | state . secret = secret
for pair in state . transfers_pair :
payer_channel = channelidentifiers_to_channels . get ( pair . payer_transfer . balance_proof . channel_identifier , )
if payer_channel :
channel . register_offchain_secret ( payer_channel , secret , secrethash , )
payee_channel = channelid... |
def _get_batch_gender ( items ) :
"""Retrieve gender for a batch of items if consistent .
Better not to specify for mixed populations , CNVkit will work
it out
https : / / github . com / bcbio / bcbio - nextgen / commit / 1a0e217c8a4d3cee10fa890fb3cfd4db5034281d # r26279752""" | genders = set ( [ population . get_gender ( x ) for x in items ] )
if len ( genders ) == 1 :
gender = genders . pop ( )
if gender != "unknown" :
return gender |
def readBoolean ( self ) :
"""Read C { Boolean } .
@ raise ValueError : Error reading Boolean .
@ rtype : C { bool }
@ return : A Boolean value , C { True } if the byte
is nonzero , C { False } otherwise .""" | byte = self . stream . read ( 1 )
if byte == '\x00' :
return False
elif byte == '\x01' :
return True
else :
raise ValueError ( "Error reading boolean" ) |
def isSelfVerificationEnabled ( self ) :
"""Returns if the user that submitted a result for this analysis must
also be able to verify the result
: returns : true or false""" | bsve = self . bika_setup . getSelfVerificationEnabled ( )
vs = self . getSelfVerification ( )
return bsve if vs == - 1 else vs == 1 |
def load_toml_validator_config ( filename ) :
"""Returns a ValidatorConfig created by loading a TOML file from the
filesystem .""" | if not os . path . exists ( filename ) :
LOGGER . info ( "Skipping validator config loading from non-existent config file:" " %s" , filename )
return ValidatorConfig ( )
LOGGER . info ( "Loading validator information from config: %s" , filename )
try :
with open ( filename ) as fd :
raw_config = fd ... |
def recursive_division ( self , cells , min_size , width , height , x = 0 , y = 0 , depth = 0 ) :
"""Recursive division :
1 . Split room randomly
1a . Dodge towards larger half if in doorway
2 . Place doorway randomly
3 . Repeat for each half""" | assert isinstance ( cells , list )
assert isinstance ( min_size , int ) or isinstance ( min_size , float )
assert isinstance ( width , int ) or isinstance ( width , float )
assert isinstance ( height , int ) or isinstance ( height , float )
assert isinstance ( x , int ) or isinstance ( x , float )
assert isinstance ( y... |
def copy_plan ( modeladmin , request , queryset ) :
"""Admin command for duplicating plans preserving quotas and pricings .""" | for plan in queryset :
plan_copy = deepcopy ( plan )
plan_copy . id = None
plan_copy . available = False
plan_copy . default = False
plan_copy . created = None
plan_copy . save ( force_insert = True )
for pricing in plan . planpricing_set . all ( ) :
pricing . id = None
prici... |
def split_hostname_from_port ( cls , hostname ) :
"""given a hostname : port return a tuple ( hostname , port )""" | bits = hostname . split ( ":" , 2 )
p = None
d = bits [ 0 ]
if len ( bits ) == 2 :
p = int ( bits [ 1 ] )
return d , p |
def _unpickle_collection ( self , collection ) :
"""Unpickles all members of the specified dictionary .""" | for mkey in collection :
if isinstance ( collection [ mkey ] , list ) :
for item in collection [ mkey ] :
item . unpickle ( self )
else :
collection [ mkey ] . unpickle ( self ) |
def get_module ( self , lpBaseOfDll ) :
"""@ type lpBaseOfDll : int
@ param lpBaseOfDll : Base address of the DLL to look for .
@ rtype : L { Module }
@ return : Module object with the given base address .""" | self . __initialize_snapshot ( )
if lpBaseOfDll not in self . __moduleDict :
msg = "Unknown DLL base address %s"
msg = msg % HexDump . address ( lpBaseOfDll )
raise KeyError ( msg )
return self . __moduleDict [ lpBaseOfDll ] |
def parse ( self ) :
"""Parse the options .""" | # Run the parser
opt , arg = self . parser . parse_known_args ( self . arguments )
self . opt = opt
self . arg = arg
self . check ( )
# Enable - - all if no particular stat or group selected
opt . all = not any ( [ getattr ( opt , stat . dest ) or getattr ( opt , group . dest ) for group in self . sample_stats . stats ... |
def get_subject_with_local_validation ( jwt_bu64 , cert_obj ) :
"""Validate the JWT and return the subject it contains .
- The JWT is validated by checking that it was signed with a CN certificate .
- The returned subject can be trusted for authz and authn operations .
- Possible validation errors include :
... | try :
jwt_dict = validate_and_decode ( jwt_bu64 , cert_obj )
except JwtException as e :
return log_jwt_bu64_info ( logging . error , str ( e ) , jwt_bu64 )
try :
return jwt_dict [ 'sub' ]
except LookupError :
log_jwt_dict_info ( logging . error , 'Missing "sub" key' , jwt_dict ) |
def string_value ( node ) :
"""Compute the string - value of a node .""" | if ( node . nodeType == node . DOCUMENT_NODE or node . nodeType == node . ELEMENT_NODE ) :
s = u''
for n in axes [ 'descendant' ] ( node ) :
if n . nodeType == n . TEXT_NODE :
s += n . data
return s
elif node . nodeType == node . ATTRIBUTE_NODE :
return node . value
elif ( node . nod... |
def has_bad_headers ( self ) :
"""Checks for bad headers i . e . newlines in subject , sender or recipients .
RFC5322 allows multiline CRLF with trailing whitespace ( FWS ) in headers""" | headers = [ self . sender , self . reply_to ] + self . recipients
for header in headers :
if _has_newline ( header ) :
return True
if self . subject :
if _has_newline ( self . subject ) :
for linenum , line in enumerate ( self . subject . split ( '\r\n' ) ) :
if not line :
... |
def subspace_detect ( detectors , stream , threshold , trig_int , moveout = 0 , min_trig = 1 , parallel = True , num_cores = None ) :
"""Conduct subspace detection with chosen detectors .
: type detectors : list
: param detectors :
list of : class : ` eqcorrscan . core . subspace . Detector ` to be used
for... | from multiprocessing import Pool , cpu_count
# First check that detector parameters are the same
parameters = [ ]
detections = [ ]
for detector in detectors :
parameter = ( detector . lowcut , detector . highcut , detector . filt_order , detector . sampling_rate , detector . multiplex , detector . stachans )
if... |
def _raw ( self , msg ) :
"""Print any command sent in raw format
: param msg : arbitrary code to be printed
: type msg : bytes""" | self . device . write ( msg )
if self . auto_flush :
self . flush ( ) |
def find_occurrences ( self , resource = None , pymodule = None ) :
"""Generate ` Occurrence ` instances""" | tools = _OccurrenceToolsCreator ( self . project , resource = resource , pymodule = pymodule , docs = self . docs )
for offset in self . _textual_finder . find_offsets ( tools . source_code ) :
occurrence = Occurrence ( tools , offset )
for filter in self . filters :
result = filter ( occurrence )
... |
def initializePage ( self ) :
"""Initializes the page based on the current structure information .""" | tree = self . uiStructureTREE
tree . blockSignals ( True )
tree . setUpdatesEnabled ( False )
self . uiStructureTREE . clear ( )
xstruct = self . scaffold ( ) . structure ( )
self . _structure = xstruct
for xentry in xstruct :
XScaffoldElementItem ( tree , xentry )
tree . blockSignals ( False )
tree . setUpdatesEna... |
def _find_contpix ( wl , fluxes , ivars , target_frac ) :
"""Find continuum pix in spec , meeting a set target fraction
Parameters
wl : numpy ndarray
rest - frame wavelength vector
fluxes : numpy ndarray
pixel intensities
ivars : numpy ndarray
inverse variances , parallel to fluxes
target _ frac : f... | print ( "Target frac: %s" % ( target_frac ) )
bad1 = np . median ( ivars , axis = 0 ) == SMALL
bad2 = np . var ( ivars , axis = 0 ) == 0
bad = np . logical_and ( bad1 , bad2 )
npixels = len ( wl ) - sum ( bad )
f_cut = 0.0001
stepsize = 0.0001
sig_cut = 0.0001
contmask = _find_contpix_given_cuts ( f_cut , sig_cut , wl ... |
def References ( self ) :
"""Get all references .
Returns :
dict :
Key ( UInt256 ) : input PrevHash
Value ( TransactionOutput ) : object .""" | if self . __references is None :
refs = { }
# group by the input prevhash
for hash , group in groupby ( self . inputs , lambda x : x . PrevHash ) :
tx , height = GetBlockchain ( ) . GetTransaction ( hash . ToBytes ( ) )
if tx is not None :
for input in group :
ref... |
def distance ( self , other_or_start = None , end = None , features = False ) :
"""check the distance between this an another interval
Parameters
other _ or _ start : Interval or int
either an integer or an Interval with a start attribute indicating
the start of the interval
end : int
if ` other _ or _ ... | if end is None :
assert other_or_start . chrom == self . chrom
other_start , other_end = get_start_end ( other_or_start , end )
if other_start > self . end :
return other_start - self . end
if self . start > other_end :
return self . start - other_end
return 0 |
def get_connection_details ( session , vcenter_resource_model , resource_context ) :
"""Methods retrieves the connection details from the vcenter resource model attributes .
: param CloudShellAPISession session :
: param VMwarevCenterResourceModel vcenter _ resource _ model : Instance of VMwarevCenterResourceMo... | session = session
resource_context = resource_context
# get vCenter connection details from vCenter resource
user = vcenter_resource_model . user
vcenter_url = resource_context . address
password = session . DecryptPassword ( vcenter_resource_model . password ) . Value
return VCenterConnectionDetails ( vcenter_url , us... |
def is_legal ( self , layers = None ) :
'''Judge whether is legal for layers''' | if layers is None :
layers = self . layers
for layer in layers :
if layer . is_delete is False :
if len ( layer . input ) != layer . input_size :
return False
if len ( layer . output ) < layer . output_size :
return False
# layer _ num < = max _ layer _ num
if self . laye... |
def gamma ( ranks_list1 , ranks_list2 ) :
'''Goodman and Kruskal ' s gamma correlation coefficient
: param ranks _ list1 : a list of ranks ( integers )
: param ranks _ list2 : a second list of ranks ( integers ) of equal length with corresponding entries
: return : Gamma correlation coefficient ( rank correla... | num_concordant_pairs = 0
num_discordant_pairs = 0
num_tied_x = 0
num_tied_y = 0
num_tied_xy = 0
num_items = len ( ranks_list1 )
for i in range ( num_items ) :
rank_1 = ranks_list1 [ i ]
rank_2 = ranks_list2 [ i ]
for j in range ( i + 1 , num_items ) :
diff1 = ranks_list1 [ j ] - rank_1
diff2... |
def _filter_hooks ( self , * hook_kinds ) :
"""Filter a list of hooks , keeping only applicable ones .""" | hooks = sum ( ( self . hooks . get ( kind , [ ] ) for kind in hook_kinds ) , [ ] )
return sorted ( hook for hook in hooks if hook . applies_to ( self . transition , self . current_state ) ) |
def getAddr ( self , ifname ) :
"""Get the inet addr for an interface .
@ param ifname : interface name
@ type ifname : string""" | if sys . platform == 'darwin' :
return ifconfig_inet ( ifname ) . get ( 'address' )
return self . _getaddr ( ifname , self . SIOCGIFADDR ) |
def init_sentry ( self , ) :
"""Initializes sentry . io error logging for this session""" | if not self . use_sentry :
return
sentry_config = self . keychain . get_service ( "sentry" )
tags = { "repo" : self . repo_name , "branch" : self . repo_branch , "commit" : self . repo_commit , "cci version" : cumulusci . __version__ , }
tags . update ( self . config . get ( "sentry_tags" , { } ) )
env = self . con... |
def get_all_migrations ( path , databases = None ) :
"""Returns a dictionary of database = > [ migrations ] representing all
migrations contained in ` ` path ` ` .""" | # database : [ ( number , full _ path ) ]
possible_migrations = defaultdict ( list )
try :
in_directory = sorted ( get_file_list ( path ) )
except OSError :
import traceback
print "An error occurred while reading migrations from %r:" % path
traceback . print_exc ( )
return { }
# Iterate through our ... |
def get_user_by_email ( server_context , email ) :
"""Get the user with the provided email . Throws a ValueError if not found .
: param server _ context : A LabKey server context . See utils . create _ server _ context .
: param email :
: return :""" | url = server_context . build_url ( user_controller , 'getUsers.api' )
payload = dict ( includeDeactivatedAccounts = True )
result = server_context . make_request ( url , payload )
if result is None or result [ 'users' ] is None :
raise ValueError ( "No Users in container" + email )
for user in result [ 'users' ] :
... |
def create ( database , tlmdict = None ) :
"""Creates a new database for the given Telemetry Dictionary and
returns a connection to it .""" | if tlmdict is None :
tlmdict = tlm . getDefaultDict ( )
dbconn = connect ( database )
for name , defn in tlmdict . items ( ) :
createTable ( dbconn , defn )
return dbconn |
def from_pb ( cls , database_pb , instance , pool = None ) :
"""Creates an instance of this class from a protobuf .
: type database _ pb :
: class : ` google . spanner . v2 . spanner _ instance _ admin _ pb2 . Instance `
: param database _ pb : A instance protobuf object .
: type instance : : class : ` ~ go... | match = _DATABASE_NAME_RE . match ( database_pb . name )
if match is None :
raise ValueError ( "Database protobuf name was not in the " "expected format." , database_pb . name , )
if match . group ( "project" ) != instance . _client . project :
raise ValueError ( "Project ID on database does not match the " "pr... |
def subscribe ( self , frame ) :
"""Handle the SUBSCRIBE command : Adds this connection to destination .""" | ack = frame . headers . get ( 'ack' )
reliable = ack and ack . lower ( ) == 'client'
self . engine . connection . reliable_subscriber = reliable
dest = frame . headers . get ( 'destination' )
if not dest :
raise ProtocolError ( 'Missing destination for SUBSCRIBE command.' )
if dest . startswith ( '/queue/' ) :
... |
def wait_for ( self , condition , interval = DEFAULT_WAIT_INTERVAL , timeout = DEFAULT_WAIT_TIMEOUT ) :
"""Wait until a condition holds by checking it in regular intervals .
Raises ` ` WaitTimeoutError ` ` on timeout .""" | start = time . time ( )
# at least execute the check once !
while True :
res = condition ( )
if res :
return res
# timeout ?
if time . time ( ) - start > timeout :
break
# wait a bit
time . sleep ( interval )
# timeout occured !
raise WaitTimeoutError ( "wait_for timed out" ) |
def _process_value ( value ) :
"""Convert the value into a human readable diff string""" | if not value :
value = _ ( "Not set" )
# XXX : bad data , e . g . in AS Method field
elif value == "None" :
value = _ ( "Not set" )
# 0 is detected as the portal UID
elif value == "0" :
pass
elif api . is_uid ( value ) :
value = _get_title_or_id_from_uid ( value )
elif isinstance ( value , ( dict ) ) :
... |
def url_params_previous_page ( self ) :
""": rtype : dict [ str , str ]""" | self . assert_has_previous_page ( )
params = { self . PARAM_OLDER_ID : str ( self . older_id ) }
self . _add_count_to_params_if_needed ( params )
return params |
def bz2_opener ( path , pattern = '' , verbose = False ) :
"""Opener that opens single bz2 compressed file .
: param str path : Path .
: param str pattern : Regular expression pattern .
: return : Filehandle ( s ) .""" | source = path if is_url ( path ) else os . path . abspath ( path )
filename = os . path . basename ( path )
if pattern and not re . match ( pattern , filename ) :
logger . verbose ( 'Skipping file: {}, did not match regex pattern "{}"' . format ( os . path . abspath ( path ) , pattern ) )
return
try :
fileh... |
def get_all_distribution_names ( url = None ) :
"""Return all distribution names known by an index .
: param url : The URL of the index .
: return : A list of all known distribution names .""" | if url is None :
url = DEFAULT_INDEX
client = ServerProxy ( url , timeout = 3.0 )
return client . list_packages ( ) |
def unregisterWalkthrough ( self , walkthrough ) :
"""Unregisters the inputed walkthrough from the application walkthroug
list .
: param walkthrough | < XWalkthrough >""" | if type ( walkthrough ) in ( str , unicode ) :
walkthrough = self . findWalkthrough ( walkthrough )
try :
self . _walkthroughs . remove ( walkthrough )
except ValueError :
pass |
def enum_device_interfaces ( h_info , guid ) :
"""Function generator that returns a device _ interface _ data enumerator
for the given device interface info and GUID parameters""" | dev_interface_data = SP_DEVICE_INTERFACE_DATA ( )
dev_interface_data . cb_size = sizeof ( dev_interface_data )
device_index = 0
while SetupDiEnumDeviceInterfaces ( h_info , None , byref ( guid ) , device_index , byref ( dev_interface_data ) ) :
yield dev_interface_data
device_index += 1
del dev_interface_data |
def delete_view ( self , request , object_id , extra_context = None ) :
"""Overrides the default to enable redirecting to the directory view after
deletion of a folder .
we need to fetch the object and find out who the parent is
before super , because super will delete the object and make it
impossible to f... | parent_folder = None
try :
obj = self . queryset ( request ) . get ( pk = unquote ( object_id ) )
parent_folder = obj . parent
except self . model . DoesNotExist :
obj = None
r = super ( FolderAdmin , self ) . delete_view ( request = request , object_id = object_id , extra_context = extra_context )
url = r ... |
def profile_slope ( self , kwargs_lens_list , lens_model_internal_bool = None , num_points = 10 ) :
"""computes the logarithmic power - law slope of a profile
: param kwargs _ lens _ list : lens model keyword argument list
: param lens _ model _ internal _ bool : bool list , indicate which part of the model to ... | theta_E = self . effective_einstein_radius ( kwargs_lens_list )
x0 = kwargs_lens_list [ 0 ] [ 'center_x' ]
y0 = kwargs_lens_list [ 0 ] [ 'center_y' ]
x , y = util . points_on_circle ( theta_E , num_points )
dr = 0.01
x_dr , y_dr = util . points_on_circle ( theta_E + dr , num_points )
if lens_model_internal_bool is None... |
def addr_spec ( self ) :
"""The addr _ spec ( username @ domain ) portion of the address , quoted
according to RFC 5322 rules , but with no Content Transfer Encoding .""" | nameset = set ( self . username )
if len ( nameset ) > len ( nameset - parser . DOT_ATOM_ENDS ) :
lp = parser . quote_string ( self . username )
else :
lp = self . username
if self . domain :
return lp + '@' + self . domain
if not lp :
return '<>'
return lp |
def monkeypatch ( ) :
"""monkeypath built - in numpy functions to call those provided by nparray instead .""" | np . array = array
np . arange = arange
np . linspace = linspace
np . logspace = logspace
np . geomspace = geomspace
np . full = full
np . full_like = full_like
np . zeros = zeros
np . zeros_like = zeros_like
np . ones = ones
np . ones_like = ones_like
np . eye = eye |
def p_const_ref ( self , p ) :
'''const _ ref : IDENTIFIER''' | p [ 0 ] = ast . ConstReference ( p [ 1 ] , lineno = p . lineno ( 1 ) ) |
def removeduplicates ( self , entries = None ) :
'''Loop over children a remove duplicate entries .
@ return - a list of removed entries''' | removed = [ ]
if entries == None :
entries = { }
new_children = [ ]
for c in self . children :
cs = str ( c )
cp = entries . get ( cs , None )
if cp :
new_children . append ( cp )
removed . append ( c )
else :
dups = c . removeduplicates ( entries )
if dups :
... |
def get_max_ptrm_check ( ptrm_checks_included_temps , ptrm_checks_all_temps , ptrm_x , t_Arai , x_Arai ) :
"""input : ptrm _ checks _ included _ temps , ptrm _ checks _ all _ temps , ptrm _ x , t _ Arai , x _ Arai .
sorts through included ptrm _ checks and finds the largest ptrm check diff ,
the sum of the tota... | if not ptrm_checks_included_temps :
return [ ] , float ( 'nan' ) , float ( 'nan' ) , float ( 'nan' ) , float ( 'nan' )
diffs = [ ]
abs_diffs = [ ]
x_Arai_compare = [ ]
ptrm_compare = [ ]
check_percents = [ ]
ptrm_checks_all_temps = list ( ptrm_checks_all_temps )
for check in ptrm_checks_included_temps : # goes thro... |
def get ( self , name , * subkey ) :
"""retrieves a data item , or loads it if it
is not present .""" | if subkey == [ ] :
return self . get_atomic ( name )
else :
return self . get_subkey ( name , tuple ( subkey ) ) |
def generate ( self , minlen , maxlen ) :
"""Generates words of different length without storing
them into memory , enforced by itertools . product""" | if minlen < 1 or maxlen < minlen :
raise ValueError ( )
for cur in range ( minlen , maxlen + 1 ) : # string product generator
str_generator = product ( self . charset , repeat = cur )
for each in str_generator : # yield the produced word
yield '' . join ( each ) + self . delimiter |
def get_task ( self , name , include_helpers = True ) :
"""Get task identified by name or raise TaskNotFound if there
is no such task
: param name : name of helper / task to get
: param include _ helpers : if True , also look for helpers
: return : task or helper identified by name""" | if not include_helpers and name in self . _helper_names :
raise TaskNotFound ( name )
try :
return getattr ( self . _tasks , name )
except AttributeError :
raise TaskNotFound ( name ) |
def _topological_sort ( self ) :
"""Kahn ' s algorithm for Topological Sorting
- Finds cycles in graph
- Computes dependency weight""" | sorted_graph = [ ]
node_map = self . _graph . get_nodes ( )
nodes = [ NodeVisitor ( node_map [ node ] ) for node in node_map ]
def get_pointers_for_edge_nodes ( visitor_decorated_node ) :
edges = [ ]
edge_ids = visitor_decorated_node . get_node ( ) . get_edges ( )
for node in nodes :
if node . get_i... |
def _validate_type ( self , item , name ) :
"""Validate the item against ` allowed _ types ` .""" | if item is None : # don ' t validate None items , since they ' ll be caught by the portion
# of the validator responsible for handling ` required ` ness
return
if not isinstance ( item , self . allowed_types ) :
item_class_name = item . __class__ . __name__
raise ArgumentError ( name , "Expected one of %s, ... |
def asizeof ( * objs , ** opts ) :
'''Return the combined size in bytes of all objects passed as positional argments .
The available options and defaults are the following .
* align = 8 * - - size alignment
* all = False * - - all current objects
* clip = 80 * - - clip ` ` repr ( ) ` ` strings
* code = Fa... | t , p = _objs_opts ( objs , ** opts )
if t :
_asizer . reset ( ** p )
s = _asizer . asizeof ( * t )
_asizer . print_stats ( objs = t , opts = opts )
# show opts as _ kwdstr
_asizer . _clear ( )
else :
s = 0
return s |
def make_energy_funnel_data ( self , cores = 1 ) :
"""Compares models created during the minimisation to the best model .
Returns
energy _ rmsd _ gen : [ ( float , float , int ) ]
A list of triples containing the BUFF score , RMSD to the
top model and generation of a model generated during the
minimisatio... | if not self . parameter_log :
raise AttributeError ( 'No parameter log data to make funnel, have you ran the ' 'optimiser?' )
model_cls = self . _params [ 'specification' ]
gen_tagged = [ ]
for gen , models in enumerate ( self . parameter_log ) :
for model in models :
gen_tagged . append ( ( model [ 0 ]... |
def send ( self , data ) :
"""Open transport , send data , and yield response chunks .""" | try :
proc = subprocess . Popen ( self . cmd , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
except OSError as exc :
raise URLError ( "Calling %r failed (%s)!" % ( ' ' . join ( self . cmd ) , exc ) )
else :
stdout , stderr = proc . communicate ( data )
if proc . r... |
def create_a10_device_instance ( self , context , a10_device_instance ) :
"""Attempt to create instance using neutron context""" | LOG . debug ( "A10DeviceInstancePlugin.create(): a10_device_instance=%s" , a10_device_instance )
config = a10_config . A10Config ( )
vthunder_defaults = config . get_vthunder_config ( )
imgr = instance_manager . InstanceManager . from_config ( config , context )
dev_instance = common_resources . remove_attributes_not_s... |
def increase_last ( self , k ) :
"""Increase the counter of the last matched rule by k .""" | rule = self . _last_rule
if rule is not None :
rule . increase_last ( k ) |
def allKeys ( self ) :
"""Returns a list of all the keys for this settings instance .
: return [ < str > , . . ]""" | if self . _customFormat :
return self . _customFormat . allKeys ( )
else :
return super ( XSettings , self ) . allKeys ( ) |
def _parse_action ( self , action , current_time ) :
"""Parse a player action .
TODO : handle cancels""" | if action . action_type == 'research' :
name = mgz . const . TECHNOLOGIES [ action . data . technology_type ]
self . _research [ action . data . player_id ] . append ( { 'technology' : name , 'timestamp' : _timestamp_to_time ( action . timestamp ) } )
elif action . action_type == 'build' :
self . _build [ a... |
def cdn_set_conf ( self , cname , originConf , environment , token ) :
"""The cdn _ set _ conf method enables the user to update an existing
origin configuration in the CDN .
The cdn _ get _ conf returns the token in the response and the
cdn _ set _ conf requires a token as one of the parameters .
The set a... | return self . client . service . cdn_set_conf ( cname , originConf , environment , token ) |
def feed_forward_builder ( name , hidden_dim , activation , trainable = True ) :
"""Get position - wise feed - forward layer builder .
: param name : Prefix of names for internal layers .
: param hidden _ dim : Hidden dimension of feed forward layer .
: param activation : Activation for feed - forward layer .... | def _feed_forward_builder ( x ) :
return FeedForward ( units = hidden_dim , activation = activation , trainable = trainable , name = name , ) ( x )
return _feed_forward_builder |
def salm2map ( salm , s , lmax , Ntheta , Nphi ) :
"""Convert mode weights of spin - weighted function to values on a grid
Parameters
salm : array _ like , complex , shape ( . . . , ( lmax + 1 ) * * 2)
Input array representing mode weights of the spin - weighted function . This array may be
multi - dimensio... | if Ntheta < 2 or Nphi < 1 :
raise ValueError ( "Input values of Ntheta={0} and Nphi={1} " . format ( Ntheta , Nphi ) + "are not allowed; they must be greater than 1 and 0, respectively." )
if lmax < 1 :
raise ValueError ( "Input value of lmax={0} " . format ( lmax ) + "is not allowed; it must be greater than 0 ... |
def list ( self , ** params ) :
"""Retrieve all lead unqualified reasons
Returns all lead unqualified reasons available to the user according to the parameters provided
: calls : ` ` get / lead _ unqualified _ reasons ` `
: param dict params : ( optional ) Search options .
: return : List of dictionaries th... | _ , _ , lead_unqualified_reasons = self . http_client . get ( "/lead_unqualified_reasons" , params = params )
return lead_unqualified_reasons |
def recurrence ( self , recurrence ) :
"""See ` recurrence ` .""" | if not is_valid_recurrence ( recurrence ) :
raise KeyError ( "'%s' is not a valid recurrence value" % recurrence )
self . _recurrence = recurrence |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.