signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def coverage ( ) :
"generate coverage report and show in browser" | coverage_index = path ( "build/coverage/index.html" )
coverage_index . remove ( )
sh ( "paver test" )
coverage_index . exists ( ) and webbrowser . open ( coverage_index ) |
def ifind_first_object ( self , ObjectClass , ** kwargs ) :
"""Retrieve the first object of type ` ` ObjectClass ` ` ,
matching the specified filters in ` ` * * kwargs ` ` - - case insensitive .
| If USER _ IFIND _ MODE is ' nocase _ collation ' this method maps to find _ first _ object ( ) .
| If USER _ IFIN... | # Call regular find ( ) if USER _ IFIND _ MODE is nocase _ collation
if self . user_manager . USER_IFIND_MODE == 'nocase_collation' :
return self . find_first_object ( ObjectClass , ** kwargs )
raise NotImplementedError |
def rgb_distance ( rgb1 , rgb2 ) :
'''Calculate the distance between two RGB sequences .''' | return sum ( map ( lambda c : ( c [ 0 ] - c [ 1 ] ) ** 2 , zip ( rgb1 , rgb2 ) ) ) |
def write ( self , b ) :
"""Write the given bytes ( binary string ) to the S3 file .
There ' s buffering happening under the covers , so this may not actually
do any HTTP transfer right away .""" | if not isinstance ( b , _BINARY_TYPES ) :
raise TypeError ( "input must be one of %r, got: %r" % ( _BINARY_TYPES , type ( b ) ) )
self . _buf . write ( b )
self . _total_bytes += len ( b )
if self . _buf . tell ( ) >= self . _min_part_size :
self . _upload_next_part ( )
return len ( b ) |
def _find_row_label_positions ( self , match_value_or_fct , levels = None ) :
"""Check the original DataFrame ' s row labels to find the locations of rows . And return the adjusted
row indexing within region ( offset if including index )""" | allmatches = find_locations ( self . df . index , match_value_or_fct , levels )
if allmatches and self . inc_index : # tramslate back
allmatches = [ m + self . nhdrs for m in allmatches ]
return allmatches |
def normalize_column_names ( df ) :
r"""Clean up whitespace in column names . See better version at ` pugnlp . clean _ columns `
> > > df = pd . DataFrame ( [ [ 1 , 2 ] , [ 3 , 4 ] ] , columns = [ ' Hello World ' , ' not here ' ] )
> > > normalize _ column _ names ( df )
[ ' hello _ world ' , ' not _ here ' ]... | columns = df . columns if hasattr ( df , 'columns' ) else df
columns = [ c . lower ( ) . replace ( ' ' , '_' ) for c in columns ]
return columns |
def stream_upload ( self , data , callback ) :
"""Generator for streaming request body data .
: param data : A file - like object to be streamed .
: param callback : Custom callback for monitoring progress .""" | while True :
chunk = data . read ( self . config . connection . data_block_size )
if not chunk :
break
if callback and callable ( callback ) :
callback ( chunk , response = None )
yield chunk |
def __get_query_range ( cls , date_field , start = None , end = None ) :
"""Create a filter dict with date _ field from start to end dates .
: param date _ field : field with the date value
: param start : date with the from value . Should be a datetime . datetime object
of the form : datetime . datetime ( 20... | if not start and not end :
return ''
start_end = { }
if start :
start_end [ "gte" ] = "%s" % start . isoformat ( )
if end :
start_end [ "lte" ] = "%s" % end . isoformat ( )
query_range = { date_field : start_end }
return query_range |
def format_attributes_json ( self ) :
"""Convert the Attributes object to json format .""" | attributes_json = { }
for key , value in self . attributes . items ( ) :
key = utils . check_str_length ( key ) [ 0 ]
value = _format_attribute_value ( value )
if value is not None :
attributes_json [ key ] = value
result = { 'attributeMap' : attributes_json }
return result |
def hbold ( * content , sep = ' ' ) :
"""Make bold text ( HTML )
: param content :
: param sep :
: return :""" | return _md ( quote_html ( _join ( * content , sep = sep ) ) , symbols = MD_SYMBOLS [ 4 ] ) |
def post_disambiguate ( self , collections ) :
"""Teostab mitmeste analüüside lemma - põhise järelühestamise . Järelühestamine
toimub kahes etapis : kõigepealt ühe dokumendikollektsiooni piires ning
seejärel üle kõigi dokumendikollektsioonide ( kui sisendis on rohkem kui 1
dokumendikollektsioon ) ... | # I etapp : ühestame ühe dokumendikollektsiooni piires
# ( nt üle kõigi samal päeval ilmunud ajaleheartiklite ) ;
for docs in collections : # 1 ) Eemaldame analüüside seast duplikaadid ja probleemsed
self . __remove_duplicate_and_problematic_analyses ( docs )
# 2 ) Leiame sõnad , mis sisaldavad nn ignor... |
def rgb2cmy ( self , img , whitebg = False ) :
"""transforms image from RGB to CMY""" | tmp = img * 1.0
if whitebg :
tmp = ( 1.0 - ( img - img . min ( ) ) / ( img . max ( ) - img . min ( ) ) )
out = tmp * 0.0
out [ : , : , 0 ] = ( tmp [ : , : , 1 ] + tmp [ : , : , 2 ] ) / 2.0
out [ : , : , 1 ] = ( tmp [ : , : , 0 ] + tmp [ : , : , 2 ] ) / 2.0
out [ : , : , 2 ] = ( tmp [ : , : , 0 ] + tmp [ : , : , 1 ]... |
def ip_access_control_lists ( self ) :
"""Access the ip _ access _ control _ lists
: returns : twilio . rest . api . v2010 . account . sip . ip _ access _ control _ list . IpAccessControlListList
: rtype : twilio . rest . api . v2010 . account . sip . ip _ access _ control _ list . IpAccessControlListList""" | if self . _ip_access_control_lists is None :
self . _ip_access_control_lists = IpAccessControlListList ( self . _version , account_sid = self . _solution [ 'account_sid' ] , )
return self . _ip_access_control_lists |
def predict ( self , dataset , output_type = 'class' , verbose = True , batch_size = 64 ) :
"""Return predictions for ` ` dataset ` ` . Predictions can be generated
as class labels or probabilities .
Parameters
dataset : SFrame | SArray | dict
The audio data to be classified .
If dataset is an SFrame , it... | from . . _mxnet import _mxnet_utils
import mxnet as mx
if not isinstance ( dataset , ( _tc . SFrame , _tc . SArray , dict ) ) :
raise TypeError ( '\'dataset\' parameter must be either an SFrame, SArray or dictionary' )
if isinstance ( dataset , dict ) :
if ( set ( dataset . keys ( ) ) != { 'sample_rate' , 'data... |
def patch ( self , id_or_uri , operation , path , value , timeout = - 1 ) :
"""Uses the PATCH to update a resource for a given logical switch group .
Only one operation can be performed in each PATCH call .
Args :
id _ or _ uri : Can be either the resource ID or the resource URI .
operation : Patch operatio... | return self . _client . patch ( id_or_uri , operation , path , value , timeout = timeout ) |
def do_set ( self , line ) :
'''Set repository attributes on the active repo .
set attribute = value
# intended use :
# directory repos :
work _ on developer - repo
set type = directory
set directory = package - directory
# http repos :
work _ on company - private - repo
set type = http
set down... | self . abort_on_invalid_active_repo ( 'set' )
repo = self . network . active_repo
attribute , eq , value = line . partition ( '=' )
if not attribute :
raise ShellError ( 'command "set" requires a non-empty attribute' )
if not eq :
raise ShellError ( 'command "set" requires a value' )
self . network . set ( repo... |
def helioY ( self , * args , ** kwargs ) :
"""NAME :
helioY
PURPOSE :
return Heliocentric Galactic rectangular y - coordinate ( aka " Y " )
INPUT :
t - ( optional ) time at which to get Y
obs = [ X , Y , Z ] - ( optional ) position and velocity of observer
( in kpc and km / s ) ( default = Object - wi... | _check_roSet ( self , kwargs , 'helioY' )
X , Y , Z = self . _helioXYZ ( * args , ** kwargs )
return Y |
def get_subgraph ( self , subvertices , normalize = False ) :
"""Creates a subgraph of the current graph
See : meth : ` molmod . graphs . Graph . get _ subgraph ` for more information .""" | graph = Graph . get_subgraph ( self , subvertices , normalize )
if normalize :
new_numbers = self . numbers [ graph . _old_vertex_indexes ]
# vertices do change
else :
new_numbers = self . numbers
# vertices don ' t change !
if self . symbols is None :
new_symbols = None
elif normalize :
new_sym... |
def updateSolutionTerminal ( self ) :
'''Update the terminal period solution . This method should be run when a
new AgentType is created or when CRRA changes .
Parameters
None
Returns
None''' | RepAgentConsumerType . updateSolutionTerminal ( self )
# Make replicated terminal period solution
StateCount = self . MrkvArray . shape [ 0 ]
self . solution_terminal . cFunc = StateCount * [ self . cFunc_terminal_ ]
self . solution_terminal . vPfunc = StateCount * [ self . solution_terminal . vPfunc ]
self . solution_... |
async def wait ( sec = 5 , ** kwargs ) :
"""Does nothing for * sec * seconds and then prints out a message .
. . note : : This function * * is not * * blocking .
. . seealso : : : func : ` blocking _ wait `
: param sec : Time to wait , in seconds .
: param kwargs : Additional parameters .""" | await asyncio . sleep ( sec )
print ( "{0}: Done waiting for {1} sec." . format ( kwargs [ 'rulename' ] , sec ) ) |
def textbetween ( variable , firstnum = None , secondnum = None , locationoftext = 'regular' ) :
"""Get The Text Between Two Parts""" | if locationoftext == 'regular' :
return variable [ firstnum : secondnum ]
elif locationoftext == 'toend' :
return variable [ firstnum : ]
elif locationoftext == 'tostart' :
return variable [ : secondnum ] |
def random_str ( n = 20 ) :
"""随机生成一串密码
: param n : 密码的长度 , 默认为20
: return : 长度为n的随机字符串""" | return '' . join ( random . sample ( string . ascii_letters + string . digits , n ) ) |
def iter ( self , name ) :
'''Iterate through values added with add ( ) from each scope frame .''' | for frame in self . frames :
vals = frame . get ( name )
if vals is None :
continue
for valu in vals :
yield valu |
def startWorker ( basedir , quiet , nodaemon ) :
"""Start worker process .
Fork and start twisted application described in basedir buildbot . tac file .
Print it ' s log messages to stdout for a while and try to figure out if
start was successful .
If quiet or nodaemon parameters are True , or we are runnin... | os . chdir ( basedir )
if quiet or nodaemon :
return launch ( nodaemon )
# we probably can ' t do this os . fork under windows
from twisted . python . runtime import platformType
if platformType == "win32" :
return launch ( nodaemon )
# fork a child to launch the daemon , while the parent process tails the
# lo... |
def remove_profile ( self ) :
"""Remove the current profile .
Make sure the user is sure .""" | profile_name = self . profile_combo . currentText ( )
# noinspection PyTypeChecker
button_selected = QMessageBox . warning ( None , 'Remove Profile' , self . tr ( 'Remove %s.' ) % profile_name , QMessageBox . Ok , QMessageBox . Cancel )
if button_selected == QMessageBox . Ok :
self . profile_combo . removeItem ( se... |
def get_type_of_fields ( fields , table ) :
"""Return data types of ` fields ` that are in ` table ` . If a given
parameter is empty return primary key .
: param fields : list - list of fields that need to be returned
: param table : sa . Table - the current table
: return : list - list of the tuples ` ( fi... | if not fields :
fields = table . primary_key
actual_fields = [ field for field in table . c . items ( ) if field [ 0 ] in fields ]
data_type_fields = { name : FIELD_TYPES . get ( type ( field_type . type ) , rc . TEXT_FIELD . value ) for name , field_type in actual_fields }
return data_type_fields |
def fetchImageUrl ( self , image_id ) :
"""Fetches the url to the original image from an image attachment ID
: param image _ id : The image you want to fethc
: type image _ id : str
: return : An url where you can download the original image
: rtype : str
: raises : FBchatException if request failed""" | image_id = str ( image_id )
data = { "photo_id" : str ( image_id ) }
j = self . _get ( ReqUrl . ATTACHMENT_PHOTO , query = data , fix_request = True , as_json = True )
url = get_jsmods_require ( j , 3 )
if url is None :
raise FBchatException ( "Could not fetch image url from: {}" . format ( j ) )
return url |
def opened ( self , * args ) :
"""Initiates communication with the remote controlled device .
: param args :""" | self . _serial_open = True
self . log ( "Opened: " , args , lvl = debug )
self . _send_command ( b'l,1' )
# Saying hello , shortly
self . log ( "Turning off engine, pump and neutralizing rudder" )
self . _send_command ( b'v' )
self . _handle_servo ( self . _machine_channel , 0 )
self . _handle_servo ( self . _rudder_ch... |
def login_open_sheet ( email , password , spreadsheet ) :
"""Connect to Google Docs spreadsheet and return the first worksheet .""" | try :
gc = gspread . login ( email , password )
worksheet = gc . open ( spreadsheet ) . sheet1
return worksheet
except :
print 'Unable to login and get spreadsheet. Check email, password, spreadsheet name.'
sys . exit ( 1 ) |
def ParseDownloadsRow ( self , parser_mediator , query , row , ** unused_kwargs ) :
"""Parses a downloads row .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
query ( str ) : query that created the row .
row ( sqlite3 ... | query_hash = hash ( query )
event_data = FirefoxDownloadEventData ( )
event_data . full_path = self . _GetRowValue ( query_hash , row , 'target' )
event_data . mime_type = self . _GetRowValue ( query_hash , row , 'mimeType' )
event_data . name = self . _GetRowValue ( query_hash , row , 'name' )
event_data . offset = se... |
def unassign_assessment_offered_from_bank ( self , assessment_offered_id , bank_id ) :
"""Removes an ` ` AssessmentOffered ` ` from a ` ` Bank ` ` .
arg : assessment _ offered _ id ( osid . id . Id ) : the ` ` Id ` ` of the
` ` AssessmentOffered ` `
arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the `... | # Implemented from template for
# osid . resource . ResourceBinAssignmentSession . unassign _ resource _ from _ bin
mgr = self . _get_provider_manager ( 'ASSESSMENT' , local = True )
lookup_session = mgr . get_bank_lookup_session ( proxy = self . _proxy )
lookup_session . get_bank ( bank_id )
# to raise NotFound
self .... |
def line_alignment ( self ) :
"""Alignment , one of ` inner ` , ` outer ` , ` center ` .""" | key = self . _data . get ( b'strokeStyleLineAlignment' ) . enum
return self . STROKE_STYLE_LINE_ALIGNMENTS . get ( key , str ( key ) ) |
def build ( self , shutit ) :
"""Initializes target ready for build and updating package management if in container .""" | if shutit . build [ 'delivery' ] in ( 'docker' , 'dockerfile' ) :
if shutit . get_current_shutit_pexpect_session_environment ( ) . install_type == 'apt' :
shutit . add_to_bashrc ( 'export DEBIAN_FRONTEND=noninteractive' )
if not shutit . command_available ( 'lsb_release' ) :
shutit . ins... |
def calculate_total_size ( apps , schema_editor ) :
"""Add ` ` total _ size ` ` field to all file / dir - type outputs .""" | Data = apps . get_model ( 'flow' , 'Data' )
for data in Data . objects . all ( ) :
hydrate_size ( data , force = True )
data . save ( ) |
def getcosmo ( cosmology ) :
"""Find cosmological parameters for named cosmo in cosmology . py list""" | defaultcosmologies = { 'dragons' : cg . DRAGONS ( ) , 'wmap1' : cg . WMAP1_Mill ( ) , 'wmap3' : cg . WMAP3_ML ( ) , 'wmap5' : cg . WMAP5_mean ( ) , 'wmap7' : cg . WMAP7_ML ( ) , 'wmap9' : cg . WMAP9_ML ( ) , 'wmap1_lss' : cg . WMAP1_2dF_mean ( ) , 'wmap3_mean' : cg . WMAP3_mean ( ) , 'wmap5_ml' : cg . WMAP5_ML ( ) , 'w... |
def __apply_mask ( address_packed , mask_packed , nr_bytes ) :
"""Perform a bitwise AND operation on all corresponding bytes between the
mask and the provided address . Mask parts set to 0 will become 0 in the
anonymized IP address as well
: param bytes address _ packed : Binary representation of the IP addre... | anon_packed = bytearray ( )
for i in range ( 0 , nr_bytes ) :
anon_packed . append ( ord ( mask_packed [ i ] ) & ord ( address_packed [ i ] ) )
return six . text_type ( ip_address ( six . binary_type ( anon_packed ) ) ) |
def _update_record ( self , identifier , rtype = None , name = None , content = None ) :
"""Updates the specified record in a new Gandi zone
' content ' should be a string or a list of strings""" | if self . protocol == 'rpc' :
return self . rpc_helper . update_record ( identifier , rtype , name , content )
data = { }
if rtype :
data [ 'rrset_type' ] = rtype
if name :
data [ 'rrset_name' ] = self . _relative_name ( name )
if content :
if isinstance ( content , ( list , tuple , set ) ) :
da... |
def validate_policy ( topic , signer , routing_policy , nitpicky = False ) :
"""Checks that the sender is allowed to emit messages for the given topic .
Args :
topic ( str ) : The message topic the ` ` signer ` ` used when sending the message .
signer ( str ) : The Common Name of the certificate used to sign ... | if topic in routing_policy : # If so . . is the signer one of those permitted senders ?
if signer in routing_policy [ topic ] : # We are good . The signer of this message is explicitly
# whitelisted to send on this topic in our config policy .
return True
else : # We have a policy for this topic and... |
def _findSamesetProteins ( protToPeps , proteins = None ) :
"""Find proteins that are mapped to an identical set of peptides .
: param protToPeps : dict , for each protein ( = key ) contains a set of
associated peptides ( = value ) . For Example { protein : { peptide , . . . } , . . . }
: param proteins : ite... | proteins = viewkeys ( protToPeps ) if proteins is None else proteins
equalEvidence = ddict ( set )
for protein in proteins :
peptides = protToPeps [ protein ]
equalEvidence [ tuple ( sorted ( peptides ) ) ] . add ( protein )
equalProteins = list ( )
for proteins in viewvalues ( equalEvidence ) :
if len ( pr... |
def throws_errors ( func ) :
"""Wraps a function responsible for implementing an API endpoint such that
any server errors that are thrown are automatically transformed into
appropriate HTTP responses .""" | @ wraps ( func )
def wrapper ( * args , ** kwargs ) :
response = func ( * args , ** kwargs )
# if no status code is provided , assume 400
if isinstance ( response , BugZooException ) :
err_jsn = flask . jsonify ( response . to_dict ( ) )
return err_jsn , 400
if isinstance ( response , tu... |
def mvp_gg ( self ) :
"""Returns most visited path in go - gui VAR format e . g . ' b r3 w c17 . . .""" | output = [ ]
for node in self . most_visited_path_nodes ( ) :
if max ( node . child_N ) <= 1 :
break
output . append ( coords . to_gtp ( coords . from_flat ( node . fmove ) ) )
return ' ' . join ( output ) |
def string ( name , value , expire = None , expireat = None , ** connection_args ) :
'''Ensure that the key exists in redis with the value specified
name
Redis key to manage
value
Data to persist in key
expire
Sets time to live for key in seconds
expireat
Sets expiration time for key via UNIX timest... | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'Key already set to defined value' }
old_key = __salt__ [ 'redis.get_key' ] ( name , ** connection_args )
if old_key != value :
__salt__ [ 'redis.set_key' ] ( name , value , ** connection_args )
ret [ 'changes' ] [ name ] = 'Value updated'
... |
def _cql_from_cass_type ( cass_type ) :
"""A string representation of the type for this column , such as " varchar "
or " map < string , int > " .""" | if issubclass ( cass_type , types . ReversedType ) :
return cass_type . subtypes [ 0 ] . cql_parameterized_type ( )
else :
return cass_type . cql_parameterized_type ( ) |
def memoize ( fn ) :
'''Cache the results of a function that only takes positional arguments .''' | cache = { }
@ wraps ( fn )
def wrapped_function ( * args ) :
if args in cache :
return cache [ args ]
else :
result = fn ( * args )
cache [ args ] = result
return result
return wrapped_function |
def is_group_or_super_group ( cls , obj ) -> bool :
"""Check chat is group or super - group
: param obj :
: return :""" | return cls . _check ( obj , [ cls . GROUP , cls . SUPER_GROUP ] ) |
def replace_suffixes_4 ( self , word ) :
"""Perform replacements on even more common suffixes .""" | length = len ( word )
replacements = { 'ational' : 'ate' , 'tional' : 'tion' , 'alize' : 'al' , 'icate' : 'ic' , 'iciti' : 'ic' , 'ical' : 'ic' , 'ful' : '' , 'ness' : '' }
for suffix in replacements . keys ( ) :
if word . endswith ( suffix ) :
suffix_length = len ( suffix )
if self . r1 <= ( length... |
def get_layout_objects ( self , * LayoutClasses , ** kwargs ) :
"""Returns a list of lists pointing to layout objects of any type matching
` LayoutClasses ` : :
[ [ 0,1,2 ] , ' div ' ] ,
[ [ 0,3 ] , ' field _ name ' ]
: param max _ level : An integer that indicates max level depth to reach when
traversing... | index = kwargs . pop ( 'index' , None )
max_level = kwargs . pop ( 'max_level' , 0 )
greedy = kwargs . pop ( 'greedy' , False )
pointers = [ ]
if index is not None and not isinstance ( index , list ) :
index = [ index ]
elif index is None :
index = [ ]
for i , layout_object in enumerate ( self . fields ) :
... |
def get_version ( ) :
"""Obtain the packge version from a python file e . g . pkg / _ _ init _ _ . py
See < https : / / packaging . python . org / en / latest / single _ source _ version . html > .""" | file_dir = os . path . realpath ( os . path . dirname ( __file__ ) )
with open ( os . path . join ( file_dir , '..' , 'behold' , 'version.py' ) ) as f :
txt = f . read ( )
version_match = re . search ( r"""^__version__ = ['"]([^'"]*)['"]""" , txt , re . M )
if version_match :
return version_match . group ( 1 )
... |
def config ( ctx ) :
"""[ GROUP ] Configuration management operations""" | from hfos import database
database . initialize ( ctx . obj [ 'dbhost' ] , ctx . obj [ 'dbname' ] )
from hfos . schemata . component import ComponentConfigSchemaTemplate
ctx . obj [ 'col' ] = model_factory ( ComponentConfigSchemaTemplate ) |
def ipv6 ( value ) :
"""Return whether or not given value is a valid IP version 6 address
( including IPv4 - mapped IPv6 addresses ) .
This validator is based on ` WTForms IPAddress validator ` _ .
. . _ WTForms IPAddress validator :
https : / / github . com / wtforms / wtforms / blob / master / wtforms / v... | ipv6_groups = value . split ( ':' )
if len ( ipv6_groups ) == 1 :
return False
ipv4_groups = ipv6_groups [ - 1 ] . split ( '.' )
if len ( ipv4_groups ) > 1 :
if not ipv4 ( ipv6_groups [ - 1 ] ) :
return False
ipv6_groups = ipv6_groups [ : - 1 ]
else :
ipv4_groups = [ ]
max_groups = 6 if ipv4_gro... |
def get_bin_dir ( self , build_module : str ) -> str :
"""Return a path to the binaries dir for a build module dir .
Create sub - tree of missing dirs as needed , and return full path
to innermost directory .""" | bin_dir = os . path . join ( self . conf . get_bin_path ( ) , build_module )
if not os . path . isdir ( bin_dir ) : # exist _ ok = True in case of concurrent creation of the same dir
os . makedirs ( bin_dir , exist_ok = True )
return bin_dir |
def gc2gdlat ( gclat ) :
"""Converts geocentric latitude to geodetic latitude using WGS84.
Parameters
gclat : array _ like
Geocentric latitude
Returns
gdlat : ndarray or float
Geodetic latitude""" | WGS84_e2 = 0.006694379990141317
# WGS84 first eccentricity squared
return np . rad2deg ( - np . arctan ( np . tan ( np . deg2rad ( gclat ) ) / ( WGS84_e2 - 1 ) ) ) |
def get_all_plugins ( self ) :
"""Gets all loaded plugins
: return : List of all plugins""" | return [ { "manifest" : i , "plugin" : self . get_plugin ( i [ "name" ] ) , "module" : self . get_module ( i [ "name" ] ) } for i in self . _manifests ] |
def set ( self , key , value ) :
"Set value to the key store ." | # if key already in data , update indexes
if not isinstance ( value , dict ) :
raise BadValueError ( 'The value {} is incorrect.' ' Values should be strings' . format ( value ) )
_value = deepcopy ( value )
if key in self . data :
self . delete_from_index ( key )
self . data [ key ] = _value
self . update_index... |
def inside_brain ( stat_dset , atlas = None , p = 0.001 ) :
'''calculates the percentage of voxels above a statistical threshold inside a brain mask vs . outside it
if ` ` atlas ` ` is ` ` None ` ` , it will try to find ` ` TT _ N27 ` `''' | atlas = find_atlas ( atlas )
if atlas == None :
return None
mask_dset = nl . suffix ( stat_dset , '_atlasfrac' )
nl . run ( [ '3dfractionize' , '-template' , nl . strip_subbrick ( stat_dset ) , '-input' , nl . calc ( [ atlas ] , '1+step(a-100)' , datum = 'short' ) , '-preserve' , '-clip' , '0.2' , '-prefix' , mask_... |
def cursor_down ( self , stats ) :
"""Set the cursor to position N - 1 in the list .""" | if self . cursor_position + 1 < self . get_pagelines ( stats ) :
self . cursor_position += 1
else :
if self . _current_page + 1 < self . _page_max :
self . _current_page += 1
else :
self . _current_page = 0
self . cursor_position = 0 |
def _from_dict ( cls , _dict ) :
"""Initialize a MessageOutput object from a json dictionary .""" | args = { }
if 'generic' in _dict :
args [ 'generic' ] = [ DialogRuntimeResponseGeneric . _from_dict ( x ) for x in ( _dict . get ( 'generic' ) ) ]
if 'intents' in _dict :
args [ 'intents' ] = [ RuntimeIntent . _from_dict ( x ) for x in ( _dict . get ( 'intents' ) ) ]
if 'entities' in _dict :
args [ 'entitie... |
def get_port_channel_detail_output_lacp_partner_oper_priority ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_port_channel_detail = ET . Element ( "get_port_channel_detail" )
config = get_port_channel_detail
output = ET . SubElement ( get_port_channel_detail , "output" )
lacp = ET . SubElement ( output , "lacp" )
partner_oper_priority = ET . SubElement ( lacp , "partner-oper-priority" )
p... |
def p_expression_unor ( self , p ) :
'expression : NOR expression % prec UNOR' | p [ 0 ] = Unor ( p [ 2 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def example_camera ( ) :
"""Example with ` morphological _ chan _ vese ` with using the default
initialization of the level - set .""" | logging . info ( 'Running: example_camera (MorphACWE)...' )
# Load the image .
img = imread ( PATH_IMG_CAMERA ) / 255.0
# Callback for visual plotting
callback = visual_callback_2d ( img )
# Morphological Chan - Vese ( or ACWE )
ms . morphological_chan_vese ( img , 35 , smoothing = 3 , lambda1 = 1 , lambda2 = 1 , iter_... |
def cache_clean ( path = None , runas = None , env = None , force = False ) :
'''Clean cached NPM packages .
If no path for a specific package is provided the entire cache will be cleared .
path
The cache subpath to delete , or None to clear the entire cache
runas
The user to run NPM with
env
Environm... | env = env or { }
if runas :
uid = salt . utils . user . get_uid ( runas )
if uid :
env . update ( { 'SUDO_UID' : uid , 'SUDO_USER' : '' } )
cmd = [ 'npm' , 'cache' , 'clean' ]
if path :
cmd . append ( path )
if force is True :
cmd . append ( '--force' )
cmd = ' ' . join ( cmd )
result = __salt__... |
def add_headers ( width = 80 , title = 'Untitled' , subtitle = '' , author = '' , email = '' , description = '' , tunings = [ ] ) :
"""Create a nice header in the form of a list of strings using the
information that has been filled in .
All arguments except ' width ' and ' tunings ' should be strings . ' width ... | result = [ '' ]
title = str . upper ( title )
result += [ str . center ( ' ' . join ( title ) , width ) ]
if subtitle != '' :
result += [ '' , str . center ( str . title ( subtitle ) , width ) ]
if author != '' or email != '' :
result += [ '' , '' ]
if email != '' :
result += [ str . center ( 'Writ... |
def parse_net_kwargs ( kwargs ) :
"""Parse arguments for the estimator .
Resolves dotted names and instantiated classes .
Examples
> > > kwargs = { ' lr ' : 0.1 , ' module _ _ nonlin ' : ' torch . nn . Hardtanh ( - 2 , max _ val = 3 ) ' }
> > > parse _ net _ kwargs ( kwargs )
{ ' lr ' : 0.1 , ' module _ _... | if not kwargs :
return kwargs
resolved = { }
for k , v in kwargs . items ( ) :
resolved [ k ] = _resolve_dotted_name ( v )
return resolved |
def forwast_autodownload ( FORWAST_URL ) :
"""Autodownloader for forwast database package for brightway . Used by ` lcopt _ bw2 _ forwast _ setup ` to get the database data . Not designed to be used on its own""" | dirpath = tempfile . mkdtemp ( )
r = requests . get ( FORWAST_URL )
z = zipfile . ZipFile ( io . BytesIO ( r . content ) )
z . extractall ( dirpath )
return os . path . join ( dirpath , 'forwast.bw2package' ) |
def _sysapi_changed_nilrt ( ) :
'''Besides the normal Linux kernel driver interfaces , NILinuxRT - supported hardware features an
extensible , plugin - based device enumeration and configuration interface named " System API " .
When an installed package is extending the API it is very hard to know all repercurs... | nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os . path . exists ( nisysapi_path ) and _file_changed_nilrt ( nisysapi_path ) :
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/" . format ( 'arm-linux-gnueabi' if 'arm' i... |
def remote_exception ( exc , tb ) :
"""Metaclass that wraps exception type in RemoteException""" | if type ( exc ) in exceptions :
typ = exceptions [ type ( exc ) ]
return typ ( exc , tb )
else :
try :
typ = type ( exc . __class__ . __name__ , ( RemoteException , type ( exc ) ) , { 'exception_type' : type ( exc ) } )
exceptions [ type ( exc ) ] = typ
return typ ( exc , tb )
ex... |
def setup_environment ( ) :
"""Set up neccessary environment variables
This appends all path of sys . path to the python path
so mayapy will find all installed modules .
We have to make sure , that we use maya libs instead of
libs of the virtual env . So we insert all the libs for mayapy
first .
: retur... | osinter = ostool . get_interface ( )
pypath = osinter . get_maya_envpath ( )
for p in sys . path :
pypath = os . pathsep . join ( ( pypath , p ) )
os . environ [ 'PYTHONPATH' ] = pypath |
def smembers ( key , host = None , port = None , db = None , password = None ) :
'''Get members in a Redis set
CLI Example :
. . code - block : : bash
salt ' * ' redis . smembers foo _ set''' | server = _connect ( host , port , db , password )
return list ( server . smembers ( key ) ) |
def set_armed_state ( self , state ) :
"""Set the armed state , also update local state .""" | self . set_service_value ( self . security_sensor_service , 'Armed' , 'newArmedValue' , state )
self . set_cache_value ( 'Armed' , state ) |
def _normalize_str ( self , string ) :
"""Remove special characters and strip spaces""" | if string :
if not isinstance ( string , str ) :
string = str ( string , 'utf-8' , 'replace' )
return unicodedata . normalize ( 'NFKD' , string ) . encode ( 'ASCII' , 'ignore' ) . decode ( 'ASCII' )
return '' |
def _add_text_ngrams ( self , witness , minimum , maximum ) :
"""Adds n - gram data from ` witness ` to the data store .
: param witness : witness to get n - grams from
: type witness : ` WitnessText `
: param minimum : minimum n - gram size
: type minimum : ` int `
: param maximum : maximum n - gram size... | text_id = self . _get_text_id ( witness )
self . _logger . info ( 'Adding n-grams ({} <= n <= {}) for {}' . format ( minimum , maximum , witness . get_filename ( ) ) )
skip_sizes = [ ]
for size in range ( minimum , maximum + 1 ) :
if self . _has_ngrams ( text_id , size ) :
self . _logger . info ( '{}-grams ... |
def dataChanged ( self , topleft , bottomright ) :
"""Marks view for repaint . : qtdoc : ` Re - implemented < QAbstractItemView . dataChanged > `""" | self . _viewIsDirty = True
super ( StimulusView , self ) . dataChanged ( topleft , bottomright ) |
def amean ( x , weights = None ) :
"""Return the weighted arithmetic mean of x""" | w_arr , x_arr = _preprocess_inputs ( x , weights )
return ( w_arr * x_arr ) . sum ( axis = 0 ) / w_arr . sum ( axis = 0 ) |
def get ( self , timeout = None ) : # type : ( float ) - > T
"""Return the result or raise the error the function has produced""" | self . wait ( timeout )
if isinstance ( self . _result , Exception ) :
raise self . _result
return self . _result |
def multidimensional_discretization ( rho , sigma , N = 3 , method = 'rouwenhorst' , m = 2 ) :
"""Discretize an VAR ( 1 ) into a markov chain . The autoregression matrix is supposed to be a scalar .
: param rho :
: param sigma :
: param N :
: param method :
: param m :
: return :""" | # rho is assumed to be a scalar
# sigma is a positive symmetric matrix
# N number of points in each non - degenerate dimension
# m : standard deviations to approximate
import scipy . linalg
from itertools import product
d = sigma . shape [ 1 ]
sigma = sigma . copy ( )
zero_columns = np . where ( sigma . sum ( axis = 0 ... |
async def read_data ( self , stream_id : int ) -> bytes :
"""Read data from the specified stream until it is closed by the remote
peer . If the stream is never ended , this never returns .""" | frames = [ f async for f in self . stream_frames ( stream_id ) ]
return b'' . join ( frames ) |
def get_poster ( self ) :
"""Returns poster data itself ( as in JPEG / GIF / PNG file )""" | if self . _posterData :
return self . _posterData
response = urllib . request . urlopen ( self . posterURL )
self . _posterData = response . read ( )
return self . _posterData |
def upgrade ( ) :
"""Upgrade database .""" | with op . batch_alter_table ( 'accounts_user_session_activity' ) as batch_op :
batch_op . add_column ( sa . Column ( 'browser' , sa . String ( 80 ) , nullable = True ) )
batch_op . add_column ( sa . Column ( 'browser_version' , sa . String ( 30 ) , nullable = True ) )
batch_op . add_column ( sa . Column ( '... |
def get_css_background ( self , uncomment = False , ** kwargs ) :
"""Get the CSS background attributes for an element .
Additional arguments :
uncomment - - surround the attributes with ` * / ` and ` / * ` so that the
template tag can be kept inside a comment block , to keep syntax
highlighters happy""" | text = self . _css_background ( ** kwargs )
if uncomment :
text = ' */ {} /* ' . format ( text )
return text |
def database_dsn ( self ) :
"""Substitute the root dir into the database DSN , for Sqlite""" | if not self . _config . library . database :
return 'sqlite:///{root}/library.db' . format ( root = self . _root )
return self . _config . library . database . format ( root = self . _root ) |
def recv_exactly ( recv_fn , size ) :
"""Use the function to read and return exactly number of bytes desired .
https : / / docs . python . org / 3 / howto / sockets . html # socket - programming - howto for
more information about why this is necessary .
: param recv _ fn : Function that can return up to given... | recv_bytes = 0
chunks = [ ]
while recv_bytes < size :
chunk = recv_fn ( size - recv_bytes )
if len ( chunk ) == 0 : # when closed or empty
break
recv_bytes += len ( chunk )
chunks . append ( chunk )
response = b'' . join ( chunks )
if len ( response ) != size :
raise ValueError
return respon... |
def set_enable_flag_keep_rect_within_constraints ( self , enable ) :
"""Enable / disables the KeepRectangleWithinConstraint for child states""" | for child_state_v in self . child_state_views ( ) :
self . keep_rect_constraints [ child_state_v ] . enable = enable
child_state_v . keep_rect_constraints [ child_state_v . _name_view ] . enable = enable |
def rule_command_cmdlist_interface_j_interface_pc_leaf_interface_port_channel_leaf ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
rule = ET . SubElement ( config , "rule" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" )
index_key = ET . SubElement ( rule , "index" )
index_key . text = kwargs . pop ( 'index' )
command = ET . SubElement ( rule , "command" )
cmdlist = ET . SubElement ( command , "cmdlist" )
interface... |
def hex_to_rgb ( hex_value ) :
"""expects : hex value , ex : # fffff
returns : rgb value , ex : ff00 / ff00 / ff00""" | if '#' in hex_value :
hex_value = hex_value . replace ( '#' , '' )
if len ( hex_value ) < 6 :
return '0000/0000/0000'
r = hex_value [ : 2 ]
g = hex_value [ 2 : 4 ]
b = hex_value [ 4 : ]
return r + '00/' + g + '00/' + b + '00' |
def _validate_pillar_roots ( pillar_roots ) :
'''If the pillar _ roots option has a key that is None then we will error out ,
just replace it with an empty list''' | if not isinstance ( pillar_roots , dict ) :
log . warning ( 'The pillar_roots parameter is not properly formatted,' ' using defaults' )
return { 'base' : _expand_glob_path ( [ salt . syspaths . BASE_PILLAR_ROOTS_DIR ] ) }
return _normalize_roots ( pillar_roots ) |
def replication_state ( self , repl_id ) :
"""Retrieves the state for the given replication . Possible values are
` ` triggered ` ` , ` ` completed ` ` , ` ` error ` ` , and ` ` None ` ` ( meaning not yet
triggered ) .
: param str repl _ id : Replication id used to identify the replication to
inspect .
: ... | if "scheduler" in self . client . features ( ) :
try :
repl_doc = Scheduler ( self . client ) . get_doc ( repl_id )
except HTTPError as err :
raise CloudantReplicatorException ( err . response . status_code , repl_id )
state = repl_doc [ 'state' ]
else :
try :
repl_doc = self . d... |
def render_field_path ( field_names ) :
"""Create a * * field path * * from a list of nested field names .
A * * field path * * is a ` ` . ` ` - delimited concatenation of the field
names . It is used to represent a nested field . For example ,
in the data
. . code - block : python
data = {
' aa ' : {
... | result = [ ]
for field_name in field_names :
match = _SIMPLE_FIELD_NAME . match ( field_name )
if match and match . group ( 0 ) == field_name :
result . append ( field_name )
else :
replaced = field_name . replace ( _BACKSLASH , _ESCAPED_BACKSLASH ) . replace ( _BACKTICK , _ESCAPED_BACKTICK ... |
def _init_metadata ( self ) :
"""stub""" | self . _min_integer_value = None
self . _max_integer_value = None
self . _integer_value_metadata = { 'element_id' : Id ( self . my_osid_object_form . _authority , self . my_osid_object_form . _namespace , 'integer_value' ) , 'element_label' : 'Integer Value' , 'instructions' : 'enter an integer value' , 'required' : Fa... |
def fq_name ( self ) :
"""Return FQDN of the resource
: rtype : FQName""" | return self . get ( 'fq_name' , self . get ( 'to' , super ( Resource , self ) . fq_name ) ) |
def open ( self , append : bool = False , write : bool = False ) :
"""Open
Pass arguments and return open file .
@ param append : Open for writing , appending to the end of the file if
it exists . Default as False .
@ param write : Open for writing , truncating the file first . Default
as False .
@ type... | flag = { ( False , False ) : 'r' , ( True , False ) : 'a' , ( True , True ) : 'a' , ( False , True ) : 'w' } [ ( append , write ) ]
realPath = self . realPath
realDir = os . path . dirname ( realPath )
if not os . path . exists ( realDir ) :
os . makedirs ( realDir , DirSettings . defaultDirChmod )
return open ( se... |
def charset ( self ) :
"""The charset from the content type .""" | header = self . environ . get ( 'CONTENT_TYPE' )
if header :
ct , options = parse_options_header ( header )
charset = options . get ( 'charset' )
if charset :
if is_known_charset ( charset ) :
return charset
return self . unknown_charset ( charset )
return self . default_charset |
def _thread ( self ) :
"""Thread entry point : does the job once , stored results , and dies .""" | # Get
args , kwargs = self . _jobs . get ( )
# Stop thread when ( None , None ) comes in
if args is None and kwargs is None :
return None
# Wrappers should exit as well
# Work
try :
self . _results . append ( self . _worker ( * args , ** kwargs ) )
return True
except Exception as e :
self . _errors . ap... |
def get_client ( key , project ) :
"""Gets a ` Client ` object ( required by the other functions ) .
TODO : docstring""" | cred = get_storage_credentials ( key )
return storage . Client ( project = project , credentials = cred ) |
def add_button_box ( self , stdbtns ) :
"""Create dialog button box and add it to the dialog layout""" | bbox = QDialogButtonBox ( stdbtns )
run_btn = bbox . addButton ( _ ( "Run" ) , QDialogButtonBox . AcceptRole )
run_btn . clicked . connect ( self . run_btn_clicked )
bbox . accepted . connect ( self . accept )
bbox . rejected . connect ( self . reject )
btnlayout = QHBoxLayout ( )
btnlayout . addStretch ( 1 )
btnlayout... |
def assess_trial ( self , trial_job_id , trial_history ) :
"""assess _ trial
Parameters
trial _ job _ id : int
trial job id
trial _ history : list
The history performance matrix of each trial
Returns
bool
AssessResult . Good or AssessResult . Bad
Raises
Exception
unrecognize exception in media... | curr_step = len ( trial_history )
if curr_step < self . start_step :
return AssessResult . Good
try :
num_trial_history = [ float ( ele ) for ele in trial_history ]
except ( TypeError , ValueError ) as error :
logger . warning ( 'incorrect data type or value:' )
logger . exception ( error )
except Excep... |
def get_scrim ( path = None , auto_write = None , shell = None , script = None , cache = { } ) :
'''Get a : class : ` Scrim ` instance . Each instance is cached so if you call
get _ scrim again with the same arguments you get the same instance .
See also :
: class : ` Scrim `''' | args = ( path , auto_write , shell , script )
if args not in cache :
cache [ args ] = Scrim ( * args )
return cache [ args ] |
def forget ( identifier ) :
'''Tells homely to forget about a dotfiles repository that was previously
added . You can then run ` homely update ` to have homely perform automatic
cleanup of anything that was installed by that dotfiles repo .
REPO
This should be the path to a local dotfiles repository that ha... | errors = False
for one in identifier :
cfg = RepoListConfig ( )
info = cfg . find_by_any ( one , "ilc" )
if not info :
warn ( "No repos matching %r" % one )
errors = True
continue
# update the config . . .
note ( "Removing record of repo [%s] at %s" % ( info . shortid ( ) , i... |
def aws ( product , tile , folder , redownload , info , entire , bands , l2a ) :
"""Download Sentinel - 2 data from Sentinel - 2 on AWS to ESA SAFE format . Download uses multiple threads .
Examples with Sentinel - 2 L1C data :
sentinelhub . aws - - product S2A _ MSIL1C _ 20170414T003551 _ N0204 _ R016 _ T54HVH... | band_list = None if bands is None else bands . split ( ',' )
data_source = DataSource . SENTINEL2_L2A if l2a else DataSource . SENTINEL2_L1C
if info :
if product is None :
click . echo ( get_safe_format ( tile = tile , entire_product = entire , data_source = data_source ) )
else :
click . echo (... |
def merge_overlaps ( self , threshold = 0.0 ) :
"""Merge overlapping labels with the same value .
Two labels are considered overlapping ,
if ` ` l2 . start - l1 . end < threshold ` ` .
Args :
threshold ( float ) : Maximal distance between two labels
to be considered as overlapping .
( default : 0.0)
E... | updated_labels = [ ]
all_intervals = self . label_tree . copy ( )
# recursivly find a group of overlapping labels with the same value
def recursive_overlaps ( interval ) :
range_start = interval . begin - threshold
range_end = interval . end + threshold
direct_overlaps = all_intervals . overlap ( range_star... |
def run_kernel ( self , func , gpu_args , instance ) :
"""Run a compiled kernel instance on a device""" | logging . debug ( 'run_kernel %s' , instance . name )
logging . debug ( 'thread block dims (%d, %d, %d)' , * instance . threads )
logging . debug ( 'grid dims (%d, %d, %d)' , * instance . grid )
try :
self . dev . run_kernel ( func , gpu_args , instance . threads , instance . grid )
except Exception as e :
if "... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.