signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def isin ( arg , values ) :
"""Check whether the value expression is contained within the indicated
list of values .
Parameters
values : list , tuple , or array expression
The values can be scalar or array - like . Each of them must be
comparable with the calling expression , or None ( NULL ) .
Examples... | op = ops . Contains ( arg , values )
return op . to_expr ( ) |
def find_windows ( elements , coordinates , processes = None , mol_size = None , adjust = 1 , pore_opt = True , increment = 1.0 , ** kwargs ) :
"""Return windows diameters and center of masses for a molecule .""" | # Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy ( coordinates )
# Center of our cartesian system is always at origin
origin = np . array ( [ 0 , 0 , 0 ] )
# Initial center of mass to reverse translation at the end
initial_com = center_of_mass ( elements , coordinates )
# Shift the ... |
def get_signatures ( self ) :
"""Return a list of the data of the signature files .
Only v1 / JAR Signing .
: rtype : list of bytes""" | signature_expr = re . compile ( r"^(META-INF/)(.*)(\.RSA|\.EC|\.DSA)$" )
signature_datas = [ ]
for i in self . get_files ( ) :
if signature_expr . search ( i ) :
signature_datas . append ( self . get_file ( i ) )
return signature_datas |
def update_parameter_group ( name , parameters , apply_method = "pending-reboot" , tags = None , region = None , key = None , keyid = None , profile = None ) :
'''Update an RDS parameter group .
CLI example : :
salt myminion boto _ rds . update _ parameter _ group my - param - group parameters = ' { " back _ lo... | res = __salt__ [ 'boto_rds.parameter_group_exists' ] ( name , tags , region , key , keyid , profile )
if not res . get ( 'exists' ) :
return { 'exists' : bool ( res ) , 'message' : 'RDS parameter group {0} does not exist.' . format ( name ) }
param_list = [ ]
for key , value in six . iteritems ( parameters ) :
... |
def _extract_params ( request_dict , param_list , param_fallback = False ) :
'''Extract pddb parameters from request''' | if not param_list or not request_dict :
return dict ( )
query = dict ( )
for param in param_list : # Retrieve all items in the form of { param : value } and
# convert { param _ _ key : value } into { param : { key : value } }
for query_key , query_value in request_dict . items ( ) :
if param == query_ke... |
def process ( self , index = None ) :
"""This will completely process a directory of elevation tiles ( as
supplied in the constructor ) . Both phases of the calculation , the
single tile and edge resolution phases are run .
Parameters
index : int / slice ( optional )
Default None - processes all tiles in ... | # Round 0 of twi processing , process the magnitude and directions of
# slopes
print "Starting slope calculation round"
self . process_twi ( index , do_edges = False , skip_uca_twi = True )
# Round 1 of twi processing
print "Starting self-area calculation round"
self . process_twi ( index , do_edges = False )
# Round 2... |
def load_dbf ( self , shapefile_name ) :
"""Attempts to load file with . dbf extension as both lower and upper case""" | dbf_ext = 'dbf'
try :
self . dbf = open ( "%s.%s" % ( shapefile_name , dbf_ext ) , "rb" )
except IOError :
try :
self . dbf = open ( "%s.%s" % ( shapefile_name , dbf_ext . upper ( ) ) , "rb" )
except IOError :
pass |
def insert ( self , index : int , item : object ) -> None :
"""The Abstract class ` MutableSequence ` leverages this insert method to
perform the ` BlueprintGroup . append ` operation .
: param index : Index to use for removing a new Blueprint item
: param item : New ` Blueprint ` object .
: return : None""... | self . _blueprints . insert ( index , item ) |
def sender ( self , value ) :
"""sender is a property to force to be always a Recipient class""" | if isinstance ( value , Recipient ) :
if value . _parent is None :
value . _parent = self
value . _field = 'from'
self . __sender = value
elif isinstance ( value , str ) :
self . __sender . address = value
self . __sender . name = ''
else :
raise ValueError ( 'sender must be an addre... |
def _set_adjustment_threshold ( self , v , load = False ) :
"""Setter method for adjustment _ threshold , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / autobw _ template / adjustment _ threshold ( container )
If this variable is read - only ( config : false ) in the
source Y... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = adjustment_threshold . adjustment_threshold , is_container = 'container' , presence = False , yang_name = "adjustment-threshold" , rest_name = "adjustment-threshold" , parent = self , path_helper = self . _path_helper , extme... |
def log_likelihood_pairwise ( data , params ) :
"""Compute the log - likelihood of model parameters .""" | loglik = 0
for winner , loser in data :
loglik -= np . logaddexp ( 0 , - ( params [ winner ] - params [ loser ] ) )
return loglik |
def generate_thumbnail_download_link_vimeo ( video_id_from_shortcode ) :
"""Thumbnail URL generator for Vimeo videos .""" | # Following the Vimeo API at https : / / developer . vimeo . com / api # video - request , we need to request the video ' s metadata and get the thumbnail from that . First , then , we ' ll get the metadata in JSON format , and then will parse it to find the thumbnail URL .
video_metadata = urlopen ( "https://vimeo.com... |
def _make_event ( self , event_type , code , value ) :
"""Make a new event and send it to the character device .""" | secs , msecs = convert_timeval ( time . time ( ) )
data = struct . pack ( EVENT_FORMAT , secs , msecs , event_type , code , value )
self . _write_device . write ( data )
self . _write_device . flush ( ) |
def is_running ( self ) :
"""Checks if the container is running .
: returns : True or False
: rtype : bool""" | state = yield from self . _get_container_state ( )
if state == "running" :
return True
if self . status == "started" : # The container crashed we need to clean
yield from self . stop ( )
return False |
def get_intended_direction ( self ) :
"""returns a Y , X value showing which direction the
agent should move in order to get to the target""" | x = 0
y = 0
if self . target_x == self . current_x and self . target_y == self . current_y :
return y , x
# target already acquired
if self . target_y > self . current_y :
y = 1
elif self . target_y < self . current_y :
y = - 1
if self . target_x > self . current_x :
x = 1
elif self . target_x < sel... |
def _rsq_adj ( self ) :
"""Adjusted R - squared .""" | n = self . n
k = self . k
return 1.0 - ( ( 1.0 - self . _rsq ) * ( n - 1.0 ) / ( n - k - 1.0 ) ) |
def include_in ( self , dist ) :
"""Ensure feature and its requirements are included in distribution
You may override this in a subclass to perform additional operations on
the distribution . Note that this method may be called more than once
per feature , and so should be idempotent .""" | if not self . available :
raise DistutilsPlatformError ( self . description + " is required, " "but is not available on this platform" )
dist . include ( ** self . extras )
for f in self . require_features :
dist . include_feature ( f ) |
def fft ( logfile ) :
'''display fft for raw ACC data in logfile''' | print ( "Processing log %s" % filename )
mlog = mavutil . mavlink_connection ( filename )
data = { 'ACC1.rate' : 1000 , 'ACC2.rate' : 1600 , 'ACC3.rate' : 1000 , 'GYR1.rate' : 1000 , 'GYR2.rate' : 800 , 'GYR3.rate' : 1000 }
for acc in [ 'ACC1' , 'ACC2' , 'ACC3' ] :
for ax in [ 'AccX' , 'AccY' , 'AccZ' ] :
d... |
def gcal2jd ( year , month , day ) :
"""Gregorian calendar date to Julian date .
The input and output are for the proleptic Gregorian calendar ,
i . e . , no consideration of historical usage of the calendar is
made .
Parameters
year : int
Year as an integer .
month : int
Month as an integer .
day... | year = int ( year )
month = int ( month )
day = int ( day )
a = ipart ( ( month - 14 ) / 12.0 )
jd = ipart ( ( 1461 * ( year + 4800 + a ) ) / 4.0 )
jd += ipart ( ( 367 * ( month - 2 - 12 * a ) ) / 12.0 )
x = ipart ( ( year + 4900 + a ) / 100.0 )
jd -= ipart ( ( 3 * x ) / 4.0 )
jd += day - 2432075.5
# was 32075 ; add 24... |
def scalar_term ( self , st ) :
"""Return a _ ScalarTermS or _ ScalarTermU from a string , to perform text and HTML substitutions""" | if isinstance ( st , binary_type ) :
return _ScalarTermS ( st , self . _jinja_sub )
elif isinstance ( st , text_type ) :
return _ScalarTermU ( st , self . _jinja_sub )
elif st is None :
return _ScalarTermU ( u ( '' ) , self . _jinja_sub )
else :
return st |
def remove_pod ( self , pod , array , ** kwargs ) :
"""Remove arrays from a pod .
: param pod : Name of the pod .
: type pod : str
: param array : Array to remove from pod .
: type array : str
: param \ * \ * kwargs : See the REST API Guide on your array for the
documentation on the request :
* * DELE... | return self . _request ( "DELETE" , "pod/{0}/array/{1}" . format ( pod , array ) , kwargs ) |
def save_user ( self , request , sociallogin , form = None ) :
"""Saves a newly signed up social login . In case of auto - signup ,
the signup form is not available .""" | u = sociallogin . user
u . set_unusable_password ( )
if form :
get_account_adapter ( ) . save_user ( request , u , form )
else :
get_account_adapter ( ) . populate_username ( request , u )
sociallogin . save ( request )
return u |
def parse_done ( self , buf : memoryview ) -> Tuple [ bool , memoryview ] :
"""Parse the continuation line sent by the client to end the ` ` IDLE ` `
command .
Args :
buf : The continuation line to parse .""" | match = self . _pattern . match ( buf )
if not match :
raise NotParseable ( buf )
done = match . group ( 1 ) . upper ( ) == self . continuation
buf = buf [ match . end ( 0 ) : ]
return done , buf |
def _find_day_section_from_indices ( indices , split_interval ) :
"""Returns a list with [ weekday , section ] identifiers found
using a list of indices .""" | cells_day = 24 * 60 // split_interval
rv = [ [ int ( math . floor ( i / cells_day ) ) , i % cells_day ] for i in indices ]
return rv |
def decorate ( fn , * args , ** kwargs ) :
"""Return a new function that replicates the behavior of the input
but also returns an additional value . Used for creating functions
of the proper type to pass to ` labeledfeatures ( ) ` .
Parameters
fn : function
* args : any
Additional parameters that the re... | def _wrapper ( * _args , ** kwargs ) :
_ret = fn ( * _args , ** kwargs )
if isinstance ( _ret , tuple ) :
return _ret + args
if len ( args ) == 0 :
return _ret
return ( _ret , ) + args
for key , value in kwargs . items ( ) :
_wrapper . __dict__ [ key ] = value
return _wrapper |
def get_top_albums ( self , period = PERIOD_OVERALL , limit = None , cacheable = True ) :
"""Returns the top albums played by a user .
* period : The period of time . Possible values :
o PERIOD _ OVERALL
o PERIOD _ 7DAYS
o PERIOD _ 1MONTH
o PERIOD _ 3MONTHS
o PERIOD _ 6MONTHS
o PERIOD _ 12MONTHS""" | params = self . _get_params ( )
params [ "period" ] = period
if limit :
params [ "limit" ] = limit
doc = self . _request ( self . ws_prefix + ".getTopAlbums" , cacheable , params )
return _extract_top_albums ( doc , self . network ) |
def view_status_code ( codes ) :
"""Return status code or random status code if more than one are given
tags :
- Status codes
parameters :
- in : path
name : codes
produces :
- text / plain
responses :
100:
description : Informational responses
200:
description : Success
300:
description... | if "," not in codes :
try :
code = int ( codes )
except ValueError :
return Response ( "Invalid status code" , status = 400 )
return status_code ( code )
choices = [ ]
for choice in codes . split ( "," ) :
if ":" not in choice :
code = choice
weight = 1
else :
... |
def count_statements ( self , query , language = 'spo' , type = 'triples' , flush = None ) :
"""Run a query in a format supported by the Fedora Resource Index
( e . g . , SPO or Sparql ) and return the count of the results .
: param query : query as a string
: param language : query language to use ; defaults... | result_format = 'count'
http_args = { 'type' : type , 'lang' : language , 'query' : query , 'format' : result_format }
return self . _query ( result_format , http_args , flush ) |
def node_str ( node ) :
"""Returns the complete menu entry text for a menu node , or " " for invisible
menu nodes . Invisible menu nodes are those that lack a prompt or that do
not have a satisfied prompt condition .
Example return value : " [ * ] Bool symbol ( BOOL ) "
The symbol name is printed in parenth... | if not node . prompt :
return ""
# Even for menu nodes for symbols and choices , it ' s wrong to check
# Symbol . visibility / Choice . visibility here . The reason is that a symbol
# ( and a choice , in theory ) can be defined in multiple locations , giving it
# multiple menu nodes , which do not necessarily all h... |
def get_item_search_session ( self , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the item search service .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . assessment . ItemSearchSession ) - an
` ` ItemSearchSession ` `
raise : NullArgument - ` ` proxy ` ` is ` ` null ` `
rai... | if not self . supports_item_search ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . ItemSearchSession ( proxy = proxy , runtime = self . _runtime ) |
def cudnnSetTensor4dDescriptorEx ( tensorDesc , dataType , n , c , h , w , nStride , cStride , hStride , wStride ) :
"""Initialize a Tensor descriptor object with strides .
This function initializes a previously created generic Tensor descriptor object into a
4D tensor , similarly to cudnnSetTensor4dDescriptor ... | status = _libcudnn . cudnnSetTensor4dDescriptorEx ( tensorDesc , dataType , n , c , h , w , nStride , cStride , hStride , wStride )
cudnnCheckStatus ( status ) |
def bank_identifier ( self ) :
"""Return the IBAN ' s Bank Identifier .""" | end = get_iban_spec ( self . country_code ) . bban_split_pos + 4
return self . _id [ 4 : end ] |
def wave_module_patched ( ) :
'''True if wave module can write data size of 0xFFFFF , False otherwise .''' | f = StringIO ( )
w = wave . open ( f , "wb" )
w . setparams ( ( 1 , 2 , 44100 , 0 , "NONE" , "no compression" ) )
patched = True
try :
w . setnframes ( ( 0xFFFFFFFF - 36 ) / w . getnchannels ( ) / w . getsampwidth ( ) )
w . _ensure_header_written ( 0 )
except struct . error :
patched = False
logger . in... |
def project_move ( object_id , input_params = { } , always_retry = False , ** kwargs ) :
"""Invokes the / project - xxxx / move API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Folders - and - Deletion # API - method % 3A - % 2Fclass - xxxx % 2Fmove""" | return DXHTTPRequest ( '/%s/move' % object_id , input_params , always_retry = always_retry , ** kwargs ) |
def key_exists ( self , key ) :
"""Check whether a key exists in the event store .
Returns True if it does , False otherwise .""" | assert isinstance ( key , str )
cursor = self . conn . cursor ( )
with contextlib . closing ( cursor ) :
cursor . execute ( 'SELECT COUNT(*) FROM events WHERE uuid=?' , ( key , ) )
res = cursor . fetchone ( )
count = res [ 0 ]
if count == 0 :
return False
else :
assert count in ( 0 , 1 ) , "Duplicat... |
def _quickLevels ( self , data ) :
"""Estimate the min / max values of * data * by subsampling .""" | while data . size > 1e6 :
ax = np . argmax ( data . shape )
sl = [ slice ( None ) ] * data . ndim
sl [ ax ] = slice ( None , None , 2 )
data = data [ sl ]
return self . _levelsFromMedianAndStd ( data ) |
def interpolate ( self , gmvs ) :
""": param gmvs :
array of intensity measure levels
: returns :
( interpolated loss ratios , interpolated covs , indices > min )""" | # gmvs are clipped to max ( iml )
gmvs_curve = numpy . piecewise ( gmvs , [ gmvs > self . imls [ - 1 ] ] , [ self . imls [ - 1 ] , lambda x : x ] )
idxs = gmvs_curve >= self . imls [ 0 ]
# indices over the minimum
gmvs_curve = gmvs_curve [ idxs ]
return self . _mlr_i1d ( gmvs_curve ) , self . _cov_for ( gmvs_curve ) , ... |
def basic_dependencies ( self ) :
"""Accesses basic dependencies from the XML output
: getter : Returns the dependency graph for basic dependencies
: type : corenlp _ xml . dependencies . DependencyGraph""" | if self . _basic_dependencies is None :
deps = self . _element . xpath ( 'dependencies[@type="basic-dependencies"]' )
if len ( deps ) > 0 :
self . _basic_dependencies = DependencyGraph ( deps [ 0 ] )
return self . _basic_dependencies |
def tx_days_above ( tasmax , thresh = '25.0 degC' , freq = 'YS' ) :
r"""Number of summer days
Number of days where daily maximum temperature exceed a threshold .
Parameters
tasmax : xarray . DataArray
Maximum daily temperature [ ° C ] or [ K ]
thresh : str
Threshold temperature on which to base evaluati... | thresh = utils . convert_units_to ( thresh , tasmax )
f = ( tasmax > ( thresh ) ) * 1
return f . resample ( time = freq ) . sum ( dim = 'time' ) |
def _prefix_from_ip_string ( self , ip_str ) :
"""Turn a netmask / hostmask string into a prefix length .
Args :
ip _ str : A netmask or hostmask , formatted as an IP address .
Returns :
The prefix length as an integer .
Raises :
NetmaskValueError : If the input is not a netmask or hostmask .""" | # Parse the netmask / hostmask like an IP address .
try :
ip_int = self . _ip_int_from_string ( ip_str )
except AddressValueError :
raise NetmaskValueError ( '%s is not a valid netmask' % ip_str )
# Try matching a netmask ( this would be / 1*0 * / as a bitwise regexp ) .
# Note that the two ambiguous cases ( al... |
def track_purchase ( self , user , items , total , purchase_id = None , campaign_id = None , template_id = None , created_at = None , data_fields = None ) :
"""The ' purchase _ id ' argument maps to ' id ' for this API endpoint .
This name is used to distinguish it from other instances where
' id ' is a part of... | call = "/api/commerce/trackPurchase"
payload = { }
if isinstance ( user , dict ) :
payload [ "user" ] = user
else :
raise TypeError ( 'user key is not in Dictionary format' )
if isinstance ( items , list ) :
payload [ "items" ] = items
else :
raise TypeError ( 'items are not in Array format' )
if isinst... |
def get_source ( path ) :
'''yields all non - empty lines in a file''' | for line in read ( path ) :
if 'import' in line or len ( line . strip ( ) ) == 0 or line . startswith ( '#' ) :
continue
if '__name__' in line and '__main__' in line :
break
else :
yield line |
def print_cmd_line ( self , s , target , source , env ) :
"""In python 3 , and in some of our tests , sys . stdout is
a String io object , and it takes unicode strings only
In other cases it ' s a regular Python 2 . x file object
which takes strings ( bytes ) , and if you pass those a
unicode object they tr... | try :
sys . stdout . write ( s + u"\n" )
except UnicodeDecodeError :
sys . stdout . write ( s + "\n" ) |
def energy ( self , sample_like , dtype = np . float ) :
"""The energy of the given sample .
Args :
sample _ like ( samples _ like ) :
A raw sample . ` sample _ like ` is an extension of
NumPy ' s array _ like structure . See : func : ` . as _ samples ` .
dtype ( : class : ` numpy . dtype ` , optional ) :... | energy , = self . energies ( sample_like , dtype = dtype )
return energy |
def _level_coords ( self ) :
"""Return a mapping of all MultiIndex levels and their corresponding
coordinate name .""" | level_coords = OrderedDict ( )
for name , index in self . indexes . items ( ) :
if isinstance ( index , pd . MultiIndex ) :
level_names = index . names
( dim , ) = self . variables [ name ] . dims
level_coords . update ( { lname : dim for lname in level_names } )
return level_coords |
def get_queryset ( self ) :
'''Parameters are already validated in the QuerySetPermission''' | model_type = self . request . GET . get ( "type" )
pk = self . request . GET . get ( "id" )
content_type_model = ContentType . objects . get ( model = model_type . lower ( ) )
Model = content_type_model . model_class ( )
model_obj = Model . objects . filter ( id = pk ) . first ( )
return Comment . objects . filter_by_o... |
def diff_trees ( left , right , diff_options = None , formatter = None ) :
"""Takes two lxml root elements or element trees""" | if formatter is not None :
formatter . prepare ( left , right )
if diff_options is None :
diff_options = { }
differ = diff . Differ ( ** diff_options )
diffs = differ . diff ( left , right )
if formatter is None :
return list ( diffs )
return formatter . format ( diffs , left ) |
def generate_defect_structure ( self , supercell = ( 1 , 1 , 1 ) ) :
"""Returns Defective Substitution structure , decorated with charge
Args :
supercell ( int , [ 3x1 ] , or [ [ ] ] ( 3x3 ) ) : supercell integer , vector , or scaling matrix""" | defect_structure = self . bulk_structure . copy ( )
defect_structure . make_supercell ( supercell )
# consider modifying velocity property to make sure defect site is decorated
# consistently with bulk structure for final defect _ structure
defect_properties = self . site . properties . copy ( )
if ( 'velocities' in se... |
def from_def ( cls , obj ) :
"""Builds a profile object from a raw player summary object""" | prof = cls ( obj [ "steamid" ] )
prof . _cache = obj
return prof |
def with_indices ( * args ) :
'''Create indices for an event class . Every event class must be decorated with this decorator .''' | def decorator ( cls ) :
for c in cls . __bases__ :
if hasattr ( c , '_indicesNames' ) :
cls . _classnameIndex = c . _classnameIndex + 1
for i in range ( 0 , cls . _classnameIndex ) :
setattr ( cls , '_classname' + str ( i ) , getattr ( c , '_classname' + str ( i ) ) )... |
def global_defaults ( ) :
"""Default configuration values and behavior toggles .
Fabric only extends this method in order to make minor adjustments and
additions to Invoke ' s ` ~ invoke . config . Config . global _ defaults ` ; see its
documentation for the base values , such as the config subtrees
control... | # TODO : hrm should the run - related things actually be derived from the
# runner _ class ? E . g . Local defines local stuff , Remote defines remote
# stuff ? Doesn ' t help with the final config tree tho . . .
# TODO : as to that , this is a core problem , Fabric wants split
# local / remote stuff , eg replace _ env... |
def _get_separated_values ( self , secondary = False ) :
"""Separate values between odd and even series stacked""" | series = self . secondary_series if secondary else self . series
positive_vals = map ( sum , zip ( * [ serie . safe_values for index , serie in enumerate ( series ) if index % 2 ] ) )
negative_vals = map ( sum , zip ( * [ serie . safe_values for index , serie in enumerate ( series ) if not index % 2 ] ) )
return list (... |
def read ( self , fileobj ) :
"""Return if all data could be read and the atom payload""" | fileobj . seek ( self . _dataoffset , 0 )
data = fileobj . read ( self . datalength )
return len ( data ) == self . datalength , data |
def _forward ( self ) :
"""Advance to the next token .
Internal methods , updates :
- self . current _ token
- self . current _ pos
Raises :
MissingTokensError : when trying to advance beyond the end of the
token flow .""" | try :
self . current_token = next ( self . tokens )
except StopIteration :
raise MissingTokensError ( "Unexpected end of token stream at %d." % self . current_pos )
self . current_pos += 1 |
def _transform_prefix ( cls , root_node , create_group_func ) :
"""Yield all the regular expressions matching a prefix of the grammar
defined by the ` Node ` instance .
This can yield multiple expressions , because in the case of on OR
operation in the grammar , we can have another outcome depending on
whic... | def transform ( node ) : # Generate regexes for all permutations of this OR . Each node
# should be in front once .
if isinstance ( node , Any ) :
for c in node . children :
for r in transform ( c ) :
yield '(?:%s)?' % r
# For a sequence . We can either have a match for the s... |
def no_selenium_errors ( func ) :
"""Decorator to create an ` EmptyPromise ` check function that is satisfied
only when ` func ` executes without a Selenium error .
This protects against many common test failures due to timing issues .
For example , accessing an element after it has been modified by JavaScrip... | def _inner ( * args , ** kwargs ) : # pylint : disable = missing - docstring
try :
return_val = func ( * args , ** kwargs )
except WebDriverException :
LOGGER . warning ( u'Exception ignored during retry loop:' , exc_info = True )
return False
else :
return return_val
return ... |
def _cleanup ( self ) :
"""Remove the connection from the stack , closing out the cursor""" | if self . _cursor :
LOGGER . debug ( 'Closing the cursor on %s' , self . pid )
self . _cursor . close ( )
self . _cursor = None
if self . _conn :
LOGGER . debug ( 'Freeing %s in the pool' , self . pid )
try :
pool . PoolManager . instance ( ) . free ( self . pid , self . _conn )
except p... |
def handle_message ( self , stream , payload ) :
'''Handle incoming messages from underlying TCP streams
: stream ZMQStream stream : A ZeroMQ stream .
See http : / / zeromq . github . io / pyzmq / api / generated / zmq . eventloop . zmqstream . html
: param dict payload : A payload to process''' | try :
payload = self . serial . loads ( payload [ 0 ] )
payload = self . _decode_payload ( payload )
except Exception as exc :
exc_type = type ( exc ) . __name__
if exc_type == 'AuthenticationError' :
log . debug ( 'Minion failed to auth to master. Since the payload is ' 'encrypted, it is not kn... |
def remove_pardir_symbols ( path , sep = os . sep , pardir = os . pardir ) :
"""Remove relative path symobls such as ' . . '
Args :
path ( str ) : A target path string
sep ( str ) : A strint to refer path delimiter ( Default : ` os . sep ` )
pardir ( str ) : A string to refer parent directory ( Default : ` ... | bits = path . split ( sep )
bits = ( x for x in bits if x != pardir )
return sep . join ( bits ) |
def instance_cache ( cls , func ) :
"""Save the cache to ` self `
This decorator take it for granted that the decorated function
is a method . The first argument of the function is ` self ` .
: param func : function to decorate
: return : the decorator""" | @ functools . wraps ( func )
def func_wrapper ( * args , ** kwargs ) :
if not args :
raise ValueError ( '`self` is not available.' )
else :
the_self = args [ 0 ]
func_key = cls . get_key ( func )
val_cache = cls . get_self_cache ( the_self , func_key )
lock = cls . get_self_cache_loc... |
def add_cell ( preso , pos , width , height , padding = 1 , top_margin = 4 , left_margin = 2 ) :
"""Add a text frame to current slide""" | available_width = SLIDE_WIDTH
available_width -= left_margin * 2
available_width -= padding * ( width - 1 )
column_width = available_width / width
avail_height = SLIDE_HEIGHT
avail_height -= top_margin
avail_height -= padding * ( height - 1 )
column_height = avail_height / height
col_pos = int ( ( pos - 1 ) % width )
r... |
def _dispatch_trigger ( self , msg ) :
"""Dispatches the message to the corresponding method .""" | if not msg . args [ 0 ] . startswith ( self . trigger_char ) :
return
split_args = msg . args [ 0 ] . split ( )
trigger = split_args [ 0 ] . lstrip ( self . trigger_char )
if trigger in self . triggers :
method = getattr ( self , trigger )
if msg . command == PRIVMSG :
if msg . dst == self . irc . n... |
def synthesize_multiple ( self , text_file , output_file_path , quit_after = None , backwards = False ) :
"""Synthesize the text contained in the given fragment list
into a WAVE file .
Return a tuple ( anchors , total _ time , num _ chars ) .
Concrete subclasses must implement at least one
of the following ... | if text_file is None :
self . log_exc ( u"text_file is None" , None , True , TypeError )
if len ( text_file ) < 1 :
self . log_exc ( u"The text file has no fragments" , None , True , ValueError )
if text_file . chars == 0 :
self . log_exc ( u"All fragments in the text file are empty" , None , True , ValueEr... |
def resume ( config_path : str , restore_from : Optional [ str ] , cl_arguments : Iterable [ str ] , output_root : str ) -> None :
"""Load config from the directory specified and start the training .
: param config _ path : path to the config file or the directory in which it is stored
: param restore _ from : ... | config = None
try :
config_path = find_config ( config_path )
restore_from = restore_from or path . dirname ( config_path )
config = load_config ( config_file = config_path , additional_args = cl_arguments )
validate_config ( config )
logging . debug ( '\tLoaded config: %s' , config )
except Excepti... |
def Call ( self , position , function_call ) :
"""Perform a function call in the inferior .
WARNING : Since Gdb ' s concept of threads can ' t be directly identified with
python threads , the function call will be made from what has to be assumed
is an arbitrary thread . This * will * interrupt the inferior .... | self . EnsureGdbPosition ( position [ 0 ] , None , None )
if not gdb . selected_thread ( ) . is_stopped ( ) :
self . Interrupt ( position )
result_value = gdb . parse_and_eval ( function_call )
return self . _UnpackGdbVal ( result_value ) |
def Axn ( mt , x , n ) :
"""( A ^ 1 ) x : n : Returns the EPV ( net single premium ) of a term insurance .""" | return ( mt . Mx [ x ] - mt . Mx [ x + n ] ) / mt . Dx [ x ] |
def __match_ancestry ( self , ancestry ) :
"""Find frames matching the given ancestry .
Returns a tuple containing the following :
* Topmost frame matching the given ancestry or the bottom - most sentry
frame if no frame matches .
* Unmatched ancestry part .""" | stack = self . __stack
if len ( stack ) == 1 :
return stack [ 0 ] , ancestry
previous = stack [ 0 ]
for frame , n in zip ( stack [ 1 : ] , xrange ( len ( ancestry ) ) ) :
if frame . id ( ) is not ancestry [ n ] :
return previous , ancestry [ n : ]
previous = frame
return frame , ancestry [ n + 1 : ] |
def close ( self ) :
"""Close ( destroy ) this USB context , and all related instances .
When this method has been called , methods on its instance will
become mosty no - ops , returning None until explicitly re - opened
( by calling open ( ) or _ _ enter _ _ ( ) ) .
Note : " exit " is a deprecated alias of... | self . __auto_open = False
self . __context_cond . acquire ( )
try :
while self . __context_refcount and self . __context_p :
self . __context_cond . wait ( )
self . _exit ( )
finally :
self . __context_cond . notifyAll ( )
self . __context_cond . release ( ) |
def key_from_password ( password ) :
"""This method just hashes self . password .""" | if isinstance ( password , unicode ) :
password = password . encode ( 'utf-8' )
if not isinstance ( password , bytes ) :
raise TypeError ( "password must be byte string, not %s" % type ( password ) )
sha = SHA256 . new ( )
sha . update ( password )
return sha . digest ( ) |
def format_html ( format_string , * args , ** kwargs ) :
"""Similar to str . format , but passes all arguments through conditional _ escape ,
and calls ' mark _ safe ' on the result . This function should be used instead
of str . format or % interpolation to build up small HTML fragments .""" | args_safe = map ( conditional_escape , args )
kwargs_safe = dict ( [ ( k , conditional_escape ( v ) ) for ( k , v ) in six . iteritems ( kwargs ) ] )
return mark_safe ( format_string . format ( * args_safe , ** kwargs_safe ) ) |
def AddTrainingOperators ( model , softmax , label ) :
"""Adds training operators to the model .""" | xent = model . LabelCrossEntropy ( [ softmax , label ] , 'xent' )
# compute the expected loss
loss = model . AveragedLoss ( xent , "loss" )
# track the accuracy of the model
AddAccuracy ( model , softmax , label )
# use the average loss we just computed to add gradient operators to the
# model
model . AddGradientOperat... |
def rename_fmapm ( bids_base , basename ) :
'''Rename magnitude fieldmap file to BIDS specification''' | files = dict ( )
for ext in [ 'nii.gz' , 'json' ] :
for echo in [ 1 , 2 ] :
fname = '{0}_e{1}.{2}' . format ( basename , echo , ext )
src = os . path . join ( bids_base , 'fmap' , fname )
if os . path . exists ( src ) :
dst = src . replace ( 'magnitude_e{0}' . format ( echo ) , '... |
def importpath ( path , error_text = None ) :
"""Import value by specified ` ` path ` ` .
Value can represent module , class , object , attribute or method .
If ` ` error _ text ` ` is not None and import will
raise ImproperlyConfigured with user friendly text .""" | result = None
attrs = [ ]
parts = path . split ( '.' )
exception = None
while parts :
try :
result = __import__ ( '.' . join ( parts ) , { } , { } , [ '' ] )
except ImportError as e :
if exception is None :
exception = e
attrs = parts [ - 1 : ] + attrs
parts = parts [... |
def disconnect ( self , sid , namespace ) :
"""Register a client disconnect from a namespace .""" | if namespace not in self . rooms :
return
rooms = [ ]
for room_name , room in six . iteritems ( self . rooms [ namespace ] . copy ( ) ) :
if sid in room :
rooms . append ( room_name )
for room in rooms :
self . leave_room ( sid , namespace , room )
if sid in self . callbacks and namespace in self . ... |
def __register_notification ( self , prop_name , method , kwargs ) :
"""Internal service which associates the given property name
to the method , and the ( prop _ name , method ) with the given
kwargs dictionary . If needed merges the dictionary , if the
given ( prop _ name , method ) pair was already registe... | key = ( prop_name , method )
if key in self . __PAT_METH_TO_KWARGS :
raise ValueError ( "In class %s method '%s' has been declared " "to be a notification for pattern '%s' " "multiple times (only one is allowed)." % ( self . __class__ , method . __name__ , prop_name ) )
if frozenset ( prop_name ) & WILDCARDS : # ch... |
def set_ylabel ( self , s , panel = None ) :
"set plot xlabel" | if panel is None :
panel = self . current_panel
self . panels [ panel ] . set_ylabel ( s ) |
def split_by_line ( content ) :
"""Split the given content into a list of items by newline .
Both \r \n and \n are supported . This is done since it seems
that TTY devices on POSIX systems use \r \n for newlines in
some instances .
If the given content is an empty string or a string of only
whitespace , a... | # Make sure we don ' t end up splitting a string with
# just a single trailing \ n or \ r \ n into multiple parts .
stripped = content . strip ( )
if not stripped :
return [ ]
if '\r\n' in stripped :
return _strip_all ( stripped . split ( '\r\n' ) )
if '\n' in stripped :
return _strip_all ( stripped . split... |
def do_stop_cluster ( self , cluster ) :
"""Completely stop the cluster
Usage :
> stop _ cluster < cluster >""" | try :
cluster = api . get_cluster ( cluster )
cluster . stop ( )
print ( "Stopping Cluster" )
except ApiException :
print ( "Cluster not found" )
return None |
def update_labels ( repo ) :
"""Update labels .""" | updated = set ( )
for label in repo . get_labels ( ) :
edit = find_label ( label . name , label . color , label . description )
if edit is not None :
print ( ' Updating {}: #{} "{}"' . format ( edit . new , edit . color , edit . description ) )
label . edit ( edit . new , edit . color , edit ... |
def get_or_create_votes ( self , row , division , candidate_election ) :
"""Gets or creates the Vote object for the given row of AP data .""" | vote . Votes . objects . get_or_create ( division = division , count = row [ "votecount" ] , pct = row [ "votepct" ] , winning = row [ "winner" ] , runoff = row [ "runoff" ] , candidate_election = candidate_election , ) |
def decrypt_pillar ( self , pillar ) :
'''Decrypt the specified pillar dictionary items , if configured to do so''' | errors = [ ]
if self . opts . get ( 'decrypt_pillar' ) :
decrypt_pillar = self . opts [ 'decrypt_pillar' ]
if not isinstance ( decrypt_pillar , dict ) :
decrypt_pillar = salt . utils . data . repack_dictlist ( self . opts [ 'decrypt_pillar' ] )
if not decrypt_pillar :
errors . append ( 'decr... |
def _prepare_fetch ( self , request : Request , response : Response ) :
'''Prepare for a fetch .
Coroutine .''' | self . _request = request
self . _response = response
yield from self . _init_stream ( )
connection_closed = self . _control_connection . closed ( )
if connection_closed :
self . _login_table . pop ( self . _control_connection , None )
yield from self . _control_stream . reconnect ( )
request . address = self .... |
def WriteMessageHandlerRequests ( self , requests , cursor = None ) :
"""Writes a list of message handler requests to the database .""" | query = ( "INSERT IGNORE INTO message_handler_requests " "(handlername, request_id, request) VALUES " )
value_templates = [ ]
args = [ ]
for r in requests :
args . extend ( [ r . handler_name , r . request_id , r . SerializeToString ( ) ] )
value_templates . append ( "(%s, %s, %s)" )
query += "," . join ( value... |
def _KillProcess ( self , pid ) :
"""Issues a SIGKILL or equivalent to the process .
Args :
pid ( int ) : process identifier ( PID ) .""" | if sys . platform . startswith ( 'win' ) :
process_terminate = 1
handle = ctypes . windll . kernel32 . OpenProcess ( process_terminate , False , pid )
ctypes . windll . kernel32 . TerminateProcess ( handle , - 1 )
ctypes . windll . kernel32 . CloseHandle ( handle )
else :
try :
os . kill ( p... |
def on_train_begin ( self , ** kwargs : Any ) -> None :
"Initialize inner arguments ." | self . wait , self . opt = 0 , self . learn . opt
super ( ) . on_train_begin ( ** kwargs ) |
def get_links ( html , outformat ) :
"""Return a list of reference links from the html .
Parameters
html : str
outformat : int
the output format of the citations
Returns
List [ str ]
the links to the references""" | if outformat == FORMAT_BIBTEX :
refre = re . compile ( r'<a href="https://scholar.googleusercontent.com(/scholar\.bib\?[^"]*)' )
elif outformat == FORMAT_ENDNOTE :
refre = re . compile ( r'<a href="https://scholar.googleusercontent.com(/scholar\.enw\?[^"]*)"' )
elif outformat == FORMAT_REFMAN :
refre = re .... |
def show_disk ( kwargs = None , conn = None , call = None ) :
'''. . versionadded : : 2015.8.0
Return information about a disk
CLI Example :
. . code - block : : bash
salt - cloud - f show _ disk my - azure name = my _ disk''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The get_disk function must be called with -f or --function.' )
if not conn :
conn = get_conn ( )
if kwargs is None :
kwargs = { }
if 'name' not in kwargs :
raise SaltCloudSystemExit ( 'A name must be specified as "name"' )
data = conn . get_disk ( kwa... |
def zip_unicode ( output , version ) :
"""Zip the Unicode files .""" | zipper = zipfile . ZipFile ( os . path . join ( output , 'unicodedata' , '%s.zip' % version ) , 'w' , zipfile . ZIP_DEFLATED )
target = os . path . join ( output , 'unicodedata' , version )
print ( 'Zipping %s.zip...' % version )
for root , dirs , files in os . walk ( target ) :
for file in files :
if file ... |
def filter_convolve_stack ( data , filters , filter_rot = False , method = 'scipy' ) :
r"""Filter convolve
This method convolves the a stack of input images with the wavelet filters
Parameters
data : np . ndarray
Input data , 3D array
filters : np . ndarray
Wavelet filters , 3D array
filter _ rot : bo... | # Return the convolved data cube .
return np . array ( [ filter_convolve ( x , filters , filter_rot = filter_rot , method = method ) for x in data ] ) |
def format_throughput ( available , used = None ) :
"""Format the read / write throughput for display""" | if used is None :
return str ( available )
percent = float ( used ) / available
return "{0:.0f}/{1:.0f} ({2:.0%})" . format ( used , available , percent ) |
def distinguish ( self , how = True ) :
"""Distinguishes this thing ( POST ) . Calls : meth : ` narwal . Reddit . distinguish ` .
: param how : either True , False , or ' admin '""" | return self . _reddit . distinguish ( self . name , how = how ) |
async def _async_start ( self , auto_register = True ) :
"""Starts the agent from a coroutine . This fires some actions :
* if auto _ register : register the agent in the server
* runs the event loop
* connects the agent to the server
* runs the registered behaviours
Args :
auto _ register ( bool , opti... | if auto_register :
await self . _async_register ( )
self . client = aioxmpp . PresenceManagedClient ( self . jid , aioxmpp . make_security_layer ( self . password , no_verify = not self . verify_security ) , loop = self . loop , logger = logging . getLogger ( self . jid . localpart ) )
# obtain an instance of the s... |
def _reassign_vd_dirrecord_extents ( vd , current_extent ) : # type : ( headervd . PrimaryOrSupplementaryVD , int ) - > Tuple [ int , List [ inode . Inode ] ]
'''An internal helper method for reassign _ extents that assigns extents to
directory records for the passed in Volume Descriptor . The current
extent is... | log_block_size = vd . logical_block_size ( )
# Here we re - walk the entire tree , re - assigning extents as necessary .
root_dir_record = vd . root_directory_record ( )
root_dir_record . set_data_location ( current_extent , 0 )
current_extent += utils . ceiling_div ( root_dir_record . data_length , log_block_size )
# ... |
def parse_named_unicode ( self , i ) :
"""Parse named Unicode .""" | value = ord ( _unicodedata . lookup ( self . get_named_unicode ( i ) ) )
single = self . get_single_stack ( )
if self . span_stack :
text = self . convert_case ( chr ( value ) , self . span_stack [ - 1 ] )
value = ord ( self . convert_case ( text , single ) ) if single is not None else ord ( text )
elif single ... |
def _start_transmit ( self , stream ) :
"""Mark the : attr : ` transmit _ side < Stream . transmit _ side > ` on ` stream ` as
ready for writing . Must only be called from the Broker thread . When the
associated file descriptor becomes ready for writing ,
: meth : ` BasicStream . on _ transmit ` will be calle... | _vv and IOLOG . debug ( '%r._start_transmit(%r)' , self , stream )
side = stream . transmit_side
assert side and side . fd is not None
self . poller . start_transmit ( side . fd , ( side , stream . on_transmit ) ) |
def _RetryLoop ( self , func , timeout = None ) :
"""Retries an operation until success or deadline .
Args :
func : The function to run . Must take a timeout , in seconds , as a single
parameter . If it raises grpc . RpcError and deadline has not be reached ,
it will be run again .
timeout : Retries will ... | timeout = timeout or self . DEFAULT_TIMEOUT
deadline = time . time ( ) + timeout
sleep = 1
while True :
try :
return func ( timeout )
except grpc . RpcError :
if time . time ( ) + sleep > deadline :
raise
time . sleep ( sleep )
sleep *= 2
timeout = deadline - ... |
def page_get_textblocks ( infile , pageno , xmltext , height ) :
"""Get text boxes out of Ghostscript txtwrite xml""" | root = xmltext
if not hasattr ( xmltext , 'findall' ) :
return [ ]
def blocks ( ) :
for span in root . findall ( './/span' ) :
bbox_str = span . attrib [ 'bbox' ]
font_size = span . attrib [ 'size' ]
pts = [ int ( pt ) for pt in bbox_str . split ( ) ]
pts [ 1 ] = pts [ 1 ] - int ... |
def matches ( self , filter_props ) :
"""Check if the filter matches the supplied properties .""" | if filter_props is None :
return False
found_one = False
for key , value in filter_props . items ( ) :
if key in self . properties and value != self . properties [ key ] :
return False
elif key in self . properties and value == self . properties [ key ] :
found_one = True
return found_one |
def get_branch ( db , root_hash , key ) :
"""Get a long - format Merkle branch""" | validate_is_bytes ( key )
return tuple ( _get_branch ( db , root_hash , encode_to_bin ( key ) ) ) |
def eventChunk ( key , lines ) :
"""Parse EVENT chunks""" | # # NOTE : RADAR file format not supported currently .
# # TODO : Add Support for RADAR file format type values
# Contants
KEYWORDS = ( 'EVENT' , 'NRPDS' , 'NRGAG' , 'COORD' , 'GAGES' , 'ACCUM' , 'RATES' , 'RADAR' )
NUM_CARDS = ( 'NRPDS' , 'NRGAG' )
VALUE_CARDS = ( 'GAGES' , 'ACCUM' , 'RATES' , 'RADAR' )
# Define resul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.