signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def stream_fastq ( file_handler ) :
'''Generator which gives all four lines if a fastq read as one string''' | next_element = ''
for i , line in enumerate ( file_handler ) :
next_element += line
if i % 4 == 3 :
yield next_element
next_element = '' |
def linear ( target , X , A1 = '' , A2 = '' ) :
r"""Calculates the rate , as well as slope and intercept of the following
function at the given value of ` X ` :
. . math : :
r = A _ { 1 } X + A _ { 2}
Parameters
A1 - > A2 : string
The dictionary keys on the target object containing the coefficients
va... | A = _parse_args ( target = target , key = A1 , default = 1.0 )
B = _parse_args ( target = target , key = A2 , default = 0.0 )
X = target [ X ]
r = A * X + B
S1 = A
S2 = B
values = { 'S1' : S1 , 'S2' : S2 , 'rate' : r }
return values |
def verify ( self ) :
"""Access the Verify Twilio Domain
: returns : Verify Twilio Domain
: rtype : twilio . rest . verify . Verify""" | if self . _verify is None :
from twilio . rest . verify import Verify
self . _verify = Verify ( self )
return self . _verify |
def approx_min_num_components ( nodes , negative_edges ) :
"""Find approximate minimum number of connected components possible
Each edge represents that two nodes must be separated
This code doesn ' t solve the problem . The problem is NP - complete and
reduces to minimum clique cover ( MCC ) . This is only a... | import utool as ut
num = 0
g_neg = nx . Graph ( )
g_neg . add_nodes_from ( nodes )
g_neg . add_edges_from ( negative_edges )
# Collapse all nodes with degree 0
if nx . __version__ . startswith ( '2' ) :
deg0_nodes = [ n for n , d in g_neg . degree ( ) if d == 0 ]
else :
deg0_nodes = [ n for n , d in g_neg . deg... |
def check_sig ( self , other ) :
"""Check overlap insignificance with another spectrum .
Also see : ref : ` pysynphot - command - checko ` .
. . note : :
Only use when : meth : ` check _ overlap ` returns " partial " .
Parameters
other : ` SourceSpectrum ` or ` SpectralElement `
The other spectrum .
R... | swave = self . wave [ N . where ( self . throughput != 0 ) ]
s1 , s2 = swave . min ( ) , swave . max ( )
owave = other . wave
o1 , o2 = owave . min ( ) , owave . max ( )
lorange = sorted ( [ s1 , o1 ] )
hirange = sorted ( [ s2 , o2 ] )
# Get the full throughput
total = self . integrate ( )
# Now get the other two piece... |
def save_waypoints_csv ( self , filename ) :
'''save waypoints to a file in a human readable CSV file''' | try : # need to remove the leading and trailing quotes in filename
self . wploader . savecsv ( filename . strip ( '"' ) )
except Exception as msg :
print ( "Failed to save %s - %s" % ( filename , msg ) )
return
print ( "Saved %u waypoints to CSV %s" % ( self . wploader . count ( ) , filename ) ) |
def _get_neutron_endpoint ( cls , json_resp ) :
"""Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service
Sends a CRITICAL service check when none are found registered in the Catalog""" | valid_endpoint = cls . _get_valid_endpoint ( json_resp , 'neutron' , 'network' )
if valid_endpoint :
return valid_endpoint
raise MissingNeutronEndpoint ( ) |
def percentage_of_reoccurring_datapoints_to_all_datapoints ( x ) :
"""Returns the percentage of unique values , that are present in the time series
more than once .
len ( different values occurring more than once ) / len ( different values )
This means the percentage is normalized to the number of unique valu... | if len ( x ) == 0 :
return np . nan
unique , counts = np . unique ( x , return_counts = True )
if counts . shape [ 0 ] == 0 :
return 0
return np . sum ( counts > 1 ) / float ( counts . shape [ 0 ] ) |
def write_csv ( graph , prefix ) :
"""Write ` ` graph ` ` as tables of nodes ( ` ` prefix - nodes . csv ` ` ) and edges
( ` ` prefix - edges . csv ` ` ) .
Parameters
graph : : ref : ` networkx . Graph < networkx : graph > `
prefix : str""" | node_headers = list ( set ( [ a for n , attrs in graph . nodes ( data = True ) for a in attrs . keys ( ) ] ) )
edge_headers = list ( set ( [ a for s , t , attrs in graph . edges ( data = True ) for a in attrs . keys ( ) ] ) )
value = lambda attrs , h : _recast_value ( attrs [ h ] ) if h in attrs else ''
with open ( pre... |
async def start ( self ) :
"""Initialize and start WebServer""" | logging . info ( 'Starting server, listening on %s.' , self . port )
runner = web . AppRunner ( self )
await runner . setup ( )
site = web . TCPSite ( runner , '' , self . port )
await site . start ( ) |
def movable_items ( self ) :
"""Filter selection
Filter items of selection that cannot be moved ( i . e . are not instances of ` Item ` ) and return the rest .""" | view = self . view
if self . _move_name_v :
yield InMotion ( self . _item , view )
else :
selected_items = set ( view . selected_items )
for item in selected_items :
if not isinstance ( item , Item ) :
continue
yield InMotion ( item , view ) |
def writequery ( log , sqlQuery , dbConn , Force = False , manyValueList = False ) :
"""* Execute a MySQL write command given a sql query *
* * Key Arguments : * *
- ` ` sqlQuery ` ` - - the MySQL command to execute
- ` ` dbConn ` ` - - the db connection
- ` ` Force ` ` - - do not exit code if error occurs ... | log . debug ( 'starting the ``writequery`` function' )
import pymysql
import warnings
warnings . filterwarnings ( 'error' , category = pymysql . Warning )
message = ""
try :
cursor = dbConn . cursor ( pymysql . cursors . DictCursor )
except Exception as e :
log . error ( 'could not create the database cursor.' ... |
def get_linearoperator ( shape , A , timer = None ) :
"""Enhances aslinearoperator if A is None .""" | ret = None
import scipy . sparse . linalg as scipylinalg
if isinstance ( A , LinearOperator ) :
ret = A
elif A is None :
ret = IdentityLinearOperator ( shape )
elif isinstance ( A , numpy . ndarray ) or isspmatrix ( A ) :
ret = MatrixLinearOperator ( A )
elif isinstance ( A , numpy . matrix ) :
ret = Ma... |
def substitute ( P , x0 , x1 , V = 0 ) :
"""Substitute a variable in a polynomial array .
Args :
P ( Poly ) : Input data .
x0 ( Poly , int ) : The variable to substitute . Indicated with either unit
variable , e . g . ` x ` , ` y ` , ` z ` , etc . or through an integer
matching the unit variables dimensio... | x0 , x1 = map ( Poly , [ x0 , x1 ] )
dim = np . max ( [ p . dim for p in [ P , x0 , x1 ] ] )
dtype = chaospy . poly . typing . dtyping ( P . dtype , x0 . dtype , x1 . dtype )
P , x0 , x1 = [ chaospy . poly . dimension . setdim ( p , dim ) for p in [ P , x0 , x1 ] ]
if x0 . shape :
x0 = [ x for x in x0 ]
else :
... |
def debug_complete ( ) :
'''Debugging route for complete .''' | if not 'uniqueId' in request . args :
raise ExperimentError ( 'improper_inputs' )
else :
unique_id = request . args [ 'uniqueId' ]
mode = request . args [ 'mode' ]
try :
user = Participant . query . filter ( Participant . uniqueid == unique_id ) . one ( )
user . status = COMPLETED
... |
def trim_trailing_silence ( self ) :
"""Trim the trailing silences of the pianorolls of all tracks . Trailing
silences are considered globally .""" | active_length = self . get_active_length ( )
for track in self . tracks :
track . pianoroll = track . pianoroll [ : active_length ] |
def action ( self , relationship ) :
"""Add a nested File Action .""" | action_obj = FileAction ( self . xid , relationship )
self . _children . append ( action_obj ) |
def load_lsa_information ( self ) :
"""Loads a dictionary from disk that maps permissible words to their LSA term vectors .""" | if not ( 49 < int ( self . clustering_parameter ) < 101 ) :
raise Exception ( 'Only LSA dimensionalities in the range 50-100' + ' are supported.' )
if not self . quiet :
print "Loading LSA term vectors..."
# the protocol2 used the pickle highest protocol and this one is a smaller file
with open ( os . path . jo... |
def __xml_scan ( node , env , path , arg ) :
"""Simple XML file scanner , detecting local images and XIncludes as implicit dependencies .""" | # Does the node exist yet ?
if not os . path . isfile ( str ( node ) ) :
return [ ]
if env . get ( 'DOCBOOK_SCANENT' , '' ) : # Use simple pattern matching for system entities . . . , no support
# for recursion yet .
contents = node . get_text_contents ( )
return sentity_re . findall ( contents )
xsl_file =... |
def has_any_permissions ( self , user ) :
"""Return a boolean to indicate whether the supplied user has any
permissions at all on the associated model""" | for perm in self . get_all_model_permissions ( ) :
if self . has_specific_permission ( user , perm . codename ) :
return True
return False |
def get_samples_with_constraints ( self , init_points_count ) :
"""Draw random samples and only save those that satisfy constraints
Finish when required number of samples is generated""" | samples = np . empty ( ( 0 , self . space . dimensionality ) )
while samples . shape [ 0 ] < init_points_count :
domain_samples = self . get_samples_without_constraints ( init_points_count )
valid_indices = ( self . space . indicator_constraints ( domain_samples ) == 1 ) . flatten ( )
if sum ( valid_indices... |
def update_variogram_model ( self , variogram_model , variogram_parameters = None , variogram_function = None , nlags = 6 , weight = False , anisotropy_scaling = 1. , anisotropy_angle = 0. ) :
"""Allows user to update variogram type and / or
variogram model parameters .
Parameters
variogram _ model : str
Ma... | if anisotropy_scaling != self . anisotropy_scaling or anisotropy_angle != self . anisotropy_angle :
if self . verbose :
print ( "Adjusting data for anisotropy..." )
self . anisotropy_scaling = anisotropy_scaling
self . anisotropy_angle = anisotropy_angle
self . X_ADJUSTED , self . Y_ADJUSTED = _... |
def nvmlSystemGetHicVersion ( ) :
r"""* Retrieves the IDs and firmware versions for any Host Interface Cards ( HICs ) in the system .
* For S - class products .
* The \ a hwbcCount argument is expected to be set to the size of the input \ a hwbcEntries array .
* The HIC must be connected to an S - class syste... | c_count = c_uint ( 0 )
hics = None
fn = _nvmlGetFunctionPointer ( "nvmlSystemGetHicVersion" )
# get the count
ret = fn ( byref ( c_count ) , None )
# this should only fail with insufficient size
if ( ( ret != NVML_SUCCESS ) and ( ret != NVML_ERROR_INSUFFICIENT_SIZE ) ) :
raise NVMLError ( ret )
# if there are no hi... |
def _dump_stats ( self ) :
'''Dumps the stats out''' | extras = { }
if 'total' in self . stats_dict :
self . logger . debug ( "Compiling total/fail dump stats" )
for key in self . stats_dict [ 'total' ] :
final = 'total_{t}' . format ( t = key )
extras [ final ] = self . stats_dict [ 'total' ] [ key ] . value ( )
for key in self . stats_dict [ '... |
def insert_multi ( self , keys , ttl = 0 , format = None , persist_to = 0 , replicate_to = 0 ) :
"""Add multiple keys . Multi variant of : meth : ` insert `
. . seealso : : : meth : ` insert ` , : meth : ` upsert _ multi ` , : meth : ` upsert `""" | return _Base . insert_multi ( self , keys , ttl = ttl , format = format , persist_to = persist_to , replicate_to = replicate_to ) |
def get_magic_comment ( self , name , expand_macros = False ) :
"""Return a value of # name = value comment in spec or None .""" | match = re . search ( r'^#\s*?%s\s?=\s?(\S+)' % re . escape ( name ) , self . txt , flags = re . M )
if not match :
return None
val = match . group ( 1 )
if expand_macros and has_macros ( val ) : # don ' t parse using rpm unless required
val = self . expand_macro ( val )
return val |
def new_concept ( self , tag , clemma = "" , tokens = None , cidx = None , ** kwargs ) :
'''Create a new concept object and add it to concept list
tokens can be a list of Token objects or token indices''' | if cidx is None :
cidx = self . new_concept_id ( )
if tokens :
tokens = ( t if isinstance ( t , Token ) else self [ t ] for t in tokens )
c = Concept ( cidx = cidx , tag = tag , clemma = clemma , sent = self , tokens = tokens , ** kwargs )
return self . add_concept ( c ) |
def calc_all_routes_info ( self , npaths = 3 , real_time = True , stop_at_bounds = False , time_delta = 0 ) :
"""Calculate all route infos .""" | routes = self . get_route ( npaths , time_delta )
results = { route [ 'routeName' ] : self . _add_up_route ( route [ 'results' ] , real_time = real_time , stop_at_bounds = stop_at_bounds ) for route in routes }
route_time = [ route [ 0 ] for route in results . values ( ) ]
route_distance = [ route [ 1 ] for route in re... |
def generate_example ( self ) :
"""Returns a single Instance .
: return : the next example
: rtype : Instance""" | data = javabridge . call ( self . jobject , "generateExample" , "()Lweka/core/Instance;" )
if data is None :
return None
else :
return Instance ( data ) |
def process_raw_data ( cls , raw_data ) :
"""Create a new model using raw API response .""" | properties = raw_data [ "properties" ]
ip_pools = [ ]
for raw_content in properties . get ( "ipPools" , [ ] ) :
raw_content [ "parentResourceID" ] = raw_data [ "resourceId" ]
raw_content [ "grandParentResourceID" ] = raw_data [ "parentResourceID" ]
ip_pools . append ( IPPools . from_raw_data ( raw_content )... |
def connection ( self ) :
"""Connect to and return mongodb database object .""" | if self . _connection is None :
self . _connection = self . client [ self . database_name ]
if self . disable_id_injector :
incoming = self . _connection . _Database__incoming_manipulators
for manipulator in incoming :
if isinstance ( manipulator , pymongo . son_manipulator . ObjectI... |
def explain ( self , expr , params = None ) :
"""Query for and return the query plan associated with the indicated
expression or SQL query .
Returns
plan : string""" | if isinstance ( expr , ir . Expr ) :
context = self . dialect . make_context ( params = params )
query_ast = self . _build_ast ( expr , context )
if len ( query_ast . queries ) > 1 :
raise Exception ( 'Multi-query expression' )
query = query_ast . queries [ 0 ] . compile ( )
else :
query = e... |
def get_smart_storage_config ( self , smart_storage_config_url ) :
"""Returns a SmartStorageConfig Instance for each controller .""" | return ( smart_storage_config . HPESmartStorageConfig ( self . _conn , smart_storage_config_url , redfish_version = self . redfish_version ) ) |
def _getStatementForEffect ( self , effect , methods ) :
'''This function loops over an array of objects containing a resourceArn and
conditions statement and generates the array of statements for the policy .''' | statements = [ ]
if len ( methods ) > 0 :
statement = self . _getEmptyStatement ( effect )
for curMethod in methods :
if curMethod [ 'conditions' ] is None or len ( curMethod [ 'conditions' ] ) == 0 :
statement [ 'Resource' ] . append ( curMethod [ 'resourceArn' ] )
else :
... |
def add_data ( self , data ) :
"""Add data to the currently in progress entry .
Args :
data ( bytes ) : The data that we want to add .
Returns :
int : An error code""" | if self . data_size - self . data_index < len ( data ) :
return Error . DESTINATION_BUFFER_TOO_SMALL
if self . in_progress is not None :
self . in_progress . data += data
return Error . NO_ERROR |
def _set_exec_ ( self , v , load = False ) :
"""Setter method for exec _ , mapped from YANG variable / aaa _ config / aaa / accounting / exec ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ exec _ is considered as a private
method . Backends looking to p... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = exec_ . exec_ , is_container = 'container' , presence = False , yang_name = "exec" , rest_name = "exec" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extension... |
def all_tamil ( word_in ) :
"""predicate checks if all letters of the input word are Tamil letters""" | if isinstance ( word_in , list ) :
word = word_in
else :
word = get_letters ( word_in )
return all ( [ ( letter in tamil_letters ) for letter in word ] ) |
def on_user_init ( target , args , kwargs ) :
"""Provide hook on : class : ` ~ invenio _ accounts . models . User ` initialization .
Automatically convert a dict to a
: class : ` ~ . UserProfile ` instance . This is needed
during e . g . user registration where Flask - Security will initialize a
user model ... | profile = kwargs . pop ( 'profile' , None )
if profile is not None and not isinstance ( profile , UserProfile ) :
profile = UserProfile ( ** profile )
if kwargs . get ( 'id' ) :
profile . user_id = kwargs [ 'id' ]
kwargs [ 'profile' ] = profile |
def to_json ( self ) :
"""Serialises a HucitAuthor to a JSON formatted string .
Example :
> > homer = kb . get _ resource _ by _ urn ( " urn : cts : greekLit : tlg0012 " )
> > homer . to _ json ( )
" name _ abbreviations " : [
" Hom . "
" urn " : " urn : cts : greekLit : tlg0012 " ,
" works " : [
" ... | names = self . get_names ( )
return json . dumps ( { "uri" : self . subject , "urn" : str ( self . get_urn ( ) ) , "names" : [ { "language" : lang , "label" : label } for lang , label in names ] , "name_abbreviations" : self . get_abbreviations ( ) , "works" : [ json . loads ( work . to_json ( ) ) for work in self . ge... |
def _load_version ( cls , unpickler , version ) :
"""A function to load a previously saved SentenceSplitter instance .
Parameters
unpickler : GLUnpickler
A GLUnpickler file handler .
version : int
Version number maintained by the class writer .""" | state , _exclude , _features = unpickler . load ( )
features = state [ 'features' ]
excluded_features = state [ 'excluded_features' ]
model = cls . __new__ ( cls )
model . _setup ( )
model . __proxy__ . update ( state )
model . _exclude = _exclude
model . _features = _features
return model |
def get ( self , rlzi , grp = None ) :
""": param rlzi : a realization index
: param grp : None ( all groups ) or a string of the form " grp - XX "
: returns : the hazard curves for the given realization""" | self . init ( )
assert self . sids is not None
pmap = probability_map . ProbabilityMap ( len ( self . imtls . array ) , 1 )
grps = [ grp ] if grp is not None else sorted ( self . pmap_by_grp )
array = self . rlzs_assoc . by_grp ( )
for grp in grps :
for gsim_idx , rlzis in enumerate ( array [ grp ] ) :
for ... |
def set_root_path ( self , root_path ) :
"""Set root path""" | self . root_path = root_path
self . install_model ( )
index = self . fsmodel . setRootPath ( root_path )
self . proxymodel . setup_filter ( self . root_path , [ ] )
self . setRootIndex ( self . proxymodel . mapFromSource ( index ) ) |
def to_mongo ( self , disjunction = True ) :
"""Create from current state a valid MongoDB query expression .
: return : MongoDB query expression
: rtype : dict""" | q = { }
# add all the main clauses to ` q `
clauses = [ e . expr for e in self . _main ]
if clauses :
if disjunction :
if len ( clauses ) + len ( self . _where ) > 1 :
q [ '$or' ] = clauses
else : # simplify ' or ' of one thing
q . update ( clauses [ 0 ] )
else :
... |
def _get_selected_items ( self ) :
"""List of currently selected items""" | selection = self . get_selection ( )
if selection . get_mode ( ) != gtk . SELECTION_MULTIPLE :
raise AttributeError ( 'selected_items only valid for ' 'select_multiple' )
model , selected_paths = selection . get_selected_rows ( )
result = [ ]
for path in selected_paths :
result . append ( model [ path ] [ 0 ] )... |
def orbit ( self , orbit ) :
"""Initialize the propagator
Args :
orbit ( Orbit )""" | self . _orbit = orbit
tle = Tle . from_orbit ( orbit )
lines = tle . text . splitlines ( )
if len ( lines ) == 3 :
_ , line1 , line2 = lines
else :
line1 , line2 = lines
self . tle = twoline2rv ( line1 , line2 , wgs72 ) |
def setApparentDecel ( self , typeID , decel ) :
"""setDecel ( string , double ) - > None
Sets the apparent deceleration in m / s ^ 2 of vehicles of this type .""" | self . _connection . _sendDoubleCmd ( tc . CMD_SET_VEHICLETYPE_VARIABLE , tc . VAR_APPARENT_DECEL , typeID , decel ) |
def process_global ( name , val = None , setval = False ) :
'''Access and set global variables for the current process .''' | p = current_process ( )
if not hasattr ( p , '_pulsar_globals' ) :
p . _pulsar_globals = { 'lock' : Lock ( ) }
if setval :
p . _pulsar_globals [ name ] = val
else :
return p . _pulsar_globals . get ( name ) |
def _set_alarm_interval ( self , v , load = False ) :
"""Setter method for alarm _ interval , mapped from YANG variable / rmon / alarm _ entry / alarm _ interval ( uint32)
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ alarm _ interval is considered as a private
meth... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'1 .. 2147483648' ] } ) , is_leaf = True , ... |
def installed ( package , version ) :
"""Check if the package meets the required version .
The version specifier consists of an optional comparator ( one of = , = = , > ,
< , > = , < = ) and an arbitrarily long version number separated by dots . The
should be as you would expect , e . g . for an installed ver... | if not exists ( package ) :
return False
number , comparator = _split_version_specifier ( version )
modversion = _query ( package , '--modversion' )
try :
result = _compare_versions ( modversion , number )
except ValueError :
msg = "{0} is not a correct version specifier" . format ( version )
raise Valu... |
def find_position ( edges , prow , bstart , bend , total = 5 ) :
"""Find a EMIR CSU bar position in a edge image .
Parameters
edges ; ndarray ,
a 2d image with 1 where is a border , 0 otherwise
prow : int ,
reference ' row ' of the bars
bstart : int ,
minimum ' x ' position of a bar ( 0 - based )
be... | nt = total // 2
# This bar is too near the border
if prow - nt < 0 or prow + nt >= edges . shape [ 0 ] :
return [ ]
s2edges = edges [ prow - nt : prow + nt + 1 , bstart : bend ]
structure = morph . generate_binary_structure ( 2 , 2 )
# 8 way conection
har , num_f = mes . label ( s2edges , structure = structure )
ce... |
def get_parser ( ) :
'''Return the command - line parser''' | parser = argparse . ArgumentParser ( description = "Reverse, undo, and calculate CRC32 checksums" )
subparsers = parser . add_subparsers ( metavar = 'action' )
poly_flip_parser = argparse . ArgumentParser ( add_help = False )
subparser_group = poly_flip_parser . add_mutually_exclusive_group ( )
subparser_group . add_ar... |
def initialize_weights_nn ( data , means , lognorm = True ) :
"""Initializes the weights with a nearest - neighbor approach using the means .""" | # TODO
genes , cells = data . shape
k = means . shape [ 1 ]
if lognorm :
data = log1p ( cell_normalize ( data ) )
for i in range ( cells ) :
for j in range ( k ) :
pass |
def set_char ( key , value ) :
"""Updates charters used to render components .""" | global _chars
category = _get_char_category ( key )
if not category :
raise KeyError
_chars [ category ] [ key ] = value |
def versions ( self ) :
"""Read versions from the table
The versions are kept in cache for the next reads .""" | if self . _versions is None :
with self . database . cursor_autocommit ( ) as cursor :
query = """
SELECT number,
date_start,
date_done,
log,
addons
FROM {}
""" . forma... |
def create_user ( username , password , permissions , users = None ) :
'''Create user accounts
CLI Example :
. . code - block : : bash
salt dell drac . create _ user [ USERNAME ] [ PASSWORD ] [ PRIVILEGES ]
salt dell drac . create _ user diana secret login , test _ alerts , clear _ logs
DRAC Privileges
... | _uids = set ( )
if users is None :
users = list_users ( )
if username in users :
log . warning ( '\'%s\' already exists' , username )
return False
for idx in six . iterkeys ( users ) :
_uids . add ( users [ idx ] [ 'index' ] )
uid = sorted ( list ( set ( range ( 2 , 12 ) ) - _uids ) , reverse = True ) .... |
def is_running ( self ) :
"""Check if the service is running .""" | try :
kill ( int ( self . pid . get ( ) ) , 0 )
return True
# Process not running , remove PID / lock file if it exists
except :
self . pid . remove ( )
self . lock . remove ( )
return False |
def signup ( self , project_name , email ) :
"""Signup for a new project .""" | uri = 'openstack/sign-up'
data = { "project_name" : project_name , "email" : email , }
post_body = json . dumps ( data )
resp , body = self . post ( uri , body = post_body )
self . expected_success ( 200 , resp . status )
body = json . loads ( body )
return rest_client . ResponseBody ( resp , body ) |
def geocode_addresses ( self , project_id , dataset_id , address_field , geometry_field , ** extra_params ) :
"""Geocode addresses in a dataset . The dataset must have a string field
with the addresses to geocode and a geometry field ( points ) for the
geocoding results .
: param project _ id : Must be a stri... | project_url = ( '/projects/{project_id}' ) . format ( project_id = project_id )
dataset_url = ( '{project_url}/datasets/{dataset_id}' ) . format ( project_url = project_url , dataset_id = dataset_id )
project_query_url = ( '{project_url}/sql' ) . format ( project_url = project_url )
dataset_data = self . get ( dataset_... |
def register_job_from_link ( self , link , key , ** kwargs ) :
"""Register a job in the ` JobArchive ` from a ` Link ` object""" | job_config = kwargs . get ( 'job_config' , None )
if job_config is None :
job_config = link . args
status = kwargs . get ( 'status' , JobStatus . unknown )
job_details = JobDetails ( jobname = link . linkname , jobkey = key , appname = link . appname , logfile = kwargs . get ( 'logfile' ) , jobconfig = job_config ,... |
def copy ( self : 'Model' , * , include : 'SetStr' = None , exclude : 'SetStr' = None , update : 'DictStrAny' = None , deep : bool = False , ) -> 'Model' :
"""Duplicate a model , optionally choose which fields to include , exclude and change .
: param include : fields to include in new model
: param exclude : f... | if include is None and exclude is None and update is None : # skip constructing values if no arguments are passed
v = self . __values__
else :
return_keys = self . _calculate_keys ( include = include , exclude = exclude , skip_defaults = False )
if return_keys :
v = { ** { k : v for k , v in self . ... |
def sort_states ( states , sort_list ) :
"""Returns a list of sorted states , original states list remains unsorted
The sort list is a list of state field : field key pairs
For example ( as YAML ) :
- data : position
- meta : created _ at
The field _ key part can be a list to simplify input
- meta : cre... | sorted_states = states . copy ( )
for sort_pair in reversed ( _convert_list_of_dict_to_tuple ( sort_list ) ) :
if sort_pair [ 0 ] . lstrip ( '-' ) in [ 'data' , 'measure' , 'meta' ] :
sorted_states = _state_value_sort ( sorted_states , sort_pair , _state_key_function )
elif sort_pair [ 0 ] == 'groupings... |
def registerUpgrader ( upgrader , typeName , oldVersion , newVersion ) :
"""Register a callable which can perform a schema upgrade between two
particular versions .
@ param upgrader : A one - argument callable which will upgrade an object . It
is invoked with an instance of the old version of the object .
@... | # assert ( typeName , oldVersion , newVersion ) not in _ upgradeRegistry , " duplicate upgrader "
# ^ this makes the tests blow up so it ' s just disabled for now ; perhaps we
# should have a specific test mode
# assert newVersion - oldVersion = = 1 , " read the doc string "
assert isinstance ( typeName , str ) , "read... |
def run ( * sheetlist ) :
'Main entry point ; launches vdtui with the given sheets already pushed ( last one is visible )' | # reduce ESC timeout to 25ms . http : / / en . chys . info / 2009/09 / esdelay - ncurses /
os . putenv ( 'ESCDELAY' , '25' )
ret = wrapper ( cursesMain , sheetlist )
if ret :
print ( ret ) |
def get_result_files ( self , result ) :
"""Return a dictionary containing filename : filepath values for each
output file associated with an id .
Result can be either a result dictionary ( e . g . , obtained with the
get _ results ( ) method ) or a result id .""" | if isinstance ( result , dict ) :
result_id = result [ 'meta' ] [ 'id' ]
else : # Should already be a string containing the id
result_id = result
result_data_dir = os . path . join ( self . get_data_dir ( ) , result_id )
filenames = next ( os . walk ( result_data_dir ) ) [ 2 ]
filename_path_pairs = [ ( f , os .... |
def read ( self ) :
"""This module is lazy - loaded by default . You can read all internal
structure by calling this method .""" | stack = [ self [ 0 ] . child ]
while stack :
current = stack . pop ( )
if current . right :
stack . append ( current . right )
if current . left :
stack . append ( current . left )
self [ 0 ] . seek ( 0 ) |
async def _set_get_started ( self ) :
"""Set the " get started " action for all configured pages .""" | page = self . settings ( )
if 'get_started' in page :
payload = page [ 'get_started' ]
else :
payload = { 'action' : 'get_started' }
await self . _send_to_messenger_profile ( page , { 'get_started' : { 'payload' : ujson . dumps ( payload ) , } , } )
logger . info ( 'Get started set for page %s' , page [ 'page_i... |
def at ( self , instant ) :
"""Iterates ( in chronological order ) over all events that are occuring during ` instant ` .
Args :
instant ( Arrow object )""" | for event in self :
if event . begin <= instant <= event . end :
yield event |
def items ( self ) :
""": return : a list of name / value attribute pairs sorted by attribute name .""" | sorted_keys = sorted ( self . keys ( ) )
return [ ( k , self [ k ] ) for k in sorted_keys ] |
def to_dict ( self , details = False , first_value = False , enforce_list = False ) :
"""Converts matches to a dict object .
: param details if True , values will be complete Match object , else it will be only string Match . value property
: type details : bool
: param first _ value if True , only the first ... | ret = MatchesDict ( )
for match in sorted ( self ) :
value = match if details else match . value
ret . matches [ match . name ] . append ( match )
if not enforce_list and value not in ret . values_list [ match . name ] :
ret . values_list [ match . name ] . append ( value )
if match . name in re... |
def get_json_response ( self , content , ** kwargs ) :
"""Returns a json response object .""" | # Don ' t care to return a django form or view in the response here .
# Remove those from the context .
if isinstance ( content , dict ) :
response_content = { k : deepcopy ( v ) for k , v in content . items ( ) if k not in ( 'form' , 'view' ) or k in ( 'form' , 'view' ) and not isinstance ( v , ( Form , View ) ) }... |
def msearch ( self , body , index = None , doc_type = None , ** query_params ) :
"""Execute several search requests within the same API .
` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / search - multi - search . html > ` _
: arg body : The request definitions ( metadata - ... | self . _es_parser . is_not_empty_params ( body )
path = self . _es_parser . make_path ( index , doc_type , EsMethods . MULTIPLE_SEARCH )
result = yield self . _perform_request ( HttpMethod . GET , path , self . _bulk_body ( body ) , params = query_params )
returnValue ( result ) |
def user_organization_membership_make_default ( self , id , membership_id , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / organization _ memberships # set - membership - as - default" | api_path = "/api/v2/users/{id}/organization_memberships/{membership_id}/make_default.json"
api_path = api_path . format ( id = id , membership_id = membership_id )
return self . call ( api_path , method = "PUT" , data = data , ** kwargs ) |
def layout_json_schema ( self ) :
"""Load layout . json schema file .""" | if self . _layout_json_schema is None and self . layout_json_schema_file is not None :
if os . path . isfile ( self . layout_json_schema_file ) :
with open ( self . layout_json_schema_file ) as fh :
self . _layout_json_schema = json . load ( fh )
return self . _layout_json_schema |
def postinit ( self , args , defaults , kwonlyargs , kw_defaults , annotations , kwonlyargs_annotations = None , varargannotation = None , kwargannotation = None , ) :
"""Do some setup after initialisation .
: param args : The names of the required arguments .
: type args : list ( AssignName )
: param default... | self . args = args
self . defaults = defaults
self . kwonlyargs = kwonlyargs
self . kw_defaults = kw_defaults
self . annotations = annotations
self . kwonlyargs_annotations = kwonlyargs_annotations
self . varargannotation = varargannotation
self . kwargannotation = kwargannotation |
def clear_file_format_cache ( ) :
"""Remove syntax - formatted lines in the cache . Use this
when you change the Pygments syntax or Token formatting
and want to redo how files may have previously been
syntax marked .""" | for fname , cache_info in file_cache . items ( ) :
for format , lines in cache_info . lines . items ( ) :
if 'plain' == format :
continue
file_cache [ fname ] . lines [ format ] = None
pass
pass
pass |
def cmd_add ( self , txt ) :
"""Enter add mode - all text entered now will be
processed as adding information until cancelled""" | self . show_output ( 'Adding ' , txt )
self . raw . add ( txt )
print ( self . raw )
return 'Added ' + txt |
def fetch_page ( cls , index , max_ = None ) :
"""Return a query set which requests a specific page .
: param index : Index of the first element of the page to fetch .
: type index : : class : ` int `
: param max _ : Maximum number of elements to fetch
: type max _ : : class : ` int ` or : data : ` None `
... | result = cls ( )
result . index = index
result . max_ = max_
return result |
def is_all_field_none ( self ) :
""": rtype : bool""" | if self . _id_ is not None :
return False
if self . _created is not None :
return False
if self . _updated is not None :
return False
if self . _public_uuid is not None :
return False
if self . _first_name is not None :
return False
if self . _middle_name is not None :
return False
if self . _la... |
def vR ( self , * args , ** kwargs ) :
"""NAME :
vR
PURPOSE :
return radial velocity at time t
INPUT :
t - ( optional ) time at which to get the radial velocity
vo = ( Object - wide default ) physical scale for velocities to use to convert
use _ physical = use to override Object - wide default for usi... | thiso = self ( * args , ** kwargs )
onet = ( len ( thiso . shape ) == 1 )
if onet :
return thiso [ 1 ]
else :
return thiso [ 1 , : ] |
def pacific_atlantic ( matrix ) :
""": type matrix : List [ List [ int ] ]
: rtype : List [ List [ int ] ]""" | n = len ( matrix )
if not n :
return [ ]
m = len ( matrix [ 0 ] )
if not m :
return [ ]
res = [ ]
atlantic = [ [ False for _ in range ( n ) ] for _ in range ( m ) ]
pacific = [ [ False for _ in range ( n ) ] for _ in range ( m ) ]
for i in range ( n ) :
dfs ( pacific , matrix , float ( "-inf" ) , i , 0 )
... |
def _commit ( self ) :
""": return : ( dict ) Response object content""" | assert self . uri is not None , Exception ( "BadArgument: uri property cannot be None" )
url = '{}/{}' . format ( self . uri , self . __class__ . __name__ )
serialized_json = jsonpickle . encode ( self , unpicklable = False , )
headers = { 'Content-Type' : 'application/json' , 'Content-Length' : str ( len ( serialized_... |
def exportable_keys ( self ) :
"""Return a list of keys that are exportable from this tuple .
Returns all keys that are not private in any of the tuples .""" | keys = collections . defaultdict ( list )
for tup in self . _tuples :
for key , private in tup . _keys_and_privacy ( ) . items ( ) :
keys [ key ] . append ( private )
return [ k for k , ps in keys . items ( ) if not any ( ps ) ] |
def get_all_signing_certs ( self , marker = None , max_items = None , user_name = None ) :
"""Get all signing certificates associated with an account .
If the user _ name is not specified , it is determined implicitly based
on the AWS Access Key ID used to sign the request .
: type marker : string
: param m... | params = { }
if marker :
params [ 'Marker' ] = marker
if max_items :
params [ 'MaxItems' ] = max_items
if user_name :
params [ 'UserName' ] = user_name
return self . get_response ( 'ListSigningCertificates' , params , list_marker = 'Certificates' ) |
def update ( name , profile = "splunk" , ** kwargs ) :
'''Update a splunk search
CLI Example :
splunk _ search . update ' my search name ' sharing = app''' | client = _get_splunk ( profile )
search = client . saved_searches [ name ]
props = _get_splunk_search_props ( search )
updates = kwargs
update_needed = False
update_set = dict ( )
diffs = [ ]
for key in sorted ( kwargs ) :
old_value = props . get ( key , None )
new_value = updates . get ( key , None )
if is... |
def f ( field : str , kwargs : Dict [ str , Any ] , default : Optional [ Any ] = None ) -> str :
"""Alias for more readable command construction""" | if default is not None :
return str ( kwargs . get ( field , default ) )
return str ( kwargs [ field ] ) |
def netconf_state_sessions_session_username ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
netconf_state = ET . SubElement ( config , "netconf-state" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring" )
sessions = ET . SubElement ( netconf_state , "sessions" )
session = ET . SubElement ( sessions , "session" )
session_id_key = ET . SubElement ( session , "sessi... |
def draw_frame ( self , x : int , y : int , width : int , height : int , title : str = "" , clear : bool = True , fg : Optional [ Tuple [ int , int , int ] ] = None , bg : Optional [ Tuple [ int , int , int ] ] = None , bg_blend : int = tcod . constants . BKGND_SET , ) -> None :
"""Draw a framed rectangle with an o... | x , y = self . _pythonic_index ( x , y )
title_ = title . encode ( "utf-8" )
# type : bytes
lib . print_frame ( self . console_c , x , y , width , height , title_ , len ( title_ ) , ( fg , ) if fg is not None else ffi . NULL , ( bg , ) if bg is not None else ffi . NULL , bg_blend , clear , ) |
def _call_with_selection ( func ) :
"""Decorator that passes a ` Selection ` built from the non - kwonly args .""" | wrapped_kwonly_params = [ param for param in inspect . signature ( func ) . parameters . values ( ) if param . kind == param . KEYWORD_ONLY ]
sel_sig = inspect . signature ( Selection )
default_sel_sig = sel_sig . replace ( parameters = [ param . replace ( default = None ) if param . default is param . empty else param... |
def add ( self , information , timeout = - 1 ) :
"""Adds a data center resource based upon the attributes specified .
Args :
information : Data center information
timeout : Timeout in seconds . Wait for task completion by default . The timeout does not abort the operation
in OneView ; it just stops waiting ... | return self . _client . create ( information , timeout = timeout ) |
def on_okButton ( self , event ) :
"""grab user input values , format them , and run huji _ magic . py with the appropriate flags""" | os . chdir ( self . WD )
options = { }
HUJI_file = self . bSizer0 . return_value ( )
if not HUJI_file :
pw . simple_warning ( "You must select a HUJI format file" )
return False
options [ 'magfile' ] = HUJI_file
magicoutfile = os . path . split ( HUJI_file ) [ 1 ] + ".magic"
outfile = os . path . join ( self . ... |
def use_comparative_catalog_view ( self ) :
"""Pass through to provider CatalogLookupSession . use _ comparative _ catalog _ view""" | self . _catalog_view = COMPARATIVE
# self . _ get _ provider _ session ( ' catalog _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_comparative_catalog_view ( )
except AttributeError :
pass |
def to_snake_case ( text ) :
"""Convert to snake case .
: param str text :
: rtype : str
: return :""" | s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , text )
return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( ) |
def _write_current_buffer_for_group_key ( self , key ) :
"""Find the buffer for a given group key , prepare it to be written
and writes it calling write ( ) method .""" | write_info = self . write_buffer . pack_buffer ( key )
self . write ( write_info . get ( 'file_path' ) , self . write_buffer . grouping_info [ key ] [ 'membership' ] )
self . write_buffer . clean_tmp_files ( write_info )
self . write_buffer . add_new_buffer_for_group ( key ) |
def log_coroutine ( self , cor , * args , ** kwargs ) :
"""Run a coroutine logging any exception raised .
This routine will not block until the coroutine is finished
nor will it return any result . It will just log if any
exception is raised by the coroutine during operation .
It is safe to call from both i... | if self . stopping :
raise LoopStoppingError ( "Could not launch coroutine because loop is shutting down: %s" % cor )
self . start ( )
cor = _instaniate_coroutine ( cor , args , kwargs )
def _run_and_log ( ) :
task = self . loop . create_task ( cor )
task . add_done_callback ( lambda x : _log_future_excepti... |
def convert_to_merged_ids ( self , id_run ) :
"""Converts any identified phrases in the run into phrase _ ids . The dictionary provides all acceptable phrases
: param id _ run : a run of token ids
: param dictionary : a dictionary of acceptable phrases described as there component token ids
: return : a run o... | i = 0
rv = [ ]
while i < len ( id_run ) :
phrase_id , offset = self . max_phrase ( id_run , i )
if phrase_id :
rv . append ( phrase_id )
i = offset
else :
rv . append ( id_run [ i ] )
i += 1
return rv |
def get_vary_headers ( self , request , response ) :
"""Hook for patching the vary header""" | headers = [ ]
accessed = False
try :
accessed = request . session . accessed
except AttributeError :
pass
if accessed :
headers . append ( "Cookie" )
return headers |
def to_latex ( self , column_format = None , longtable = False , encoding = None , multicolumn = False , multicolumn_format = None , multirow = False ) :
"""Render a DataFrame to a LaTeX tabular / longtable environment output .""" | from pandas . io . formats . latex import LatexFormatter
latex_renderer = LatexFormatter ( self , column_format = column_format , longtable = longtable , multicolumn = multicolumn , multicolumn_format = multicolumn_format , multirow = multirow )
if encoding is None :
encoding = 'utf-8'
if hasattr ( self . buf , 'wr... |
def check_dupl_sources ( self ) : # used in print _ csm _ info
"""Extracts duplicated sources , i . e . sources with the same source _ id in
different source groups . Raise an exception if there are sources with
the same ID which are not duplicated .
: returns : a list of list of sources , ordered by source _... | dd = collections . defaultdict ( list )
for src_group in self . src_groups :
for src in src_group :
try :
srcid = src . source_id
except AttributeError : # src is a Node object
srcid = src [ 'id' ]
dd [ srcid ] . append ( src )
dupl = [ ]
for srcid , srcs in sorted ( ... |
def id ( self , id ) :
"""Sets the id of this BulkResponse .
Bulk ID
: param id : The id of this BulkResponse .
: type : str""" | if id is None :
raise ValueError ( "Invalid value for `id`, must not be `None`" )
if id is not None and not re . search ( '^[A-Za-z0-9]{32}' , id ) :
raise ValueError ( "Invalid value for `id`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`" )
self . _id = id |
def js_click ( self , selector , by = By . CSS_SELECTOR ) :
"""Clicks an element using pure JS . Does not use jQuery .""" | selector , by = self . __recalculate_selector ( selector , by )
if by == By . LINK_TEXT :
message = ( "Pure JavaScript doesn't support clicking by Link Text. " "You may want to use self.jquery_click() instead, which " "allows this with :contains(), assuming jQuery isn't blocked. " "For now, self.js_click() will use... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.