signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def has_error ( self ) :
"""Queries the server to check if the job has an error .
Returns True or False .""" | self . get_info ( )
if 'status' not in self . info :
return False
if 'hasError' not in self . info [ 'status' ] :
return False
return self . info [ 'status' ] [ 'hasError' ] |
def write_fits ( self , fitsfile ) :
"""Write the ROI model to a FITS file .""" | tab = self . create_table ( )
hdu_data = fits . table_to_hdu ( tab )
hdus = [ fits . PrimaryHDU ( ) , hdu_data ]
fits_utils . write_hdus ( hdus , fitsfile ) |
def visit ( d , op ) :
"""Recursively call op ( d ) for all list subelements and dictionary ' values ' that d may have .""" | op ( d )
if isinstance ( d , list ) :
for i in d :
visit ( i , op )
elif isinstance ( d , dict ) :
for i in itervalues ( d ) :
visit ( i , op ) |
def create_ondemand_instances ( ec2 , image_id , spec , num_instances = 1 ) :
"""Requests the RunInstances EC2 API call but accounts for the race between recently created
instance profiles , IAM roles and an instance creation that refers to them .
: rtype : list [ Instance ]""" | instance_type = spec [ 'instance_type' ]
log . info ( 'Creating %s instance(s) ... ' , instance_type )
for attempt in retry_ec2 ( retry_for = a_long_time , retry_while = inconsistencies_detected ) :
with attempt :
return ec2 . run_instances ( image_id , min_count = num_instances , max_count = num_instances ... |
def download ( self , chunk_size = 1024 ) :
"""Download attachment
Args :
chunk _ size ( int ) : Byte - size of chunked download request stream
Returns :
BytesIO : Stream ready for reading containing the attachment file contents""" | stream = BytesIO ( )
response = self . _swimlane . request ( 'get' , 'attachment/download/{}' . format ( self . file_id ) , stream = True )
for chunk in response . iter_content ( chunk_size ) :
stream . write ( chunk )
stream . seek ( 0 )
return stream |
def initializeSessionAsBob ( sessionState , sessionVersion , parameters ) :
""": type sessionState : SessionState
: type sessionVersion : int
: type parameters : BobAxolotlParameters""" | sessionState . setSessionVersion ( sessionVersion )
sessionState . setRemoteIdentityKey ( parameters . getTheirIdentityKey ( ) )
sessionState . setLocalIdentityKey ( parameters . getOurIdentityKey ( ) . getPublicKey ( ) )
secrets = bytearray ( )
if sessionVersion >= 3 :
secrets . extend ( RatchetingSession . getDis... |
def remove_connection ( self , alias ) :
"""Remove connection from the registry . Raises ` ` KeyError ` ` if connection
wasn ' t found .""" | errors = 0
for d in ( self . _conns , self . _kwargs ) :
try :
del d [ alias ]
except KeyError :
errors += 1
if errors == 2 :
raise KeyError ( 'There is no connection with alias %r.' % alias ) |
def load_config ( path , env_var , default_path = None , exit_on_config_errors = True ) :
'''Returns configuration dict from parsing either the file described by
` ` path ` ` or the environment variable described by ` ` env _ var ` ` as YAML .''' | if path is None : # When the passed path is None , we just want the configuration
# defaults , not actually loading the whole configuration .
return { }
if default_path is None : # This is most likely not being used from salt , i . e . , could be salt - cloud
# or salt - api which have not yet migrated to the new d... |
def refine_arccalibration ( sp , poly_initial , wv_master , poldeg , nrepeat = 3 , ntimes_match_wv = 2 , nwinwidth_initial = 7 , nwinwidth_refined = 5 , times_sigma_reject = 5 , interactive = False , threshold = 0 , plottitle = None , decimal_places = 4 , ylogscale = False , geometry = None , pdf = None , debugplot = 0... | # check that nrepeat is larger than zero
if nrepeat <= 0 :
raise ValueError ( "Unexpected nrepeat=" , str ( nrepeat ) )
# check that the requested polynomial degree is equal or larger than
# the degree of the initial polynomial
if poldeg < len ( poly_initial . coef ) - 1 :
raise ValueError ( "Polynomial degree ... |
def handle_class_prepared ( sender , ** kwargs ) :
"""See if this class needs registering of fields""" | from . settings import M2M_REGISTRY , FK_REGISTRY
from . registration import registry
sender_app = sender . _meta . app_label
sender_name = sender . _meta . model_name
for key , val in list ( FK_REGISTRY . items ( ) ) :
app_name , model_name = key . split ( '.' )
if app_name == sender_app and sender_name == mod... |
def _create_save_scenario_action ( self ) :
"""Create action for save scenario dialog .""" | icon = resources_path ( 'img' , 'icons' , 'save-as-scenario.svg' )
self . action_save_scenario = QAction ( QIcon ( icon ) , self . tr ( 'Save Current Scenario' ) , self . iface . mainWindow ( ) )
message = self . tr ( 'Save current scenario to text file' )
self . action_save_scenario . setStatusTip ( message )
self . a... |
def trade ( self ) :
"""每次交易的pivot表
Returns :
pd . DataFrame
此处的pivot _ table一定要用np . sum""" | return self . history_table . pivot_table ( index = [ 'datetime' , 'account_cookie' ] , columns = 'code' , values = 'amount' , aggfunc = np . sum ) . fillna ( 0 ) . sort_index ( ) |
def average_build_durations ( connection , packages ) :
"""Return the average build duration for list of packages ( or containers ) .
: param connection : txkoji . Connection
: param list packages : package names . These must all be containers , or they
must all be RPMs ( do not mix and match . )
: returns ... | containers = [ name for name in packages if name . endswith ( '-container' ) ]
if len ( containers ) == len ( packages ) :
containers = True
elif len ( containers ) == 0 :
containers = False
else : # This is going to be too complicated to do with multicalls .
raise NotImplementedError ( 'cannot mix containe... |
def get_string ( self , offset = 0 ) :
"""Return non space chars from current position until a whitespace .""" | if not self . has_space ( offset = offset ) :
return ''
# Get a char for each char in the current string from pos onward
# solong as the char is not whitespace .
string = self . string
pos = self . pos + offset
for i , char in enumerate ( string [ pos : ] ) :
if char . isspace ( ) :
return string [ pos ... |
def upload ( ) :
"""Uploads to PyPI""" | env = os . environ . copy ( )
print ( env )
env [ 'PYTHONPATH' ] = "./pynt"
print ( env )
# subprocess . call ( [ ' ssh - add ' , ' ~ / . ssh / id _ rsa ' ] )
pipe = subprocess . Popen ( [ 'python' , 'setup.py' , 'sdist' , 'upload' ] , env = env )
pipe . wait ( ) |
async def reset ( request : web . Request ) -> web . Response :
"""Execute a reset of the requested parts of the user configuration .""" | data = await request . json ( )
ok , bad_key = _check_reset ( data )
if not ok :
return web . json_response ( { 'message' : '{} is not a valid reset option' . format ( bad_key ) } , status = 400 )
log . info ( "Reset requested for {}" . format ( ', ' . join ( data . keys ( ) ) ) )
if data . get ( 'tipProbe' ) :
... |
def get_response ( self , key , serializable = False ) :
"""Get the value of a key from etcd .""" | range_request = self . _build_get_range_request ( key , serializable = serializable )
return self . kvstub . Range ( range_request , self . timeout , credentials = self . call_credentials , metadata = self . metadata ) |
def command_help_long ( self ) :
"""Return command help for use in global parser usage string
@ TODO update to support self . current _ indent from formatter""" | indent = " " * 2
# replace with current _ indent
help = "Command must be one of:\n"
for action_name in self . parser . valid_commands :
help += "%s%-10s %-70s\n" % ( indent , action_name , self . parser . commands [ action_name ] . desc_short . capitalize ( ) )
help += '\nSee \'%s help COMMAND\' for help and inform... |
def get_unix_tput_terminal_size ( ) :
"""Get the terminal size of a UNIX terminal using the tput UNIX command .
Ref : http : / / stackoverflow . com / questions / 263890 / how - do - i - find - the - width - height - of - a - terminal - window""" | import subprocess
try :
proc = subprocess . Popen ( [ "tput" , "cols" ] , stdin = subprocess . PIPE , stdout = subprocess . PIPE )
output = proc . communicate ( input = None )
cols = int ( output [ 0 ] )
proc = subprocess . Popen ( [ "tput" , "lines" ] , stdin = subprocess . PIPE , stdout = subprocess .... |
def getFilesFromAFolder ( path ) :
"""Getting all the files in a folder .
Args :
path : The path in which looking for the files
Returns :
list : The list of filenames found .""" | from os import listdir
from os . path import isfile , join
# onlyfiles = [ f for f in listdir ( path ) if isfile ( join ( path , f ) ) ]
onlyFiles = [ ]
for f in listdir ( path ) :
if isfile ( join ( path , f ) ) :
onlyFiles . append ( f )
return onlyFiles |
def list_json_files ( directory , recursive = False ) :
"""Return a list of file paths for JSON files within ` directory ` .
Args :
directory : A path to a directory .
recursive : If ` ` True ` ` , this function will descend into all
subdirectories .
Returns :
A list of JSON file paths directly under ` ... | json_files = [ ]
for top , dirs , files in os . walk ( directory ) :
dirs . sort ( )
# Get paths to each file in ` files `
paths = ( os . path . join ( top , f ) for f in sorted ( files ) )
# Add all the . json files to our return collection
json_files . extend ( x for x in paths if is_json ( x ) )
... |
def raise_remote_error ( error_code : int ) -> None :
"""Raise the appropriate error with a remote error code .""" | try :
error = next ( ( v for k , v in ERROR_CODES . items ( ) if k == error_code ) )
raise RequestError ( error )
except StopIteration :
raise RequestError ( 'Unknown remote error code returned: {0}' . format ( error_code ) ) |
def parent ( self ) :
'''We use parent for some initial data''' | if not hasattr ( self , '_parent' ) :
if 'parent' in self . kwargs :
try :
self . _parent = Page . objects . get ( id = self . kwargs [ "parent" ] )
except Exception as e :
raise e
else :
if hasattr ( self . request , 'leonardo_page' ) :
self . _parent... |
def line_tokenizer ( self , text ) :
"""From a . txt file , outputs lines as string in list .
input : 21 . u2 - wa - a - ru at - ta e2 - kal2 - la - ka _ e2 _ - ka wu - e - er
22 . . . . u2 - ul szi - . . .
23 . . . . x . . .
output : [ ' 21 . u2 - wa - a - ru at - ta e2 - kal2 - la - ka _ e2 _ - ka wu - e ... | line_output = [ ]
with open ( text , mode = 'r+' , encoding = 'utf8' ) as file :
lines = file . readlines ( )
assert isinstance ( text , str ) , 'Incoming argument must be a string.'
for line in lines : # Strip out damage characters
if not self . damage : # Add ' xn ' - - missing sign or number ?
li... |
def get_nearest ( self , path , return_type = 'file' , strict = True , all_ = False , ignore_strict_entities = None , full_search = False , ** kwargs ) :
'''Walk up the file tree from the specified path and return the
nearest matching file ( s ) .
Args :
path ( str ) : The file to search from .
return _ typ... | entities = { }
for ent in self . entities . values ( ) :
m = ent . regex . search ( path )
if m :
entities [ ent . name ] = ent . _astype ( m . group ( 1 ) )
# Remove any entities we want to ignore when strict matching is on
if strict and ignore_strict_entities is not None :
for k in ignore_strict_e... |
def generate_one ( self ) :
"""Generate a single element .
Returns
element
An element from the domain .
Examples
> > > generator = RepellentGenerator ( [ ' a ' , ' b ' ] )
> > > gen _ item = generator . generate _ one ( )
> > > gen _ item in [ ' a ' , ' b ' ]
True""" | # Get the weights for all items in the domain
weights = [ self . probability_func ( self . generated [ element ] ) for element in self . domain ]
# Sample from the domain using the weights
element = random . choices ( self . domain , weights = weights ) [ 0 ]
# Update the generated values and return
self . generated [ ... |
def item_at ( self , row , column ) :
"""Returns the TableItem instance at row , column cordinates
Args :
row ( int ) : zero based index
column ( int ) : zero based index""" | return self . children [ str ( row ) ] . children [ str ( column ) ] |
def upload_file ( self , localFileName , remoteFileName = None , connId = 'default' ) :
"""Sends file from local drive to current directory on FTP server in binary mode .
Returns server output .
Parameters :
- localFileName - file name or path to a file on a local drive .
- remoteFileName ( optional ) - a n... | thisConn = self . __getConnection ( connId )
outputMsg = ""
remoteFileName_ = ""
localFilePath = os . path . normpath ( localFileName )
if not os . path . isfile ( localFilePath ) :
raise FtpLibraryError ( "Valid file path should be provided." )
else :
if remoteFileName == None :
fileTuple = os . path .... |
def olympic_sprints ( data_set = 'rogers_girolami_data' ) :
"""All olympics sprint winning times for multiple output prediction .""" | X = np . zeros ( ( 0 , 2 ) )
Y = np . zeros ( ( 0 , 1 ) )
cats = { }
for i , dataset in enumerate ( [ olympic_100m_men , olympic_100m_women , olympic_200m_men , olympic_200m_women , olympic_400m_men , olympic_400m_women ] ) :
data = dataset ( )
year = data [ 'X' ]
time = data [ 'Y' ]
X = np . vstack ( (... |
def clear_published ( self ) :
"""stub""" | if ( self . get_published_metadata ( ) . is_read_only ( ) or self . get_published_metadata ( ) . is_required ( ) ) :
raise NoAccess ( )
self . my_osid_object_form . _my_map [ 'published' ] = self . _published_metadata [ 'default_published_values' ] [ 0 ] |
async def do_after_sleep ( delay : float , coro , * args , ** kwargs ) :
"""Performs an action after a set amount of time .
This function only calls the coroutine after the delay ,
preventing asyncio complaints about destroyed coros .
: param delay : Time in seconds
: param coro : Coroutine to run
: param... | await asyncio . sleep ( delay )
return await coro ( * args , ** kwargs ) |
def _get_property ( name ) :
"""Delegate property to self . loop""" | ret = property ( lambda self : getattr ( self . loop , name ) )
if six . PY3 : # _ _ doc _ _ is readonly in Py2
try :
ret . __doc__ = getattr ( TrainLoop , name ) . __doc__
except AttributeError :
pass
return ret |
def _process_dbxref ( self ) :
"""We bring in the dbxref identifiers and store them in a hashmap for
lookup in other functions .
Note that some dbxrefs aren ' t mapped to identifiers .
For example , 5004018 is mapped to a string ,
" endosome & imaginal disc epithelial cell | somatic clone . . . "
In those... | raw = '/' . join ( ( self . rawdir , 'dbxref' ) )
LOG . info ( "processing dbxrefs" )
line_counter = 0
with open ( raw , 'r' ) as f :
filereader = csv . reader ( f , delimiter = '\t' , quotechar = '\"' )
f . readline ( )
# read the header row ; skip
for line in filereader :
( dbxref_id , db_id ,... |
def scalar ( self , value , step , name ) :
"""Plot a scalar value .
: param value : int or float , the value on the y - axis
: param step : int or float , the value on the x - axis
: param name : String , the name of the variable to be used during visualization""" | # Spaces not allowed for scalar variable name
assert len ( name . split ( " " ) ) < 2 , "Ensure that you don't have spaces in your variable name, use '_' instead."
name = "scalar_" + name
self . previous . append ( name )
if self . previous [ - 1 ] not in self . previous [ : - 1 ] :
self . c . execute ( """INSERT I... |
def p_nonfluent_def ( self , p ) :
'''nonfluent _ def : IDENT LPAREN param _ list RPAREN COLON LCURLY NON _ FLUENT COMMA type _ spec COMMA DEFAULT ASSIGN _ EQUAL range _ const RCURLY SEMI
| IDENT COLON LCURLY NON _ FLUENT COMMA type _ spec COMMA DEFAULT ASSIGN _ EQUAL range _ const RCURLY SEMI''' | if len ( p ) == 16 :
p [ 0 ] = PVariable ( name = p [ 1 ] , fluent_type = 'non-fluent' , range_type = p [ 9 ] , param_types = p [ 3 ] , default = p [ 13 ] )
else :
p [ 0 ] = PVariable ( name = p [ 1 ] , fluent_type = 'non-fluent' , range_type = p [ 6 ] , default = p [ 10 ] ) |
def kde ( data , bw , cmap = 'hot' , method = 'hist' , scaling = 'sqrt' , alpha = 220 , cut_below = None , clip_above = None , binsize = 1 , cmap_levels = 10 , show_colorbar = False ) :
"""Kernel density estimation visualization
: param data : data access object
: param bw : kernel bandwidth ( in screen coordin... | from geoplotlib . layers import KDELayer
_global_config . layers . append ( KDELayer ( data , bw , cmap , method , scaling , alpha , cut_below , clip_above , binsize , cmap_levels , show_colorbar ) ) |
def namedb_get_all_names ( cur , current_block , offset = None , count = None , include_expired = False ) :
"""Get a list of all names in the database , optionally
paginated with offset and count . Exclude expired names . Include revoked names .""" | unexpired_query = ""
unexpired_args = ( )
if not include_expired : # all names , including expired ones
unexpired_query , unexpired_args = namedb_select_where_unexpired_names ( current_block )
unexpired_query = 'WHERE {}' . format ( unexpired_query )
query = "SELECT name FROM name_records JOIN namespaces ON nam... |
def uniform_crossover ( parents ) :
"""Perform uniform crossover on two parent chromosomes .
Randomly take genes from one parent or the other .
Ex . p1 = xxxxx , p2 = yyyyy , child = xyxxy""" | chromosome_length = len ( parents [ 0 ] )
children = [ [ ] , [ ] ]
for i in range ( chromosome_length ) :
selected_parent = random . randint ( 0 , 1 )
# Take from the selected parent , and add it to child 1
# Take from the other parent , and add it to child 2
children [ 0 ] . append ( parents [ selected... |
def _init_qualifier ( qualifier , qual_repo ) :
"""Initialize the flavors of a qualifier from the qualifier repo and
initialize propagated .""" | qual_dict_entry = qual_repo [ qualifier . name ]
qualifier . propagated = False
if qualifier . tosubclass is None :
if qual_dict_entry . tosubclass is None :
qualifier . tosubclass = True
else :
qualifier . tosubclass = qual_dict_entry . tosubclass
if qualifier . overridable is None :
if qua... |
def _create_lists ( config , results , current , stack , inside_cartesian = None ) :
"""An ugly recursive method to transform config dict
into a tree of AbstractNestedList .""" | # Have we done it already ?
try :
return results [ current ]
except KeyError :
pass
# Check recursion depth and detect loops
if current in stack :
raise ConfigurationError ( 'Rule {!r} is recursive: {!r}' . format ( stack [ 0 ] , stack ) )
if len ( stack ) > 99 :
raise ConfigurationError ( 'Rule {!r} is... |
def get_pool_context ( self ) : # TODO : Add in - process caching
"""Builds context for the WF pool .
Returns :
Context dict .""" | context = { self . current . lane_id : self . current . role , 'self' : self . current . role }
for lane_id , role_id in self . current . pool . items ( ) :
if role_id :
context [ lane_id ] = lazy_object_proxy . Proxy ( lambda : self . role_model ( super_context ) . objects . get ( role_id ) )
return contex... |
async def unregister ( self , channel , event , callback ) :
"""Safely unregister a callback from the list of ` ` event ` `
callbacks for ` ` channel _ name ` ` .
: param channel : channel name
: param event : event name
: param callback : callback to execute when event on channel occurs
: return : a coro... | channel = self . channel ( channel , create = False )
if channel :
channel . unregister ( event , callback )
if not channel :
await channel . disconnect ( )
self . channels . pop ( channel . name )
return channel |
def fetch_host_ip ( host : str ) -> str :
"""Fetch ip by host""" | try :
ip = socket . gethostbyname ( host )
except socket . gaierror :
return ''
return ip |
def pseudo_raw_input ( self , prompt : str ) -> str :
"""Began life as a copy of cmd ' s cmdloop ; like raw _ input but
- accounts for changed stdin , stdout
- if input is a pipe ( instead of a tty ) , look at self . echo
to decide whether to print the prompt and the input""" | if self . use_rawinput :
try :
if sys . stdin . isatty ( ) : # Wrap in try since terminal _ lock may not be locked when this function is called from unit tests
try : # A prompt is about to be drawn . Allow asynchronous changes to the terminal .
self . terminal_lock . release ( )
... |
def draw_pdf ( buffer , invoice ) :
"""Draws the invoice""" | canvas = Canvas ( buffer , pagesize = A4 )
canvas . translate ( 0 , 29.7 * cm )
canvas . setFont ( 'Helvetica' , 10 )
canvas . saveState ( )
header_func ( canvas )
canvas . restoreState ( )
canvas . saveState ( )
footer_func ( canvas )
canvas . restoreState ( )
canvas . saveState ( )
address_func ( canvas )
canvas . re... |
def clear ( self ) :
"""Clear the statement _ group , citation , evidence , and annotations .""" | self . statement_group = None
self . citation . clear ( )
self . evidence = None
self . annotations . clear ( ) |
def get_actions ( self , commands ) :
"""Get parameterized actions from command list based on command type and verb .""" | actions = [ ]
for type , turn_based , verb in commands :
if len ( self . action_filter ) != 0 and verb not in self . action_filter :
continue
if type == 'DiscreteMovement' :
if verb in { "move" , "turn" , "look" , "strafe" , "jumpmove" , "jumpstrafe" } :
actions . append ( verb + " 1... |
def saveSheets ( fn , * vsheets , confirm_overwrite = False ) :
'Save sheet ` vs ` with given filename ` fn ` .' | givenpath = Path ( fn )
# determine filetype to save as
filetype = ''
basename , ext = os . path . splitext ( fn )
if ext :
filetype = ext [ 1 : ]
filetype = filetype or options . save_filetype
if len ( vsheets ) > 1 :
if not fn . endswith ( '/' ) : # forcibly specify save individual files into directory by end... |
def run ( samples , run_parallel , stage ) :
"""Run structural variation detection .
The stage indicates which level of structural variant calling to run .
- initial , callers that can be used in subsequent structural variation steps ( cnvkit - > lumpy )
- standard , regular batch calling
- ensemble , post ... | to_process , extras , background = _batch_split_by_sv ( samples , stage )
processed = run_parallel ( "detect_sv" , ( [ xs , background , stage ] for xs in to_process . values ( ) ) )
finalized = ( run_parallel ( "finalize_sv" , [ ( [ xs [ 0 ] for xs in processed ] , processed [ 0 ] [ 0 ] [ "config" ] ) ] ) if len ( pro... |
def transformer_en_de_512 ( dataset_name = None , src_vocab = None , tgt_vocab = None , pretrained = False , ctx = cpu ( ) , root = os . path . join ( get_home_dir ( ) , 'models' ) , ** kwargs ) :
r"""Transformer pretrained model .
Embedding size is 400 , and hidden layer size is 1150.
Parameters
dataset _ na... | predefined_args = { 'num_units' : 512 , 'hidden_size' : 2048 , 'dropout' : 0.1 , 'epsilon' : 0.1 , 'num_layers' : 6 , 'num_heads' : 8 , 'scaled' : True , 'share_embed' : True , 'embed_size' : 512 , 'tie_weights' : True , 'embed_initializer' : None }
mutable_args = frozenset ( [ 'num_units' , 'hidden_size' , 'dropout' ,... |
def from_str ( cls , tagstring ) :
"""Create a tag by parsing the tag of a message
: param tagstring : A tag string described in the irc protocol
: type tagstring : : class : ` str `
: returns : A tag
: rtype : : class : ` Tag `
: raises : None""" | m = cls . _parse_regexp . match ( tagstring )
return cls ( name = m . group ( 'name' ) , value = m . group ( 'value' ) , vendor = m . group ( 'vendor' ) ) |
def _transform_filter_to_sql ( filter_block , node , context ) :
"""Transform a Filter block to its corresponding SQLAlchemy expression .
Args :
filter _ block : Filter , the Filter block to transform .
node : SqlNode , the node Filter block applies to .
context : CompilationContext , global compilation sta... | expression = filter_block . predicate
return _expression_to_sql ( expression , node , context ) |
def mod ( ctx , number , divisor ) :
"""Returns the remainder after number is divided by divisor""" | number = conversions . to_decimal ( number , ctx )
divisor = conversions . to_decimal ( divisor , ctx )
return number - divisor * _int ( ctx , number / divisor ) |
def get ( self , sid ) :
"""Constructs a DocumentContext
: param sid : The sid
: returns : twilio . rest . preview . sync . service . document . DocumentContext
: rtype : twilio . rest . preview . sync . service . document . DocumentContext""" | return DocumentContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = sid , ) |
def random_sense ( ambiguous_word : str , pos = None ) -> "wn.Synset" :
"""Returns a random sense .
: param ambiguous _ word : String , a single word .
: param pos : String , one of ' a ' , ' r ' , ' s ' , ' n ' , ' v ' , or None .
: return : A random Synset .""" | if pos is None :
return custom_random . choice ( wn . synsets ( ambiguous_word ) )
else :
return custom_random . choice ( wn . synsets ( ambiguous_word , pos ) ) |
def address ( self ) :
"""Should be called to get client direct address
@ method address
@ returns { String } client direct address""" | if self . isDirect ( ) :
base36 = self . _iban [ 4 : ]
asInt = int ( base36 , 36 )
return to_checksum_address ( pad_left_hex ( baseN ( asInt , 16 ) , 20 ) )
return "" |
def delete_thumbnails ( self , source_cache = None ) :
"""Delete any thumbnails generated from the source image .
: arg source _ cache : An optional argument only used for optimisation
where the source cache instance is already known .
: returns : The number of files deleted .""" | source_cache = self . get_source_cache ( )
deleted = 0
if source_cache :
thumbnail_storage_hash = utils . get_storage_hash ( self . thumbnail_storage )
for thumbnail_cache in source_cache . thumbnails . all ( ) : # Only attempt to delete the file if it was stored using the
# same storage as is currently use... |
def render ( self , template_name : str , ** ctx ) :
"""Convenience method for rendering a template .
: param template _ name : The template ' s name . Can either be a full path ,
or a filename in the controller ' s template folder .
: param ctx : Context variables to pass into the template .""" | if '.' not in template_name :
template_file_extension = ( self . Meta . template_file_extension or app . config . TEMPLATE_FILE_EXTENSION )
template_name = f'{template_name}{template_file_extension}'
if self . Meta . template_folder_name and os . sep not in template_name :
template_name = os . path . join (... |
def get_most_specific_tinfo_dcnt ( goids , go2nt ) :
"""Get the GO ID with the highest GO term annotation information value .""" | # go2nt _ usr = { go : go2nt [ go ] for go in goids }
# return max ( go2nt _ usr . items ( ) , key = lambda t : [ t [ 1 ] . tinfo , t [ 1 ] . dcnt ] ) [ 0]
return max ( _get_go2nt ( goids , go2nt ) , key = lambda t : [ t [ 1 ] . tinfo , t [ 1 ] . dcnt ] ) [ 0 ] |
def fetch_state_data ( self , states ) :
"""Fetch census estimates from table .""" | print ( "Fetching census data" )
for table in CensusTable . objects . all ( ) :
api = self . get_series ( table . series )
for variable in table . variables . all ( ) :
estimate = "{}_{}" . format ( table . code , variable . code )
print ( ">> Fetching {} {} {}" . format ( table . year , table .... |
def collect ( self , top , sup , argv = None , parent = "" ) :
"""means this element is part of a larger object , hence a property of
that object""" | try :
argv_copy = sd_copy ( argv )
return [ self . repr ( top , sup , argv_copy , parent = parent ) ] , [ ]
except AttributeError as exc :
print ( "#!!!!" , exc )
return [ ] , [ ] |
def is_palatal ( c , lang ) :
"""Is the character a palatal""" | o = get_offset ( c , lang )
return ( o >= PALATAL_RANGE [ 0 ] and o <= PALATAL_RANGE [ 1 ] ) |
def has_entry ( self , name ) : # type : ( str ) - > bool
'''An internal method to tell if we have already parsed an entry of the
named type .
Parameters :
name - The name of the entry to check .
Returns :
True if we have already parsed an entry of the named type , False otherwise .''' | return getattr ( self . dr_entries , name ) or getattr ( self . ce_entries , name ) |
def interrupt_kernel ( self ) :
"""Interrupt kernel of current client .""" | client = self . get_current_client ( )
if client is not None :
self . switch_to_plugin ( )
client . stop_button_click_handler ( ) |
def value ( self , n = 0 ) :
"""Returns the value or values measured by the sensor . Check num _ values to
see how many values there are . Values with N > = num _ values will return
an error . The values are fixed point numbers , so check decimals to see
if you need to divide to get the actual value .""" | n = int ( n )
self . _value [ n ] , value = self . get_attr_int ( self . _value [ n ] , 'value' + str ( n ) )
return value |
def model_code_key_prefix ( code_location_key_prefix , model_name , image ) :
"""Returns the s3 key prefix for uploading code during model deployment
The location returned is a potential concatenation of 2 parts
1 . code _ location _ key _ prefix if it exists
2 . model _ name or a name derived from the image ... | training_job_name = sagemaker . utils . name_from_image ( image )
return '/' . join ( filter ( None , [ code_location_key_prefix , model_name or training_job_name ] ) ) |
def arange ( start , stop = None , step = 1.0 , repeat = 1 , infer_range = False , name = None , dtype = None ) :
"""Returns evenly spaced values within a given interval .
Values are generated within the half - open interval [ ` start ` , ` stop ` ) . In other
words , the interval includes ` start ` but exclude... | if dtype is None :
dtype = _numpy . float32
return _internal . _arange ( start = start , stop = stop , step = step , repeat = repeat , infer_range = infer_range , name = name , dtype = dtype ) |
def drop_database ( self , name_or_database ) :
"""Drop a database .
Raises : class : ` TypeError ` if ` name _ or _ database ` is not an instance of
: class : ` basestring ` ( : class : ` str ` in python 3 ) or
: class : ` ~ pymongo . database . Database ` .
: Parameters :
- ` name _ or _ database ` : th... | name = name_or_database
if isinstance ( name , database . Database ) :
name = name . name
if not isinstance ( name , string_type ) :
raise TypeError ( "name_or_database must be an instance " "of %s or a Database" % ( string_type . __name__ , ) )
self . _purge_index ( name )
with self . _socket_for_reads ( ReadP... |
def _cutoff ( table , frequency_cutoff ) :
'''Generate new codon frequency table given a mean cutoff .
: param table : codon frequency table of form { amino acid : codon : frequency }
: type table : dict
: param frequency _ cutoff : value between 0 and 1.0 for mean frequency cutoff
: type frequency _ cutoff... | new_table = { }
# IDEA : cutoff should be relative to most - frequent codon , not average ?
for amino_acid , codons in table . iteritems ( ) :
average_cutoff = frequency_cutoff * sum ( codons . values ( ) ) / len ( codons )
new_table [ amino_acid ] = { }
for codon , frequency in codons . iteritems ( ) :
... |
def unregister ( self , fileobj ) :
"""Remove interest in IO events from the specified fileobj
: param fileobj :
Any existing file - like object that has a fileno ( ) method and was
previously registered with : meth : ` register ( ) `
: raises ValueError :
if ` fileobj ` is invalid or not supported
: ra... | fd = _get_fd ( fileobj )
key = self . _fd_map [ fd ]
try :
self . _epoll . unregister ( fd )
except OSError :
pass
del self . _fd_map [ fd ]
return key |
def get_listing_calendar ( self , listing_id , starting_date = datetime . datetime . now ( ) , calendar_months = 6 ) :
"""Get host availability calendar for a given listing""" | params = { '_format' : 'host_calendar_detailed' }
starting_date_str = starting_date . strftime ( "%Y-%m-%d" )
ending_date_str = ( starting_date + datetime . timedelta ( days = 30 ) ) . strftime ( "%Y-%m-%d" )
r = self . _session . get ( API_URL + "/calendars/{}/{}/{}" . format ( str ( listing_id ) , starting_date_str ,... |
def main ( args = None ) :
"""Call the CLI interface and wait for the result .""" | retcode = 0
try :
ci = CliInterface ( )
args = ci . parser . parse_args ( )
result = args . func ( args )
if result is not None :
print ( result )
retcode = 0
except Exception :
retcode = 1
traceback . print_exc ( )
sys . exit ( retcode ) |
def get_lists ( client ) :
'''Gets all the client ' s lists''' | response = client . authenticated_request ( client . api . Endpoints . LISTS )
return response . json ( ) |
def get_child_nodes ( docgraph , parent_node_id , data = False ) :
"""Yield all nodes that the given node dominates or spans .""" | return select_neighbors_by_edge_attribute ( docgraph = docgraph , source = parent_node_id , attribute = 'edge_type' , value = [ EdgeTypes . dominance_relation ] , data = data ) |
def covariance_ellipse ( P , deviations = 1 ) :
"""Returns a tuple defining the ellipse representing the 2 dimensional
covariance matrix P .
Parameters
P : nd . array shape ( 2,2)
covariance matrix
deviations : int ( optional , default = 1)
# of standard deviations . Default is 1.
Returns ( angle _ ra... | U , s , _ = linalg . svd ( P )
orientation = math . atan2 ( U [ 1 , 0 ] , U [ 0 , 0 ] )
width = deviations * math . sqrt ( s [ 0 ] )
height = deviations * math . sqrt ( s [ 1 ] )
if height > width :
raise ValueError ( 'width must be greater than height' )
return ( orientation , width , height ) |
def inference ( images , num_classes , for_training = False , restore_logits = True , scope = None ) :
"""Build Inception v3 model architecture .
See here for reference : http : / / arxiv . org / abs / 1512.00567
Args :
images : Images returned from inputs ( ) or distorted _ inputs ( ) .
num _ classes : num... | # Parameters for BatchNorm .
batch_norm_params = { # Decay for the moving averages .
'decay' : BATCHNORM_MOVING_AVERAGE_DECAY , # epsilon to prevent 0s in variance .
'epsilon' : 0.001 , }
# Set weight _ decay for weights in Conv and FC layers .
with slim . arg_scope ( [ slim . ops . conv2d , slim . ops . fc ] , weight_... |
def setItemPolicy ( self , item , policy ) :
"""Sets the policy of the given item""" | index = item . _combobox_indices [ self . ColAction ] . get ( policy , 0 )
self . _updateItemComboBoxIndex ( item , self . ColAction , index )
combobox = self . itemWidget ( item , self . ColAction )
if combobox :
combobox . setCurrentIndex ( index ) |
def classify_dataset ( dataset , fn ) :
"""Classify dataset via fn
Parameters
dataset : list
A list of data
fn : function
A function which recieve : attr : ` data ` and return classification string .
It if is None , a function which return the first item of the
: attr : ` data ` will be used ( See ` `... | if fn is None :
fn = default_classify_function
# classify dataset via classify _ fn
classified_dataset = OrderedDict ( )
for data in dataset :
classify_name = fn ( data )
if classify_name not in classified_dataset :
classified_dataset [ classify_name ] = [ ]
classified_dataset [ classify_name ] ... |
def appendPoint ( self , position = None , type = "line" , smooth = False , name = None , identifier = None , point = None ) :
"""Append a point to the contour .""" | if point is not None :
if position is None :
position = point . position
type = point . type
smooth = point . smooth
if name is None :
name = point . name
if identifier is not None :
identifier = point . identifier
self . insertPoint ( len ( self . points ) , position = posit... |
def add ( self , resource ) :
"""Add a resource change or an iterable collection of them .
Allows multiple resource _ change objects for the same
resource ( ie . URI ) and preserves the order of addition .""" | if isinstance ( resource , collections . Iterable ) :
for r in resource :
self . add_if_changed ( r )
else :
self . add_if_changed ( resource ) |
def perform_proxy ( self , proxy_ticket , headers = None ) :
'''Fetch a response from the remote CAS ` proxy ` endpoint .''' | url = self . _get_proxy_url ( ticket = proxy_ticket )
logging . debug ( '[CAS] Proxy URL: {}' . format ( url ) )
return self . _perform_cas_call ( url , ticket = proxy_ticket , headers = headers , ) |
def convert_from_unicode ( data ) :
"""converts unicode data to a string
: param data : the data to convert
: return :""" | # if isinstance ( data , basestring ) :
if isinstance ( data , str ) :
return str ( data )
elif isinstance ( data , collectionsAbc . Mapping ) :
return dict ( map ( convert_from_unicode , data . items ( ) ) )
elif isinstance ( data , collectionsAbc . Iterable ) :
return type ( data ) ( map ( convert_from_un... |
def gen_version ( do_write = True , txt = None ) :
"""Generate a version based on git tag info . This will write the
couchbase / _ version . py file . If not inside a git tree it will
raise a CantInvokeGit exception - which is normal
( and squashed by setup . py ) if we are running from a tarball""" | if txt is None :
txt = get_git_describe ( )
try :
info = VersionInfo ( txt )
vstr = info . package_version
except MalformedGitTag :
warnings . warn ( "Malformed input '{0}'" . format ( txt ) )
vstr = '0.0.0' + txt
if not do_write :
print ( vstr )
return
lines = ( '# This file automatically g... |
def scan ( self , data , dlen = None ) :
'''Scan a data block for matching signatures .
@ data - A string of data to scan .
@ dlen - If specified , signatures at offsets larger than dlen will be ignored .
Returns a list of SignatureResult objects .''' | results = [ ]
matched_offsets = set ( )
# Since data can potentially be quite a large string , make it available to other
# methods via a class attribute so that it doesn ' t need to be passed around to
# different methods over and over again .
self . data = data
# If dlen wasn ' t specified , search all of self . data... |
def click_button ( self , index_or_name ) :
"""Click button""" | _platform_class_dict = { 'ios' : 'UIAButton' , 'android' : 'android.widget.Button' }
if self . _is_support_platform ( _platform_class_dict ) :
class_name = self . _get_class ( _platform_class_dict )
self . _click_element_by_class_name ( class_name , index_or_name ) |
def download_archive ( self , name , file_path ) :
"""Download archived logs of the OS Volume .
Args :
name : Name of the OS Volume .
file _ path ( str ) : Destination file path .
Returns :
bool : Indicates if the resource was successfully downloaded .""" | uri = self . URI + "/archive/" + name
return self . _client . download ( uri , file_path ) |
def _shuffle_tfrecord ( path , random_gen ) :
"""Shuffle a single record file in memory .""" | # Read all records
record_iter = tf . compat . v1 . io . tf_record_iterator ( path )
all_records = [ r for r in utils . tqdm ( record_iter , desc = "Reading..." , unit = " examples" , leave = False ) ]
# Shuffling in memory
random_gen . shuffle ( all_records )
# Write all record back
with tf . io . TFRecordWriter ( pat... |
def validipaddr ( address ) :
"""Returns True if ` address ` is a valid IPv4 address .
> > > validipaddr ( ' 192.168.1.1 ' )
True
> > > validipaddr ( ' 192.168.1.800 ' )
False
> > > validipaddr ( ' 192.168.1 ' )
False""" | try :
octets = address . split ( '.' )
if len ( octets ) != 4 :
return False
for x in octets :
if not ( 0 <= int ( x ) <= 255 ) :
return False
except ValueError :
return False
return True |
def waitForEvent ( self , event_name , predicate , timeout = DEFAULT_TIMEOUT ) :
"""Wait for an event of a specific name that satisfies the predicate .
This call will block until the expected event has been received or time
out .
The predicate function defines the condition the event is expected to
satisfy ... | deadline = time . time ( ) + timeout
while time . time ( ) <= deadline : # Calculate the max timeout for the next event rpc call .
rpc_timeout = deadline - time . time ( )
if rpc_timeout < 0 :
break
# A single RPC call cannot exceed MAX _ TIMEOUT .
rpc_timeout = min ( rpc_timeout , MAX_TIMEOUT )... |
def writes ( self , nb , metadata = None , ** kwargs ) :
"""Return the text representation of the notebook""" | if self . fmt . get ( 'format_name' ) == 'pandoc' :
metadata = insert_jupytext_info_and_filter_metadata ( metadata , self . ext , self . implementation )
cells = [ ]
for cell in nb . cells :
cell_metadata = filter_metadata ( copy ( cell . metadata ) , self . fmt . get ( 'cell_metadata_filter' ) , _I... |
def frequency_bins ( header ) :
'''Returnes the frequency - axis lower bin edge values for the spectrogram .''' | center_frequency = 1.0e6 * header [ 'rf_center_frequency' ]
if header [ "number_of_subbands" ] > 1 :
center_frequency += header [ "subband_spacing_hz" ] * ( header [ "number_of_subbands" ] / 2.0 - 0.5 )
return np . fft . fftshift ( np . fft . fftfreq ( int ( header [ "number_of_subbands" ] * constants . bins_per_ha... |
def parse_memory ( s ) :
"""Converts bytes expression to number of mebibytes .
If no unit is specified , ` ` MiB ` ` is used .""" | if isinstance ( s , integer ) :
out = s
elif isinstance ( s , float ) :
out = math_ceil ( s )
elif isinstance ( s , string ) :
s = s . replace ( ' ' , '' )
if not s :
raise context . ValueError ( "Could not interpret %r as a byte unit" % s )
if s [ 0 ] . isdigit ( ) :
for i , c in en... |
def get_post_replies ( self , * args , ** kwargs ) :
"""Return a get _ content generator for inboxed submission replies .
The additional parameters are passed directly into
: meth : ` . get _ content ` . Note : the ` url ` parameter cannot be altered .""" | return self . get_content ( self . config [ 'post_replies' ] , * args , ** kwargs ) |
def format_camel_case ( text ) :
"""Example : :
ThisIsVeryGood
* * 中文文档 * *
将文本格式化为各单词首字母大写 , 拼接而成的长变量名 。""" | text = text . strip ( )
if len ( text ) == 0 : # if empty string , return it
raise ValueError ( "can not be empty string!" )
else :
text = text . lower ( )
# lower all char
# delete redundant empty space
words = list ( )
word = list ( )
for char in text :
if char in ALPHA_DIGITS :
... |
def draw_rect ( grid , attr , dc , rect ) :
"""Draws a rect""" | dc . SetBrush ( wx . Brush ( wx . Colour ( 15 , 255 , 127 ) , wx . SOLID ) )
dc . SetPen ( wx . Pen ( wx . BLUE , 1 , wx . SOLID ) )
dc . DrawRectangleRect ( rect ) |
def command_insert ( prog_name , prof_mgr , prof_name , prog_args ) :
"""Insert components .""" | # Retrieve arguments
parser = argparse . ArgumentParser ( prog = prog_name )
parser . add_argument ( "components" , metavar = "comps" , nargs = argparse . REMAINDER , help = "system components" )
args = parser . parse_args ( prog_args )
# Profile load
prof_stub = prof_mgr . load ( prof_name )
# Collect component stubs
... |
def DecompressionFile ( src_fp , algorithm ) :
"""This looks like a class to users , but is actually a function that instantiates a class based on algorithm .""" | if algorithm == "lzma" :
return lzma . open ( src_fp , "r" )
if algorithm == "snappy" :
return SnappyFile ( src_fp , "rb" )
if algorithm :
raise InvalidConfigurationError ( "invalid compression algorithm: {!r}" . format ( algorithm ) )
return src_fp |
async def get_initial_offset_async ( self ) : # throws InterruptedException , ExecutionException
"""Gets the initial offset for processing the partition .
: rtype : str""" | _logger . info ( "Calling user-provided initial offset provider %r %r" , self . host . guid , self . partition_id )
starting_checkpoint = await self . host . storage_manager . get_checkpoint_async ( self . partition_id )
if not starting_checkpoint : # No checkpoint was ever stored . Use the initialOffsetProvider instea... |
def html ( self ) :
'''Get full page HTML .
. . warning : : This can get pretty slow on long pages .''' | if not getattr ( self , '_html' , False ) :
query_params = { 'prop' : 'revisions' , 'rvprop' : 'content' , 'rvlimit' : 1 , 'rvparse' : '' , 'titles' : self . title }
request = _wiki_request ( query_params )
self . _html = request [ 'query' ] [ 'pages' ] [ self . pageid ] [ 'revisions' ] [ 0 ] [ '*' ]
return... |
def matches_rule ( message , rule , destinations = None ) :
"does Message message match against the specified rule ." | if not isinstance ( message , Message ) :
raise TypeError ( "message must be a Message" )
# end if
rule = unformat_rule ( rule )
eavesdrop = rule . get ( "eavesdrop" , "false" ) == "true"
def match_message_type ( expect , actual ) :
return actual == Message . type_from_string ( expect )
# end match _ message _ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.