signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def any_hook ( * hook_patterns ) :
"""Assert that the currently executing hook matches one of the given patterns .
Each pattern will match one or more hooks , and can use the following
special syntax :
* ` ` db - relation - { joined , changed } ` ` can be used to match multiple hooks
( in this case , ` ` db... | current_hook = hookenv . hook_name ( )
# expand { role : interface } patterns
i_pat = re . compile ( r'{([^:}]+):([^}]+)}' )
hook_patterns = _expand_replacements ( i_pat , hookenv . role_and_interface_to_relations , hook_patterns )
# expand { A , B , C , . . . } patterns
c_pat = re . compile ( r'{((?:[^:,}]+,?)+)}' )
h... |
def parse_readme ( ) :
"""Parse contents of the README .""" | # Get the long description from the relevant file
here = os . path . abspath ( os . path . dirname ( __file__ ) )
readme_path = os . path . join ( here , 'README.md' )
with codecs . open ( readme_path , encoding = 'utf-8' ) as handle :
long_description = handle . read ( )
return long_description |
def dictlist_convert_to_bool ( dict_list : Iterable [ Dict ] , key : str ) -> None :
"""Process an iterable of dictionaries . For each dictionary ` ` d ` ` , convert
( in place ) ` ` d [ key ] ` ` to a bool . If that fails , convert it to ` ` None ` ` .""" | for d in dict_list : # d [ key ] = True if d [ key ] = = " Y " else False
d [ key ] = 1 if d [ key ] == "Y" else 0 |
def check_acknowledgment ( self , ds ) :
'''Check if acknowledgment / acknowledgment attribute is present . Because
acknowledgement has its own check , we are keeping it out of the Global
Attributes ( even though it is a Global Attr ) .
: param netCDF4 . Dataset ds : An open netCDF dataset''' | check = False
messages = [ ]
if hasattr ( ds , 'acknowledgment' ) or hasattr ( ds , 'acknowledgement' ) :
check = True
else :
messages . append ( "acknowledgment/acknowledgement not present" )
# name = " Global Attributes " so gets grouped with Global Attributes
return Result ( BaseCheck . MEDIUM , check , "Glo... |
def get_or_create_generic ( self , content_object = None , ** kwargs ) :
"""Gets or creates a generic object . This is a wrapper for
get _ or _ create ( . . . ) when you need to get or create a generic object .
: param obj : the object to get or create
: param kwargs : any other kwargs that the model accepts ... | if content_object :
kwargs [ 'content_type' ] = ContentType . objects . get_for_model ( content_object )
kwargs [ 'object_id' ] = content_object . id
return self . get_or_create ( ** kwargs ) |
def relocate_image ( self , new_ImageBase ) :
"""Apply the relocation information to the image using the provided new image base .
This method will apply the relocation information to the image . Given the new base ,
all the relocations will be processed and both the raw data and the section ' s data
will be ... | relocation_difference = new_ImageBase - self . OPTIONAL_HEADER . ImageBase
if self . OPTIONAL_HEADER . DATA_DIRECTORY [ 5 ] . Size :
if not hasattr ( self , 'DIRECTORY_ENTRY_BASERELOC' ) :
self . parse_data_directories ( directories = [ DIRECTORY_ENTRY [ 'IMAGE_DIRECTORY_ENTRY_BASERELOC' ] ] )
for reloc... |
def freeze ( obj ) :
"""Transform tree of dict and list in read - only
data structure .
dict instances are transformed to FrozenDict , lists
in FrozenList .""" | if isinstance ( obj , collections . Mapping ) :
return FrozenDict ( { freeze ( k ) : freeze ( v ) for k , v in six . iteritems ( obj ) } )
elif isinstance ( obj , list ) :
return FrozenList ( [ freeze ( e ) for e in obj ] )
else :
return obj |
def move_page ( request , page_id , extra_context = None ) :
"""Move the page to the requested target , at the given
position .""" | page = Page . objects . get ( pk = page_id )
target = request . POST . get ( 'target' , None )
position = request . POST . get ( 'position' , None )
if target is not None and position is not None :
try :
target = Page . objects . get ( pk = target )
except Page . DoesNotExist :
pass
# TO... |
def beacon ( config ) :
'''Monitor the memory usage of the minion
Specify thresholds for percent used and only emit a beacon
if it is exceeded .
. . code - block : : yaml
beacons :
memusage :
- percent : 63%''' | ret = [ ]
_config = { }
list ( map ( _config . update , config ) )
_current_usage = psutil . virtual_memory ( )
current_usage = _current_usage . percent
monitor_usage = _config [ 'percent' ]
if '%' in monitor_usage :
monitor_usage = re . sub ( '%' , '' , monitor_usage )
monitor_usage = float ( monitor_usage )
if cu... |
def set_C_flag ( self , oper_1 , oper_2 , result , type ) :
"""Set C flag
C flag is set if the unsigned number overflows
This condition is obtained if :
1 . In addition , the result is smaller than either of the operands
2 . In subtraction , if the second operand is larger than the first
This should not b... | # TODO is this correct ?
if type == 'add' :
if result < oper_1 :
self . set_APSR_flag_to_value ( 'C' , 1 )
else :
self . set_APSR_flag_to_value ( 'C' , 0 )
elif type == 'sub' :
if oper_1 < oper_2 : # If there was a borrow , then set to zero
self . set_APSR_flag_to_value ( 'C' , 0 )
... |
def create_srpm ( dist = 'el7' ) :
"""Create an srpm
Requires that sources are available in local directory
dist : set package dist tag ( default : el7)""" | if not RPM_AVAILABLE :
raise RpmModuleNotAvailable ( )
path = os . getcwd ( )
try :
specfile = spec_fn ( )
spec = Spec ( specfile )
except Exception :
return
rpmdefines = [ "--define 'dist .{}'" . format ( dist ) , "--define '_sourcedir {}'" . format ( path ) , "--define '_srcrpmdir {}'" . format ( path... |
def set_seq2 ( self , b ) :
"""Same as SequenceMatcher . set _ seq2 , but uses the c chainb
implementation .""" | if b is self . b and hasattr ( self , 'isbjunk' ) :
return
self . b = b
if not isinstance ( self . a , list ) :
self . a = list ( self . a )
if not isinstance ( self . b , list ) :
self . b = list ( self . b )
# Types must be hashable to work in the c layer . This check lines will
# raise the correct error ... |
def send ( self , data = None , headers = None , ttl = 0 , gcm_key = None , reg_id = None , content_encoding = "aes128gcm" , curl = False , timeout = None ) :
"""Encode and send the data to the Push Service .
: param data : A serialized block of data ( see encode ( ) ) .
: type data : str
: param headers : A ... | # Encode the data .
if headers is None :
headers = dict ( )
encoded = { }
headers = CaseInsensitiveDict ( headers )
if data :
encoded = self . encode ( data , content_encoding )
if "crypto_key" in encoded : # Append the p256dh to the end of any existing crypto - key
crypto_key = headers . get ( "cry... |
def _set_rabbitmq_channel ( self , channel ) :
"""Assign the channel object to the tinman global object .
: param pika . channel . Channel channel : The pika channel""" | setattr ( self . application . attributes , self . CHANNEL , channel ) |
def upstream ( self , table , chrom_or_feat , start = None , end = None , k = 1 ) :
"""Return k - nearest upstream features
Parameters
table : str or table
table against which to query
chrom _ or _ feat : str or feat
either a chromosome , e . g . ' chr3 ' or a feature with . chrom , . start ,
. end attr... | res = self . knearest ( table , chrom_or_feat , start , end , k , "up" )
end = getattr ( chrom_or_feat , "end" , end )
start = getattr ( chrom_or_feat , "start" , start )
rev = getattr ( chrom_or_feat , "strand" , "+" ) == "-"
if rev :
return [ x for x in res if x . end > start ]
else :
return [ x for x in res ... |
def scale ( self , new_volume : float ) -> "Lattice" :
"""Return a new Lattice with volume new _ volume by performing a
scaling of the lattice vectors so that length proportions and angles
are preserved .
Args :
new _ volume :
New volume to scale to .
Returns :
New lattice with desired volume .""" | versors = self . matrix / self . abc
geo_factor = abs ( dot ( np . cross ( versors [ 0 ] , versors [ 1 ] ) , versors [ 2 ] ) )
ratios = np . array ( self . abc ) / self . c
new_c = ( new_volume / ( geo_factor * np . prod ( ratios ) ) ) ** ( 1 / 3.0 )
return Lattice ( versors * ( new_c * ratios ) ) |
def reset_parameter ( self , params ) :
"""Reset parameters of Booster .
Parameters
params : dict
New parameters for Booster .
Returns
self : Booster
Booster with new parameters .""" | if any ( metric_alias in params for metric_alias in ( 'metric' , 'metrics' , 'metric_types' ) ) :
self . __need_reload_eval_info = True
params_str = param_dict_to_str ( params )
if params_str :
_safe_call ( _LIB . LGBM_BoosterResetParameter ( self . handle , c_str ( params_str ) ) )
self . params . update ( par... |
def get_url_title ( url ) :
r"""Request HTML for the page at the URL indicated and return it ' s < title > property
> > > get _ url _ title ( ' mozilla . com ' ) . strip ( )
' Internet for people , not profit \ n — Mozilla '""" | parsed_url = try_parse_url ( url )
if parsed_url is None :
return None
try :
r = requests . get ( parsed_url . geturl ( ) , stream = False , allow_redirects = True , timeout = 5 )
tree = parse_html ( r . content )
title = tree . findtext ( './/title' )
return title
except ConnectionError :
loggi... |
def update_message_type ( self , message_type ) :
"""Update an existing message type
: param message _ type : is the updated message type that the
client wants to update""" | self . _validate_uuid ( message_type . message_type_id )
url = "/notification/v1/message-type/{}" . format ( message_type . message_type_id )
response = NWS_DAO ( ) . putURL ( url , self . _write_headers ( ) , self . _json_body ( message_type . json_data ( ) ) )
if response . status != 204 :
raise DataFailureExcept... |
def init ( ffi , lib ) :
"""Return RingBuffer class using the given CFFI instance .""" | class RingBuffer ( _RingBufferBase ) :
__doc__ = _RingBufferBase . __doc__
_ffi = ffi
_lib = lib
return RingBuffer |
def plot ( self , t = 0. , min = - 15. , max = 15 , ns = 21 , savefilename = None ) :
"""NAME :
plot
PURPOSE :
plot the potential
INPUT :
t - time to evaluate the potential at
min - minimum x
max - maximum x
ns - grid in x
savefilename - save to or restore from this savefile ( pickle )
OUTPUT : ... | if not savefilename == None and os . path . exists ( savefilename ) :
print ( "Restoring savefile " + savefilename + " ..." )
savefile = open ( savefilename , 'rb' )
potx = pickle . load ( savefile )
xs = pickle . load ( savefile )
savefile . close ( )
else :
xs = nu . linspace ( min , max , ns ... |
def decrypt ( data , key ) :
'''decrypt the data with the key''' | data_len = len ( data )
data = ffi . from_buffer ( data )
key = ffi . from_buffer ( __tobytes ( key ) )
out_len = ffi . new ( 'size_t *' )
result = lib . xxtea_decrypt ( data , data_len , key , out_len )
ret = ffi . buffer ( result , out_len [ 0 ] ) [ : ]
lib . free ( result )
return ret |
def get_archive ( self , archive_name , default_version = None ) :
'''Retrieve a data archive
Parameters
archive _ name : str
Name of the archive to retrieve
default _ version : version
str or : py : class : ` ~ distutils . StrictVersion ` giving the default
version number to be used on read operations ... | auth , archive_name = self . _normalize_archive_name ( archive_name )
res = self . manager . get_archive ( archive_name )
if default_version is None :
default_version = self . _default_versions . get ( archive_name , None )
if ( auth is not None ) and ( auth != res [ 'authority_name' ] ) :
raise ValueError ( 'A... |
def readline ( self , raise_exception = False ) :
"""Read a line and return it . If " raise _ exception " is set ,
raise _ ConnectionDeadError if the read fails , otherwise return
an empty string .""" | buf = self . buffer
if self . socket :
recv = self . socket . recv
else :
recv = lambda bufsize : ''
while True :
index = buf . find ( '\r\n' )
if index >= 0 :
break
data = recv ( 4096 )
if not data : # connection close , let ' s kill it and raise
self . mark_dead ( 'connection c... |
def polarity ( self ) :
"""Return the polarity score as a float within the range [ - 1.0 , 1.0]""" | scores = [ w . polarity for w in self . words if w . polarity != 0 ]
if not scores :
return 0.0
return sum ( scores ) / float ( len ( scores ) ) |
def select_one ( self , tag ) :
"""Select a single tag .""" | tags = self . select ( tag , limit = 1 )
return tags [ 0 ] if tags else None |
def whitener_lss ( self ) :
r"""This function takes the linear state space system
that is an input to the Kalman class and it converts
that system to the time - invariant whitener represenation
given by
. . math : :
\ tilde { x } _ { t + 1 } ^ * = \ tilde { A } \ tilde { x } + \ tilde { C } v
a = \ tild... | K = self . K_infinity
# Get the matrix sizes
n , k , m , l = self . ss . n , self . ss . k , self . ss . m , self . ss . l
A , C , G , H = self . ss . A , self . ss . C , self . ss . G , self . ss . H
Atil = np . vstack ( [ np . hstack ( [ A , np . zeros ( ( n , n ) ) , np . zeros ( ( n , l ) ) ] ) , np . hstack ( [ do... |
def format_completion_message ( self , defFile , completionsList ) :
'''Format the completions suggestions in the following format :
@ @ COMPLETIONS ( modFile ( token , description ) , ( token , description ) , ( token , description ) ) END @ @''' | compMsg = [ ]
compMsg . append ( '%s' % defFile )
for tup in completionsList :
compMsg . append ( ',' )
compMsg . append ( '(' )
compMsg . append ( str ( self . remove_invalid_chars ( tup [ 0 ] ) ) )
# token
compMsg . append ( ',' )
compMsg . append ( self . remove_invalid_chars ( tup [ 1 ] ) )
... |
def get_all_hosted_zones ( self , start_marker = None , zone_list = None ) :
"""Returns a Python data structure with information about all
Hosted Zones defined for the AWS account .
: param int start _ marker : start marker to pass when fetching additional
results after a truncated list
: param list zone _ ... | params = { }
if start_marker :
params = { 'marker' : start_marker }
response = self . make_request ( 'GET' , '/%s/hostedzone' % self . Version , params = params )
body = response . read ( )
boto . log . debug ( body )
if response . status >= 300 :
raise exception . DNSServerError ( response . status , response ... |
def _find_usage_apis ( self ) :
"""Find usage on APIs / RestAPIs , and resources that are limited per - API .
Update ` self . limits ` .""" | api_ids = [ ]
logger . debug ( 'Finding usage for APIs' )
regional_count = 0
private_count = 0
edge_count = 0
paginator = self . conn . get_paginator ( 'get_rest_apis' )
for resp in paginator . paginate ( ) :
for api in resp [ 'items' ] :
api_ids . append ( api [ 'id' ] )
epconf = api . get ( 'endpo... |
def create_namespaced_deployment ( self , namespace , body , ** kwargs ) : # noqa : E501
"""create _ namespaced _ deployment # noqa : E501
create a Deployment # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > t... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_namespaced_deployment_with_http_info ( namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . create_namespaced_deployment_with_http_info ( namespace , body , ** kwargs )
# noqa : E501
re... |
def _find_usage_elbv1 ( self ) :
"""Find usage for ELBv1 / Classic ELB and update the appropriate limits .
: returns : number of Classic ELBs in use
: rtype : int""" | logger . debug ( "Checking usage for ELBv1" )
self . connect ( )
lbs = paginate_dict ( self . conn . describe_load_balancers , alc_marker_path = [ 'NextMarker' ] , alc_data_path = [ 'LoadBalancerDescriptions' ] , alc_marker_param = 'Marker' )
for lb in lbs [ 'LoadBalancerDescriptions' ] :
self . limits [ 'Listeners... |
def _Bound_Ph ( P , h ) :
"""Region definition for input P y h
Parameters
P : float
Pressure , [ MPa ]
h : float
Specific enthalpy , [ kJ / kg ]
Returns
region : float
IAPWS - 97 region code
References
Wagner , W ; Kretzschmar , H - J : International Steam Tables : Properties of
Water and Stea... | region = None
if Pmin <= P <= Ps_623 :
h14 = _Region1 ( _TSat_P ( P ) , P ) [ "h" ]
h24 = _Region2 ( _TSat_P ( P ) , P ) [ "h" ]
h25 = _Region2 ( 1073.15 , P ) [ "h" ]
hmin = _Region1 ( 273.15 , P ) [ "h" ]
hmax = _Region5 ( 2273.15 , P ) [ "h" ]
if hmin <= h <= h14 :
region = 1
elif... |
def on_scenario_directory_radio_toggled ( self , flag ) :
"""Autoconnect slot activated when scenario _ directory _ radio is checked .
: param flag : Flag indicating whether the checkbox was toggled on or
off .
: type flag : bool""" | if flag :
self . output_directory . setText ( self . source_directory . text ( ) )
self . output_directory_chooser . setEnabled ( not flag ) |
def on_display_n_changed ( self , combo ) :
"""Set the destination display in dconf .""" | i = combo . get_active_iter ( )
if not i :
return
model = combo . get_model ( )
first_item_path = model . get_path ( model . get_iter_first ( ) )
if model . get_path ( i ) == first_item_path :
val_int = ALWAYS_ON_PRIMARY
else :
val = model . get_value ( i , 0 )
val_int = int ( val . split ( ) [ 0 ] )
... |
async def get_joined_rooms ( self ) -> List [ str ] :
"""Get the list of rooms the user is in . See also : ` API reference ` _
Returns :
The list of room IDs the user is in .
. . _ API reference :
https : / / matrix . org / docs / spec / client _ server / r0.3.0 . html # get - matrix - client - r0 - joined ... | await self . ensure_registered ( )
response = await self . client . request ( "GET" , "/joined_rooms" )
return response [ "joined_rooms" ] |
def exempt ( self , obj ) :
"""decorator to mark a view as exempt from htmlmin .""" | name = '%s.%s' % ( obj . __module__ , obj . __name__ )
@ wraps ( obj )
def __inner ( * a , ** k ) :
return obj ( * a , ** k )
self . _exempt_routes . add ( name )
return __inner |
def setup_catalogs ( portal , catalogs_definition = { } , force_reindex = False , catalogs_extension = { } , force_no_reindex = False ) :
"""Setup the given catalogs . Redefines the map between content types and
catalogs and then checks the indexes and metacolumns , if one index / column
doesn ' t exist in the ... | # If not given catalogs _ definition , use the LIMS one
if not catalogs_definition :
catalogs_definition = getCatalogDefinitions ( )
# Merge the catalogs definition of the extension with the primary
# catalog definition
definition = _merge_catalog_definitions ( catalogs_definition , catalogs_extension )
# Mapping c... |
def get_random_password ( self , length = 32 , chars = None ) :
"""Helper function that gets a random password .
: param length : The length of the random password .
: type length : int
: param chars : A string with characters to choose from . Defaults to all ASCII letters and digits .
: type chars : str""" | if chars is None :
chars = string . ascii_letters + string . digits
return '' . join ( random . choice ( chars ) for x in range ( length ) ) |
def _apply_perspective ( coords : FlowField , coeffs : Points ) -> FlowField :
"Transform ` coords ` with ` coeffs ` ." | size = coords . flow . size ( )
# compress all the dims expect the last one ang adds ones , coords become N * 3
coords . flow = coords . flow . view ( - 1 , 2 )
# Transform the coeffs in a 3*3 matrix with a 1 at the bottom left
coeffs = torch . cat ( [ coeffs , FloatTensor ( [ 1 ] ) ] ) . view ( 3 , 3 )
coords . flow =... |
def configure ( self , config ) :
"""Configures component by passing configuration parameters .
: param config : configuration parameters to be set .""" | self . _dependency_resolver . configure ( config )
self . _logger . configure ( config ) |
def run ( func , args = [ ] , kwargs = { } , service = 'lambda' , capture_response = False , remote_aws_lambda_function_name = None , remote_aws_region = None , ** task_kwargs ) :
"""Instead of decorating a function with @ task , you can just run it directly .
If you were going to do func ( * args , * * kwargs ) ... | lambda_function_name = remote_aws_lambda_function_name or os . environ . get ( 'AWS_LAMBDA_FUNCTION_NAME' )
aws_region = remote_aws_region or os . environ . get ( 'AWS_REGION' )
task_path = get_func_task_path ( func )
return ASYNC_CLASSES [ service ] ( lambda_function_name = lambda_function_name , aws_region = aws_regi... |
def make_quadtree ( points , size_u , size_v , ** kwargs ) :
"""Generates a quadtree - like structure from surface control points .
This function generates a 2 - dimensional list of control point coordinates . Considering the object - oriented
representation of a quadtree data structure , first dimension of the... | # Get keyword arguments
extrapolate = kwargs . get ( 'extrapolate' , True )
# Convert control points array into 2 - dimensional form
points2d = [ ]
for i in range ( 0 , size_u ) :
row_list = [ ]
for j in range ( 0 , size_v ) :
row_list . append ( points [ j + ( i * size_v ) ] )
points2d . append ( r... |
def _lookup_attributes ( glyph_name , data ) :
"""Look up glyph attributes in data by glyph name , alternative name or
production name in order or return empty dictionary .
Look up by alternative and production names for legacy projects and
because of issue # 232.""" | attributes = ( data . names . get ( glyph_name ) or data . alternative_names . get ( glyph_name ) or data . production_names . get ( glyph_name ) or { } )
return attributes |
def getlist ( self , section , option , raw = False , vars = None , fallback = [ ] , delimiters = ',' ) :
"""A convenience method which coerces the option in the specified section to a list of strings .""" | v = self . get ( section , option , raw = raw , vars = vars , fallback = fallback )
return self . _convert_to_list ( v , delimiters = delimiters ) |
def delete ( self ) :
"""Deletes the key .""" | r = self . _h . _http_resource ( method = 'DELETE' , resource = ( 'user' , 'keys' , self . id ) )
r . raise_for_status ( ) |
def version_by_pip ( package ) :
"""Don ' t use this for bumping code , unless it is dot installed ,
this is going to look at pip installed packages ?
: param package :
: return :""" | command = "pip show {0}" . format ( package )
result = execute_get_text ( command )
for line in result . split ( "\n" ) :
if line . startswith ( "Version" ) :
return line . split ( ":" ) [ 0 ]
return None |
def update ( self , chat_id , op_user , name = None , owner = None , add_user_list = None , del_user_list = None ) :
"""修改会话
详情请参考
https : / / qydev . weixin . qq . com / wiki / index . php ? title = 企业会话接口说明
: param chat _ id : 会话 ID
: param op _ user : 操作人 userid
: param name : 会话标题
: param owner : 管理... | data = optionaldict ( chatid = chat_id , op_user = op_user , name = name , owner = owner , add_user_list = add_user_list , del_user_list = del_user_list , )
return self . _post ( 'chat/update' , data = data ) |
def add_request_handlers_dict ( self , rh_dict ) :
"""Add fake request handler functions from a dict keyed by request name
Note the keys must be the KATCP message name ( i . e . " the - request " , not
" the _ request " )
The request - handler interface is more or less compatible with request handler API
in... | # Check that all the callables have docstrings as strings
for req_func in rh_dict . values ( ) :
assert req_func . __doc__ , "Even fake request handlers must have docstrings"
self . _fkc . request_handlers . update ( rh_dict )
self . _fic . _interface_changed . set ( ) |
def where_entry_date ( query , datespec ) :
"""Where clause for entries which match a textual date spec
datespec - - The date spec to check for , in YYYY [ [ - ] MM [ [ - ] DD ] ] format""" | date , interval , _ = utils . parse_date ( datespec )
start_date , end_date = date . span ( interval )
return orm . select ( e for e in query if e . local_date >= start_date . naive and e . local_date <= end_date . naive ) |
def pprint ( to_be_printed ) :
"""nicely formated print""" | try :
import pprint as pp
# generate an instance PrettyPrinter
# pp . PrettyPrinter ( ) . pprint ( to _ be _ printed )
pp . pprint ( to_be_printed )
except ImportError :
if isinstance ( to_be_printed , dict ) :
print ( '{' )
for k , v in to_be_printed . items ( ) :
print ... |
def writefits ( self , * args , ** kwargs ) :
"""Write to file using default waveset .""" | old_wave = self . wave
self . wave = self . _wavetable
try :
super ( UniformTransmission , self ) . writefits ( * args , ** kwargs )
finally :
self . wave = old_wave |
def _add_default_branch ( self , body ) :
"""Add a default body for this conditional ( the ` else ` branch ) .""" | assert isinstance ( body , CodeStatement )
if isinstance ( body , CodeBlock ) :
self . else_body = body
else :
self . else_body . _add ( body ) |
def merge_values ( values1 , values2 ) :
'''Merges two numpy arrays by calculating all possible combinations of rows''' | array1 = values_to_array ( values1 )
array2 = values_to_array ( values2 )
if array1 . size == 0 :
return array2
if array2 . size == 0 :
return array1
merged_array = [ ]
for row_array1 in array1 :
for row_array2 in array2 :
merged_row = np . hstack ( ( row_array1 , row_array2 ) )
merged_array... |
def _wrapinstance ( func , ptr , base = None ) :
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default .
Based on http : / / nathanhorne . com / pyqtpyside - wrap - instance
Usage :
This mechanism kicks in under these circumstances .
1 . Qt . py is using ... | assert isinstance ( ptr , long ) , "Argument 'ptr' must be of type <long>"
assert ( base is None ) or issubclass ( base , Qt . QtCore . QObject ) , ( "Argument 'base' must be of type <QObject>" )
if base is None :
q_object = func ( long ( ptr ) , Qt . QtCore . QObject )
meta_object = q_object . metaObject ( )
... |
def signature ( self ) :
"""Create a signature for this method , only in Python > 3.4""" | if not use_signature :
raise NotImplementedError ( "Python 3 only." )
if self . static :
parameters = ( Parameter ( name = 'cls' , kind = Parameter . POSITIONAL_ONLY ) , )
else :
parameters = ( Parameter ( name = 'self' , kind = Parameter . POSITIONAL_ONLY ) , )
if self . input_transform :
return signat... |
def ctc_beam_search_decoder ( probs_seq , alphabet , beam_size , cutoff_prob = 1.0 , cutoff_top_n = 40 , scorer = None ) :
"""Wrapper for the CTC Beam Search Decoder .
: param probs _ seq : 2 - D list of probability distributions over each time
step , with each element being a list of normalized
probabilities... | beam_results = swigwrapper . ctc_beam_search_decoder ( probs_seq , alphabet . config_file ( ) , beam_size , cutoff_prob , cutoff_top_n , scorer )
beam_results = [ ( res . probability , alphabet . decode ( res . tokens ) ) for res in beam_results ]
return beam_results |
def sparklineData ( data , filename ) :
"""Writes reward and action data for plotting sparklines with PGF / TikZ .
@ see : http : / / www . texample . net / tikz / examples / weather - stations - data /""" | fd = file ( filename , "w+b" )
for name in data . keys ( ) :
action , reward = data [ name ]
altName = name . lower ( ) . replace ( "_" , "" )
fd . write ( "\def" )
fd . write ( "\REWARDDATA%s{" % altName )
for i , r in enumerate ( reward ) :
fd . write ( "(%.2f,%.3f)" % ( i / 10.0 , r / 10.... |
def parse_minionqc_report ( self , s_name , f ) :
'''Parses minionqc ' s ' summary . yaml ' report file for results .
Uses only the " All reads " stats . Ignores " Q > = x " part .''' | try : # Parsing as OrderedDict is slightly messier with YAML
# http : / / stackoverflow . com / a / 21048064/713980
def dict_constructor ( loader , node ) :
return OrderedDict ( loader . construct_pairs ( node ) )
yaml . add_constructor ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , dict_const... |
def get_form_kwargs ( self ) :
'''Pass the set of invoices to the form for creation''' | kwargs = super ( InvoiceNotificationView , self ) . get_form_kwargs ( )
kwargs [ 'invoices' ] = self . toNotify
return kwargs |
def parse_name_and_version ( p ) :
"""A utility method used to get name and version from a string .
From e . g . a Provides - Dist value .
: param p : A value in a form ' foo ( 1.0 ) '
: return : The name and version as a tuple .""" | m = NAME_VERSION_RE . match ( p )
if not m :
raise DistlibException ( 'Ill-formed name/version string: \'%s\'' % p )
d = m . groupdict ( )
return d [ 'name' ] . strip ( ) . lower ( ) , d [ 'ver' ] |
def atan ( x ) :
"""tan ( x )
Trigonometric arc tan function .""" | _math = infer_math ( x )
if _math is math :
return _math . atan ( x )
else :
return _math . arctan ( x ) |
def _get_async ( self , ** q_options ) :
"""Internal version of get _ async ( ) .""" | res = yield self . fetch_async ( 1 , ** q_options )
if not res :
raise tasklets . Return ( None )
raise tasklets . Return ( res [ 0 ] ) |
def update_surge ( api_client , surge_multiplier ) :
"""Use an UberRidesClient to update surge and print the results .
Parameters
api _ client ( UberRidesClient )
An authorized UberRidesClient with ' request ' scope .
surge _ mutliplier ( float )
The surge multiple for a sandbox product . A multiplier gre... | try :
update_surge = api_client . update_sandbox_product ( SURGE_PRODUCT_ID , surge_multiplier = surge_multiplier , )
except ( ClientError , ServerError ) as error :
fail_print ( error )
else :
success_print ( update_surge . status_code ) |
def covariance ( left , right , where = None , how = 'sample' ) :
"""Compute covariance of two numeric array
Parameters
how : { ' sample ' , ' pop ' } , default ' sample '
Returns
cov : double scalar""" | expr = ops . Covariance ( left , right , how , where ) . to_expr ( )
return expr |
def __eliminate_unused_constraits ( self , objects ) :
"""Eliminate constraints which mention objects not in ' objects ' .
In graph - theory terms , this is finding subgraph induced by
ordered vertices .""" | result = [ ]
for c in self . constraints_ :
if c [ 0 ] in objects and c [ 1 ] in objects :
result . append ( c )
return result |
def addDataset ( self , dataset ) :
"""Adds the given data set to this chart widget .
: param dataSet | < XChartDataset >""" | self . _datasets . append ( dataset )
self . _dataChanged = True
self . _addDatasetAction ( dataset ) |
def _solve ( self , sense = None ) :
"""Remove old constraints and then solve the current problem .
Args :
sense : Minimize or maximize the objective .
( : class : ` . lp . ObjectiveSense )
Returns :
The Result object for the solved LP problem""" | # Remove the constraints from the last run
while len ( self . _remove_constr ) > 0 :
self . _remove_constr . pop ( ) . delete ( )
try :
return self . _prob . solve ( sense = sense )
except lp . SolverError as e :
raise_from ( MOMAError ( text_type ( e ) ) , e )
finally :
self . _remove_constr = [ ] |
def hidden_next_pages ( self ) :
"""Check if the next pages where sliced .
Example :
> > > map ( lambda i : _ SlicedPaginator ( i , 6 , 3 ) . hidden _ next _ pages ( ) , range ( 1 , 7 ) )
[ True , True , True , True , False , False ]
> > > map ( lambda i : _ SlicedPaginator ( i , 7 , 3 ) . hidden _ next _ p... | next_pages = self . next_pages ( )
return len ( next_pages ) > 0 and next_pages [ - 1 ] < self . npages |
def update ( self , capacity = values . unset , available = values . unset ) :
"""Update the WorkerChannelInstance
: param unicode capacity : The total number of Tasks worker should handle for this TaskChannel type .
: param bool available : Toggle the availability of the WorkerChannel .
: returns : Updated W... | return self . _proxy . update ( capacity = capacity , available = available , ) |
def next ( self ) :
"""Get next GridOut object from cursor .""" | # Work around " super is not iterable " issue in Python 3 . x
next_file = super ( GridOutCursor , self ) . next ( )
return GridOut ( self . __root_collection , file_document = next_file , session = self . session ) |
def add_to_parent ( self ) :
"""Adds this node to the parent ' s ` ` children ` ` collection if it exists .""" | parent = self . parent
if parent is not None :
try :
children = parent . children
except AttributeError :
pass
else :
include ( children , self ) |
def plt2xyz ( fname ) :
"""Convert a Compass plot file to XYZ pointcloud""" | parser = CompassPltParser ( fname )
plt = parser . parse ( )
for segment in plt :
for command in segment :
if command . cmd == 'd' :
if plt . utm_zone :
x , y , z = command . x * FT_TO_M , command . y * FT_TO_M , command . z * FT_TO_M
else :
x , y , z ... |
def avg_abs ( self ) :
"""return the mean of absolute values""" | # XXX rename this method
if len ( self . values ) > 0 :
return sum ( map ( abs , self . values ) ) / float ( len ( self . values ) )
else :
return None |
def cmd_messagerate ( self , args ) :
'''control behaviour of the module''' | if len ( args ) == 0 :
print ( self . usage ( ) )
elif args [ 0 ] == "status" :
print ( self . status ( ) )
elif args [ 0 ] == "reset" :
self . reset ( )
else :
print ( self . usage ( ) ) |
def handleOACK ( self , pkt ) :
"""This method handles an OACK from the server , syncing any accepted
options .""" | if len ( pkt . options . keys ( ) ) > 0 :
if pkt . match_options ( self . context . options ) :
log . info ( "Successful negotiation of options" )
# Set options to OACK options
self . context . options = pkt . options
for key in self . context . options :
log . info ( " ... |
def _crc16 ( data , crc , table ) :
"""table for caclulating CRC ( list of 256 integers )
: param bytes data : Data for calculating CRC .
: param int crc : Initial value .
: param list table : Table for caclulating CRC ( list of 256 integers )
: return : calculated value of CRC""" | bytes_to_int = lambda x : ord ( x ) if sys . version_info . major == 2 else x
for byte in data :
crc = ( ( crc << 8 ) & 0xff00 ) ^ table [ ( ( crc >> 8 ) & 0xff ) ^ bytes_to_int ( byte ) ]
return crc & 0xffff |
def _get_song ( self ) :
'''Used internally to get the current track and make sure it exists .''' | # Try to get the current track from the start metasong
if self . at_beginning : # Make sure it exists .
if self . pos < len ( self . start ) : # It exists , so return it .
return self . start [ self . pos ]
# It doesn ' t exist , so let ' s move on !
self . at_beginning = False
# Generate a new ... |
def metric_name ( self , name , group , description = '' , tags = None ) :
"""Create a MetricName with the given name , group , description and tags ,
plus default tags specified in the metric configuration .
Tag in tags takes precedence if the same tag key is specified in
the default metric configuration .
... | combined_tags = dict ( self . config . tags )
combined_tags . update ( tags or { } )
return MetricName ( name , group , description , combined_tags ) |
def dist_calc ( surf , cortex , source_nodes ) :
"""Calculate exact geodesic distance along cortical surface from set of source nodes .
" dist _ type " specifies whether to calculate " min " , " mean " , " median " , or " max " distance values
from a region - of - interest . If running only on single node , def... | cortex_vertices , cortex_triangles = surf_keep_cortex ( surf , cortex )
translated_source_nodes = translate_src ( source_nodes , cortex )
data = gdist . compute_gdist ( cortex_vertices , cortex_triangles , source_indices = translated_source_nodes )
dist = recort ( data , surf , cortex )
del data
return dist |
def global_include ( self , pattern ) :
"""Include all files anywhere in the current directory that match the
pattern . This is very inefficient on large file trees .""" | if self . allfiles is None :
self . findall ( )
match = translate_pattern ( os . path . join ( '**' , pattern ) )
found = [ f for f in self . allfiles if match . match ( f ) ]
self . extend ( found )
return bool ( found ) |
def griditer ( x , y , ncol , nrow = None , step = 1 ) :
"""Iterate through a grid of tiles .
Args :
x ( int ) : x start - coordinate
y ( int ) : y start - coordinate
ncol ( int ) : number of tile columns
nrow ( int ) : number of tile rows . If not specified , this
defaults to ncol , s . t . a quadratic... | if nrow is None :
nrow = ncol
yield from itertools . product ( range ( x , x + ncol , step ) , range ( y , y + nrow , step ) ) |
def stop_all ( self , run_order = - 1 ) :
"""Runs stop method on all modules less than the passed - in run _ order .
Used when target is exporting itself mid - build , so we clean up state
before committing run files etc .""" | shutit_global . shutit_global_object . yield_to_draw ( )
# sort them so they ' re stopped in reverse order
for module_id in self . module_ids ( rev = True ) :
shutit_module_obj = self . shutit_map [ module_id ]
if run_order == - 1 or shutit_module_obj . run_order <= run_order :
if self . is_installed ( ... |
def do_list_modules ( self , long_output = None , sort_order = None ) :
"""Display a list of loaded modules .
Config items :
- shutit . list _ modules [ ' long ' ]
If set , also print each module ' s run order value
- shutit . list _ modules [ ' sort ' ]
Select the column by which the list is ordered :
... | shutit_global . shutit_global_object . yield_to_draw ( )
cfg = self . cfg
# list of module ids and other details
# will also contain column headers
table_list = [ ]
if long_output is None :
long_output = self . list_modules [ 'long' ]
if sort_order is None :
sort_order = self . list_modules [ 'sort' ]
if long_o... |
def get_impala_queries ( self , start_time , end_time , filter_str = "" , limit = 100 , offset = 0 ) :
"""Returns a list of queries that satisfy the filter
@ type start _ time : datetime . datetime . Note that the datetime must either be
time zone aware or specified in the server time zone . See
the python da... | params = { 'from' : start_time . isoformat ( ) , 'to' : end_time . isoformat ( ) , 'filter' : filter_str , 'limit' : limit , 'offset' : offset , }
return self . _get ( "impalaQueries" , ApiImpalaQueryResponse , params = params , api_version = 4 ) |
def set_log_file ( local_file = None ) :
"""设置日志记录 , 按照每天一个文件 , 记录包括 info 以及以上级别的内容 ;
日志格式采取日志文件名直接加上日期 , 比如 fish _ test . log . 2018-05-27
: param :
* local _ fie : ( string ) 日志文件名
: return : 无
举例如下 : :
from fishbase . fish _ logger import *
from fishbase . fish _ file import *
log _ abs _ filenam... | default_log_file = 'default.log'
_formatter = logging . Formatter ( '%(asctime)s %(levelname)s %(filename)s[ln:%(lineno)d] %(message)s' )
if local_file is not None :
default_log_file = local_file
# time rotating file handler
# _ tfh = TimedRotatingFileHandler ( default _ log _ file , when = " midnight " )
_tfh = Sa... |
def get_element ( parent_to_parse , element_path = None ) :
""": return : an element from the parent or parsed from a Dictionary , XML string
or file . If element _ path is not provided the root element is returned .""" | if parent_to_parse is None :
return None
elif isinstance ( parent_to_parse , ElementTree ) :
parent_to_parse = parent_to_parse . getroot ( )
elif hasattr ( parent_to_parse , 'read' ) :
parent_to_parse = string_to_element ( parent_to_parse . read ( ) )
elif isinstance ( parent_to_parse , STRING_TYPES ) :
... |
def get_or_create_data_group ( self , title : str ) -> DataGroup :
"""Get ( or create ) a data group .
: param title : The title of the data group .
: return : The new : py : class : ` nion . swift . Facade . DataGroup ` object .
: rtype : : py : class : ` nion . swift . Facade . DataGroup `
. . versionadde... | return DataGroup ( self . __document_model . get_or_create_data_group ( title ) ) |
def get_hook ( self , id ) :
""": calls : ` GET / orgs / : owner / hooks / : id < http : / / developer . github . com / v3 / orgs / hooks > ` _
: param id : integer
: rtype : : class : ` github . Hook . Hook `""" | assert isinstance ( id , ( int , long ) ) , id
headers , data = self . _requester . requestJsonAndCheck ( "GET" , self . url + "/hooks/" + str ( id ) )
return github . Hook . Hook ( self . _requester , headers , data , completed = True ) |
def positions ( self , x , y ) : # type : ( int , int ) - > List [ ( Point , Point ) ]
"""Get all positions , that can be combined to get word parsed at specified position .
: param x : X coordinate .
: param y : Y coordinate .
: return : List of tuples with two Point instances .""" | return [ ( Point ( x , v ) , Point ( x + 1 + v , y - 1 - v ) ) for v in range ( y ) ] |
def get_tags_from_job ( user , job_id ) :
"""Retrieve all tags attached to a job .""" | job = v1_utils . verify_existence_and_get ( job_id , _TABLE )
if not user . is_in_team ( job [ 'team_id' ] ) and not user . is_read_only_user ( ) :
raise dci_exc . Unauthorized ( )
JTT = models . JOIN_JOBS_TAGS
query = ( sql . select ( [ models . TAGS ] ) . select_from ( JTT . join ( models . TAGS ) ) . where ( JTT... |
def _modify ( self , ** patch ) :
"""Override modify to check kwargs before request sent to device .""" | if 'state' in patch :
if patch [ 'state' ] not in [ 'user-up' , 'user-down' , 'unchecked' , 'fqdn-up' ] :
msg = "The node resource does not support a modify with the " "value of the 'state' attribute as %s. The accepted " "values are 'user-up', 'user-down', 'unchecked', or 'fqdn-up'" % patch [ 'state' ]
... |
def _bit_is_one ( self , n , hash_bytes ) :
"""Check if the n ( index ) of hash _ bytes is 1 or 0.""" | scale = 16
# hexadecimal
if not hash_bytes [ int ( n / ( scale / 2 ) ) ] >> int ( ( scale / 2 ) - ( ( n % ( scale / 2 ) ) + 1 ) ) & 1 == 1 :
return False
return True |
def retrieve_from_cache ( self ) :
"""Try to retrieve the node ' s content from a cache
This method is called from multiple threads in a parallel build ,
so only do thread safe stuff here . Do thread unsafe stuff in
built ( ) .
Returns true if the node was successfully retrieved .""" | if self . nocache :
return None
if not self . is_derived ( ) :
return None
return self . get_build_env ( ) . get_CacheDir ( ) . retrieve ( self ) |
def NS ( domain , resolve = True , nameserver = None ) :
'''Return a list of IPs of the nameservers for ` ` domain ` `
If ` ` resolve ` ` is False , don ' t resolve names .
CLI Example :
. . code - block : : bash
salt ns1 dig . NS google . com''' | dig = [ 'dig' , '+short' , six . text_type ( domain ) , 'NS' ]
if nameserver is not None :
dig . append ( '@{0}' . format ( nameserver ) )
cmd = __salt__ [ 'cmd.run_all' ] ( dig , python_shell = False )
# In this case , 0 is not the same as False
if cmd [ 'retcode' ] != 0 :
log . warning ( 'dig returned exit co... |
def active_joined_organisations ( doc ) :
"""View for getting organisations associated with a user""" | if doc . get ( 'type' ) == 'user' and doc . get ( 'state' ) != 'deactivated' :
for org_id , state in doc . get ( 'organisations' , { } ) . items ( ) :
if state [ 'state' ] == 'deactivated' :
continue
org = { '_id' : org_id }
yield [ doc [ '_id' ] , None ] , org
try :
... |
def do_help ( self , argv ) :
"""help [ COMMAND ] Prints help for the specified COMMAND . ' h '
and ' ? ' are synonyms .""" | if argv [ 1 : ] :
for arg in argv [ 1 : ] :
if self . _do_one_help ( arg ) :
break
else : # If bare ' help ' is called , print this class ' s doc
# string ( if it has one ) .
doc = self . _doc_to_help ( self . __class__ )
if doc :
sys . stdout . write ( doc + '\n' )
sys .... |
def process_data ( self , value ) :
"""Process the Python data applied to this field and store the result .
This will be called during form construction by the form ' s ` kwargs ` or
` obj ` argument .
Converting ORM object to primary key for client form .
: param value : The python object containing the va... | if value :
if self . is_related :
self . data = self . datamodel . get_related_interface ( self . col_name ) . get_pk_value ( value )
else :
self . data = self . datamodel . get ( value )
else :
self . data = None |
def afw_complementation ( afw : dict ) -> dict :
"""Returns a AFW reading the complemented language read by
input AFW .
Let : math : ` A = ( Σ , S , s ^ 0 , ρ , F ) ` . Define : math : ` Ā = ( Σ , S ,
s ^ 0 , \ overline { ρ } , S − F ) ` ,
where : math : ` \ overline { ρ } ( s , a ) = \ overline { ρ ( s , ... | completed_input = afw_completion ( deepcopy ( afw ) )
complemented_afw = { 'alphabet' : completed_input [ 'alphabet' ] , 'states' : completed_input [ 'states' ] , 'initial_state' : completed_input [ 'initial_state' ] , 'accepting_states' : completed_input [ 'states' ] . difference ( afw [ 'accepting_states' ] ) , 'tran... |
def response ( status , description , resource = DefaultResource ) : # type : ( HTTPStatus , str , Optional [ Resource ] ) - > Callable
"""Define an expected response .
The values are based off ` Swagger < https : / / swagger . io / specification > ` _ .""" | def inner ( o ) :
value = Response ( status , description , resource )
try :
getattr ( o , 'responses' ) . add ( value )
except AttributeError :
setattr ( o , 'responses' , { value } )
return o
return inner |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.