signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_power_factor ( self , output = 'eigs' , doping_levels = True , relaxation_time = 1e-14 ) :
"""Gives the power factor ( Seebeck ^ 2 * conductivity ) in units
microW / ( m * K ^ 2 ) in either a full 3x3 tensor form ,
as 3 eigenvalues , or as the average value ( trace / 3.0 ) If
doping _ levels = True , ... | result = None
result_doping = None
if doping_levels :
result_doping = { doping : { t : [ ] for t in self . _seebeck_doping [ doping ] } for doping in self . _seebeck_doping }
for doping in result_doping :
for t in result_doping [ doping ] :
for i in range ( len ( self . doping [ doping ] ) )... |
def dict_setdiff ( dict_ , negative_keys ) :
r"""returns a copy of dict _ without keys in the negative _ keys list
Args :
dict _ ( dict ) :
negative _ keys ( list ) :""" | keys = [ key for key in six . iterkeys ( dict_ ) if key not in set ( negative_keys ) ]
subdict_ = dict_subset ( dict_ , keys )
return subdict_ |
def post ( self , url , headers = None , ** kwargs ) :
"""Sends a POST request to a URL .
: param url : The URL .
: type url : ` ` string ` `
: param headers : A list of pairs specifying the headers for the HTTP
response ( for example , ` ` [ ( ' Content - Type ' : ' text / cthulhu ' ) , ( ' Token ' : ' bor... | if headers is None :
headers = [ ]
headers . append ( ( "Content-Type" , "application/x-www-form-urlencoded" ) ) ,
# We handle GET - style arguments and an unstructured body . This is here
# to support the receivers / stream endpoint .
if 'body' in kwargs :
body = kwargs . pop ( 'body' )
if len ( kwargs ) >... |
def query_put_bounders ( query , partition_column , start , end ) :
"""Put bounders in the query
Args :
query : SQL query string
partition _ column : partition _ column name
start : lower _ bound
end : upper _ bound
Returns :
Query with bounders""" | where = " WHERE TMP_TABLE.{0} >= {1} AND TMP_TABLE.{0} <= {2}" . format ( partition_column , start , end )
query_with_bounders = "SELECT * FROM ({0}) AS TMP_TABLE {1}" . format ( query , where )
return query_with_bounders |
def _update_usage_plan_apis ( plan_id , apis , op , region = None , key = None , keyid = None , profile = None ) :
'''Helper function that updates the usage plan identified by plan _ id by adding or removing it to each of the stages , specified by apis parameter .
apis
a list of dictionaries , where each dictio... | try :
patchOperations = [ ]
for api in apis :
patchOperations . append ( { 'op' : op , 'path' : '/apiStages' , 'value' : '{0}:{1}' . format ( api [ 'apiId' ] , api [ 'stage' ] ) } )
res = None
if patchOperations :
conn = _get_conn ( region = region , key = key , keyid = keyid , profile =... |
def get_all_zones ( self , zones = None , filters = None ) :
"""Get all Availability Zones associated with the current region .
: type zones : list
: param zones : Optional list of zones . If this list is present ,
only the Zones associated with these zone names
will be returned .
: type filters : dict
... | params = { }
if zones :
self . build_list_params ( params , zones , 'ZoneName' )
if filters :
self . build_filter_params ( params , filters )
return self . get_list ( 'DescribeAvailabilityZones' , params , [ ( 'item' , Zone ) ] , verb = 'POST' ) |
def check_release_files ( package_info , * args ) :
"""Does the package have release files ?
: param package _ info : package _ info dictionary
: return : Tuple ( is the condition True or False ? , reason if it is False else None )""" | reason = "No release files uploaded"
result = False
release_urls = args [ 0 ]
if len ( release_urls ) > 0 :
result = True
return result , reason , HAS_RELEASE_FILES |
def logger ( self ) :
"""Instantiates and returns a ServiceLogger instance""" | if not hasattr ( self , '_logger' ) or not self . _logger :
self . _logger = ServiceLogger ( )
return self . _logger |
def find_or_create_by_name ( self , item_name , items_list , item_type ) :
"""See if item with item _ name exists in item _ list .
If not , create that item .
Either way , return an item of type item _ type .""" | item = self . find_by_name ( item_name , items_list )
if not item :
item = self . data_lists [ item_type ] [ 2 ] ( item_name , None )
return item |
def convert_args ( self , command , args ) :
"""Converts ` ` str - > int ` ` or ` ` register - > int ` ` .""" | for wanted , arg in zip ( command . argtypes ( ) , args ) :
wanted = wanted . type_
if ( wanted == "const" ) :
try :
yield to_int ( arg )
except :
if ( arg in self . processor . constants ) :
yield self . processor . constants [ arg ]
else :
... |
def transformer_moe_layer_v1 ( inputs , output_dim , hparams , train , master_dtype = tf . bfloat16 , slice_dtype = tf . float32 ) :
"""Local mixture of experts that works well on TPU .
Adapted from the paper https : / / arxiv . org / abs / 1701.06538
Note : until the algorithm and inferface solidify , we pass ... | orig_inputs = inputs
input_dim = inputs . shape . dims [ - 1 ]
hidden_dim = mtf . Dimension ( "expert_hidden" , hparams . moe_hidden_size )
experts_dim = mtf . Dimension ( "experts" , hparams . moe_num_experts )
group_size_dim = mtf . Dimension ( "group" , hparams . moe_group_size )
batch_dim = mtf . Dimension ( orig_i... |
def add_nodes ( self , nodes , nesting = 1 ) :
"""Adds edges indicating the call - tree for the procedures listed in
the nodes .""" | hopNodes = set ( )
# nodes in this hop
hopEdges = [ ]
# edges in this hop
# get nodes and edges for this hop
for i , n in zip ( range ( len ( nodes ) ) , nodes ) :
r , g , b = rainbowcolour ( i , len ( nodes ) )
colour = '#%02X%02X%02X' % ( r , g , b )
for p in n . calls :
if p not in hopNodes :
... |
def validate ( self , instance , value ) :
"""Check the class of the container and validate each element
This returns a copy of the container to prevent unwanted sharing of
pointers .""" | if not self . coerce and not isinstance ( value , self . _class_container ) :
self . error ( instance , value )
if self . coerce and not isinstance ( value , CONTAINERS ) :
value = [ value ]
if not isinstance ( value , self . _class_container ) :
out_class = self . _class_container
else :
out_class = va... |
def LightcurveHDU ( model ) :
'''Construct the data HDU file containing the arrays and the observing info .''' | # Get mission cards
cards = model . _mission . HDUCards ( model . meta , hdu = 1 )
# Add EVEREST info
cards . append ( ( 'COMMENT' , '************************' ) )
cards . append ( ( 'COMMENT' , '* EVEREST INFO *' ) )
cards . append ( ( 'COMMENT' , '************************' ) )
cards . append ( ( 'MISSION' , m... |
def default ( self , request , tag ) :
"""Render the initial value of the wrapped L { Parameter } instance .""" | if self . parameter . default is not None :
tag [ self . parameter . default ]
return tag |
def _new_empty_handle ( ) :
"""Returns a new empty handle .
Empty handle can be used to hold a result .
Returns
handle
A new empty ` NDArray ` handle .""" | hdl = NDArrayHandle ( )
check_call ( _LIB . MXNDArrayCreateNone ( ctypes . byref ( hdl ) ) )
return hdl |
def _spin_up ( self , images , duration ) :
"""Simulate the motors getting warmed up .""" | total = 0
# pylint : disable = no - member
for image in images :
self . microbit . display . show ( image )
time . sleep ( 0.05 )
total += 0.05
if total >= duration :
return
remaining = duration - total
self . _full_speed_rumble ( images [ - 2 : ] , remaining )
self . set_display ( ) |
def config_args ( self ) :
"""Set config options""" | # Module list options :
self . arg_parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' + str ( __version__ ) )
self . arg_parser . add_argument ( '--verbose' , action = 'store_true' , dest = 'verbosemode' , help = _ ( 'set verbose terminal output' ) )
self . arg_parser . add_argument ( '-s'... |
def get_subscription_from_cli ( name = None ) :
'''Get the default , or named , subscription id from CLI ' s local cache .
Args :
name ( str ) : Optional subscription name . If this is set , the subscription id of the named
subscription is returned from the CLI cache if present . If not set , the subscription... | home = os . path . expanduser ( '~' )
azure_profile_path = home + os . sep + '.azure' + os . sep + 'azureProfile.json'
if os . path . isfile ( azure_profile_path ) is False :
print ( 'Error from get_subscription_from_cli(): Cannot find ' + azure_profile_path )
return None
with io . open ( azure_profile_path , '... |
def setPosition ( self , poiID , x , y ) :
"""setPosition ( string , ( double , double ) ) - > None
Sets the position coordinates of the poi .""" | self . _connection . _beginMessage ( tc . CMD_SET_POI_VARIABLE , tc . VAR_POSITION , poiID , 1 + 8 + 8 )
self . _connection . _string += struct . pack ( "!Bdd" , tc . POSITION_2D , x , y )
self . _connection . _sendExact ( ) |
def zipWithUniqueId ( self ) :
"""Zips this RDD with generated unique Long ids .
Items in the kth partition will get ids k , n + k , 2 * n + k , . . . , where
n is the number of partitions . So there may exist gaps , but this
method won ' t trigger a spark job , which is different from
L { zipWithIndex }
... | n = self . getNumPartitions ( )
def func ( k , it ) :
for i , v in enumerate ( it ) :
yield v , i * n + k
return self . mapPartitionsWithIndex ( func ) |
def rsdl ( self ) :
"""Compute fixed point residual .""" | return np . linalg . norm ( ( self . X - self . Yprv ) . ravel ( ) ) |
def TokenClient ( domain , token , user_agent = None , request_encoder = default_request_encoder , response_decoder = default_response_decoder , ) :
"""Creates a Freshbooks client for a freshbooks domain , using
token - based auth .
The optional request _ encoder and response _ decoder parameters can be
passe... | return AuthorizingClient ( domain , transport . TokenAuthorization ( token ) , request_encoder , response_decoder , user_agent = user_agent ) |
def init ( req , model ) : # pylint : disable = unused - argument
"""Determine the pagination preference by query parameter
Numbers only , > = 0 , & each query param may only be
specified once .
: return : Paginator object""" | limit = req . get_param ( 'page[limit]' ) or goldman . config . PAGE_LIMIT
offset = req . get_param ( 'page[offset]' ) or 0
try :
return Paginator ( limit , offset )
except ValueError :
raise InvalidQueryParams ( ** { 'detail' : 'The page[\'limit\'] & page[\'offset\'] query ' 'params may only be specified once ... |
def get_pokemon_by_name ( self , name ) :
"""Returns an array of Pokemon objects containing all the forms of the
Pokemon specified the name of the Pokemon .""" | endpoint = '/pokemon/' + str ( name )
return self . make_request ( self . BASE_URL + endpoint ) |
def get_upregulated_genes_network ( self ) -> Graph :
"""Get the graph of up - regulated genes .
: return Graph : Graph of up - regulated genes .""" | logger . info ( "In get_upregulated_genes_network()" )
deg_graph = self . graph . copy ( )
# deep copy graph
not_diff_expr = self . graph . vs ( up_regulated_eq = False )
# delete genes which are not differentially expressed or have no connections to others
deg_graph . delete_vertices ( not_diff_expr . indices )
deg_gr... |
def watch_docs ( c ) :
"""Watch both doc trees & rebuild them if files change .
This includes e . g . rebuilding the API docs if the source code changes ;
rebuilding the WWW docs if the README changes ; etc .
Reuses the configuration values ` ` packaging . package ` ` or ` ` tests . package ` `
( the former... | # TODO : break back down into generic single - site version , then create split
# tasks as with docs / www above . Probably wants invoke # 63.
# NOTE : ' www ' / ' docs ' refer to the module level sub - collections . meh .
# Readme & WWW triggers WWW
www_c = Context ( config = c . config . clone ( ) )
www_c . update ( ... |
def dicom_read ( directory , pixeltype = 'float' ) :
"""Read a set of dicom files in a directory into a single ANTsImage .
The origin of the resulting 3D image will be the origin of the
first dicom image read .
Arguments
directory : string
folder in which all the dicom images exist
Returns
ANTsImage
... | slices = [ ]
imgidx = 0
for imgpath in os . listdir ( directory ) :
if imgpath . endswith ( '.dcm' ) :
if imgidx == 0 :
tmp = image_read ( os . path . join ( directory , imgpath ) , dimension = 3 , pixeltype = pixeltype )
origin = tmp . origin
spacing = tmp . spacing
... |
def beta_geometric_nbd_model_transactional_data ( T , r , alpha , a , b , observation_period_end = "2019-1-1" , freq = "D" , size = 1 ) :
"""Generate artificial transactional data according to the BG / NBD model .
See [ 1 ] for model details
Parameters
T : int , float or array _ like
The length of time obse... | observation_period_end = pd . to_datetime ( observation_period_end )
if type ( T ) in [ float , int ] :
start_date = [ observation_period_end - pd . Timedelta ( T - 1 , unit = freq ) ] * size
T = T * np . ones ( size )
else :
start_date = [ observation_period_end - pd . Timedelta ( T [ i ] - 1 , unit = freq... |
def check_presence_of_mandatory_args ( args , mandatory_args ) :
'''Checks whether all mandatory arguments are passed .
This function aims at methods with many arguments
which are passed as kwargs so that the order
in which the are passed does not matter .
: args : The dictionary passed as args .
: mandat... | missing_args = [ ]
for name in mandatory_args :
if name not in args . keys ( ) :
missing_args . append ( name )
if len ( missing_args ) > 0 :
raise ValueError ( 'Missing mandatory arguments: ' + ', ' . join ( missing_args ) )
else :
return True |
def _addsub_int_array ( self , other , op ) :
"""Add or subtract array - like of integers equivalent to applying
` _ time _ shift ` pointwise .
Parameters
other : Index , ExtensionArray , np . ndarray
integer - dtype
op : { operator . add , operator . sub }
Returns
result : same class as self""" | # _ addsub _ int _ array is overriden by PeriodArray
assert not is_period_dtype ( self )
assert op in [ operator . add , operator . sub ]
if self . freq is None : # GH # 19123
raise NullFrequencyError ( "Cannot shift with no freq" )
elif isinstance ( self . freq , Tick ) : # easy case where we can convert to timede... |
def angular_separation ( lonp1 , latp1 , lonp2 , latp2 ) :
"""Compute the angles between lon / lat points p1 and p2 given in radians .
On the unit sphere , this also corresponds to the great circle distance .
p1 and p2 can be numpy arrays of the same length .""" | xp1 , yp1 , zp1 = lonlat2xyz ( lonp1 , latp1 )
xp2 , yp2 , zp2 = lonlat2xyz ( lonp2 , latp2 )
# # dot products to obtain angles
angles = np . arccos ( ( xp1 * xp2 + yp1 * yp2 + zp1 * zp2 ) )
# # As this is a unit sphere , angle = length
return angles |
def undo ( self , x_prec ) :
"""Transform the unknowns to original coordinates
This method also transforms the gradient to preconditioned coordinates""" | if self . scales is None :
return x_prec
else :
return np . dot ( self . rotation , x_prec / self . scales ) |
def _get_optional_attrs ( kws ) :
"""Given keyword args , return optional _ attributes to be loaded into the GODag .""" | vals = OboOptionalAttrs . attributes . intersection ( kws . keys ( ) )
if 'sections' in kws :
vals . add ( 'relationship' )
if 'norel' in kws :
vals . discard ( 'relationship' )
return vals |
def bads_report ( bads , path_prefix = None ) :
"""Return a nice report of bad architectures in ` bads `
Parameters
bads : set
set of length 2 or 3 tuples . A length 2 tuple is of form
` ` ( depending _ lib , missing _ archs ) ` ` meaning that an arch in
` require _ archs ` was missing from ` ` depending ... | path_processor = ( ( lambda x : x ) if path_prefix is None else get_rp_stripper ( path_prefix ) )
reports = [ ]
for result in bads :
if len ( result ) == 3 :
depended_lib , depending_lib , missing_archs = result
reports . append ( "{0} needs {1} {2} missing from {3}" . format ( path_processor ( depe... |
def inlink_file ( self , filepath ) :
"""Create a symbolic link to the specified file in the
directory containing the input files of the task .""" | if not os . path . exists ( filepath ) :
logger . debug ( "Creating symbolic link to not existent file %s" % filepath )
# Extract the Abinit extension and add the prefix for input files .
root , abiext = abi_splitext ( filepath )
infile = "in_" + abiext
infile = self . indir . path_in ( infile )
# Link path to dest... |
def swap_axis_to_0 ( x , axis ) :
"""Insert a new singleton axis at position 0 and swap it with the
specified axis . The resulting array has an additional dimension ,
with ` ` axis ` ` + 1 ( which was ` ` axis ` ` before the insertion of the
new axis ) of ` ` x ` ` at position 0 , and a singleton axis at posi... | return np . ascontiguousarray ( np . swapaxes ( x [ np . newaxis , ... ] , 0 , axis + 1 ) ) |
def print_in_box ( text ) :
"""Prints ` text ` surrounded by a box made of * s""" | print ( '' )
print ( '*' * ( len ( text ) + 6 ) )
print ( '** ' + text + ' **' )
print ( '*' * ( len ( text ) + 6 ) )
print ( '' ) |
def error ( self , msg ) :
'''error ( msg : string )
Print a usage message incorporating ' msg ' to stderr and exit .
This keeps option parsing exit status uniform for all parsing errors .''' | self . print_usage ( sys . stderr )
self . exit ( salt . defaults . exitcodes . EX_USAGE , '{0}: error: {1}\n' . format ( self . get_prog_name ( ) , msg ) ) |
def _merge_flags ( new_flags , old_flags = None , conf = 'any' ) :
'''Merges multiple lists of flags removing duplicates and resolving conflicts
giving priority to lasts lists .''' | if not old_flags :
old_flags = [ ]
args = [ old_flags , new_flags ]
if conf == 'accept_keywords' :
tmp = new_flags + [ i for i in old_flags if _check_accept_keywords ( new_flags , i ) ]
else :
tmp = portage . flatten ( args )
flags = { }
for flag in tmp :
if flag [ 0 ] == '-' :
flags [ flag [ 1 ... |
def _register_external_service ( self , plugin_name , plugin_instance ) :
"""Register an external service .
: param plugin _ name : Service name
: param plugin _ instance : PluginBase
: return :""" | for attr in plugin_instance . get_external_services ( ) . keys ( ) :
if attr in self . _external_services :
raise PluginException ( "External service with name {} already exists! Unable to add " "services from plugin {}." . format ( attr , plugin_name ) )
self . _external_services [ attr ] = plugin_inst... |
def load_from_s3 ( self , bucket , prefix = None ) :
"""Load messages previously saved to S3.""" | n = 0
if prefix :
prefix = '%s/' % prefix
else :
prefix = '%s/' % self . id [ 1 : ]
rs = bucket . list ( prefix = prefix )
for key in rs :
n += 1
m = self . new_message ( key . get_contents_as_string ( ) )
self . write ( m )
return n |
def moveOrder ( self , orderNumber , rate , amount = None , postOnly = None , immediateOrCancel = None ) :
"""Cancels an order and places a new one of the same type in a single
atomic transaction , meaning either both operations will succeed or both
will fail . Required POST parameters are " orderNumber " and "... | return self . _private ( 'moveOrder' , orderNumber = orderNumber , rate = rate , amount = amount , postOnly = postOnly , immediateOrCancel = immediateOrCancel ) |
def shift_down_left ( self , times = 1 ) :
"""Finds Location shifted down left by 1
: rtype : Location""" | try :
return Location ( self . _rank - times , self . _file - times )
except IndexError as e :
raise IndexError ( e ) |
def _lookup_parent ( self , cls ) :
"""Lookup a transitive parent object that is an instance
of a given class .""" | codeobj = self . parent
while codeobj is not None and not isinstance ( codeobj , cls ) :
codeobj = codeobj . parent
return codeobj |
def list_prediction ( self , species , to_this_composition = True ) :
"""Args :
species :
list of species
to _ this _ composition :
If true , substitutions with this as a final composition
will be found . If false , substitutions with this as a
starting composition will be found ( these are slightly
d... | for sp in species :
if get_el_sp ( sp ) not in self . p . species :
raise ValueError ( "the species {} is not allowed for the" "probability model you are using" . format ( sp ) )
max_probabilities = [ ]
for s1 in species :
if to_this_composition :
max_p = max ( [ self . p . cond_prob ( s2 , s1 )... |
def inspect ( self ) :
"""Fetches image information from the client .""" | policy = self . policy
image_name = format_image_tag ( ( self . config_id . config_name , self . config_id . instance_name ) )
image_id = policy . images [ self . client_name ] . get ( image_name )
if image_id :
self . detail = { 'Id' : image_id }
# Currently there is no need for actually inspecting the image .... |
def get_available_extension ( name , user = None , host = None , port = None , maintenance_db = None , password = None , runas = None ) :
'''Get info about an available postgresql extension
CLI Example :
. . code - block : : bash
salt ' * ' postgres . get _ available _ extension plpgsql''' | return available_extensions ( user = user , host = host , port = port , maintenance_db = maintenance_db , password = password , runas = runas ) . get ( name , None ) |
def get_submission ( submission_uuid , read_replica = False ) :
"""Retrieves a single submission by uuid .
Args :
submission _ uuid ( str ) : Identifier for the submission .
Kwargs :
read _ replica ( bool ) : If true , attempt to use the read replica database .
If no read replica is available , use the de... | if not isinstance ( submission_uuid , six . string_types ) :
if isinstance ( submission_uuid , UUID ) :
submission_uuid = six . text_type ( submission_uuid )
else :
raise SubmissionRequestError ( msg = "submission_uuid ({!r}) must be serializable" . format ( submission_uuid ) )
cache_key = Submi... |
def flood_fill_aplx ( self , * args , ** kwargs ) :
"""Unreliably flood - fill APLX to a set of application cores .
. . note : :
Most users should use the : py : meth : ` . load _ application ` wrapper
around this method which guarantees successful loading .
This method can be called in either of the follow... | # Coerce the arguments into a single form . If there are two arguments
# then assume that we have filename and a map of chips and cores ;
# otherwise there should be ONE argument which is of the form of the
# return value of ` build _ application _ map ` .
application_map = { }
if len ( args ) == 1 :
application_ma... |
def validate ( self , result , spec ) : # noqa Yes , it ' s too complex .
"""Validate that the result has the correct structure .""" | if spec is None : # None matches anything .
return
if isinstance ( spec , dict ) :
if not isinstance ( result , dict ) :
raise ValueError ( 'Dictionary expected, but %r found.' % result )
if spec :
spec_value = next ( iter ( spec . values ( ) ) )
# Yay Python 3!
for value in ... |
def list_annotations ( self ) -> List [ Namespace ] :
"""List all annotations .""" | return self . session . query ( Namespace ) . filter ( Namespace . is_annotation ) . all ( ) |
def cosinebell ( n , fraction ) :
"""Return a cosine bell spanning n pixels , masking a fraction of pixels
Parameters
n : int
Number of pixels .
fraction : float
Length fraction over which the data will be masked .""" | mask = np . ones ( n )
nmasked = int ( fraction * n )
for i in range ( nmasked ) :
yval = 0.5 * ( 1 - np . cos ( np . pi * float ( i ) / float ( nmasked ) ) )
mask [ i ] = yval
mask [ n - i - 1 ] = yval
return mask |
def ustack ( arrs , axis = 0 ) :
"""Join a sequence of arrays along a new axis while preserving units
The axis parameter specifies the index of the new axis in the
dimensions of the result . For example , if ` ` axis = 0 ` ` it will be the
first dimension and if ` ` axis = - 1 ` ` it will be the last dimensio... | v = np . stack ( arrs , axis = axis )
v = _validate_numpy_wrapper_units ( v , arrs )
return v |
def _folder_item_report_visibility ( self , analysis_brain , item ) :
"""Set if the hidden field can be edited ( enabled / disabled )
: analysis _ brain : Brain that represents an analysis
: item : analysis ' dictionary counterpart to be represented as a row""" | # Users that can Add Analyses to an Analysis Request must be able to
# set the visibility of the analysis in results report , also if the
# current state of the Analysis Request ( e . g . verified ) does not allow
# the edition of other fields . Note that an analyst has no privileges
# by default to edit this value , c... |
def tokenizer ( self ) :
"""Datasets can provide support for segmentation ( aka tokenization ) in two ways :
- by providing an orthography profile at etc / orthography . tsv or
- by overwriting this method to return a custom tokenizer callable .
: return : A callable to do segmentation .
The expected signat... | profile = self . dir / 'etc' / 'orthography.tsv'
if profile . exists ( ) :
profile = Profile . from_file ( str ( profile ) , form = 'NFC' )
default_spec = list ( next ( iter ( profile . graphemes . values ( ) ) ) . keys ( ) )
for grapheme in [ '^' , '$' ] :
if grapheme not in profile . graphemes :
... |
def get_points ( self , measurement = None , tags = None ) :
"""Return a generator for all the points that match the given filters .
: param measurement : The measurement name
: type measurement : str
: param tags : Tags to look for
: type tags : dict
: return : Points generator""" | # Raise error if measurement is not str or bytes
if not isinstance ( measurement , ( bytes , type ( b'' . decode ( ) ) , type ( None ) ) ) :
raise TypeError ( 'measurement must be an str or None' )
for series in self . _get_series ( ) :
series_name = series . get ( 'measurement' , series . get ( 'name' , 'resul... |
def convert_strtime_datetime ( dt_str ) :
"""Converts datetime isoformat string to datetime ( dt ) object
Args :
: dt _ str ( str ) : input string in ' 2017-12-30T18:48:00.353Z ' form
or similar
Returns :
TYPE : datetime object""" | dt , _ , us = dt_str . partition ( "." )
dt = datetime . datetime . strptime ( dt , "%Y-%m-%dT%H:%M:%S" )
us = int ( us . rstrip ( "Z" ) , 10 )
return dt + datetime . timedelta ( microseconds = us ) |
def CreateGroup ( r , name , alloc_policy = None , dry_run = False ) :
"""Creates a new node group .
@ type name : str
@ param name : the name of node group to create
@ type alloc _ policy : str
@ param alloc _ policy : the desired allocation policy for the group , if any
@ type dry _ run : bool
@ param... | query = { "dry-run" : dry_run , }
body = { "name" : name , "alloc_policy" : alloc_policy }
return r . request ( "post" , "/2/groups" , query = query , content = body ) |
def sum_transactions ( transactions ) :
"""Sums transactions into a total of remaining vacation days .""" | workdays_per_year = 250
previous_date = None
rate = 0
day_sum = 0
for transaction in transactions :
date , action , value = _parse_transaction_entry ( transaction )
if previous_date is None :
previous_date = date
elapsed = workdays . networkdays ( previous_date , date , stat_holidays ( ) ) - 1
i... |
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] :
"""Get all the database column names for the specified table .""" | return [ info . name for info in gen_columns_info ( engine , tablename ) ] |
def to_valid_density_matrix ( density_matrix_rep : Union [ int , np . ndarray ] , num_qubits : int , dtype : Type [ np . number ] = np . complex64 ) -> np . ndarray :
"""Verifies the density _ matrix _ rep is valid and converts it to ndarray form .
This method is used to support passing a matrix , a vector ( wave... | if ( isinstance ( density_matrix_rep , np . ndarray ) and density_matrix_rep . ndim == 2 ) :
if density_matrix_rep . shape != ( 2 ** num_qubits , 2 ** num_qubits ) :
raise ValueError ( 'Density matrix was not square and of size 2 ** num_qubit, ' 'instead was {}' . format ( density_matrix_rep . shape ) )
... |
def get_learning_objectives ( self ) :
"""This method also mirrors that in the Item .""" | # This is pretty much identicial to the method in assessment . Item !
mgr = self . _get_provider_manager ( 'LEARNING' )
lookup_session = mgr . get_objective_lookup_session ( proxy = getattr ( self , "_proxy" , None ) )
lookup_session . use_federated_objective_bank_view ( )
return lookup_session . get_objectives_by_ids ... |
def get_waveset ( model ) :
"""Get optimal wavelengths for sampling a given model .
Parameters
model : ` ~ astropy . modeling . Model `
Model .
Returns
waveset : array - like or ` None `
Optimal wavelengths . ` None ` if undefined .
Raises
synphot . exceptions . SynphotError
Invalid model .""" | if not isinstance ( model , Model ) :
raise SynphotError ( '{0} is not a model.' . format ( model ) )
if isinstance ( model , _CompoundModel ) :
waveset = model . _tree . evaluate ( WAVESET_OPERATORS , getter = None )
else :
waveset = _get_sampleset ( model )
return waveset |
def make_sloppy_codec ( encoding ) :
"""Take a codec name , and return a ' sloppy ' version of that codec that can
encode and decode the unassigned bytes in that encoding .
Single - byte encodings in the standard library are defined using some
boilerplate classes surrounding the functions that do the actual w... | # Make a bytestring of all 256 possible bytes .
all_bytes = bytes ( range ( 256 ) )
# Get a list of what they would decode to in Latin - 1.
sloppy_chars = list ( all_bytes . decode ( 'latin-1' ) )
# Get a list of what they decode to in the given encoding . Use the
# replacement character for unassigned bytes .
if PY26 ... |
def parse ( readDataInstance , sectionHeadersInstance ) :
"""Returns a new L { Sections } object .
@ type readDataInstance : L { ReadData }
@ param readDataInstance : A L { ReadData } object with data to be parsed as a L { Sections } object .
@ type sectionHeadersInstance : instance
@ param sectionHeadersIn... | sData = Sections ( )
for sectionHdr in sectionHeadersInstance :
if sectionHdr . sizeOfRawData . value > len ( readDataInstance . data ) :
print "Warning: SizeOfRawData is larger than file."
if sectionHdr . pointerToRawData . value > len ( readDataInstance . data ) :
print "Warning: PointerToRawD... |
def decode_aes256 ( cipher , iv , data , encryption_key ) :
"""Decrypt AES - 256 bytes .
Allowed ciphers are : : ecb , : cbc .
If for : ecb iv is not used and should be set to " " .""" | if cipher == 'cbc' :
aes = AES . new ( encryption_key , AES . MODE_CBC , iv )
elif cipher == 'ecb' :
aes = AES . new ( encryption_key , AES . MODE_ECB )
else :
raise ValueError ( 'Unknown AES mode' )
d = aes . decrypt ( data )
# http : / / passingcuriosity . com / 2009 / aes - encryption - in - python - wit... |
def get_bitcoind_client ( ) :
"""Connect to the bitcoind node""" | bitcoind_opts = get_bitcoin_opts ( )
bitcoind_host = bitcoind_opts [ 'bitcoind_server' ]
bitcoind_port = bitcoind_opts [ 'bitcoind_port' ]
bitcoind_user = bitcoind_opts [ 'bitcoind_user' ]
bitcoind_passwd = bitcoind_opts [ 'bitcoind_passwd' ]
return create_bitcoind_service_proxy ( bitcoind_user , bitcoind_passwd , serv... |
def compile_files_cwd ( * args , ** kwargs ) :
"""change working directory to contract ' s dir in order to avoid symbol
name conflicts""" | # get root directory of the contracts
compile_wd = os . path . commonprefix ( args [ 0 ] )
# edge case - compiling a single file
if os . path . isfile ( compile_wd ) :
compile_wd = os . path . dirname ( compile_wd )
# remove prefix from the files
if compile_wd [ - 1 ] != '/' :
compile_wd += '/'
file_list = [ x ... |
def sanitize ( self ) :
"""Sanitize all fields of the KNX message .""" | self . repeat = self . repeat % 2
self . priority = self . priority % 4
self . src_addr = self . src_addr % 0x10000
self . dst_addr = self . dst_addr % 0x10000
self . multicast = self . multicast % 2
self . routing = self . routing % 8
self . length = self . length % 16
for i in range ( 0 , self . length - 1 ) :
se... |
def snmp_server_host_source_interface_source_interface_type_loopback_loopback ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
snmp_server = ET . SubElement ( config , "snmp-server" , xmlns = "urn:brocade.com:mgmt:brocade-snmp" )
host = ET . SubElement ( snmp_server , "host" )
ip_key = ET . SubElement ( host , "ip" )
ip_key . text = kwargs . pop ( 'ip' )
community_key = ET . SubElement ( host , "community" )
... |
def query ( self , query , args = ( ) , as_dict = False , suppress_warnings = True , reconnect = None ) :
"""Execute the specified query and return the tuple generator ( cursor ) .
: param query : mysql query
: param args : additional arguments for the client . cursor
: param as _ dict : If as _ dict is set t... | if reconnect is None :
reconnect = config [ 'database.reconnect' ]
cursor = client . cursors . DictCursor if as_dict else client . cursors . Cursor
cur = self . _conn . cursor ( cursor = cursor )
logger . debug ( "Executing SQL:" + query [ 0 : 300 ] )
try :
with warnings . catch_warnings ( ) :
if suppre... |
def angularjs ( parser , token ) :
"""Conditionally switch between AngularJS and Django variable expansion for ` ` { { ` ` and ` ` } } ` `
keeping Django ' s expansion for ` ` { % ` ` and ` ` % } ` `
Usage : :
{ % angularjs 1 % } or simply { % angularjs % }
{ % process variables through the AngularJS templa... | bits = token . contents . split ( )
if len ( bits ) < 2 :
bits . append ( '1' )
values = [ parser . compile_filter ( bit ) for bit in bits [ 1 : ] ]
django_nodelist = parser . parse ( ( 'endangularjs' , ) )
angular_nodelist = NodeList ( )
for node in django_nodelist : # convert all occurrences of VariableNode into ... |
def zip_a_folder ( src , dst ) :
"""Add a folder and everything inside to zip archive .
Example : :
| - - - paper
| - - - algorithm . pdf
| - - - images
| - - - 1 . jpg
zip _ a _ folder ( " paper " , " paper . zip " )
paper . zip
| - - - paper
| - - - algorithm . pdf
| - - - images
| - - - 1 .... | src , dst = os . path . abspath ( src ) , os . path . abspath ( dst )
cwd = os . getcwd ( )
todo = list ( )
dirname , basename = os . path . split ( src )
os . chdir ( dirname )
for dirname , _ , fnamelist in os . walk ( basename ) :
for fname in fnamelist :
newname = os . path . join ( dirname , fname )
... |
def _remove_layer ( self , layer ) :
"""remove the layer and its input / output edges""" | successors = self . get_successors ( layer )
predecessors = self . get_predecessors ( layer )
# remove all edges
for succ in successors :
self . _remove_edge ( layer , succ )
for pred in predecessors :
self . _remove_edge ( pred , layer )
# remove layer in the data structures
self . keras_layer_map . pop ( laye... |
def finalize_download ( url , download_to_file , content_type , request ) :
"""Finalizes the download operation by doing various checks , such as format
type , size check etc .""" | # If format is given , a format check is performed .
if content_type and content_type not in request . headers [ 'content-type' ] :
msg = 'The downloaded file is not of the desired format'
raise InvenioFileDownloadError ( msg )
# Save the downloaded file to desired or generated location .
to_file = open ( downl... |
def compress ( condition , data , axis = 0 , out = None , blen = None , storage = None , create = 'array' , ** kwargs ) :
"""Return selected slices of an array along given axis .""" | # setup
if out is not None : # argument is only there for numpy API compatibility
raise NotImplementedError ( 'out argument is not supported' )
storage = _util . get_storage ( storage )
blen = _util . get_blen_array ( data , blen )
length = len ( data )
nnz = count_nonzero ( condition )
if axis == 0 :
_util . c... |
def create_process_behavior ( self , behavior , process_id ) :
"""CreateProcessBehavior .
[ Preview API ] Creates a single behavior in the given process .
: param : class : ` < ProcessBehaviorCreateRequest > < azure . devops . v5_0 . work _ item _ tracking _ process . models . ProcessBehaviorCreateRequest > ` b... | route_values = { }
if process_id is not None :
route_values [ 'processId' ] = self . _serialize . url ( 'process_id' , process_id , 'str' )
content = self . _serialize . body ( behavior , 'ProcessBehaviorCreateRequest' )
response = self . _send ( http_method = 'POST' , location_id = 'd1800200-f184-4e75-a5f2-ad0b04b... |
def trim ( value ) :
'''Raise an exception if value is empty . Otherwise strip it down .
: param value :
: return :''' | value = ( value or '' ) . strip ( )
if not value :
raise CommandExecutionError ( "Empty value during sanitation" )
return six . text_type ( value ) |
def _match_vcs_scheme ( url ) : # type : ( str ) - > Optional [ str ]
"""Look for VCS schemes in the URL .
Returns the matched VCS scheme , or None if there ' s no match .""" | from pipenv . patched . notpip . _internal . vcs import VcsSupport
for scheme in VcsSupport . schemes :
if url . lower ( ) . startswith ( scheme ) and url [ len ( scheme ) ] in '+:' :
return scheme
return None |
def CheckStyle ( filename , linenumber , clean_lines , errors ) :
"""Check style issues . These are :
No extra spaces between command and parenthesis
Matching spaces between parenthesis and arguments
No repeated logic in else ( ) , endif ( ) , endmacro ( )""" | CheckIndent ( filename , linenumber , clean_lines , errors )
CheckCommandSpaces ( filename , linenumber , clean_lines , errors )
line = clean_lines . raw_lines [ linenumber ]
if line . find ( '\t' ) != - 1 :
errors ( filename , linenumber , 'whitespace/tabs' , 'Tab found; please use spaces' )
if line and line [ - 1... |
def chained_parameter_variation ( subject , durations , y0 , varied_params , default_params = None , integrate_kwargs = None , x0 = None , npoints = 1 , numpy = None ) :
"""Integrate an ODE - system for a serie of durations with some parameters changed in - between
Parameters
subject : function or ODESys instan... | assert len ( durations ) > 0 , 'need at least 1 duration (preferably many)'
assert npoints > 0 , 'need at least 1 point per duration'
for k , v in varied_params . items ( ) :
if len ( v ) != len ( durations ) :
raise ValueError ( "Mismathced lengths of durations and varied_params" )
if isinstance ( subject ... |
def _parse_wikiheadlines ( path ) :
"""Generates examples from Wikiheadlines dataset file .""" | lang_match = re . match ( r".*\.([a-z][a-z])-([a-z][a-z])$" , path )
assert lang_match is not None , "Invalid Wikiheadlines filename: %s" % path
l1 , l2 = lang_match . groups ( )
with tf . io . gfile . GFile ( path ) as f :
for line in f :
s1 , s2 = line . split ( "|||" )
yield { l1 : s1 . strip ( )... |
def process_output ( self , data , output_prompt , input_lines , output , is_doctest , decorator , image_file ) :
"""Process data block for OUTPUT token .""" | TAB = ' ' * 4
if is_doctest and output is not None :
found = output
found = found . strip ( )
submitted = data . strip ( )
if self . directive is None :
source = 'Unavailable'
content = 'Unavailable'
else :
source = self . directive . state . document . current_source
... |
def _get_algorithm ( self , algorithm_name ) :
"""Get the specific algorithm .
: param str algorithm _ name : name of the algorithm to use ( file name ) .
: return : algorithm object .""" | try :
algorithm = anomaly_detector_algorithms [ algorithm_name ]
return algorithm
except KeyError :
raise exceptions . AlgorithmNotFound ( 'luminol.AnomalyDetector: ' + str ( algorithm_name ) + ' not found.' ) |
def update_schema ( schema_old , schema_new ) :
"""Given an old BigQuery schema , update it with a new one .
Where a field name is the same , the new will replace the old . Any
new fields not present in the old schema will be added .
Arguments :
schema _ old : the old schema to update
schema _ new : the n... | old_fields = schema_old [ "fields" ]
new_fields = schema_new [ "fields" ]
output_fields = list ( old_fields )
field_indices = { field [ "name" ] : i for i , field in enumerate ( output_fields ) }
for field in new_fields :
name = field [ "name" ]
if name in field_indices : # replace old field with new field of s... |
def should_be_hidden_as_cause ( exc ) :
"""Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error""" | # reduced traceback in case of HasWrongType ( instance _ of checks )
from valid8 . validation_lib . types import HasWrongType , IsWrongType
return isinstance ( exc , ( HasWrongType , IsWrongType ) ) |
def clear_queues ( self , manager ) :
"""Release the resources associated to the queues of this instance
: param manager : Manager ( ) object
: type manager : None | object
: return : None""" | for queue in ( self . to_q , self . from_q ) :
if queue is None :
continue
# If we got no manager , we directly call the clean
if not manager :
try :
queue . close ( )
queue . join_thread ( )
except AttributeError :
pass
# else :
# q . _ ca... |
def pore_coords ( target ) :
r"""The average of the pore coords""" | network = target . project . network
Ts = network . throats ( target . name )
conns = network [ 'throat.conns' ]
coords = network [ 'pore.coords' ]
return _sp . mean ( coords [ conns ] , axis = 1 ) [ Ts ] |
def worker_exec ( self , max_num , default_ext = '' , queue_timeout = 5 , req_timeout = 5 , ** kwargs ) :
"""Target method of workers .
Get task from ` ` task _ queue ` ` and then download files and process meta
data . A downloader thread will exit in either of the following cases :
1 . All parser threads hav... | self . max_num = max_num
while True :
if self . signal . get ( 'reach_max_num' ) :
self . logger . info ( 'downloaded images reach max num, thread %s' ' is ready to exit' , current_thread ( ) . name )
break
try :
task = self . in_queue . get ( timeout = queue_timeout )
except queue .... |
def listen ( self , once = False ) :
"""Listen for changes in all registered listeners .
Use add _ listener before calling this funcion to listen for desired
events or set ` once ` to True to listen for initial room information""" | if once : # we listen for time event and return false so our
# run _ queues function will be also falsy and break the loop
self . add_listener ( "time" , lambda _ : False )
return self . conn . listen ( ) |
def validate ( config ) :
"""Validate a configuration file .""" | with open ( config ) as fh :
data = utils . yaml_load ( fh . read ( ) )
jsonschema . validate ( data , CONFIG_SCHEMA ) |
def get_bucket_type_props ( self , bucket_type ) :
"""Get properties for a bucket - type""" | self . _check_bucket_types ( bucket_type )
url = self . bucket_type_properties_path ( bucket_type . name )
status , headers , body = self . _request ( 'GET' , url )
if status == 200 :
props = json . loads ( bytes_to_str ( body ) )
return props [ 'props' ]
else :
raise RiakError ( 'Error getting bucket-type ... |
def add_token_without_limits ( self , token_address : TokenAddress , ) -> Address :
"""Register token of ` token _ address ` with the token network .
This applies for versions prior to 0.13.0 of raiden - contracts ,
since limits were hardcoded into the TokenNetwork contract .""" | return self . _add_token ( token_address = token_address , additional_arguments = dict ( ) , ) |
def _put ( self , * args , ** kwargs ) :
"""A wrapper for putting things . It will also json encode your ' data ' parameter
: returns : The response of your put
: rtype : dict""" | if 'data' in kwargs :
kwargs [ 'data' ] = json . dumps ( kwargs [ 'data' ] )
response = requests . put ( * args , ** kwargs )
response . raise_for_status ( ) |
def decrypt_from ( self , f , mac_bytes = 10 ) :
"""Decrypts a message from f .""" | ctx = DecryptionContext ( self . curve , f , self , mac_bytes )
yield ctx
ctx . read ( ) |
def note_revert ( self , note_id , version ) :
"""Function to revert a specific note ( Requires login ) ( UNTESTED ) .
Parameters :
note _ id ( int ) : The note id to update .
version ( int ) : The version to revert to .""" | params = { 'id' : note_id , 'version' : version }
return self . _get ( 'note/revert' , params , method = 'PUT' ) |
def post_helper ( form_tag = True , edit_mode = False ) :
"""Post ' s form layout helper""" | helper = FormHelper ( )
helper . form_action = '.'
helper . attrs = { 'data_abide' : '' }
helper . form_tag = form_tag
fieldsets = [ Row ( Column ( 'text' , css_class = 'small-12' ) , ) , ]
# Threadwatch option is not in edit form
if not edit_mode :
fieldsets . append ( Row ( Column ( 'threadwatch' , css_class = 's... |
def _parse_pairwise_input ( indices1 , indices2 , MDlogger , fname = '' ) :
r"""For input of pairwise type ( distances , inverse distances , contacts ) checks the
type of input the user gave and reformats it so that : py : func : ` DistanceFeature ` ,
: py : func : ` InverseDistanceFeature ` , and ContactFeatur... | if is_iterable_of_int ( indices1 ) :
MDlogger . warning ( 'The 1D arrays input for %s have been sorted, and ' 'index duplicates have been eliminated.\n' 'Check the output of describe() to see the actual order of the features' % fname )
# Eliminate duplicates and sort
indices1 = np . unique ( indices1 )
... |
def get_cusum ( self , mag ) :
"""Return max - min of cumulative sum .
Parameters
mag : array _ like
An array of magnitudes .
Returns
mm _ cusum : float
Max - min of cumulative sum .""" | c = np . cumsum ( mag - self . weighted_mean ) / len ( mag ) / self . weighted_std
return np . max ( c ) - np . min ( c ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.