signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _convert_value_to_native ( value ) :
"""Converts pysnmp objects into native Python objects .""" | if isinstance ( value , Counter32 ) :
return int ( value . prettyPrint ( ) )
if isinstance ( value , Counter64 ) :
return int ( value . prettyPrint ( ) )
if isinstance ( value , Gauge32 ) :
return int ( value . prettyPrint ( ) )
if isinstance ( value , Integer ) :
return int ( value . prettyPrint ( ) )
... |
def finalize ( self , outcome = None ) :
"""Finalize state
This method is called when the run method finishes
: param rafcon . core . logical _ port . Outcome outcome : final outcome of the state
: return : Nothing for the moment""" | # Set the final outcome of the state
if outcome is not None :
self . final_outcome = outcome
# If we are within a concurrency state , we have to notify it about our finalization
if self . concurrency_queue :
self . concurrency_queue . put ( self . state_id )
logger . debug ( "Finished execution of {0}: {1}" . f... |
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] :
"""Rate limit a function .""" | return util . rate_limited ( max_per_hour , * args ) |
def inject_target ( self , target , dependencies = None , derived_from = None , synthetic = False ) :
"""Injects a fully realized Target into the BuildGraph .
: API : public
: param Target target : The Target to inject .
: param list < Address > dependencies : The Target addresses that ` target ` depends on .... | if self . contains_address ( target . address ) :
raise ValueError ( 'Attempted to inject synthetic {target} derived from {derived_from}' ' into the BuildGraph with address {address}, but there is already a Target' ' {existing_target} with that address' . format ( target = target , derived_from = derived_from , add... |
def load_dependency ( self , module_name , dependencies , recursive , greedy , ismapping = False ) :
"""Loads the module with the specified name if it isn ' t already loaded .""" | key = module_name . lower ( )
if key not in self . modules :
if key == "fortpy" : # Manually specify the correct path to the fortpy . f90 that shipped with
# the distribution
from fortpy . utility import get_fortpy_templates_dir
from os import path
fpy_path = path . join ( get_fortpy_tem... |
def _create ( cls , writer_spec , filename_suffix ) :
"""Helper method that actually creates the file in cloud storage .""" | writer = cls . _open_file ( writer_spec , filename_suffix )
return cls ( writer , writer_spec = writer_spec ) |
def forum_id ( self ) :
"""小组发帖要用的 forum _ id""" | html = self . request ( self . team_url ) . text
soup = BeautifulSoup ( html )
return soup . find ( id = 'forum_id' ) . attrs [ 'value' ] |
def drop_user ( self , username ) :
"""Drop a user from InfluxDB .
: param username : the username to drop
: type username : str""" | text = "DROP USER {0}" . format ( quote_ident ( username ) , method = "POST" )
self . query ( text , method = "POST" ) |
def file_xext ( filepath ) :
"""Get the file extension wrt compression from the filename ( is it tar or targz )
: param str filepath : Path to the file
: return str ext : Compression extension name""" | ext = os . path . splitext ( filepath ) [ 1 ]
if ext == '.gz' :
xext = os . path . splitext ( os . path . splitext ( filepath ) [ 0 ] ) [ 1 ]
if xext == '.tar' :
ext = xext + ext
elif ext == '.tar' :
pass
# ext is already . tar
else :
ext = ''
return ext |
def install_notebook_hook ( notebook_type , load , show_doc , show_app , overwrite = False ) :
'''Install a new notebook display hook .
Bokeh comes with support for Jupyter notebooks built - in . However , there are
other kinds of notebooks in use by different communities . This function
provides a mechanism ... | if notebook_type in _HOOKS and not overwrite :
raise RuntimeError ( "hook for notebook type %r already exists" % notebook_type )
_HOOKS [ notebook_type ] = dict ( load = load , doc = show_doc , app = show_app ) |
def get_groupname ( taskfileinfo ) :
"""Return a suitable name for a groupname for the given taskfileinfo .
: param taskfileinfo : the taskfile info for the file that needs a group when importing / referencing
: type taskfileinfo : : class : ` jukeboxcore . filesys . TaskFileInfo `
: returns : None
: rtype ... | element = taskfileinfo . task . element
name = element . name
return name + "_grp" |
def copy_preset ( preset_dir , project_dir ) :
"""Copy contents of preset into new project
If package . json contains the key " contents " , limit
the files copied to those present in this list .
Arguments :
preset _ dir ( str ) : Absolute path to preset
project _ dir ( str ) : Absolute path to new projec... | os . makedirs ( project_dir )
package_file = os . path . join ( preset_dir , "package.json" )
with open ( package_file ) as f :
package = json . load ( f )
for fname in os . listdir ( preset_dir ) :
src = os . path . join ( preset_dir , fname )
contents = package . get ( "contents" ) or [ ]
if fname not... |
def chunks ( arr , size ) :
"""Splits a list into chunks
: param arr : list to split
: type arr : : class : ` list `
: param size : number of elements in each chunk
: type size : : class : ` int `
: return : generator object
: rtype : : class : ` generator `""" | for i in _range ( 0 , len ( arr ) , size ) :
yield arr [ i : i + size ] |
def s3_download ( url , dst ) : # type : ( str , str ) - > None
"""Download a file from S3.
Args :
url ( str ) : the s3 url of the file .
dst ( str ) : the destination where the file will be saved .""" | url = parse . urlparse ( url )
if url . scheme != 's3' :
raise ValueError ( "Expecting 's3' scheme, got: %s in %s" % ( url . scheme , url ) )
bucket , key = url . netloc , url . path . lstrip ( '/' )
region = os . environ . get ( 'AWS_REGION' , os . environ . get ( _params . REGION_NAME_ENV ) )
s3 = boto3 . resourc... |
def affine_matrix_from_points ( v0 , v1 , shear = True , scale = True , usesvd = True ) :
"""Return affine transform matrix to register two point sets .
v0 and v1 are shape ( ndims , \ * ) arrays of at least ndims non - homogeneous
coordinates , where ndims is the dimensionality of the coordinate space .
If s... | v0 = numpy . array ( v0 , dtype = numpy . float64 , copy = True )
v1 = numpy . array ( v1 , dtype = numpy . float64 , copy = True )
ndims = v0 . shape [ 0 ]
if ndims < 2 or v0 . shape [ 1 ] < ndims or v0 . shape != v1 . shape :
raise ValueError ( "input arrays are of wrong shape or type" )
# move centroids to origi... |
def projection ( table , exprs ) :
"""Compute new table expression with the indicated column expressions from
this table .
Parameters
exprs : column expression , or string , or list of column expressions and
strings . If strings passed , must be columns in the table already
Returns
projection : TableExp... | import ibis . expr . analysis as L
if isinstance ( exprs , ( Expr , str ) ) :
exprs = [ exprs ]
projector = L . Projector ( table , exprs )
op = projector . get_result ( )
return op . to_expr ( ) |
def classnameify ( s ) :
"""Makes a classname""" | return '' . join ( w if w in ACRONYMS else w . title ( ) for w in s . split ( '_' ) ) |
def command_line ( self ) :
'''Return a string to open read files with''' | file_format = self . guess_sequence_input_file_format ( self . read_file )
logging . debug ( "Detected file format %s" % file_format )
if file_format == self . FORMAT_FASTA :
cmd = """cat %s""" % ( self . read_file )
elif file_format == self . FORMAT_FASTQ_GZ :
cmd = """zcat %s | awk '{print ">" substr($0,2);ge... |
def clean ( self ) :
"""Prevents cycles in the tree .""" | super ( CTENode , self ) . clean ( )
if self . parent and self . pk in getattr ( self . parent , self . _cte_node_path ) :
raise ValidationError ( _ ( "A node cannot be made a descendant of itself." ) ) |
def makeTauchenAR1 ( N , sigma = 1.0 , rho = 0.9 , bound = 3.0 ) :
'''Function to return a discretized version of an AR1 process .
See http : / / www . fperri . net / TEACHING / macrotheory08 / numerical . pdf for details
Parameters
N : int
Size of discretized grid
sigma : float
Standard deviation of th... | yN = bound * sigma / ( ( 1 - rho ** 2 ) ** 0.5 )
y = np . linspace ( - yN , yN , N )
d = y [ 1 ] - y [ 0 ]
trans_matrix = np . ones ( ( N , N ) )
for j in range ( N ) :
for k_1 in range ( N - 2 ) :
k = k_1 + 1
trans_matrix [ j , k ] = stats . norm . cdf ( ( y [ k ] + d / 2.0 - rho * y [ j ] ) / sigm... |
def encode ( self , message , k = None ) :
'''Encode one message block ( up to 255 ) into an ecc''' | if not k :
k = self . k
message , _ = self . pad ( message , k = k )
if self . algo == 1 :
mesecc = self . ecc_manager . encode ( message , k = k )
elif self . algo == 2 :
mesecc = self . ecc_manager . encode_fast ( message , k = k )
elif self . algo == 3 or self . algo == 4 :
mesecc = rs_encode_msg ( m... |
def fork ( self , ** args ) :
'''fork any gist by providing gistID or gistname ( for authenticated user )''' | if 'name' in args :
self . gist_name = args [ 'name' ]
self . gist_id = self . getMyID ( self . gist_name )
elif 'id' in args :
self . gist_id = args [ 'id' ]
else :
raise Exception ( 'Either provide authenticated user\'s Unambigious Gistname or any unique Gistid to be forked' )
r = requests . post ( '%... |
def get_tmp_file ( dir = None ) :
"Create and return a tmp filename , optionally at a specific path . ` os . remove ` when done with it ." | with tempfile . NamedTemporaryFile ( delete = False , dir = dir ) as f :
return f . name |
def update ( self ) :
"""Sends the current screen contents to Mate Light""" | display_data = [ ]
for y in range ( self . height ) :
for x in range ( self . width ) :
for color in self . matrix [ x ] [ y ] :
display_data . append ( int ( color ) )
checksum = bytearray ( [ 0 , 0 , 0 , 0 ] )
data_as_bytes = bytearray ( display_data )
data = data_as_bytes + checksum
sock = so... |
def escape ( identifier , ansi_quotes , should_quote ) :
"""Escape identifiers .
ANSI uses single quotes , but many databases use back quotes .""" | if not should_quote ( identifier ) :
return identifier
quote = '"' if ansi_quotes else '`'
identifier = identifier . replace ( quote , 2 * quote )
return '{0}{1}{2}' . format ( quote , identifier , quote ) |
def delete_property ( self , content_id , property_key , callback = None ) :
"""Deletes a content property .
: param content _ id ( string ) : The ID for the content that owns the property to be deleted .
: param property _ key ( string ) : The name of the property to be deleted .
: param callback : OPTIONAL ... | return self . _service_delete_request ( "rest/api/content/{id}/property/{key}" "" . format ( id = content_id , key = property_key ) , callback = callback ) |
def sensitivity ( Ntp , Nfn , eps = numpy . spacing ( 1 ) ) :
"""Sensitivity
Wikipedia entry https : / / en . wikipedia . org / wiki / Sensitivity _ and _ specificity
Parameters
Ntp : int > = 0
Number of true positives .
Nfn : int > = 0
Number of false negatives .
eps : float
eps .
Default value n... | return float ( Ntp / ( Ntp + Nfn + eps ) ) |
def create_group_dampening ( self , group_id , dampening ) :
"""Create a new group dampening
: param group _ id : Group Trigger id attached to dampening
: param dampening : Dampening definition to be created .
: type dampening : Dampening
: return : Group Dampening created""" | data = self . _serialize_object ( dampening )
url = self . _service_url ( [ 'triggers' , 'groups' , group_id , 'dampenings' ] )
return Dampening ( self . _post ( url , data ) ) |
def unstructured_bugs ( self ) :
"""Get bugs that match this line in the Bug Suggestions artifact for this job .""" | components = self . _serialized_components ( )
if not components :
return [ ]
from treeherder . model . error_summary import get_useful_search_results
job = Job . objects . get ( guid = self . job_guid )
rv = [ ]
ids_seen = set ( )
for item in get_useful_search_results ( job ) :
if all ( component in item [ "se... |
def arc_by_center ( x , y , arc_box , constant_length , thickness , gaussian_width ) :
"""Arc with Gaussian fall - off after the solid ring - shaped region and specified
by point of tangency ( x and y ) and arc width and height .
This function calculates the start and end radian from the given width and
heigh... | arc_w = arc_box [ 0 ]
arc_h = abs ( arc_box [ 1 ] )
if arc_w == 0.0 : # arc _ w = 0 , don ' t draw anything
radius = 0.0
angles = ( 0.0 , 0.0 )
elif arc_h == 0.0 : # draw a horizontal line , width = arc _ w
return smooth_rectangle ( x , y , arc_w , thickness , 0.0 , gaussian_width )
else :
if constant_l... |
def salt_main ( ) :
'''Publish commands to the salt system from the command line on the
master .''' | import salt . cli . salt
if '' in sys . path :
sys . path . remove ( '' )
client = salt . cli . salt . SaltCMD ( )
_install_signal_handlers ( client )
client . run ( ) |
def expect ( self , msg ) -> T :
"""Unwraps the option . Raises an exception if the value is : py : data : ` NONE ` .
Args :
msg : The exception message .
Returns :
The wrapped value .
Raises :
` ` ValueError ` ` with message provided by ` ` msg ` ` if the value is : py : data : ` NONE ` .
Examples : ... | if self . _is_some :
return self . _val
raise ValueError ( msg ) |
def _get_platlib_dir ( cmd ) :
"""Given a build command , return the name of the appropriate platform - specific
build subdirectory directory ( e . g . build / lib . linux - x86_64-2.7)""" | plat_specifier = '.{0}-{1}' . format ( cmd . plat_name , sys . version [ 0 : 3 ] )
return os . path . join ( cmd . build_base , 'lib' + plat_specifier ) |
def process_exception ( self , request : AxesHttpRequest , exception ) : # pylint : disable = inconsistent - return - statements
"""Exception handler that processes exceptions raised by the Axes signal handler when request fails with login .
Only ` ` axes . exceptions . AxesSignalPermissionDenied ` ` exception is... | if isinstance ( exception , AxesSignalPermissionDenied ) :
return get_lockout_response ( request ) |
def _ProcessCompressedStreamTypes ( self , mediator , path_spec , type_indicators ) :
"""Processes a data stream containing compressed stream types such as : bz2.
Args :
mediator ( ParserMediator ) : mediates the interactions between
parsers and other components , such as storage and abort signals .
path _ ... | number_of_type_indicators = len ( type_indicators )
if number_of_type_indicators == 0 :
return
self . processing_status = definitions . STATUS_INDICATOR_COLLECTING
if number_of_type_indicators > 1 :
display_name = mediator . GetDisplayName ( )
logger . debug ( ( 'Found multiple format type indicators: {0:s}... |
def mark_rewrite ( self , * names ) :
"""Mark import names as needing to be re - written .
The named module or package as well as any nested modules will
be re - written on import .""" | already_imported = set ( names ) . intersection ( set ( sys . modules ) )
if already_imported :
for name in already_imported :
if name not in self . _rewritten_names :
self . _warn_already_imported ( name )
self . _must_rewrite . update ( names ) |
def get_devices ( ads , ** kwargs ) :
"""Finds a list of AndroidDevice instance from a list that has specific
attributes of certain values .
Example :
get _ devices ( android _ devices , label = ' foo ' , phone _ number = ' 1234567890 ' )
get _ devices ( android _ devices , model = ' angler ' )
Args :
a... | def _get_device_filter ( ad ) :
for k , v in kwargs . items ( ) :
if not hasattr ( ad , k ) :
return False
elif getattr ( ad , k ) != v :
return False
return True
filtered = filter_devices ( ads , _get_device_filter )
if not filtered :
raise Error ( 'Could not find a ... |
def set_parent ( self , parent ) :
"""Set the parent reftrack object
If a parent gets deleted , the children will be deleted too .
. . Note : : Once the parent is set , it cannot be set again !
: param parent : the parent reftrack object
: type parent : : class : ` Reftrack ` | None
: returns : None
: r... | assert self . _parent is None or self . _parent is parent , "Cannot change the parent. Can only set from None."
if parent and self . _parent is parent :
return
self . _parent = parent
if parent :
refobjinter = self . get_refobjinter ( )
refobj = self . get_refobj ( )
# set the parent of the refobj only ... |
def position ( self ) :
'''If this locus spans a single base , this property gives that position .
Otherwise , raises a ValueError .''' | if self . end != self . start + 1 :
raise ValueError ( "Not a single base: %s" % str ( self ) )
return self . start |
def log_predictive_density ( self , x_test , y_test , Y_metadata = None ) :
"""Calculation of the log predictive density
. . math :
p ( y _ { * } | D ) = p ( y _ { * } | f _ { * } ) p ( f _ { * } | \ mu _ { * } \\ sigma ^ { 2 } _ { * } )
: param x _ test : test locations ( x _ { * } )
: type x _ test : ( Nx... | mu_star , var_star = self . _raw_predict ( x_test )
return self . likelihood . log_predictive_density ( y_test , mu_star , var_star , Y_metadata = Y_metadata ) |
def merge ( args ) :
"""% prog merge bedfiles > newbedfile
Concatenate bed files together . Performing seqid and name changes to avoid
conflicts in the new bed file .""" | p = OptionParser ( merge . __doc__ )
p . set_outfile ( )
opts , args = p . parse_args ( args )
if len ( args ) < 1 :
sys . exit ( not p . print_help ( ) )
bedfiles = args
fw = must_open ( opts . outfile , "w" )
for bedfile in bedfiles :
bed = Bed ( bedfile )
pf = op . basename ( bedfile ) . split ( "." ) [ ... |
def corpus ( self ) :
'''Command to add a corpus to the dsrt library''' | # Initialize the addcorpus subcommand ' s argparser
description = '''The corpus subcommand has a number of subcommands of its own, including:
list\t-\tlists all available corpora in dsrt's library
add\t-\tadds a corpus to dsrt's library'''
parser = argparse . ArgumentParser ( description = descr... |
def cluster_count_key_in_slots ( self , slot ) :
"""Return the number of local keys in the specified hash slot .""" | if not isinstance ( slot , int ) :
raise TypeError ( "Expected slot to be of type int, got {}" . format ( type ( slot ) ) )
return self . execute ( b'CLUSTER' , b'COUNTKEYSINSLOT' , slot ) |
def peak_in_power ( events , dat , s_freq , method , value = None ) :
"""Define peak in power of the signal .
Parameters
events : ndarray ( dtype = ' int ' )
N x 3 matrix with start , peak , end samples
dat : ndarray ( dtype = ' float ' )
vector with the original data
s _ freq : float
sampling frequen... | dat = diff ( dat )
# remove 1 / f
peak = empty ( events . shape [ 0 ] )
peak . fill ( nan )
if method is not None :
for i , one_event in enumerate ( events ) :
if method == 'peak' :
x0 = one_event [ 1 ] - value / 2 * s_freq
x1 = one_event [ 1 ] + value / 2 * s_freq
elif metho... |
def find ( pattern , path = os . path . curdir , recursive = False ) :
"""Find absolute file / folder paths with the given ` ` re ` ` pattern .
Args :
* pattern : search pattern , support both string ( exact match ) and ` re ` pattern .
* path : root path to start searching , default is current working direct... | root = realpath ( path )
Finder = lambda item : regex . is_regex ( pattern ) and pattern . match ( item ) or ( pattern == item )
if recursive :
for base , dirs , files in os . walk ( root , topdown = True ) :
for segment in itertools . chain ( filter ( Finder , files ) , filter ( Finder , dirs ) ) :
... |
def _stdin_ ( p ) :
"""Takes input from user . Works for Python 2 and 3.""" | _v = sys . version [ 0 ]
return input ( p ) if _v is '3' else raw_input ( p ) |
def _adjustment_reactions ( self ) :
"""Yield all the non exchange reactions in the model .""" | for reaction_id in self . _model . reactions :
if not self . _model . is_exchange ( reaction_id ) :
yield reaction_id |
def dispatch ( self , request , * args , ** kwargs ) :
"""Override dispatch to call appropriate methods :
* $ query - ng _ query
* $ get - ng _ get
* $ save - ng _ save
* $ delete and $ remove - ng _ delete""" | allowed_methods = self . get_allowed_methods ( )
try :
if request . method == 'GET' and 'GET' in allowed_methods :
if 'pk' in request . GET or self . slug_field in request . GET :
return self . ng_get ( request , * args , ** kwargs )
return self . ng_query ( request , * args , ** kwargs ... |
def furnsh ( path ) :
"""Load one or more SPICE kernels into a program .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / furnsh _ c . html
: param path : one or more paths to kernels
: type path : str or list of str""" | if isinstance ( path , list ) :
for p in path :
libspice . furnsh_c ( stypes . stringToCharP ( p ) )
else :
path = stypes . stringToCharP ( path )
libspice . furnsh_c ( path ) |
def archive_experiment ( experiment ) :
"""Archives an experiment""" | redis = oz . redis . create_connection ( )
oz . bandit . Experiment ( redis , experiment ) . archive ( ) |
def from_description ( cls , table ) :
"""Factory method that uses the dynamo3 ' describe ' return value""" | throughput = table . provisioned_throughput
attrs = { }
for data in getattr ( table , "attribute_definitions" , [ ] ) :
field = TableField ( data [ "AttributeName" ] , TYPES_REV [ data [ "AttributeType" ] ] )
attrs [ field . name ] = field
for data in getattr ( table , "key_schema" , [ ] ) :
name = data [ "... |
async def parse_response ( response : ClientResponse , schema : dict ) -> Any :
"""Validate and parse the BMA answer
: param response : Response of aiohttp request
: param schema : The expected response structure
: return : the json data""" | try :
data = await response . json ( )
response . close ( )
if schema is not None :
jsonschema . validate ( data , schema )
return data
except ( TypeError , json . decoder . JSONDecodeError ) as e :
raise jsonschema . ValidationError ( "Could not parse json : {0}" . format ( str ( e ) ) ) |
def get_table_idcb_field ( endianess , data ) :
"""Return data from a packed TABLE _ IDC _ BFLD bit - field .
: param str endianess : The endianess to use when packing values ( ' > ' or ' < ' )
: param str data : The packed and machine - formatted data to parse
: rtype : tuple
: return : Tuple of ( proc _ n... | bfld = struct . unpack ( endianess + 'H' , data [ : 2 ] ) [ 0 ]
proc_nbr = bfld & 2047
std_vs_mfg = bool ( bfld & 2048 )
proc_flag = bool ( bfld & 4096 )
flag1 = bool ( bfld & 8192 )
flag2 = bool ( bfld & 16384 )
flag3 = bool ( bfld & 32768 )
return ( proc_nbr , std_vs_mfg , proc_flag , flag1 , flag2 , flag3 ) |
def update ( cls , domain , login , options , alias_add , alias_del ) :
"""Update a mailbox .""" | cls . echo ( 'Updating your mailbox.' )
result = cls . call ( 'domain.mailbox.update' , domain , login , options )
if alias_add or alias_del :
current_aliases = cls . info ( domain , login ) [ 'aliases' ]
aliases = current_aliases [ : ]
if alias_add :
for alias in alias_add :
if alias no... |
def imagetransformer1d_base_8l_64by64 ( ) :
"""hparams fo 12 layer big 1d model for imagenet 64x64.""" | hparams = image_transformer_base ( )
hparams . num_heads = 8
hparams . hidden_size = 512
hparams . filter_size = 2048
hparams . num_decoder_layers = 8
hparams . batch_size = 1
hparams . block_length = 512
hparams . block_width = 768
hparams . layer_prepostprocess_dropout = 0.1
hparams . max_length = 14000
hparams . unc... |
def sortSkyCatalog ( self ) :
"""Sort and clip the source catalog based on the flux range specified
by the user . It keeps a copy of the original full list in order to
support iteration .""" | if len ( self . all_radec_orig [ 2 ] . nonzero ( ) [ 0 ] ) == 0 :
warn_str = "Source catalog NOT trimmed by flux/mag. No fluxes read in for sources!"
print ( '\nWARNING: ' , warn_str , '\n' )
log . warning ( warn_str )
return
clip_catalog = False
clip_prefix = ''
for k in sortKeys :
for p in self . ... |
def cancel_withdraw ( self , address_id ) :
"""申请取消提现虚拟币
: param address _ id :
: return : {
" status " : " ok " ,
" data " : 700""" | params = { }
path = f'/v1/dw/withdraw-virtual/{address_id}/cancel'
def _wrapper ( _func ) :
@ wraps ( _func )
def handle ( ) :
_func ( api_key_post ( params , path ) )
return handle
return _wrapper |
def canonical_url ( configs , endpoint_type = PUBLIC ) :
"""Returns the correct HTTP URL to this host given the state of HTTPS
configuration , hacluster and charm configuration .
: param configs : OSTemplateRenderer config templating object to inspect
for a complete https context .
: param endpoint _ type :... | scheme = _get_scheme ( configs )
address = resolve_address ( endpoint_type )
if is_ipv6 ( address ) :
address = "[{}]" . format ( address )
return '%s://%s' % ( scheme , address ) |
def write_message ( self , message ) :
"""Writes a message to this chat connection ' s handler""" | logging . debug ( "Sending message {mes} to {usr}" . format ( mes = message , usr = self . id ) )
self . handler . write_message ( message ) |
def getItem ( self , itemId ) :
"""gets the refernce to the Items class which manages content on a
given AGOL or Portal site .""" | url = "%s/items/%s" % ( self . root , itemId )
return Item ( url = url , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) |
def create_packages ( self ) :
"""Create missing packages joining the vendor root to the base of the vendored distribution .
For example , given a root at ` ` / home / jake / dev / pantsbuild / pex ` ` and a vendored distribution at
` ` pex / vendor / _ vendored / requests ` ` this method would create the follo... | for index , _ in enumerate ( self . _subpath_components ) :
relpath = _PACKAGE_COMPONENTS + self . _subpath_components [ : index + 1 ] + [ '__init__.py' ]
touch ( os . path . join ( self . ROOT , * relpath ) ) |
def parse_uri ( value ) :
"""Parses a value into a head and tail pair based on the finding the
last ' # ' or ' / ' as is standard with URI fromats
args :
value : string value to parse
returns :
tuple : ( lookup , end )""" | value = RdfNsManager . clean_iri ( value )
lookup = None
end = None
try :
lookup = value [ : value . rindex ( '#' ) + 1 ]
end = value [ value . rindex ( '#' ) + 1 : ]
except ValueError :
try :
lookup = value [ : value . rindex ( '/' ) + 1 ]
end = value [ value . rindex ( '/' ) + 1 : ]
ex... |
def process ( self , useProductionNames = None , optimizeCFF = True ) :
"""useProductionNames :
By default , when value is None , this will rename glyphs using the
' public . postscriptNames ' in then UFO lib . If the mapping is not
present , no glyph names are renamed .
If the value is False , no glyphs ar... | if useProductionNames is None :
useProductionNames = self . ufo . lib . get ( USE_PRODUCTION_NAMES , not self . ufo . lib . get ( GLYPHS_DONT_USE_PRODUCTION_NAMES ) and self . _postscriptNames is not None )
if useProductionNames :
self . _rename_glyphs_from_ufo ( )
if optimizeCFF and 'CFF ' in self . otf :
... |
def classify ( self , classifier_id , text , ** kwargs ) :
"""Classify a phrase .
Returns label information for the input . The status must be ` Available ` before you
can use the classifier to classify text .
: param str classifier _ id : Classifier ID to use .
: param str text : The submitted phrase . The... | if classifier_id is None :
raise ValueError ( 'classifier_id must be provided' )
if text is None :
raise ValueError ( 'text must be provided' )
headers = { }
if 'headers' in kwargs :
headers . update ( kwargs . get ( 'headers' ) )
sdk_headers = get_sdk_headers ( 'natural_language_classifier' , 'V1' , 'class... |
def to_bytes_or_none ( value ) :
"""Converts C char arrays to bytes and C NULL values to None .""" | if value == ffi . NULL :
return None
elif isinstance ( value , ffi . CData ) :
return ffi . string ( value )
else :
raise ValueError ( 'Value must be char[] or NULL' ) |
def find_config_files ( path = [ '~/.vcspull' ] , match = [ '*' ] , filetype = [ 'json' , 'yaml' ] , include_home = False ) :
"""Return repos from a directory and match . Not recursive .
: param path : list of paths to search
: type path : list
: param match : list of globs to search against
: type match : ... | configs = [ ]
if include_home is True :
configs . extend ( find_home_config_files ( ) )
if isinstance ( path , list ) :
for p in path :
configs . extend ( find_config_files ( p , match , filetype ) )
return configs
else :
path = os . path . expanduser ( path )
if isinstance ( match , lis... |
def build_uri ( self , id_or_uri ) :
"""Helps to build the URI from resource id and validate the URI .
Args :
id _ or _ uri : ID / URI of the resource .
Returns :
Returns a valid resource URI""" | if not id_or_uri :
logger . exception ( RESOURCE_CLIENT_INVALID_ID )
raise ValueError ( RESOURCE_CLIENT_INVALID_ID )
if "/" in id_or_uri :
self . validate_resource_uri ( id_or_uri )
return id_or_uri
else :
return self . _base_uri + "/" + id_or_uri |
def median ( self , name , ** kwargs ) :
"""Median of the distribution .""" | data = self . get ( name , ** kwargs )
return np . percentile ( data , [ 50 ] ) |
def _wrap_stream_errors ( callable_ ) :
"""Wrap errors for Unary - Stream and Stream - Stream gRPC callables .
The callables that return iterators require a bit more logic to re - map
errors when iterating . This wraps both the initial invocation and the
iterator of the return value to re - map errors .""" | _patch_callable_name ( callable_ )
@ general_helpers . wraps ( callable_ )
def error_remapped_callable ( * args , ** kwargs ) :
try :
result = callable_ ( * args , ** kwargs )
return _StreamingResponseIterator ( result )
except grpc . RpcError as exc :
six . raise_from ( exceptions . fro... |
def _febrl_links ( df ) :
"""Get the links of a FEBRL dataset .""" | index = df . index . to_series ( )
keys = index . str . extract ( r'rec-(\d+)' , expand = True ) [ 0 ]
index_int = numpy . arange ( len ( df ) )
df_helper = pandas . DataFrame ( { 'key' : keys , 'index' : index_int } )
# merge the two frame and make MultiIndex .
pairs_df = df_helper . merge ( df_helper , on = 'key' ) [... |
def rev ( self , rev ) :
"""Return a new identity with the given revision""" | d = self . dict
d [ 'revision' ] = rev
return self . from_dict ( d ) |
def unionByName ( self , other ) :
"""Returns a new : class : ` DataFrame ` containing union of rows in this and another frame .
This is different from both ` UNION ALL ` and ` UNION DISTINCT ` in SQL . To do a SQL - style set
union ( that does deduplication of elements ) , use this function followed by : func ... | return DataFrame ( self . _jdf . unionByName ( other . _jdf ) , self . sql_ctx ) |
def lower_folded_outputs ( ir_blocks ) :
"""Lower standard folded output fields into GremlinFoldedContextField objects .""" | folds , remaining_ir_blocks = extract_folds_from_ir_blocks ( ir_blocks )
if not remaining_ir_blocks :
raise AssertionError ( u'Expected at least one non-folded block to remain: {} {} ' u'{}' . format ( folds , remaining_ir_blocks , ir_blocks ) )
output_block = remaining_ir_blocks [ - 1 ]
if not isinstance ( output_... |
def normalize ( X ) :
"""equivalent to scipy . preprocessing . normalize on sparse matrices
, but lets avoid another depedency just for a small utility function""" | X = coo_matrix ( X )
X . data = X . data / sqrt ( bincount ( X . row , X . data ** 2 ) ) [ X . row ]
return X |
def sum_to_balance ( self ) :
"""Sum the Legs of the QuerySet to get a ` Balance ` _ object""" | result = self . values ( "amount_currency" ) . annotate ( total = models . Sum ( "amount" ) )
return Balance ( [ Money ( r [ "total" ] , r [ "amount_currency" ] ) for r in result ] ) |
def _get_distance_scaling_term ( self , C , mag , rrup ) :
"""Returns the distance scaling parameter""" | return ( C [ "r1" ] + C [ "r2" ] * mag ) * np . log10 ( rrup + C [ "r3" ] ) |
def serialize_to_json ( self , name , datas ) :
"""Serialize given datas to any object from assumed JSON string .
Arguments :
name ( string ) : Name only used inside possible exception message .
datas ( dict ) : Datas to serialize .
Returns :
object : Object depending from JSON content .""" | data_object = datas . get ( 'object' , None )
if data_object is None :
msg = ( "JSON reference '{}' lacks of required 'object' variable" )
raise SerializerError ( msg . format ( name ) )
try :
content = json . loads ( data_object , object_pairs_hook = OrderedDict )
except json . JSONDecodeError as e :
m... |
def get_image_entrypoint ( image ) :
'''Gets the image entrypoint''' | info = docker_inspect_or_pull ( image )
try :
return info [ 'Config' ] [ 'Entrypoint' ]
except KeyError as ke :
raise DockerError ( 'Failed to inspect image: JSON result missing key {}' . format ( ke ) ) |
def _convert_to_fill ( cls , fill_dict ) :
"""Convert ` ` fill _ dict ` ` to an openpyxl v2 Fill object
Parameters
fill _ dict : dict
A dict with one or more of the following keys ( or their synonyms ) ,
' fill _ type ' ( ' patternType ' , ' patterntype ' )
' start _ color ' ( ' fgColor ' , ' fgcolor ' ) ... | from openpyxl . styles import PatternFill , GradientFill
_pattern_fill_key_map = { 'patternType' : 'fill_type' , 'patterntype' : 'fill_type' , 'fgColor' : 'start_color' , 'fgcolor' : 'start_color' , 'bgColor' : 'end_color' , 'bgcolor' : 'end_color' , }
_gradient_fill_key_map = { 'fill_type' : 'type' , }
pfill_kwargs = ... |
def run_sparql_on ( q , ontology ) :
"""Run a SPARQL query ( q ) on a given Ontology ( Enum EOntology )""" | logging . info ( "Connecting to " + ontology . value + " SPARQL endpoint..." )
sparql = SPARQLWrapper ( ontology . value )
logging . info ( "Made wrapper: {}" . format ( sparql ) )
sparql . setQuery ( q )
sparql . setReturnFormat ( JSON )
logging . info ( "Query: {}" . format ( q ) )
results = sparql . query ( ) . conv... |
def get_gmn_version ( base_url ) :
"""Return the version currently running on a GMN instance .
( is _ gmn , version _ or _ error )""" | home_url = d1_common . url . joinPathElements ( base_url , 'home' )
try :
response = requests . get ( home_url , verify = False )
except requests . exceptions . ConnectionError as e :
return False , str ( e )
if not response . ok :
return False , 'invalid /home. status={}' . format ( response . status_code ... |
def animate ( self , images , delay = .25 ) :
"""Displays each of the input images in order , pausing for " delay "
seconds after each image .
Keyword arguments :
image - - An iterable collection of Image objects .
delay - - How many seconds to wait after displaying an image before
displaying the next one... | for image in images : # Draw the image on the display buffer .
self . set_image ( image )
# Draw the buffer to the display hardware .
self . write_display ( )
time . sleep ( delay ) |
def redirect_territory ( level , code ) :
"""Implicit redirect given the INSEE code .
Optimistically redirect to the latest valid / known INSEE code .""" | territory = GeoZone . objects . valid_at ( datetime . now ( ) ) . filter ( code = code , level = 'fr:{level}' . format ( level = level ) ) . first ( )
return redirect ( url_for ( 'territories.territory' , territory = territory ) ) |
def DisplayGetter ( accessor , * args , ** kwargs ) :
"""Returns a Getter that gets the display name for a model field with choices .""" | short_description = get_pretty_name ( accessor )
accessor = 'get_%s_display' % accessor
getter = Getter ( accessor , * args , ** kwargs )
getter . short_description = short_description
return getter |
def resize_imgs ( fnames , targ , path , new_path , resume = True , fn = None ) :
"""Enlarge or shrink a set of images in the same directory to scale , such that the smaller of the height or width dimension is equal to targ .
Note :
- - This function is multithreaded for efficiency .
- - When destination file... | target_path = path_for ( path , new_path , targ )
if resume :
subdirs = { os . path . dirname ( p ) for p in fnames }
subdirs = { s for s in subdirs if os . path . exists ( os . path . join ( target_path , s ) ) }
already_resized_fnames = set ( )
for subdir in subdirs :
files = [ os . path . joi... |
def _line_load ( network , grid , crit_lines ) :
"""Checks for over - loading issues of lines .
Parameters
network : : class : ` ~ . grid . network . Network `
grid : : class : ` ~ . grid . grids . LVGrid ` or : class : ` ~ . grid . grids . MVGrid `
crit _ lines : : pandas : ` pandas . DataFrame < dataframe... | if isinstance ( grid , LVGrid ) :
grid_level = 'lv'
else :
grid_level = 'mv'
for line in list ( grid . graph . lines ( ) ) :
i_line_allowed_per_case = { }
i_line_allowed_per_case [ 'feedin_case' ] = line [ 'line' ] . type [ 'I_max_th' ] * line [ 'line' ] . quantity * network . config [ 'grid_expansion_l... |
def import_agent ( self , parent , agent_uri = None , agent_content = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None ) :
"""Imports the specified agent from a ZIP file .
Uploads new intents and entity types without delet... | # Wrap the transport method to add retry and timeout logic .
if 'import_agent' not in self . _inner_api_calls :
self . _inner_api_calls [ 'import_agent' ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . import_agent , default_retry = self . _method_configs [ 'ImportAgent' ] . retry , defa... |
def create_dialog_node ( self , workspace_id , dialog_node , description = None , conditions = None , parent = None , previous_sibling = None , output = None , context = None , metadata = None , next_step = None , title = None , node_type = None , event_name = None , variable = None , actions = None , digress_in = None... | if workspace_id is None :
raise ValueError ( 'workspace_id must be provided' )
if dialog_node is None :
raise ValueError ( 'dialog_node must be provided' )
if output is not None :
output = self . _convert_model ( output , DialogNodeOutput )
if next_step is not None :
next_step = self . _convert_model ( ... |
def get_output ( self , include_exceptions = False ) :
"""Return the output in the correct ordering .
: rtype : list [ Tuple [ contentitem , O ] ]""" | # Order all rendered items in the correct sequence .
# Don ' t assume the derived tables are in perfect shape , hence the dict + KeyError handling .
# The derived tables could be truncated / reset or store _ output ( ) could be omitted .
ordered_output = [ ]
for item_id in self . output_ordering :
contentitem = sel... |
def _parse_results ( self , raw_results , includes_qualifiers ) :
"""Parse WMI query results in a more comprehensive form .
Returns : List of WMI objects
' freemegabytes ' : 19742.0,
' name ' : ' C : ' ,
' avgdiskbytesperwrite ' : 1536.0
' freemegabytes ' : 19742.0,
' name ' : ' D : ' ,
' avgdiskbytes... | results = [ ]
for res in raw_results : # Ensure all properties are available . Use case - insensitivity
# because some properties are returned with different cases .
item = CaseInsensitiveDict ( )
for prop_name in self . property_names :
item [ prop_name ] = None
for wmi_property in res . Properties... |
def join_group_with_token ( self , group_hashtag , group_jid , join_token ) :
"""Tries to join into a specific group , using a cryptographic token that was received earlier from a search
: param group _ hashtag : The public hashtag of the group into which to join ( like ' # Music ' )
: param group _ jid : The J... | log . info ( "[+] Trying to join the group '{}' with JID {}" . format ( group_hashtag , group_jid ) )
return self . _send_xmpp_element ( roster . GroupJoinRequest ( group_hashtag , join_token , group_jid ) ) |
def __json_strnum_to_bignum ( json_object ) :
"""Converts json string numerals to native python bignums .""" | for key in ( 'id' , 'week' , 'in_reply_to_id' , 'in_reply_to_account_id' , 'logins' , 'registrations' , 'statuses' ) :
if ( key in json_object and isinstance ( json_object [ key ] , six . text_type ) ) :
try :
json_object [ key ] = int ( json_object [ key ] )
except ValueError :
... |
def set_swimlane ( self , value ) :
"""Store record ids in separate location for later use , but ignore initial value""" | # Move single record into list to be handled the same by cursor class
if not self . multiselect :
if value and not isinstance ( value , list ) :
value = [ value ]
# Values come in as a list of record ids or None
value = value or [ ]
records = SortedDict ( )
for record_id in value :
records [ record_id ]... |
def fstat_sig ( self ) :
"""p - value of the F - statistic .""" | return 1.0 - scs . f . cdf ( self . fstat , self . df_reg , self . df_err ) |
def get_path ( self , origX , origY , destX , destY ) :
"""Get the shortest path from origXY to destXY .
Returns :
List [ Tuple [ int , int ] ] : Returns a list walking the path from orig
to dest .
This excludes the starting point and includes the destination .
If no path is found then an empty list is re... | return super ( AStar , self ) . get_path ( origX , origY , destX , destY ) |
def is_call ( self , call ) :
"""Locate genotypes with a given call .
Parameters
call : array _ like , int , shape ( ploidy , )
The genotype call to find .
Returns
out : ndarray , bool , shape ( n _ variants , n _ samples )
Array where elements are True if the genotype is ` call ` .
Examples
> > > i... | # guard conditions
if not len ( call ) == self . shape [ - 1 ] :
raise ValueError ( 'invalid call ploidy: %s' , repr ( call ) )
if self . ndim == 2 :
call = np . asarray ( call ) [ np . newaxis , : ]
else :
call = np . asarray ( call ) [ np . newaxis , np . newaxis , : ]
out = np . all ( self . values == ca... |
def item_selection_changed ( self ) :
"""List widget item selection change handler .""" | row = self . current_row ( )
if self . count ( ) and row >= 0 :
if '</b></big><br>' in self . list . currentItem ( ) . text ( ) and row == 0 :
self . next_row ( )
if self . mode == self . FILE_MODE :
try :
stack_index = self . paths . index ( self . filtered_path [ row ] )
... |
def manage_git_folder ( gh_token , temp_dir , git_id , * , pr_number = None ) :
"""Context manager to avoid readonly problem while cleanup the temp dir .
If PR number is given , use magic branches " pull " from Github .""" | _LOGGER . debug ( "Git ID %s" , git_id )
if Path ( git_id ) . exists ( ) :
yield git_id
return
# Do not erase a local folder , just skip here
# Clone the specific branch
split_git_id = git_id . split ( "@" )
branch = split_git_id [ 1 ] if len ( split_git_id ) > 1 else None
clone_to_path ( gh_token , temp_dir , ... |
def canonicalize ( assess_id ) :
"""Takes an assessment / question ' s ID and canonicalizeicalizes it across iterations of
a course .""" | hash_regex = re . compile ( r'\w{32}' )
lines = assess_id . split ( '\n' )
canon_lines = [ ]
parsing_code = False
for line in lines :
line = line . strip ( )
if not parsing_code and len ( line ) > 0 :
for prompt in DICT_PROMPT_TO_CHARACTER :
if line . startswith ( prompt ) :
... |
def validateMembership ( likelihood , p , mc_source_id = 1 ) :
"""Plot membership probabilities and MC source ids together .""" | cut_mc_source_id = ( likelihood . catalog . mc_source_id == mc_source_id )
# Spatial
projector = ugali . utils . projector . Projector ( likelihood . kernel . lon , likelihood . kernel . lat )
x , y = projector . sphereToImage ( likelihood . catalog . lon , likelihood . catalog . lat )
pylab . figure ( )
pylab . scatte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.