signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def json_response_schema ( expected_object_schema ) :
"""Make a schema for a " standard " server response .
Standard server responses have ' status ' : True
and possibly ' indexing ' : True set .""" | schema = { 'type' : 'object' , 'properties' : { 'status' : { 'type' : 'boolean' , } , 'indexing' : { 'type' : 'boolean' , } , 'lastblock' : { 'anyOf' : [ { 'type' : 'integer' , 'minimum' : 0 , } , { 'type' : 'null' , } , ] , } , } , 'required' : [ 'status' , 'indexing' , 'lastblock' ] , }
# fold in the given object sch... |
def mousePressEvent ( self , event ) :
"""Selects all the text if the property is set after this widget
first gains focus .
: param event | < QMouseEvent >""" | super ( XLineEdit , self ) . mousePressEvent ( event )
if self . _focusedIn and self . selectAllOnFocus ( ) :
self . selectAll ( )
self . _focusedIn = False |
def to_string ( cls , error_code ) :
"""Returns the string message for the given ` ` error _ code ` ` .
Args :
cls ( JLinkEraseErrors ) : the ` ` JLinkEraseErrors ` ` class
error _ code ( int ) : error code to convert
Returns :
An error string corresponding to the error code .
Raises :
ValueError : if... | if error_code == cls . ILLEGAL_COMMAND :
return 'Failed to erase sector.'
return super ( JLinkEraseErrors , cls ) . to_string ( error_code ) |
def is_base_form ( self , univ_pos , morphology = None ) :
"""Check whether we ' re dealing with an uninflected paradigm , so we can
avoid lemmatization entirely .""" | morphology = { } if morphology is None else morphology
others = [ key for key in morphology if key not in ( POS , 'Number' , 'POS' , 'VerbForm' , 'Tense' ) ]
if univ_pos == 'noun' and morphology . get ( 'Number' ) == 'sing' :
return True
elif univ_pos == 'verb' and morphology . get ( 'VerbForm' ) == 'inf' :
ret... |
def read_data_event ( self , whence , complete = False , can_flush = False ) :
"""Creates a transition to a co - routine for retrieving data as bytes .
Args :
whence ( Coroutine ) : The co - routine to return to after the data is satisfied .
complete ( Optional [ bool ] ) : True if STREAM _ END should be emit... | return Transition ( None , _read_data_handler ( whence , self , complete , can_flush ) ) |
def make_force ( q_vars , mass ) :
"""Fluxion with the potential energy of the eight planets sytem""" | # Number of bodies
B : int = len ( mass )
# Build the potential energy fluxion by iterating over distinct pairs of bodies
U = fl . Const ( 0.0 )
for i in range ( B ) :
for j in range ( i + 1 , B ) :
U += U_ij ( q_vars , mass , i , j )
# Varname arrays for both the coordinate system and U
vn_q = np . array (... |
def hash64 ( data : Any , seed : int = 0 ) -> int :
"""Non - cryptographic , deterministic , fast hash .
Args :
data : data to hash
seed : seed
Returns :
signed 64 - bit integer""" | # MurmurHash3
c_data = to_str ( data )
if mmh3 :
c_signed_low , _ = mmh3 . hash64 ( data , seed = seed , x64arch = IS_64_BIT )
return c_signed_low
py_data = to_bytes ( c_data )
py_signed_low , _ = pymmh3_hash64 ( py_data , seed = seed )
return py_signed_low |
def deleted ( self , base : pathlib . PurePath = pathlib . PurePath ( ) , include_children : bool = True , include_directories : bool = True ) -> Iterator [ str ] :
"""Find the paths of entities deleted between the left and right entities
in this comparison .
: param base : The base directory to recursively app... | if self . is_deleted :
yield str ( base / self . left . name ) |
def recv ( self , picture , * args ) :
"""Receive a ' picture ' message to the socket ( or actor ) . See zsock _ send for
the format and meaning of the picture . Returns the picture elements into
a series of pointers as provided by the caller :
i = int * ( stores signed integer )
4 = uint32 _ t * ( stores 3... | return lib . zsock_recv ( self . _as_parameter_ , picture , * args ) |
def get_dataframe_from_data ( data ) :
"""Parameters
data : string or pandas dataframe .
If string , data should be an absolute or relative path to a CSV file
containing the long format data for this choice model . Note long format
has one row per available alternative for each observation . If pandas
dat... | if isinstance ( data , str ) :
if data . endswith ( ".csv" ) :
dataframe = pd . read_csv ( data )
else :
msg_1 = "data = {} is of unknown file type."
msg_2 = " Please pass path to csv."
raise ValueError ( msg_1 . format ( data ) + msg_2 )
elif isinstance ( data , pd . DataFrame )... |
def next ( self ) :
"""Return the next service
self . current ( ) will continue to return that service until the
next call to this method .""" | try :
self . _current = self . services . pop ( 0 )
except IndexError :
raise StopIteration
else :
return self . _current |
def make_grid ( image_batch ) :
"""Turns a batch of images into one big image .
: param image _ batch : ndarray , shape ( batch _ size , rows , cols , channels )
: returns : a big image containing all ` batch _ size ` images in a grid""" | m , ir , ic , ch = image_batch . shape
pad = 3
padded = np . zeros ( ( m , ir + pad * 2 , ic + pad * 2 , ch ) )
padded [ : , pad : - pad , pad : - pad , : ] = image_batch
m , ir , ic , ch = padded . shape
pr = int ( np . sqrt ( m ) )
pc = int ( np . ceil ( float ( m ) / pr ) )
extra_m = pr * pc
assert extra_m > m
padde... |
def get_packages ( self , offset = None , limit = None , api = None ) :
"""Return list of packages that belong to this automation
: param offset : Pagination offset .
: param limit : Pagination limit .
: param api : sevenbridges Api instance .
: return : AutomationPackage collection""" | api = api or self . _API
return AutomationPackage . query ( automation = self . id , offset = offset , limit = limit , api = api ) |
def multiindex_from_product_levels ( levels : Sequence [ pd . Index ] , names : Optional [ Sequence [ str ] ] = None ) -> pd . MultiIndex :
"""Creating a MultiIndex from a product without refactorizing levels .
Keeping levels the same gives back the original labels when we unstack .
Parameters
levels : sequen... | if any ( not isinstance ( lev , pd . Index ) for lev in levels ) :
raise TypeError ( 'levels must be a list of pd.Index objects' )
split_labels , levels = zip ( * [ lev . factorize ( ) for lev in levels ] )
labels_mesh = np . meshgrid ( * split_labels , indexing = 'ij' )
labels = [ x . ravel ( ) for x in labels_mes... |
def squared_distance ( self , other ) :
"""Squared distance from a SparseVector or 1 - dimensional NumPy array .
> > > a = SparseVector ( 4 , [ 1 , 3 ] , [ 3.0 , 4.0 ] )
> > > a . squared _ distance ( a )
0.0
> > > a . squared _ distance ( array . array ( ' d ' , [ 1 . , 2 . , 3 . , 4 . ] ) )
11.0
> > >... | assert len ( self ) == _vector_size ( other ) , "dimension mismatch"
if isinstance ( other , np . ndarray ) or isinstance ( other , DenseVector ) :
if isinstance ( other , np . ndarray ) and other . ndim != 1 :
raise Exception ( "Cannot call squared_distance with %d-dimensional array" % other . ndim )
i... |
def ad_stat ( data ) :
"""Calculates the Anderson - Darling statistic for sorted values from U ( 0 , 1 ) .
The statistic is not defined if any of the values is exactly 0 or 1 . You
will get infinity as a result and a divide - by - zero warning for such values .
The warning can be silenced or raised using nump... | samples = len ( data )
factors = arange ( 1 , 2 * samples , 2 )
return - samples - ( factors * log ( data * ( 1 - data [ : : - 1 ] ) ) ) . sum ( ) / samples |
def destroy_droplet ( self , droplet_id , scrub_data = False ) :
"""This method destroys one of your droplets - this is irreversible .
Required parameters :
droplet _ id :
Numeric , this is the id of your droplet that you want to destroy
Optional parameters
scrub _ data :
Boolean , this will strictly wr... | params = { }
if scrub_data :
params [ 'scrub_data' ] = True
json = self . request ( '/droplets/%s/destroy' % droplet_id , method = 'GET' , params = params )
status = json . get ( 'status' )
if status == 'OK' :
return json . get ( 'event_id' )
else :
message = json . get ( 'message' )
raise DOPException ... |
def rl_dashes ( x ) :
"""Replace dash to long / medium dashes""" | patterns = ( # тире
( re . compile ( u'(^|(.\\s))\\-\\-?(([\\s\u202f].)|$)' , re . MULTILINE | re . UNICODE ) , u'\\1\u2014\\3' ) , # диапазоны между цифрами - en dash
( re . compile ( u'(\\d[\\s\u2009]*)\\-([\\s\u2009]*\d)' , re . MULTILINE | re . UNICODE ) , u'\\1\u2013\\2' ) , # TODO : а что с минусом ?
)
return _su... |
def _get_channels ( self ) :
"""获取channel列表""" | self . _channel_list = [ # { ' name ' : ' 红心兆赫 ' , ' channel _ id ' : - 3 } ,
{ 'name' : '我的私人兆赫' , 'channel_id' : 0 } , { 'name' : '每日私人歌单' , 'channel_id' : - 2 } , { 'name' : '豆瓣精选兆赫' , 'channel_id' : - 10 } , # 心情 / 场景
{ 'name' : '工作学习' , 'channel_id' : 153 } , { 'name' : '户外' , 'channel_id' : 151 } , { 'name' : '休息... |
def create_vm ( vm_name , cpu , memory , image , version , datacenter , datastore , placement , interfaces , disks , scsi_devices , serial_ports = None , ide_controllers = None , sata_controllers = None , cd_drives = None , advanced_configs = None , service_instance = None ) :
'''Creates a virtual machine container... | # If datacenter is specified , set the container reference to start search
# from it instead
container_object = salt . utils . vmware . get_datacenter ( service_instance , datacenter )
( resourcepool_object , placement_object ) = salt . utils . vmware . get_placement ( service_instance , datacenter , placement = placem... |
def tupleize_version ( version ) :
"""Split ` ` version ` ` into a lexicographically comparable tuple .
"1.0.3 " - > ( ( 1 , 0 , 3 ) , )
"1.0.3 - dev " - > ( ( 1 , 0 , 3 ) , ( " dev " , ) )
"1.0.3 - rc - 5 " - > ( ( 1 , 0 , 3 ) , ( " rc " , ) , ( 5 , ) )""" | if version is None :
return ( ( "unknown" , ) , )
if version . startswith ( "<unknown" ) :
return ( ( "unknown" , ) , )
split = re . split ( "(?:\.|(-))" , version )
parsed = tuple ( try_fix_num ( x ) for x in split if x )
# Put the tuples in groups by " - "
def is_dash ( s ) :
return s == "-"
grouped = gro... |
def _build_likelihood ( self ) :
r"""Construct a tf function to compute the likelihood of a general GP
model .
\ log p ( Y , V | theta ) .""" | K = self . kern . K ( self . X )
L = tf . cholesky ( K + tf . eye ( tf . shape ( self . X ) [ 0 ] , dtype = settings . float_type ) * settings . numerics . jitter_level )
F = tf . matmul ( L , self . V ) + self . mean_function ( self . X )
return tf . reduce_sum ( self . likelihood . logp ( F , self . Y ) ) |
def function_name ( self ) :
"""Returns name of the function to invoke . If no function identifier is provided , this method will return name of
the only function from the template
: return string : Name of the function
: raises InvokeContextException : If function identifier is not provided""" | if self . _function_identifier :
return self . _function_identifier
# Function Identifier is * not * provided . If there is only one function in the template ,
# default to it .
all_functions = [ f for f in self . _function_provider . get_all ( ) ]
if len ( all_functions ) == 1 :
return all_functions [ 0 ] . na... |
def rts_smoother ( Xs , Ps , Fs , Qs ) :
"""Runs the Rauch - Tung - Striebal Kalman smoother on a set of
means and covariances computed by a Kalman filter . The usual input
would come from the output of ` KalmanFilter . batch _ filter ( ) ` .
Parameters
Xs : numpy . array
array of the means ( state variab... | if len ( Xs ) != len ( Ps ) :
raise ValueError ( 'length of Xs and Ps must be the same' )
n = Xs . shape [ 0 ]
dim_x = Xs . shape [ 1 ]
# smoother gain
K = zeros ( ( n , dim_x , dim_x ) )
x , P , pP = Xs . copy ( ) , Ps . copy ( ) , Ps . copy ( )
for k in range ( n - 2 , - 1 , - 1 ) :
pP [ k ] = dot ( dot ( Fs ... |
def learn ( self , matches , recall ) :
'''Takes in a set of training pairs and predicates and tries to find
a good set of blocking rules .''' | compound_length = 2
dupe_cover = Cover ( self . blocker . predicates , matches )
dupe_cover . dominators ( cost = self . total_cover )
dupe_cover . compound ( compound_length )
comparison_count = self . comparisons ( dupe_cover , compound_length )
dupe_cover . dominators ( cost = comparison_count , comparison = True )
... |
def append ( self , value ) :
"""Appends an item to the list . Similar to list . append ( ) .""" | self . _values . append ( self . _type_checker . CheckValue ( value ) )
if not self . _message_listener . dirty :
self . _message_listener . Modified ( ) |
def css ( self , * props , ** kwprops ) :
"""Adds css properties to this element .""" | self . _stable = False
styles = { }
if props :
if len ( props ) == 1 and isinstance ( props [ 0 ] , Mapping ) :
styles = props [ 0 ]
else :
raise WrongContentError ( self , props , "Arguments not valid" )
elif kwprops :
styles = kwprops
else :
raise WrongContentError ( self , None , "arg... |
def add_file ( self , path , yaml ) :
"""Adds given file to the file index""" | if is_job_config ( yaml ) :
name = self . get_job_name ( yaml )
file_data = FileData ( path = path , yaml = yaml )
self . files [ path ] = file_data
self . jobs [ name ] = file_data
else :
self . files [ path ] = FileData ( path = path , yaml = yaml ) |
def open_grpc_channel ( endpoint ) :
"""open grpc channel :
- for http : / / we open insecure _ channel
- for https : / / we open secure _ channel ( with default credentials )
- without prefix we open insecure _ channel""" | if ( endpoint . startswith ( "https://" ) ) :
return grpc . secure_channel ( remove_http_https_prefix ( endpoint ) , grpc . ssl_channel_credentials ( ) )
return grpc . insecure_channel ( remove_http_https_prefix ( endpoint ) ) |
def plot_scalar ( step , var , field = None , axis = None , set_cbar = True , ** extra ) :
"""Plot scalar field .
Args :
step ( : class : ` ~ stagpy . stagyydata . _ Step ` ) : a step of a StagyyData
instance .
var ( str ) : the scalar field name .
field ( : class : ` numpy . array ` ) : if not None , it ... | if var in phyvars . FIELD :
meta = phyvars . FIELD [ var ]
else :
meta = phyvars . FIELD_EXTRA [ var ]
meta = phyvars . Varf ( misc . baredoc ( meta . description ) , meta . dim )
if step . geom . threed :
raise NotAvailableError ( 'plot_scalar only implemented for 2D fields' )
xmesh , ymesh , fld = get... |
def to_sif ( graph , output_path ) :
"""Generates Simple Interaction Format output file from provided graph .
The SIF specification is described
` here < http : / / wiki . cytoscape . org / Cytoscape _ User _ Manual / Network _ Formats > ` _ .
: func : ` . to _ sif ` will generate a . sif file describing the ... | warnings . warn ( "Removed in 0.8. Use write_csv instead." , DeprecationWarning )
graph = _strip_list_attributes ( graph )
if output_path [ - 4 : ] == ".sif" :
output_path = output_path [ : - 4 ]
if nx . number_of_nodes ( graph ) == 0 : # write an empty file ( for a non - existant graph )
f = open ( output_path... |
def binary_operation_comparison ( self , rule , left , right , ** kwargs ) :
"""Implementation of : py : func : ` pynspect . traversers . RuleTreeTraverser . binary _ operation _ comparison ` interface .""" | return self . evaluate_binop_comparison ( rule . operation , left , right , ** kwargs ) |
def _fix_port_assignment ( self ) :
"""The : attr : ` port ` attribute can be set either by name or by its numeric
value . This method attempt to fix the semantics of name / number as its
extremely convenient .""" | port_name = ''
port_number = None
if self . _port :
if isinstance ( self . _port , int ) :
port_number = self . _port
port_name = get_port_name ( port_number )
elif isinstance ( self . _port , string_types ) :
port_name = self . _port
port_number = get_port_number ( port_name )
... |
def ed25519_private_key_to_string ( key ) :
"""Convert an ed25519 private key to a base64 - encoded string .
Args :
key ( Ed25519PrivateKey ) : the key to write to the file .
Returns :
str : the key representation as a str""" | return base64 . b64encode ( key . private_bytes ( encoding = serialization . Encoding . Raw , format = serialization . PrivateFormat . Raw , encryption_algorithm = serialization . NoEncryption ( ) ) , None ) . decode ( 'utf-8' ) |
def trigger ( self , events , * args , ** kwargs ) :
"""Fires the given * events * ( string or list of strings ) . All callbacks
associated with these * events * will be called and if their respective
objects have a * times * value set it will be used to determine when to
remove the associated callback from t... | # Make sure our _ on _ off _ events dict is present ( if first invokation )
if not hasattr ( self , '_on_off_events' ) :
self . _on_off_events = { }
if not hasattr ( self , 'exc_info' ) :
self . exc_info = None
logging . debug ( "OnOffMixin triggering event(s): %s" % events )
if isinstance ( events , ( str , un... |
def clone ( self , user , repo , branch = None , rw = True ) :
'''Clones a new repository
: param user : namespace of the repository
: param repo : name slug of the repository
: Param branch : branch to pull as tracking
This command is fairly simple , and pretty close to the real ` git clone `
command , e... | log . info ( 'Cloning {}…' . format ( repo ) )
project = self . get_repository ( user , repo )
if not branch :
branch = self . get_project_default_branch ( project )
is_empty = self . is_repository_empty ( project )
if is_empty :
self . repository . init ( )
else :
url = self . get_parent_project_url ( user... |
def potential ( self , x , y , kwargs , k = None ) :
"""lensing potential
: param x : x - position ( preferentially arcsec )
: type x : numpy array
: param y : y - position ( preferentially arcsec )
: type y : numpy array
: param kwargs : list of keyword arguments of lens model parameters matching the len... | x = np . array ( x , dtype = float )
y = np . array ( y , dtype = float )
bool_list = self . _bool_list ( k )
x_ , y_ , kwargs_copy = self . _update_foreground ( x , y , kwargs )
potential = np . zeros_like ( x )
for i , func in enumerate ( self . func_list ) :
if bool_list [ i ] is True :
if self . _model_... |
def update ( self , instance ) :
"""this is an upsert method : replaces or creates the DB representation of the model instance""" | assert isinstance ( instance , self . model_klass )
if instance . db_id :
query = { '_id' : ObjectId ( instance . db_id ) }
else :
query = build_db_query ( self . primary_key , instance . key )
self . ds . update ( self . collection_name , query , instance )
return instance . db_id |
def from_ ( self , table , alias = None ) :
"""Establece el origen de datos ( y un alias opcionalmente ) .""" | if isinstance ( table , str ) :
table = [ [ table , alias ] ]
self . raw_tables = table
return self |
def _set_authentication_key ( self , v , load = False ) :
"""Setter method for authentication _ key , mapped from YANG variable / ntp / authentication _ key ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ authentication _ key is considered as a private
method... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "keyid" , authentication_key . authentication_key , yang_name = "authentication-key" , rest_name = "authentication-key" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _pat... |
def execute_cql_query ( self , query , compression ) :
"""Executes a CQL ( Cassandra Query Language ) statement and returns a
CqlResult containing the results .
Parameters :
- query
- compression""" | self . _seqid += 1
d = self . _reqs [ self . _seqid ] = defer . Deferred ( )
self . send_execute_cql_query ( query , compression )
return d |
def get_mac_address_table_input_request_type_get_interface_based_request_forwarding_interface_interface_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_mac_address_table = ET . Element ( "get_mac_address_table" )
config = get_mac_address_table
input = ET . SubElement ( get_mac_address_table , "input" )
request_type = ET . SubElement ( input , "request-type" )
get_interface_based_request = ET . SubElement ( request_type , "get-int... |
def temp_directory ( * args , ** kwargs ) :
"""Context manager returns a path created by mkdtemp and cleans it up afterwards .""" | path = tempfile . mkdtemp ( * args , ** kwargs )
try :
yield path
finally :
shutil . rmtree ( path ) |
def lmpool ( cvals ) :
"""Load the variables contained in an internal buffer into the
kernel pool .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / lmpool _ c . html
: param cvals : list of strings .
: type cvals : list of str""" | lenvals = ctypes . c_int ( len ( max ( cvals , key = len ) ) + 1 )
n = ctypes . c_int ( len ( cvals ) )
cvals = stypes . listToCharArrayPtr ( cvals , xLen = lenvals , yLen = n )
libspice . lmpool_c ( cvals , lenvals , n ) |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : BuildContext for this BuildInstance
: rtype : twilio . rest . serverless . v1 . service . build . BuildContext""" | if self . _context is None :
self . _context = BuildContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = self . _solution [ 'sid' ] , )
return self . _context |
def p_elif_clause ( p ) :
'''elif _ clause : ELIF compound _ list THEN compound _ list
| ELIF compound _ list THEN compound _ list ELSE compound _ list
| ELIF compound _ list THEN compound _ list elif _ clause''' | parts = [ ]
for i in range ( 1 , len ( p ) ) :
if isinstance ( p [ i ] , ast . node ) :
parts . append ( p [ i ] )
else :
parts . append ( ast . node ( kind = 'reservedword' , word = p [ i ] , pos = p . lexspan ( i ) ) )
p [ 0 ] = parts |
def _inject_synthetic_target ( self , vt , sources ) :
"""Create , inject , and return a synthetic target for the given target and workdir .
: param vt : A codegen input VersionedTarget to inject a synthetic target for .
: param sources : A FilesetWithSpec to inject for the target .""" | target = vt . target
# NB : For stability , the injected target exposes the stable - symlinked ` vt . results _ dir ` ,
# rather than the hash - named ` vt . current _ results _ dir ` .
synthetic_target_dir = self . synthetic_target_dir ( target , vt . results_dir )
synthetic_target_type = self . synthetic_target_type ... |
def save_state ( self ) :
"""Save state of the system to a dump file : attr : ` System . filename `""" | if not self . filename :
self . logger . error ( 'Filename not specified. Could not save state' )
return
self . logger . debug ( 'Saving system state to %s' , self . filename )
for i in reversed ( range ( self . num_state_backups ) ) :
fname = self . filename if i == 0 else '%s.%d' % ( self . filename , i )... |
def _factorize_from_iterable ( values ) :
"""Factorize an input ` values ` into ` categories ` and ` codes ` . Preserves
categorical dtype in ` categories ` .
* This is an internal function *
Parameters
values : list - like
Returns
codes : ndarray
categories : Index
If ` values ` has a categorical d... | from pandas . core . indexes . category import CategoricalIndex
if not is_list_like ( values ) :
raise TypeError ( "Input must be list-like" )
if is_categorical ( values ) :
if isinstance ( values , ( ABCCategoricalIndex , ABCSeries ) ) :
values = values . _values
categories = CategoricalIndex ( val... |
def add_hook ( self , key_name , hook_name , hook_dict ) :
"""Add hook to the keyframe key _ name .""" | kf = self . dct [ key_name ]
if 'hooks' not in kf :
kf [ 'hooks' ] = { }
kf [ 'hooks' ] [ str ( hook_name ) ] = hook_dict |
def _element_append_path ( start_element , # type : ET . Element
element_names # type : Iterable [ Text ]
) : # type : ( . . . ) - > ET . Element
"""Append the list of element names as a path to the provided start element .
: return : The final element along the path .""" | end_element = start_element
for element_name in element_names :
new_element = ET . Element ( element_name )
end_element . append ( new_element )
end_element = new_element
return end_element |
def _is_compact_jws ( self , jws ) :
"""Check if we ' ve got a compact signed JWT
: param jws : The message
: return : True / False""" | try :
jwt = JWSig ( ) . unpack ( jws )
except Exception as err :
logger . warning ( 'Could not parse JWS: {}' . format ( err ) )
return False
if "alg" not in jwt . headers :
return False
if jwt . headers [ "alg" ] is None :
jwt . headers [ "alg" ] = "none"
if jwt . headers [ "alg" ] not in SIGNER_AL... |
def render_uploads ( content , template_path = "adminfiles/render/" ) :
"""Replace all uploaded file references in a content string with the
results of rendering a template found under ` ` template _ path ` ` with
the ` ` FileUpload ` ` instance and the key = value options found in the
file reference .
So i... | def _replace ( match ) :
upload , options = parse_match ( match )
return render_upload ( upload , template_path , ** options )
return oembed_replace ( substitute_uploads ( content , _replace ) ) |
def flatten_list ( multiply_list ) :
"""碾平 list : :
> > > a = [ 1 , 2 , [ 3 , 4 ] , [ [ 5 , 6 ] , [ 7 , 8 ] ] ]
> > > flatten _ list ( a )
[1 , 2 , 3 , 4 , 5 , 6 , 7 , 8]
: param multiply _ list : 混淆的多层列表
: return : 单层的 list""" | if isinstance ( multiply_list , list ) :
return [ rv for l in multiply_list for rv in flatten_list ( l ) ]
else :
return [ multiply_list ] |
def plot_sim ( ax , cell , synapse , grid_electrode , point_electrode , letter = 'a' ) :
'''create a plot''' | fig = plt . figure ( figsize = ( 3.27 * 2 / 3 , 3.27 * 2 / 3 ) )
ax = fig . add_axes ( [ .1 , .05 , .9 , .9 ] , aspect = 'equal' , frameon = False )
phlp . annotate_subplot ( ax , ncols = 1 , nrows = 1 , letter = letter , fontsize = 16 )
cax = fig . add_axes ( [ 0.8 , 0.2 , 0.02 , 0.2 ] , frameon = False )
LFP = np . m... |
def pot_to_rpole_aligned ( pot , sma , q , F , d , component = 1 ) :
"""Transforms surface potential to polar radius""" | q = q_for_component ( q , component = component )
Phi = pot_for_component ( pot , q , component = component )
logger . debug ( "libphobe.roche_pole(q={}, F={}, d={}, Omega={})" . format ( q , F , d , pot ) )
return libphoebe . roche_pole ( q , F , d , pot ) * sma |
def add_profiler ( self , id , profiler ) :
"""Add a profiler for RDD ` id `""" | if not self . profilers :
if self . profile_dump_path :
atexit . register ( self . dump_profiles , self . profile_dump_path )
else :
atexit . register ( self . show_profiles )
self . profilers . append ( [ id , profiler , False ] ) |
def _connect_func ( builder , obj , signal_name , handler_name , connect_object , flags , cls ) :
'''Handles GtkBuilder signal connect events''' | if connect_object is None :
extra = ( )
else :
extra = ( connect_object , )
# The handler name refers to an attribute on the template instance ,
# so ask GtkBuilder for the template instance
template_inst = builder . get_object ( cls . __gtype_name__ )
if template_inst is None : # This should never happen
e... |
def get_vertices ( self , indexed = None ) :
"""Get the vertices
Parameters
indexed : str | None
If Note , return an array ( N , 3 ) of the positions of vertices in
the mesh . By default , each unique vertex appears only once .
If indexed is ' faces ' , then the array will instead contain three
vertices... | if indexed is None :
if ( self . _vertices is None and self . _vertices_indexed_by_faces is not None ) :
self . _compute_unindexed_vertices ( )
return self . _vertices
elif indexed == 'faces' :
if ( self . _vertices_indexed_by_faces is None and self . _vertices is not None ) :
self . _vertic... |
def rotation_matrix ( phi , theta , psi ) :
"""Retourne la matrice de rotation décrite par les angles d ' Euler donnés en paramètres""" | return np . dot ( Rz_matrix ( phi ) , np . dot ( Rx_matrix ( theta ) , Rz_matrix ( psi ) ) ) |
def get_attributes ( user , service ) :
"""Return a dictionary of user attributes from the set of configured
callback functions .""" | attributes = { }
for path in get_callbacks ( service ) :
callback = import_string ( path )
attributes . update ( callback ( user , service ) )
return attributes |
def create_parser ( ) :
"""Return command - line parser .""" | parser = argparse . ArgumentParser ( description = docstring_summary ( __doc__ ) , prog = 'autopep8' )
parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s {} ({})' . format ( __version__ , _get_package_version ( ) ) )
parser . add_argument ( '-v' , '--verbose' , action = 'count' , default = 0... |
def matrix_iter_detail ( matrix , version , scale = 1 , border = None ) :
"""Returns an iterator / generator over the provided matrix which includes
the border and the scaling factor .
This iterator / generator returns different values for dark / light modules
and therefor the different parts ( like the finde... | from segno import encoder
check_valid_border ( border )
scale = int ( scale )
check_valid_scale ( scale )
border = get_border ( version , border )
width , height = get_symbol_size ( version , scale = 1 , border = 0 )
is_micro = version < 1
# Create an empty matrix with invalid 0x2 values
alignment_matrix = encoder . ma... |
def simulate ( self , partition , outdir , jobhandler = default_jobhandler , batchsize = 1 , ** kwargs ) :
"""Simulate a set of alignments from the parameters inferred on a partition
: param partition :
: return :""" | results = self . get_partition_results ( partition )
DEFAULT_DNA_MODEL = 'GTR'
DEFAULT_PROTEIN_MODEL = 'LG08'
# Collect argument list
args = [ None ] * len ( self . collection )
for result in results :
if len ( result [ 'partitions' ] ) > 1 :
places = dict ( ( j , i ) for ( i , j ) in enumerate ( rec . name... |
def export ( self , path , epoch = 0 ) :
"""Export HybridBlock to json format that can be loaded by
` SymbolBlock . imports ` , ` mxnet . mod . Module ` or the C + + interface .
. . note : : When there are only one input , it will have name ` data ` . When there
Are more than one inputs , they will be named a... | if not self . _cached_graph :
raise RuntimeError ( "Please first call block.hybridize() and then run forward with " "this block at least once before calling export." )
sym = self . _cached_graph [ 1 ]
sym . save ( '%s-symbol.json' % path )
arg_names = set ( sym . list_arguments ( ) )
aux_names = set ( sym . list_au... |
def update_datatype ( self , datatype , w = None , dw = None , pw = None , return_body = None , timeout = None , include_context = None ) :
"""Sends an update to a Riak Datatype to the server . This operation is not
idempotent and so will not be retried automatically .
: param datatype : the datatype with pendi... | _validate_timeout ( timeout )
with self . _transport ( ) as transport :
return transport . update_datatype ( datatype , w = w , dw = dw , pw = pw , return_body = return_body , timeout = timeout , include_context = include_context ) |
def pydot__tree_to_png ( tree , filename , rankdir = "LR" ) :
"""Creates a colorful image that represents the tree ( data + children , without meta )
Possible values for ` rankdir ` are " TB " , " LR " , " BT " , " RL " , corresponding to
directed graphs drawn from top to bottom , from left to right , from bott... | import pydot
graph = pydot . Dot ( graph_type = 'digraph' , rankdir = rankdir )
i = [ 0 ]
def new_leaf ( leaf ) :
node = pydot . Node ( i [ 0 ] , label = repr ( leaf ) )
i [ 0 ] += 1
graph . add_node ( node )
return node
def _to_pydot ( subtree ) :
color = hash ( subtree . data ) & 0xffffff
colo... |
def disttar ( target , source , env ) :
"""tar archive builder""" | import tarfile
env_dict = env . Dictionary ( )
if env_dict . get ( "DISTTAR_FORMAT" ) in [ "gz" , "bz2" ] :
tar_format = env_dict [ "DISTTAR_FORMAT" ]
else :
tar_format = ""
# split the target directory , filename , and stuffix
base_name = str ( target [ 0 ] ) . split ( '.tar' ) [ 0 ]
( target_dir , dir_name ) ... |
def send_and_return_status ( self , send , expect = None , shutit_pexpect_child = None , timeout = None , fail_on_empty_before = True , record_command = True , exit_values = None , echo = None , escape = False , retry = 3 , note = None , assume_gnu = True , follow_on_commands = None , loglevel = logging . INFO ) :
... | shutit_global . shutit_global_object . yield_to_draw ( )
shutit_pexpect_child = shutit_pexpect_child or self . get_current_shutit_pexpect_session ( ) . pexpect_child
shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child )
shutit_pexpect_session . send ( ShutItSendSpec ( shutit_pex... |
def md5sum ( filen ) :
'''Calculate the md5sum of a file .''' | with open ( filen , 'rb' ) as fileh :
md5 = hashlib . md5 ( fileh . read ( ) )
return md5 . hexdigest ( ) |
def from_dynacRepr ( cls , pynacRepr ) :
"""Construct a ` ` Steerer ` ` instance from the Pynac lattice element""" | f = float ( pynacRepr [ 1 ] [ 0 ] [ 0 ] )
p = 'HV' [ int ( pynacRepr [ 1 ] [ 0 ] [ 1 ] ) ]
return cls ( f , p ) |
def previous_layout ( pymux , variables ) :
"Select previous layout ." | pane = pymux . arrangement . get_active_window ( )
if pane :
pane . select_previous_layout ( ) |
def _DecodeURL ( self , url ) :
"""Decodes the URL , replaces % XX to their corresponding characters .
Args :
url ( str ) : encoded URL .
Returns :
str : decoded URL .""" | if not url :
return ''
decoded_url = urlparse . unquote ( url )
if isinstance ( decoded_url , py2to3 . BYTES_TYPE ) :
try :
decoded_url = decoded_url . decode ( 'utf-8' )
except UnicodeDecodeError as exception :
decoded_url = decoded_url . decode ( 'utf-8' , errors = 'replace' )
logg... |
def remove_time_series ( self , label_values ) :
"""Remove the time series for specific label values .
: type label _ values : list ( : class : ` LabelValue ` )
: param label _ values : Label values of the time series to remove .""" | if label_values is None :
raise ValueError
if any ( lv is None for lv in label_values ) :
raise ValueError
if len ( label_values ) != self . _len_label_keys :
raise ValueError
self . _remove_time_series ( label_values ) |
def set_user_preferences_from_request ( request ) :
"""Sets user subscription preferences using data from a request .
Expects data sent by form built with ` sitemessage _ prefs _ table ` template tag .
: param request :
: rtype : bool
: return : Flag , whether prefs were found in the request .""" | prefs = [ ]
for pref in request . POST . getlist ( _PREF_POST_KEY ) :
message_alias , messenger_alias = pref . split ( _ALIAS_SEP )
try :
get_registered_message_type ( message_alias )
get_registered_messenger_object ( messenger_alias )
except ( UnknownMessengerError , UnknownMessageTypeError... |
def write ( self , message , flush = True ) :
if isinstance ( message , bytes ) : # pragma : no cover
message = message . decode ( 'utf-8' )
"""A Writting like write method , delayed at each char""" | for char in message :
time . sleep ( self . delay * ( 4 if char == '\n' else 1 ) )
super ( Writting , self ) . write ( char , flush ) |
def get_resource_by_agent ( self , agent_id ) :
"""Gets the ` ` Resource ` ` associated with the given agent .
arg : agent _ id ( osid . id . Id ) : ` ` Id ` ` of the ` ` Agent ` `
return : ( osid . resource . Resource ) - associated resource
raise : NotFound - ` ` agent _ id ` ` is not found
raise : NullAr... | collection = JSONClientValidated ( 'resource' , collection = 'Resource' , runtime = self . _runtime )
result = collection . find_one ( dict ( { 'agentIds' : { '$in' : [ str ( agent_id ) ] } } , ** self . _view_filter ( ) ) )
return objects . Resource ( osid_object_map = result , runtime = self . _runtime , proxy = self... |
def locateChild ( self , ctx , segments ) :
"""Attempt to locate the child via the ' . fragment ' attribute , then fall
back to normal locateChild behavior .""" | if self . fragment is not None : # There are still a bunch of bogus subclasses of this class , which
# are used in a variety of distasteful ways . ' fragment ' * should *
# always be set to something that isn ' t None , but there ' s no way to
# make sure that it will be for the moment . Every effort should be
# made t... |
def gcmt_to_simple_array ( self , centroid_location = True ) :
"""Converts the GCMT catalogue to a simple array of
[ ID , year , month , day , hour , minute , second , long . , lat . , depth , Mw ,
strike1 , dip1 , rake1 , strike2 , dip2 , rake2 , b - plunge , b - azimuth ,
b - eigenvalue , p - plunge , p - a... | catalogue = np . zeros ( [ self . get_number_tensors ( ) , 29 ] , dtype = float )
for iloc , tensor in enumerate ( self . gcmts ) :
catalogue [ iloc , 0 ] = iloc
if centroid_location :
catalogue [ iloc , 1 ] = float ( tensor . centroid . date . year )
catalogue [ iloc , 2 ] = float ( tensor . ce... |
def gitignore_template ( self , language ) :
"""Returns the template for language .
: returns : str""" | url = self . _build_url ( 'gitignore' , 'templates' , language )
json = self . _json ( self . _get ( url ) , 200 )
if not json :
return ''
return json . get ( 'source' , '' ) |
def PluginRunToTagToContent ( self , plugin_name ) :
"""Returns a 2 - layer dictionary of the form { run : { tag : content } } .
The ` content ` referred above is the content field of the PluginData proto
for the specified plugin within a Summary . Value proto .
Args :
plugin _ name : The name of the plugin... | mapping = { }
for run in self . Runs ( ) :
try :
tag_to_content = self . GetAccumulator ( run ) . PluginTagToContent ( plugin_name )
except KeyError : # This run lacks content for the plugin . Try the next run .
continue
mapping [ run ] = tag_to_content
return mapping |
def start_background_task ( self , target , * args , ** kwargs ) :
"""Start a background task .
This is a utility function that applications can use to start a
background task .
: param target : the target function to execute .
: param args : arguments to pass to the function .
: param kwargs : keyword ar... | th = threading . Thread ( target = target , args = args , kwargs = kwargs )
th . start ( )
return th |
async def main ( ) :
"""Run .""" | async with ClientSession ( ) as websession :
try : # Create a client :
client = Client ( '<EMAIL>' , '<PASSWORD>' , websession )
await client . async_init ( )
print ( 'Showing active Tiles:' )
print ( await client . tiles . all ( ) )
print ( 'Showing all Tiles:' )
pri... |
def triple ( self ) :
"""This module ' s target " triple " specification , as a string .""" | # LLVMGetTarget ( ) points inside a std : : string managed by LLVM .
with ffi . OutputString ( owned = False ) as outmsg :
ffi . lib . LLVMPY_GetTarget ( self , outmsg )
return str ( outmsg ) |
def get_query_columns ( query ) :
""": type query str
: rtype : list [ str ]""" | columns = [ ]
last_keyword = None
last_token = None
# print ( preprocess _ query ( query ) )
# these keywords should not change the state of a parser
# and not " reset " previously found SELECT keyword
keywords_ignored = [ 'AS' , 'AND' , 'OR' , 'IN' , 'IS' , 'NOT' , 'NOT NULL' , 'LIKE' , 'CASE' , 'WHEN' ]
# these funct... |
def calculate_width_and_height ( url_parts , options ) :
'''Appends width and height information to url''' | width = options . get ( 'width' , 0 )
has_width = width
height = options . get ( 'height' , 0 )
has_height = height
flip = options . get ( 'flip' , False )
flop = options . get ( 'flop' , False )
if flip :
width = width * - 1
if flop :
height = height * - 1
if not has_width and not has_height :
if flip :
... |
def get_current_user_ids ( self , db_read = None ) :
"""Returns current user ids and the count .""" | db_read = db_read or self . db_read
return self . user_ids . using ( db_read ) |
def setProfile ( self , name ) :
"""Assign a PROFILE to this unnamed component .
Used by vCard , not by vCalendar .""" | if self . name or self . useBegin :
if self . name == name :
return
raise VObjectError ( "This component already has a PROFILE or " "uses BEGIN." )
self . name = name . upper ( ) |
def readlinkabs ( l ) :
"""Return an absolute path for the destination
of a symlink""" | assert ( os . path . islink ( l ) )
p = os . readlink ( l )
if os . path . isabs ( p ) :
return os . path . abspath ( p )
return os . path . abspath ( os . path . join ( os . path . dirname ( l ) , p ) ) |
def random_redshift_array ( log , sampleNumber , lowerRedshiftLimit , upperRedshiftLimit , redshiftResolution , pathToOutputPlotDirectory , plot = False ) :
"""* Generate a NumPy array of random distances given a sample number and distance limit *
* * Key Arguments : * *
- ` ` log ` ` - - logger
- ` ` sampleN... | # # # # # # > IMPORTS # # # # #
# # STANDARD LIB # #
# # THIRD PARTY # #
import matplotlib . pyplot as plt
import numpy as np
import numpy . random as npr
# # LOCAL APPLICATION # #
import dryxPython . astrotools as da
redshiftDistribution = np . arange ( 0. , upperRedshiftLimit , redshiftResolution )
closestNumber = la... |
def create_tcp_monitor ( self , topics , batch_size = 1 , batch_duration = 0 , compression = 'gzip' , format_type = 'json' ) :
"""Creates a TCP Monitor instance in Device Cloud for a given list of topics
: param topics : a string list of topics ( e . g . [ ' DeviceCore [ U ] ' ,
' FileDataCore ' ] ) .
: param... | monitor_xml = """\
<Monitor>
<monTopic>{topics}</monTopic>
<monBatchSize>{batch_size}</monBatchSize>
<monFormatType>{format_type}</monFormatType>
<monTransportType>tcp</monTransportType>
<monCompression>{compression}</monCompression>
</Monitor>... |
def _file_details ( filename ) :
"""Grab the start and end of the file""" | max_head , max_foot = _max_lengths ( )
with open ( filename , "rb" ) as fin :
head = fin . read ( max_head )
try :
fin . seek ( - max_foot , os . SEEK_END )
except IOError :
fin . seek ( 0 )
foot = fin . read ( )
return head , foot |
def sign_raw_data ( raw_data , privatekey_hex ) :
"""Sign a string of data .
Returns signature as a base64 string""" | if not isinstance ( raw_data , ( str , unicode ) ) :
raise ValueError ( "Data is not a string" )
raw_data = str ( raw_data )
si = ECSigner ( privatekey_hex )
si . update ( raw_data )
return si . finalize ( ) |
def append_op ( self , operation ) :
"""Append an : class : ` Operation < stellar _ base . operation . Operation > ` to
the list of operations .
Add the operation specified if it doesn ' t already exist in the list of
operations of this : class : ` Builder ` instance .
: param operation : The operation to a... | if operation not in self . ops :
self . ops . append ( operation )
return self |
def __download_from_s3 ( self , key , dest_dir ) :
"""Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory , assumes that the args have been
validated by the public caller methods , and attempts to
download the specified key to the dest... | log = logging . getLogger ( self . cls_logger + '.__download_from_s3' )
filename = key . split ( '/' ) [ - 1 ]
if filename is None :
log . error ( 'Could not determine the filename from key: %s' , key )
return None
destination = dest_dir + '/' + filename
log . info ( 'Attempting to download %s from bucket %s to... |
def write ( self ) :
"""Rewrite the configuration file . It rewrites the same file than
PaperworkConfig . read ( ) read .""" | logger . info ( "Updating %s ..." % self . __configfile )
for setting in self . settings . values ( ) :
setting . update ( self . _configparser )
file_path = self . __configfile
try :
with open ( file_path , 'w' ) as file_descriptor :
self . _configparser . write ( file_descriptor )
logger . info ( ... |
def update_gunicorns ( ) :
"""Updates the dict of gunicorn processes . Run the ps command and parse its
output for processes named after gunicorn , building up a dict of gunicorn
processes . When new gunicorns are discovered , run the netstat command to
determine the ports they ' re serving on .""" | global tick
tick += 1
if ( tick * screen_delay ) % ps_delay != 0 :
return
tick = 0
for pid in gunicorns :
gunicorns [ pid ] . update ( { "workers" : 0 , "mem" : 0 } )
ps = Popen ( PS_ARGS , stdout = PIPE ) . communicate ( ) [ 0 ] . split ( "\n" )
headings = ps . pop ( 0 ) . split ( )
name_col = headings . index... |
def bulk_get ( cls , tasks , api = None ) :
"""Retrieve tasks with specified ids in bulk
: param tasks : Tasks to be retrieved .
: param api : Api instance .
: return : List of TaskBulkRecord objects .""" | api = api or cls . _API
task_ids = [ Transform . to_task ( task ) for task in tasks ]
data = { 'task_ids' : task_ids }
logger . info ( 'Getting tasks in bulk.' )
response = api . post ( url = cls . _URL [ 'bulk_get' ] , data = data )
return TaskBulkRecord . parse_records ( response = response , api = api ) |
def process ( self , metric , handler ) :
"""process a single diamond metric
@ type metric : diamond . metric . Metric
@ param metric : metric to process
@ type handler : diamond . handler . sentry . SentryHandler
@ param handler : configured Sentry graphite handler
@ rtype None""" | match = self . regexp . match ( metric . path )
if match :
minimum = Minimum ( metric . value , self . min )
maximum = Maximum ( metric . value , self . max )
if minimum . is_error or maximum . is_error :
self . counter_errors += 1
message = "%s Warning on %s: %.1f" % ( self . name , handler... |
def create_fileset_with_spec ( cls , rel_path , * patterns , ** kwargs ) :
""": param rel _ path : The relative path to create a FilesetWithSpec for .
: param patterns : glob patterns to apply .
: param exclude : A list of { , r , z } globs objects , strings , or lists of strings to exclude .
NB : this argume... | for pattern in patterns :
if not isinstance ( pattern , string_types ) :
raise ValueError ( "Expected string patterns for {}: got {}" . format ( cls . __name__ , patterns ) )
raw_exclude = kwargs . pop ( 'exclude' , [ ] )
buildroot = get_buildroot ( )
root = os . path . normpath ( os . path . join ( buildro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.