signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _with_columns ( self , columns ) :
"""Create a table from a sequence of columns , copying column labels .""" | table = type ( self ) ( )
for label , column in zip ( self . labels , columns ) :
self . _add_column_and_format ( table , label , column )
return table |
def cmd_alt ( self , args ) :
'''show altitude''' | print ( "Altitude: %.1f" % self . status . altitude )
qnh_pressure = self . get_mav_param ( 'AFS_QNH_PRESSURE' , None )
if qnh_pressure is not None and qnh_pressure > 0 :
ground_temp = self . get_mav_param ( 'GND_TEMP' , 21 )
pressure = self . master . field ( 'SCALED_PRESSURE' , 'press_abs' , 0 )
qnh_alt ... |
def add_space ( self , line ) :
"""Add a Space object to the section
Used during initial parsing mainly
Args :
line ( str ) : one line that defines the space , maybe whitespaces""" | if not isinstance ( self . last_item , Space ) :
space = Space ( self . _structure )
self . _structure . append ( space )
self . last_item . add_line ( line )
return self |
def get_hdrs ( flds_all , ** kws ) :
"""Return headers , given user - specified key - word args .""" | # Return Headers if the user explicitly lists them .
hdrs = kws . get ( 'hdrs' , None )
if hdrs is not None :
return hdrs
# User may specify a subset of fields or a column order using prt _ flds
if 'prt_flds' in kws :
return kws [ 'prt_flds' ]
# All fields in the namedtuple will be in the headers
return flds_al... |
def substr ( self , name , start = None , size = None ) :
"""Return a substring of the string at key ` ` name ` ` . ` ` start ` ` and ` ` size ` `
are 0 - based integers specifying the portion of the string to return .
Like * * Redis . SUBSTR * *
: param string name : the key name
: param int start : Option... | if start is not None and size is not None :
start = get_integer ( 'start' , start )
size = get_integer ( 'size' , size )
return self . execute_command ( 'substr' , name , start , size )
elif start is not None :
start = get_integer ( 'start' , start )
return self . execute_command ( 'substr' , name ,... |
def ad_address ( mode , hit_id ) :
"""Get the address of the ad on AWS .
This is used at the end of the experiment to send participants
back to AWS where they can complete and submit the HIT .""" | if mode == "debug" :
address = '/complete'
elif mode in [ "sandbox" , "live" ] :
username = os . getenv ( 'psiturk_access_key_id' , config . get ( "psiTurk Access" , "psiturk_access_key_id" ) )
password = os . getenv ( 'psiturk_secret_access_id' , config . get ( "psiTurk Access" , "psiturk_secret_access_id"... |
def force_bytes ( s , encoding = 'utf-8' , strings_only = False , errors = 'strict' ) :
"""Similar to smart _ bytes , except that lazy instances are resolved to
strings , rather than kept as lazy objects .
If strings _ only is True , don ' t convert ( some ) non - string - like objects .""" | if isinstance ( s , memoryview ) :
s = bytes ( s )
if isinstance ( s , bytes ) :
if encoding == 'utf-8' :
return s
else :
return s . decode ( 'utf-8' , errors ) . encode ( encoding , errors )
if strings_only and ( s is None or isinstance ( s , int ) ) :
return s
if not isinstance ( s , s... |
def from_robot ( cls , robot , ** kwargs ) :
"""Construct a Nearest Neighbor forward model from an existing dataset .""" | m = cls ( len ( robot . m_feats ) , len ( robot . s_feats ) , ** kwargs )
return m |
def features ( self ) :
"""list : Get the features stored in memory or in the GFF file""" | if self . feature_file :
log . debug ( '{}: reading features from feature file {}' . format ( self . id , self . feature_path ) )
with open ( self . feature_path ) as handle :
feats = list ( GFF . parse ( handle ) )
if len ( feats ) > 1 :
log . warning ( 'Too many sequences in GFF' )... |
def pfull_from_ps ( bk , pk , ps , pfull_coord ) :
"""Compute pressure at full levels from surface pressure .""" | return to_pfull_from_phalf ( phalf_from_ps ( bk , pk , ps ) , pfull_coord ) |
def attached_pane ( self ) :
"""Return the attached : class : ` Pane ` .
Returns
: class : ` Pane `""" | for pane in self . _panes :
if 'pane_active' in pane : # for now pane _ active is a unicode
if pane . get ( 'pane_active' ) == '1' :
return Pane ( window = self , ** pane )
else :
continue
return [ ] |
def _unquote_cookie ( s : str ) -> str :
"""Handle double quotes and escaping in cookie values .
This method is copied verbatim from the Python 3.5 standard
library ( http . cookies . _ unquote ) so we don ' t have to depend on
non - public interfaces .""" | # If there aren ' t any doublequotes ,
# then there can ' t be any special characters . See RFC 2109.
if s is None or len ( s ) < 2 :
return s
if s [ 0 ] != '"' or s [ - 1 ] != '"' :
return s
# We have to assume that we must decode this string .
# Down to work .
# Remove the " s
s = s [ 1 : - 1 ]
# Check for sp... |
def template_exists_db ( self , template ) :
"""Receives a template and checks if it exists in the database
using the template name and language""" | name = utils . camel_to_snake ( template [ 0 ] ) . upper ( )
language = utils . camel_to_snake ( template [ 3 ] )
try :
models . EmailTemplate . objects . get ( name = name , language = language )
except models . EmailTemplate . DoesNotExist :
return False
return True |
def run_command ( self , config_file ) :
""": param str config _ file : The name of config file .""" | config = configparser . ConfigParser ( )
config . read ( config_file )
rdbms = config . get ( 'database' , 'rdbms' ) . lower ( )
label_regex = config . get ( 'constants' , 'label_regex' )
constants = self . create_constants ( rdbms )
constants . main ( config_file , label_regex ) |
def _Backward3_T_Ps ( P , s ) :
"""Backward equation for region 3 , T = f ( P , s )
Parameters
P : float
Pressure , [ MPa ]
s : float
Specific entropy , [ kJ / kgK ]
Returns
T : float
Temperature , [ K ]""" | sc = 4.41202148223476
if s <= sc :
T = _Backward3a_T_Ps ( P , s )
else :
T = _Backward3b_T_Ps ( P , s )
return T |
def parse ( cls , fptr , offset , length ) :
"""Parse XML box .
Parameters
fptr : file
Open file object .
offset : int
Start position of box in bytes .
length : int
Length of the box in bytes .
Returns
XMLBox
Instance of the current XML box .""" | num_bytes = offset + length - fptr . tell ( )
read_buffer = fptr . read ( num_bytes )
if sys . hexversion < 0x03000000 and codecs . BOM_UTF8 in read_buffer : # Python3 with utf - 8 handles this just fine . Actually so does
# Python2 right here since we decode using utf - 8 . The real
# problem comes when _ _ str _ _ is... |
def _is_non_string_iterable ( value ) :
"""Whether a value is iterable .""" | if isinstance ( value , str ) :
return False
if hasattr ( value , '__iter__' ) :
return True
if isinstance ( value , collections . abc . Sequence ) :
return True
return False |
def mean ( self ) -> Optional [ float ] :
"""Statistical mean of all values entered into histogram .
This number is precise , because we keep the necessary data
separate from bin contents .""" | if self . _stats : # TODO : should be true always ?
if self . total > 0 :
return self . _stats [ "sum" ] / self . total
else :
return np . nan
else :
return None |
def strip_prompt ( self , a_string ) :
"""Strip ' Done ' from command output""" | output = super ( NetscalerSSH , self ) . strip_prompt ( a_string )
lines = output . split ( self . RESPONSE_RETURN )
if "Done" in lines [ - 1 ] :
return self . RESPONSE_RETURN . join ( lines [ : - 1 ] )
else :
return output |
def parse_inline_styles ( self , data = None , import_type = 'string' ) :
"""Function for parsing styles defined in the body of the document .
This only includes data inside of HTML < style > tags , a URL , or file to open .""" | if data is None :
raise
parser = cssutils . CSSParser ( )
if import_type == 'string' : # print " importing string with url = % s " % self . url _ root
sheet = parser . parseString ( data , href = self . url_root )
elif import_type == 'url' :
if data [ : 5 ] . lower ( ) == 'http:' or data [ : 6 ] . lower ( )... |
def pixel ( self , coord_x , coord_y ) : # type : ( int , int ) - > Pixel
"""Returns the pixel value at a given position .
: param int coord _ x : The x coordinate .
: param int coord _ y : The y coordinate .
: return tuple : The pixel value as ( R , G , B ) .""" | try :
return self . pixels [ coord_y ] [ coord_x ]
# type : ignore
except IndexError :
raise ScreenShotError ( "Pixel location ({}, {}) is out of range." . format ( coord_x , coord_y ) ) |
def overlap ( self , query , subject ) :
"""Accessory function to check if two ranges overlap""" | if ( self . pt_within ( query [ 0 ] , subject ) or self . pt_within ( query [ 1 ] , subject ) or self . pt_within ( subject [ 0 ] , query ) or self . pt_within ( subject [ 1 ] , query ) ) :
return True
return False |
def merge ( self , other , forceMerge = False ) :
"""Merge two reads by concatenating their sequence data and their
quality data ( < self > first , then < other > ) ; < self > and < other > must have
the same sequence name . A new merged FastqSequence object is returned ;
< Self > and < other > are left unalt... | if self . sequenceName != other . sequenceName and not forceMerge :
raise NGSReadError ( "cannot merge " + self . sequenceName + " with " + other . sequenceName + " -- different " + "sequence names" )
name = self . sequenceName
seq = self . sequenceData + other . sequenceData
qual = self . sequenceQual + other . se... |
def mask_distance ( image , voxelspacing = None , mask = slice ( None ) ) :
r"""Computes the distance of each point under the mask to the mask border taking the
voxel - spacing into account .
Note that this feature is independent of the actual image content , but depends
solely the mask image . Therefore alwa... | if type ( image ) == tuple or type ( image ) == list :
image = image [ 0 ]
return _extract_mask_distance ( image , mask = mask , voxelspacing = voxelspacing ) |
def insert ( self , schema , fields , ** kwargs ) :
"""Persist d into the db
schema - - Schema ( )
fields - - dict - - the values to persist
return - - int - - the primary key of the row just inserted""" | r = 0
with self . connection ( ** kwargs ) as connection :
kwargs [ 'connection' ] = connection
try :
with self . transaction ( ** kwargs ) :
r = self . _insert ( schema , fields , ** kwargs )
except Exception as e :
exc_info = sys . exc_info ( )
if self . handle_error ( ... |
def set_trafo_costs ( network , args , cost110_220 = 7500 , cost110_380 = 17333 , cost220_380 = 14166 ) :
"""Set capital costs for extendable transformers in respect
to PyPSA [ € / MVA ]
Parameters
network : : class : ` pypsa . Network
Overall container of PyPSA
cost110_220 : capital costs for 110/220kV t... | network . transformers [ "v_nom0" ] = network . transformers . bus0 . map ( network . buses . v_nom )
network . transformers [ "v_nom1" ] = network . transformers . bus1 . map ( network . buses . v_nom )
network . transformers . loc [ ( network . transformers . v_nom0 == 110 ) & ( network . transformers . v_nom1 == 220... |
def listFileParentsByLumi ( self , block_name = '' , logical_file_name = [ ] ) :
"""required parameter : block _ name
returns : [ { child _ parent _ id _ list : [ ( cid1 , pid1 ) , ( cid2 , pid2 ) , . . . ( cidn , pidn ) ] } ]""" | # self . logger . debug ( " lfn % s , block _ name % s " % ( logical _ file _ name , block _ name ) )
if not block_name :
dbsExceptionHandler ( 'dbsException-invalid-input' , "Child block_name is required for fileparents/listFileParentsByLumi api" , self . logger . exception )
with self . dbi . connection ( ) as co... |
def set ( self , data = None ) :
"""Sets the event""" | self . __data = data
self . __exception = None
self . __event . set ( ) |
def add_edge ( self , source , target , interaction = '-' , directed = True , dataframe = True ) :
"""Add a single edge from source to target .""" | new_edge = { 'source' : source , 'target' : target , 'interaction' : interaction , 'directed' : directed }
return self . add_edges ( [ new_edge ] , dataframe = dataframe ) |
async def process_feed ( self , url , send_mentions = True ) :
"""process a feed""" | self . _feed_domains . add ( utils . get_domain ( url ) )
if url in self . _processed_feeds :
LOGGER . debug ( "Skipping already processed feed %s" , url )
return
self . _processed_feeds . add ( url )
LOGGER . debug ( "++WAIT: %s: get feed" , url )
feed , previous , updated = await feeds . get_feed ( self , url... |
def stdev ( self ) :
"""- > # float : func : numpy . std of the timing intervals""" | return round ( np . std ( self . array ) , self . precision ) if len ( self . array ) else None |
def get ( self , section_name , key_name , ) :
"""Replicate configparser . get ( ) functionality
Args :
section _ name ( str ) : section name in config
key _ name ( str ) : key name in config . section _ name
Returns :
str : do not check defaults , only return local value
Raises :
KeyError : unable to... | value = None
try :
value = self . local_config . get ( section_name , key_name )
except Exception as error_msg :
self . logger . warning ( '%s.%s not found in local config' , section_name , key_name )
try :
value = self . global_config . get ( section_name , key_name )
except Exception as error_... |
def verify ( password , encoded ) :
"""Verify a Password
: param password :
: param encoded :
: return : True or False""" | algorithm , iterations , salt , h = split ( encoded )
to_verify = encode ( password , algorithm , salt , int ( iterations ) )
return hmac . compare_digest ( to_verify . encode ( ) , encoded . encode ( ) ) |
def validate_attr ( self , append ) :
"""validate that we have the same order as the existing & same dtype""" | if append :
existing_fields = getattr ( self . attrs , self . kind_attr , None )
if ( existing_fields is not None and existing_fields != list ( self . values ) ) :
raise ValueError ( "appended items do not match existing items" " in table!" )
existing_dtype = getattr ( self . attrs , self . dtype_at... |
def chrome_setup_view ( request ) :
"""Set up a browser - side GCM session .
This * requires * a valid login session . A " token " POST parameter is saved under the " gcm _ token "
parameter in the logged in user ' s NotificationConfig .""" | logger . debug ( request . POST )
token = None
if request . method == "POST" :
if "token" in request . POST :
token = request . POST . get ( "token" )
if not token :
return HttpResponse ( '{"error":"Invalid data."}' , content_type = "text/json" )
ncfg , _ = NotificationConfig . objects . get_or_create (... |
def step1 ( expnum , ccd , prefix = '' , version = 'p' , sex_thresh = _SEX_THRESHOLD , wave_thresh = _WAVE_THRESHOLD , maxcount = _MAX_COUNT , dry_run = False ) :
"""run the actual step1jmp / matt codes .
expnum : the CFHT expousre to process
ccd : which ccd in the mosaic to process
fwhm : the image quality ,... | storage . get_file ( expnum , ccd , prefix = prefix , version = version , ext = 'mopheader' )
filename = storage . get_image ( expnum , ccd , version = version , prefix = prefix )
fwhm = storage . get_fwhm ( expnum , ccd , prefix = prefix , version = version )
basename = os . path . splitext ( filename ) [ 0 ]
logging ... |
def get_corresponding_lineno ( self , lineno ) :
"""Return the source line number of a line number in the
generated bytecode as they are not in sync .""" | for template_line , code_line in reversed ( self . debug_info ) :
if code_line <= lineno :
return template_line
return 1 |
def get_all_tasks ( self , course ) :
""": return : a table containing taskid = > Task pairs""" | tasks = self . get_readable_tasks ( course )
output = { }
for task in tasks :
try :
output [ task ] = self . get_task ( course , task )
except :
pass
return output |
def _prefix_from_prefix_string ( cls , prefixlen_str ) :
"""Return prefix length from a numeric string
Args :
prefixlen _ str : The string to be converted
Returns :
An integer , the prefix length .
Raises :
NetmaskValueError : If the input is not a valid netmask""" | # int allows a leading + / - as well as surrounding whitespace ,
# so we ensure that isn ' t the case
if not _BaseV4 . _DECIMAL_DIGITS . issuperset ( prefixlen_str ) :
cls . _report_invalid_netmask ( prefixlen_str )
try :
prefixlen = int ( prefixlen_str )
except ValueError :
cls . _report_invalid_netmask ( ... |
def _watch ( self ) :
"""Start an asynchronous watch against this model .
See : meth : ` add _ observer ` to register an onchange callback .""" | async def _all_watcher ( ) :
try :
allwatcher = client . AllWatcherFacade . from_connection ( self . connection ( ) )
while not self . _watch_stopping . is_set ( ) :
try :
results = await utils . run_with_interrupt ( allwatcher . Next ( ) , self . _watch_stopping , loop =... |
def replace ( needle , with_ = None , in_ = None ) :
"""Replace occurrences of string ( s ) with other string ( s ) in ( a ) string ( s ) .
Unlike the built in : meth : ` str . replace ` method , this function provides
clean API that clearly distinguishes the " needle " ( string to replace ) ,
the replacement... | if needle is None :
raise TypeError ( "replacement needle cannot be None" )
if not needle :
raise ValueError ( "replacement needle cannot be empty" )
if is_string ( needle ) :
replacer = Replacer ( ( needle , ) )
else :
ensure_iterable ( needle )
if not is_mapping ( needle ) :
if all ( imap ... |
def do_connect ( self , arg ) :
'''Connect to the arm .''' | if self . arm . is_connected ( ) :
print ( self . style . error ( 'Error: ' , 'Arm is already connected.' ) )
else :
try :
port = self . arm . connect ( )
print ( self . style . success ( 'Success: ' , 'Connected to \'{}\'.' . format ( port ) ) )
except r12 . ArmException as e :
prin... |
def _extract_readnum ( read_dict ) :
"""Extract read numbers from old - style fastqs .
Handles read 1 and 2 specifications where naming is
readname / 1 readname / 2""" | pat = re . compile ( r"(?P<readnum>/\d+)$" )
parts = pat . split ( read_dict [ "name" ] )
if len ( parts ) == 3 :
name , readnum , endofline = parts
read_dict [ "name" ] = name
read_dict [ "readnum" ] = readnum
else :
read_dict [ "readnum" ] = ""
return read_dict |
def set_device_offset ( self , x_offset , y_offset ) :
"""Sets an offset that is added to the device coordinates
determined by the CTM when drawing to surface .
One use case for this method is
when we want to create a : class : ` Surface ` that redirects drawing
for a portion of an onscreen surface
to an ... | cairo . cairo_surface_set_device_offset ( self . _pointer , x_offset , y_offset )
self . _check_status ( ) |
def close_authenticator ( self ) :
"""Close the CBS auth channel and session .""" | _logger . info ( "Shutting down CBS session on connection: %r." , self . _connection . container_id )
try :
_logger . debug ( "Unlocked CBS to close on connection: %r." , self . _connection . container_id )
self . _cbs_auth . destroy ( )
_logger . info ( "Auth closed, destroying session on connection: %r." ... |
def setup_datafind_from_pregenerated_lcf_files ( cp , ifos , outputDir , tags = None ) :
"""This function is used if you want to run with pregenerated lcf frame
cache files .
Parameters
cp : ConfigParser . ConfigParser instance
This contains a representation of the information stored within the
workflow c... | if tags is None :
tags = [ ]
datafindcaches = [ ]
for ifo in ifos :
search_string = "datafind-pregenerated-cache-file-%s" % ( ifo . lower ( ) , )
frame_cache_file_name = cp . get_opt_tags ( "workflow-datafind" , search_string , tags = tags )
curr_cache = lal . Cache . fromfilenames ( [ frame_cache_file_... |
def transformWith ( self , func , other , keepSerializer = False ) :
"""Return a new DStream in which each RDD is generated by applying a function
on each RDD of this DStream and ' other ' DStream .
` func ` can have two arguments of ( ` rdd _ a ` , ` rdd _ b ` ) or have three
arguments of ( ` time ` , ` rdd ... | if func . __code__ . co_argcount == 2 :
oldfunc = func
func = lambda t , a , b : oldfunc ( a , b )
assert func . __code__ . co_argcount == 3 , "func should take two or three arguments"
jfunc = TransformFunction ( self . _sc , func , self . _jrdd_deserializer , other . _jrdd_deserializer )
dstream = self . _sc .... |
def overall_statistics ( RACC , RACCU , TPR , PPV , TP , FN , FP , POP , P , TOP , jaccard_list , CEN_dict , MCEN_dict , AUC_dict , classes , table ) :
"""Return overall statistics .
: param RACC : random accuracy
: type RACC : dict
: param TPR : sensitivity , recall , hit rate , or true positive rate
: typ... | population = list ( POP . values ( ) ) [ 0 ]
overall_accuracy = overall_accuracy_calc ( TP , population )
overall_random_accuracy_unbiased = overall_random_accuracy_calc ( RACCU )
overall_random_accuracy = overall_random_accuracy_calc ( RACC )
overall_kappa = reliability_calc ( overall_random_accuracy , overall_accurac... |
def arguments ( function , extra_arguments = 0 ) :
"""Returns the name of all arguments a function takes""" | if not hasattr ( function , '__code__' ) :
return ( )
return function . __code__ . co_varnames [ : function . __code__ . co_argcount + extra_arguments ] |
def rm_pawn ( self , name , * args ) :
"""Remove the : class : ` Pawn ` by the given name .""" | if name not in self . pawn :
raise KeyError ( "No Pawn named {}" . format ( name ) )
# Currently there ' s no way to connect Pawns with Arrows but I
# think there will be , so , insurance
self . rm_arrows_to_and_from ( name )
pwn = self . pawn . pop ( name )
if pwn in self . selection_candidates :
self . select... |
def get_parse ( self , show = True , proxy = None , timeout = 0 ) :
"""GET MediaWiki : API action = parse request
https : / / en . wikipedia . org / w / api . php ? action = help & modules = parse
Required { params } : title OR pageid
- title : < str > article title
- pageid : < int > Wikipedia database ID ... | if not self . params . get ( 'title' ) and not self . params . get ( 'pageid' ) :
raise ValueError ( "get_parse needs title or pageid" )
self . _get ( 'parse' , show , proxy , timeout )
return self |
def create ( self , argv ) :
"""Create a search job .""" | opts = cmdline ( argv , FLAGS_CREATE )
if len ( opts . args ) != 1 :
error ( "Command requires a search expression" , 2 )
query = opts . args [ 0 ]
job = self . service . jobs . create ( opts . args [ 0 ] , ** opts . kwargs )
print ( job . sid ) |
def build ( self ) :
"""The decoder computational graph consists of three components :
(1 ) the input node ` decoder _ input `
(2 ) the embedding node ` decoder _ embed `
(3 ) the recurrent ( RNN ) part ` decoder _ rnn `
(4 ) the output of the decoder RNN ` decoder _ output `
(5 ) the classification outpu... | # Grab hyperparameters from self . config :
hidden_dim = self . config [ 'encoding-layer-width' ]
recurrent_unit = self . config [ 'recurrent-unit-type' ]
bidirectional = False
# self . config [ ' encoding - layer - bidirectional ' ]
vocab_size = self . data . properties . vocab_size
embedding_dim = math . ceil ( math ... |
def wrap ( self , req , result ) :
"""Wrap method return results . The return value of the action
method and of the action extensions is passed through this
method before being returned to the caller . Instances of
` webob . Response ` are thrown , to abort the rest of action and
extension processing ; othe... | if isinstance ( result , webob . exc . HTTPException ) : # It ' s a webob HTTP exception ; use raise to bail out
# immediately and pass it upstream
raise result
elif isinstance ( result , webob . Response ) : # Straight - up webob Response object ; we raise
# AppathyResponse to bail out
raise exceptions . Appat... |
def app_main ( self , experiment = None , last = False , new = False , verbose = False , verbosity_level = None , no_modification = False , match = False ) :
"""The main function for parsing global arguments
Parameters
experiment : str
The id of the experiment to use
last : bool
If True , the last experim... | if match :
patt = re . compile ( experiment )
matches = list ( filter ( patt . search , self . config . experiments ) )
if len ( matches ) > 1 :
raise ValueError ( "Found multiple matches for %s: %s" % ( experiment , matches ) )
elif len ( matches ) == 0 :
raise ValueError ( "No experime... |
def setattr ( self , name , val ) :
"""Change the attribute value of the UI element . Not all attributes can be casted to text . If changing the
immutable attributes or attributes which do not exist , the InvalidOperationException exception is raised .
Args :
name : attribute name
val : new attribute value ... | nodes = self . _do_query ( multiple = False )
try :
return self . poco . agent . hierarchy . setAttr ( nodes , name , val )
except UnableToSetAttributeException as e :
raise InvalidOperationException ( '"{}" of "{}"' . format ( str ( e ) , self ) ) |
def _set_redistribute_ospf ( self , v , load = False ) :
"""Setter method for redistribute _ ospf , mapped from YANG variable / rbridge _ id / ipv6 / router / ospf / redistribute / redistribute _ ospf ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ redistr... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = redistribute_ospf . redistribute_ospf , is_container = 'container' , presence = True , yang_name = "redistribute-ospf" , rest_name = "ospf" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods... |
def push_pos ( self , * args ) :
"""Set my current position , expressed as proportions of the board ' s
width and height , into the ` ` _ x ` ` and ` ` _ y ` ` keys of the
entity in my ` ` proxy ` ` property , such that it will be
recorded in the database .""" | self . proxy [ '_x' ] = self . x / self . board . width
self . proxy [ '_y' ] = self . y / self . board . height |
def AssertIterableType ( iterable , expected_item_type ) :
"""Ensures that given iterable container has certain type .
Args :
iterable : An iterable container to assert the type for .
expected _ item _ type : An expected type of the container items .
Raises :
TypeError : If given container does is not an ... | # We do not consider iterators to be iterables even though Python does . An
# " iterable " should be a type that can be iterated ( that is : an iterator can
# be constructed for them ) . Iterators should not be considered to be iterable
# because it makes no sense to construct an iterator for iterator . The most
# impo... |
def __f2d ( frac_coords , v ) :
"""Converts fractional coordinates to discrete coordinates with respect to
the grid size of v""" | # frac _ coords = frac _ coords % 1
return np . array ( [ int ( frac_coords [ 0 ] * v . shape [ 0 ] ) , int ( frac_coords [ 1 ] * v . shape [ 1 ] ) , int ( frac_coords [ 2 ] * v . shape [ 2 ] ) ] ) |
def register_view ( self , view ) :
"""Called when the View was registered
Can be used e . g . to connect signals . Here , the destroy signal is connected to close the application""" | super ( StateEditorController , self ) . register_view ( view )
view . prepare_the_labels ( )
# the preparation of the labels is done here to take into account plugin hook changes
view [ 'add_input_port_button' ] . connect ( 'clicked' , self . inputs_ctrl . on_add )
view [ 'add_output_port_button' ] . connect ( 'clicke... |
def sinkhorn_lpl1_mm ( a , labels_a , b , M , reg , eta = 0.1 , numItermax = 10 , numInnerItermax = 200 , stopInnerThr = 1e-9 , verbose = False , log = False , to_numpy = True ) :
"""Solve the entropic regularization optimal transport problem with nonconvex
group lasso regularization on GPU
If the input matrix ... | a , labels_a , b , M = utils . to_gpu ( a , labels_a , b , M )
p = 0.5
epsilon = 1e-3
indices_labels = [ ]
labels_a2 = cp . asnumpy ( labels_a )
classes = npp . unique ( labels_a2 )
for c in classes :
idxc , = utils . to_gpu ( npp . where ( labels_a2 == c ) )
indices_labels . append ( idxc )
W = np . zeros ( M ... |
def clip ( self , lower = 0 , upper = 127 ) :
"""Clip the pianorolls of all tracks by the given lower and upper bounds .
Parameters
lower : int or float
The lower bound to clip the pianorolls . Defaults to 0.
upper : int or float
The upper bound to clip the pianorolls . Defaults to 127.""" | for track in self . tracks :
track . clip ( lower , upper ) |
def _get_service_info ( service ) :
'''return details about given connman service''' | service_info = pyconnman . ConnService ( os . path . join ( SERVICE_PATH , service ) )
data = { 'label' : service , 'wireless' : service_info . get_property ( 'Type' ) == 'wifi' , 'connectionid' : six . text_type ( service_info . get_property ( 'Ethernet' ) [ 'Interface' ] ) , 'hwaddr' : six . text_type ( service_info ... |
def on_change_checkout ( self ) :
'''When you change checkin _ date or checkout _ date it will checked it
and update the qty of hotel folio line
@ param self : object pointer''' | configured_addition_hours = 0
fwhouse_id = self . folio_id . warehouse_id
fwc_id = fwhouse_id or fwhouse_id . company_id
if fwc_id :
configured_addition_hours = fwhouse_id . company_id . additional_hours
myduration = 0
if not self . checkin_date :
self . checkin_date = time . strftime ( DEFAULT_SERVER_DATETIME_... |
def _gssa ( self , initial_conditions , t_max ) :
"""This function is inspired from Yoav Ram ' s code available at :
http : / / nbviewer . ipython . org / github / yoavram / ipython - notebooks / blob / master / GSSA . ipynb
: param initial _ conditions : the initial conditions of the system
: param t _ max :... | # set the initial conditions and t0 = 0.
species_over_time = [ np . array ( initial_conditions ) . astype ( "int16" ) ]
t = 0
time_points = [ t ]
while t < t_max and species_over_time [ - 1 ] . sum ( ) > 0 :
last = species_over_time [ - 1 ]
e , dt = self . _draw ( last )
t += dt
species_over_time . appe... |
def write_pdb ( self , path ) :
"""Outputs a PDB file with the current contents of the system""" | if self . master is None and self . positions is None :
raise ValueError ( 'Topology and positions are needed to write output files.' )
with open ( path , 'w' ) as f :
PDBFile . writeFile ( self . topology , self . positions , f ) |
def __create_image ( self , inpt , hashfun ) :
"""Creates the avatar based on the input and
the chosen hash function .""" | if hashfun not in generator . HASHES . keys ( ) :
print ( "Unknown or unsupported hash function. Using default: %s" % self . DEFAULT_HASHFUN )
algo = self . DEFAULT_HASHFUN
else :
algo = hashfun
return generator . generate ( inpt , algo ) |
def _get_os ( self ) :
'''Get operating system summary''' | return { 'name' : self . _grain ( 'os' ) , 'family' : self . _grain ( 'os_family' ) , 'arch' : self . _grain ( 'osarch' ) , 'release' : self . _grain ( 'osrelease' ) , } |
def cake ( return_X_y = True ) :
"""cake dataset
Parameters
return _ X _ y : bool ,
if True , returns a model - ready tuple of data ( X , y )
otherwise , returns a Pandas DataFrame
Returns
model - ready tuple of data ( X , y )
OR
Pandas DataFrame
Notes
X contains the category of recipe used tran... | # y is real
# recommend LinearGAM
cake = pd . read_csv ( PATH + '/cake.csv' , index_col = 0 )
if return_X_y :
X = cake [ [ 'recipe' , 'replicate' , 'temperature' ] ] . values
X [ : , 0 ] = np . unique ( cake . values [ : , 1 ] , return_inverse = True ) [ 1 ]
X [ : , 1 ] -= 1
y = cake [ 'angle' ] . value... |
def transact ( self , transaction = None ) :
"""Customize calling smart contract transaction functions to use ` personal _ sendTransaction `
instead of ` eth _ sendTransaction ` and to estimate gas limit . This function
is largely copied from web3 ContractFunction with important addition .
Note : will fallbac... | if transaction is None :
transact_transaction = { }
else :
transact_transaction = dict ( ** transaction )
if 'data' in transact_transaction :
raise ValueError ( "Cannot set data in transact transaction" )
cf = self . _contract_function
if cf . address is not None :
transact_transaction . setdefault ( 't... |
def file2abspath ( filename , this_file = __file__ ) :
"""generate absolute path for the given file and base dir""" | return os . path . abspath ( os . path . join ( os . path . dirname ( os . path . abspath ( this_file ) ) , filename ) ) |
def _fast_dataset ( variables : 'OrderedDict[Any, Variable]' , coord_variables : Mapping [ Any , Variable ] , ) -> 'Dataset' :
"""Create a dataset as quickly as possible .
Beware : the ` variables ` OrderedDict is modified INPLACE .""" | from . dataset import Dataset
variables . update ( coord_variables )
coord_names = set ( coord_variables )
return Dataset . _from_vars_and_coord_names ( variables , coord_names ) |
def from_signed_raw ( cls : Type [ PeerType ] , raw : str ) -> PeerType :
"""Return a Peer instance from a signed raw format string
: param raw : Signed raw format string
: return :""" | lines = raw . splitlines ( True )
n = 0
version = int ( Peer . parse_field ( "Version" , lines [ n ] ) )
n += 1
Peer . parse_field ( "Type" , lines [ n ] )
n += 1
currency = Peer . parse_field ( "Currency" , lines [ n ] )
n += 1
pubkey = Peer . parse_field ( "Pubkey" , lines [ n ] )
n += 1
block_uid = BlockUID . from_s... |
def _var_bounds ( self ) :
"""Returns bounds on the optimisation variables .""" | x0 = array ( [ ] )
xmin = array ( [ ] )
xmax = array ( [ ] )
for var in self . om . vars :
x0 = r_ [ x0 , var . v0 ]
xmin = r_ [ xmin , var . vl ]
xmax = r_ [ xmax , var . vu ]
return x0 , xmin , xmax |
def increment_extension_daily_stat ( self , publisher_name , extension_name , version , stat_type ) :
"""IncrementExtensionDailyStat .
[ Preview API ] Increments a daily statistic associated with the extension
: param str publisher _ name : Name of the publisher
: param str extension _ name : Name of the exte... | route_values = { }
if publisher_name is not None :
route_values [ 'publisherName' ] = self . _serialize . url ( 'publisher_name' , publisher_name , 'str' )
if extension_name is not None :
route_values [ 'extensionName' ] = self . _serialize . url ( 'extension_name' , extension_name , 'str' )
if version is not N... |
def filter_curriculum ( curriculum , week , weekday = None ) :
"""筛选出指定星期 [ 和指定星期几 ] 的课程
: param curriculum : 课程表数据
: param week : 需要筛选的周数 , 是一个代表周数的正整数
: param weekday : 星期几 , 是一个代表星期的整数 , 1-7 对应周一到周日
: return : 如果 weekday 参数没给出 , 返回的格式与原课表一致 , 但只包括了在指定周数的课程 , 否则返回指定周数和星期几的当天课程""" | if weekday :
c = [ deepcopy ( curriculum [ weekday - 1 ] ) ]
else :
c = deepcopy ( curriculum )
for d in c :
l = len ( d )
for t_idx in range ( l ) :
t = d [ t_idx ]
if t is None :
continue
# 一般同一时间课程不会重复 , 重复时给出警告
t = list ( filter ( lambda k : week in k [ '上... |
def get_local_client ( c_path = os . path . join ( syspaths . CONFIG_DIR , 'master' ) , mopts = None , skip_perm_errors = False , io_loop = None , auto_reconnect = False ) :
'''. . versionadded : : 2014.7.0
Read in the config and return the correct LocalClient object based on
the configured transport
: param ... | if mopts :
opts = mopts
else : # Late import to prevent circular import
import salt . config
opts = salt . config . client_config ( c_path )
# TODO : AIO core is separate from transport
return LocalClient ( mopts = opts , skip_perm_errors = skip_perm_errors , io_loop = io_loop , auto_reconnect = auto_reconn... |
def call ( napalm_device , method , * args , ** kwargs ) :
'''Calls arbitrary methods from the network driver instance .
Please check the readthedocs _ page for the updated list of getters .
. . _ readthedocs : http : / / napalm . readthedocs . org / en / latest / support / index . html # getters - support - ma... | result = False
out = None
opts = napalm_device . get ( '__opts__' , { } )
retry = kwargs . pop ( '__retry' , True )
# retry executing the task ?
force_reconnect = kwargs . get ( 'force_reconnect' , False )
if force_reconnect :
log . debug ( 'Forced reconnection initiated' )
log . debug ( 'The current opts (unde... |
def discover ( timeout = 5 ) :
"""Convenience method to discover UPnP devices on the network . Returns a
list of ` upnp . Device ` instances . Any invalid servers are silently
ignored .""" | devices = { }
for entry in scan ( timeout ) :
if entry . location in devices :
continue
try :
devices [ entry . location ] = Device ( entry . location )
except Exception as exc :
log = _getLogger ( "ssdp" )
log . error ( 'Error \'%s\' for %s' , exc , entry . location )
return... |
def loop_until_closed ( self , suppress_warning = False ) :
'''Execute a blocking loop that runs and executes event callbacks
until the connection is closed ( e . g . by hitting Ctrl - C ) .
While this method can be used to run Bokeh application code " outside "
the Bokeh server , this practice is HIGHLY DISC... | suppress_warning
# shut up flake
from bokeh . util . deprecation import deprecated
deprecated ( "ClientSession.loop_until_closed is deprecated, and will be removed in an eventual 2.0 release. " "Run Bokeh applications directly on a Bokeh server instead. See:\n\n" " https//docs.bokeh.org/en/latest/docs/user_guide/ser... |
def search ( self , song_title , limit = 1 ) :
"""根据歌曲名搜索歌曲
: params : song _ title : 歌曲名
limit : 搜索数量""" | url = "http://music.163.com/api/search/pc"
headers = { 'Cookie' : 'appver=1.5.2' , 'Referer' : 'http://music.163.com' }
payload = { 's' : song_title , 'limit' : limit , 'type' : 1 }
r = requests . post ( url , params = payload , headers = headers )
data = json . loads ( r . text )
if data [ 'code' ] == 200 :
return... |
def create ( self , type , friendly_name = values . unset , certificate = values . unset , private_key = values . unset , sandbox = values . unset , api_key = values . unset , secret = values . unset ) :
"""Create a new CredentialInstance
: param CredentialInstance . PushService type : The Credential type
: par... | data = values . of ( { 'Type' : type , 'FriendlyName' : friendly_name , 'Certificate' : certificate , 'PrivateKey' : private_key , 'Sandbox' : sandbox , 'ApiKey' : api_key , 'Secret' : secret , } )
payload = self . _version . create ( 'POST' , self . _uri , data = data , )
return CredentialInstance ( self . _version , ... |
def get_extents ( self , element , ranges , range_type = 'combined' ) :
"""Make adjustments to plot extents by computing
stacked bar heights , adjusting the bar baseline
and forcing the x - axis to be categorical .""" | if self . batched :
overlay = self . current_frame
element = Bars ( overlay . table ( ) , kdims = element . kdims + overlay . kdims , vdims = element . vdims )
for kd in overlay . kdims :
ranges [ kd . name ] [ 'combined' ] = overlay . range ( kd )
extents = super ( BarPlot , self ) . get_extents ( ... |
def log_response ( handler ) :
"""Acturally , logging response is not a server ' s responsibility ,
you should use http tools like Chrome Developer Tools to analyse the response .
Although this function and its setting ( LOG _ RESPONSE ) is not recommended to use ,
if you are laze as I was and working in deve... | content_type = handler . _headers . get ( 'Content-Type' , None )
headers_str = handler . _generate_headers ( )
block = 'Response Infomations:\n' + headers_str . strip ( )
if content_type and ( 'text' in content_type or 'json' in content_type ) :
limit = 0
if 'LOG_RESPONSE_LINE_LIMIT' in settings :
limi... |
def _getError ( self , device , message ) :
"""Get the error message or value stored in the Qik hardware .
: Parameters :
device : ` int `
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol .
message : ` bool `
If set to ` True ` a text message will be ... | cmd = self . _COMMAND . get ( 'get-error' )
self . _writeData ( cmd , device )
result = [ ]
bits = [ ]
try :
num = self . _serial . read ( size = 1 )
num = ord ( num )
except serial . SerialException as e :
self . _log and self . _log . error ( "Error: %s" , e , exc_info = True )
raise e
except TypeErro... |
def generate ( self , text ) :
"""Generate and save avatars , return a list of file name : [ filename _ s , filename _ m , filename _ l ] .
: param text : The text used to generate image .""" | sizes = current_app . config [ 'AVATARS_SIZE_TUPLE' ]
path = current_app . config [ 'AVATARS_SAVE_PATH' ]
suffix = { sizes [ 0 ] : 's' , sizes [ 1 ] : 'm' , sizes [ 2 ] : 'l' }
for size in sizes :
image_byte_array = self . get_image ( string = str ( text ) , width = int ( size ) , height = int ( size ) , pad = int ... |
def is_valid ( hal_id ) :
"""Check that a given HAL id is a valid one .
: param hal _ id : The HAL id to be checked .
: returns : Boolean indicating whether the HAL id is valid or not .
> > > is _ valid ( " hal - 01258754 , version 1 " )
True
> > > is _ valid ( " hal - 01258754 " )
True
> > > is _ val... | match = REGEX . match ( hal_id )
return ( match is not None ) and ( match . group ( 0 ) == hal_id ) |
def _GetChunkForReading ( self , chunk ) :
"""Returns the relevant chunk from the datastore and reads ahead .""" | try :
return self . chunk_cache . Get ( chunk )
except KeyError :
pass
# We don ' t have this chunk already cached . The most common read
# access pattern is contiguous reading so since we have to go to
# the data store already , we read ahead to reduce round trips .
missing_chunks = [ ]
for chunk_number in ran... |
def isBlockComment ( self , line , column ) :
"""Check if text at given position is a block comment .
If language is not known , or text is not parsed yet , ` ` False ` ` is returned""" | return self . _highlighter is not None and self . _highlighter . isBlockComment ( self . document ( ) . findBlockByNumber ( line ) , column ) |
def to_pickle ( self , filepath ) :
"""Parameters
filepath : str .
Should end in . pkl . If it does not , " . pkl " will be appended to the
passed string .
Returns
None . Saves the model object to the location specified by ` filepath ` .""" | if not isinstance ( filepath , str ) :
raise ValueError ( "filepath must be a string." )
if not filepath . endswith ( ".pkl" ) :
filepath = filepath + ".pkl"
with open ( filepath , "wb" ) as f :
pickle . dump ( self , f )
print ( "Model saved to {}" . format ( filepath ) )
return None |
def hourly_dew_point ( self ) :
"""A data collection containing hourly dew points over they day .""" | dpt_data = self . _humidity_condition . hourly_dew_point_values ( self . _dry_bulb_condition )
return self . _get_daily_data_collections ( temperature . DewPointTemperature ( ) , 'C' , dpt_data ) |
def _encode_query ( query ) :
"""Quote all values of a query string .""" | if query == '' :
return query
query_args = [ ]
for query_kv in query . split ( '&' ) :
k , v = query_kv . split ( '=' )
query_args . append ( k + "=" + quote ( v . encode ( 'utf-8' ) ) )
return '&' . join ( query_args ) |
def update ( self ) :
"""Update this ` ~ photutils . isophote . EllipseSample ` instance with
the intensity integrated at the ( x0 , y0 ) center position using
bilinear integration . The local gradient is set to ` None ` .""" | s = self . extract ( )
self . mean = s [ 2 ] [ 0 ]
self . gradient = None
self . gradient_error = None
self . gradient_relative_error = None |
def restriction ( lam , mu , orbitals , U , beta ) :
"""Equation that determines the restriction on lagrange multipier""" | return 2 * orbitals * fermi_dist ( - ( mu + lam ) , beta ) - expected_filling ( - 1 * lam , orbitals , U , beta ) |
def sha256_digest ( instr ) :
'''Generate a sha256 hash of a given string .''' | return salt . utils . stringutils . to_unicode ( hashlib . sha256 ( salt . utils . stringutils . to_bytes ( instr ) ) . hexdigest ( ) ) |
def mxmt ( m1 , m2 ) :
"""Multiply a 3x3 matrix and the transpose of another 3x3 matrix .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / mxmt _ c . html
: param m1 : 3x3 double precision matrix .
: type m1 : 3x3 - Element Array of floats
: param m2 : 3x3 double precision mat... | m1 = stypes . toDoubleMatrix ( m1 )
m2 = stypes . toDoubleMatrix ( m2 )
mout = stypes . emptyDoubleMatrix ( )
libspice . mxmt_c ( m1 , m2 , mout )
return stypes . cMatrixToNumpy ( mout ) |
def find_file ( search_dir , file_pattern ) :
"""Search for a file in a directory , and return the first match .
If the file is not found return an empty string
Args :
search _ dir : The root directory to search in
file _ pattern : A unix - style wildcard pattern representing
the file to find
Returns : ... | for root , dirnames , fnames in os . walk ( search_dir ) :
for fname in fnames :
if fnmatch . fnmatch ( fname , file_pattern ) :
return os . path . join ( root , fname )
return "" |
def attachment_show ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / attachments # show - attachment" | api_path = "/api/v2/attachments/{id}.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , ** kwargs ) |
def run ( self ) :
"""Starts the blotter
Connects to the TWS / GW , processes and logs market data ,
and broadcast it over TCP via ZeroMQ ( which algo subscribe to )""" | self . _check_unique_blotter ( )
# connect to mysql
self . mysql_connect ( )
self . context = zmq . Context ( zmq . REP )
self . socket = self . context . socket ( zmq . PUB )
self . socket . bind ( "tcp://*:" + str ( self . args [ 'zmqport' ] ) )
db_modified = 0
contracts = [ ]
prev_contracts = [ ]
first_run = True
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.