signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def expand_braces ( pattern ) :
"""Find the rightmost , innermost set of braces and , if it contains a
comma - separated list , expand its contents recursively ( any of its items
may itself be a list enclosed in braces ) .
Return the full list of expanded strings .""" | res = set ( )
# Used instead of s . strip ( ' { } ' ) because strip is greedy .
# We want to remove only ONE leading { and ONE trailing } , if both exist
def remove_outer_braces ( s ) :
if s [ 0 ] == '{' and s [ - 1 ] == '}' :
return s [ 1 : - 1 ]
return s
match = EXPAND_BRACES_RE . search ( pattern )
i... |
def read_files ( filenames ) :
"""Read a file into memory .""" | if isinstance ( filenames , list ) :
for filename in filenames :
with open ( filename , 'r' ) as infile :
return infile . read ( )
else :
with open ( filenames , 'r' ) as infile :
return infile . read ( ) |
def select ( self , selection_specs = None , ** kwargs ) :
"""Applies selection by dimension name
Applies a selection along the dimensions of the object using
keyword arguments . The selection may be narrowed to certain
objects using selection _ specs . For container objects the
selection will be applied to... | if selection_specs is not None and not isinstance ( selection_specs , ( list , tuple ) ) :
selection_specs = [ selection_specs ]
# Apply all indexes applying on this object
vdims = self . vdims + [ 'value' ] if self . vdims else [ ]
kdims = self . kdims
local_kwargs = { k : v for k , v in kwargs . items ( ) if k in... |
def _ignore_interrupts ( self ) :
"""Ignore interrupt and termination signals . Used as a pre - execution
function ( preexec _ fn ) for subprocess . Popen calls that pypiper will
control over ( i . e . , manually clean up ) .""" | signal . signal ( signal . SIGINT , signal . SIG_IGN )
signal . signal ( signal . SIGTERM , signal . SIG_IGN ) |
def __rm_names_on_csv_cols ( d ) :
"""Remove the variableNames from the columns .
: param dict d : Named csv data
: return list list : One list for names , one list for column data""" | _names = [ ]
_data = [ ]
for name , data in d . items ( ) :
_names . append ( name )
_data . append ( data )
return _names , _data |
def post ( url , data = None , json = None , ** kwargs ) :
"""A wrapper for ` ` requests . post ` ` .""" | _set_content_type ( kwargs )
if _content_type_is_json ( kwargs ) and data is not None :
data = dumps ( data )
_log_request ( 'POST' , url , kwargs , data )
response = requests . post ( url , data , json , ** kwargs )
_log_response ( response )
return response |
def evaluate_policy ( model , mdr , tol = 1e-8 , maxit = 2000 , grid = { } , verbose = True , initial_guess = None , hook = None , integration_orders = None , details = False , interp_type = 'cubic' ) :
"""Compute value function corresponding to policy ` ` dr ` `
Parameters :
model :
" dtcscc " model . Must c... | process = model . exogenous
dprocess = process . discretize ( )
n_ms = dprocess . n_nodes ( )
# number of exogenous states
n_mv = dprocess . n_inodes ( 0 )
# this assume number of integration nodes is constant
x0 = model . calibration [ 'controls' ]
v0 = model . calibration [ 'values' ]
parms = model . calibration [ 'p... |
def walk_some_dirs ( self , levels = - 1 , pattern = None ) :
"""D . walkdirs ( ) - > iterator over subdirs , recursively .
With the optional ' pattern ' argument , this yields only
directories whose names match the given pattern . For
example , mydir . walkdirs ( ' * test ' ) yields only directories
with n... | if not levels :
yield self
raise StopIteration
levels -= 1
for child in self . dirs ( ) :
if pattern is None or child . fnmatch ( pattern ) :
yield child
if levels :
for subsubdir in child . walk_some_dirs ( levels , pattern ) :
yield subsubdir |
def _PrintEventsStatus ( self , events_status ) :
"""Prints the status of the events .
Args :
events _ status ( EventsStatus ) : events status .""" | if events_status :
table_view = views . CLITabularTableView ( column_names = [ 'Events:' , 'Filtered' , 'In time slice' , 'Duplicates' , 'MACB grouped' , 'Total' ] , column_sizes = [ 15 , 15 , 15 , 15 , 15 , 0 ] )
table_view . AddRow ( [ '' , events_status . number_of_filtered_events , events_status . number_of... |
def received_char_count ( self , count ) :
'''Set recieved char count limit
Args :
count : the amount of received characters you want to stop at .
Returns :
None
Raises :
None''' | n1 = count / 100
n2 = ( count - ( n1 * 100 ) ) / 10
n3 = ( count - ( ( n1 * 100 ) + ( n2 * 10 ) ) )
self . send ( '^PC' + chr ( n1 ) + chr ( n2 ) + chr ( n3 ) ) |
def set_location ( self , new_location ) :
"""Set / change the location of this content .
Note that this does NOT change the actual location of the file . To do
so , use the ` copy _ to ` method .""" | self . _load_raw_content ( )
self . _location = new_location
self . get_filepath ( renew = True )
return |
def get_format_suffix ( self , ** kwargs ) :
"""Determine if the request includes a ' . json ' style format suffix""" | if self . settings . FORMAT_SUFFIX_KWARG :
return kwargs . get ( self . settings . FORMAT_SUFFIX_KWARG ) |
def clear_bit ( self , position : int ) :
"""Clears the value at position
: param position : integer between 0 and 7 , inclusive
: return : None""" | if position > ( self . _bit_width - 1 ) :
raise ValueError ( 'position greater than the bit width' )
self . _value &= ~ ( 1 << position )
self . _text_update ( ) |
def lifted_pauli ( pauli_sum : Union [ PauliSum , PauliTerm ] , qubits : List [ int ] ) :
"""Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object .
Useful for generating the full Hamiltonian after a particular fermion to
pauli transfo... | if isinstance ( pauli_sum , PauliTerm ) :
pauli_sum = PauliSum ( [ pauli_sum ] )
n_qubits = len ( qubits )
result_hilbert = np . zeros ( ( 2 ** n_qubits , 2 ** n_qubits ) , dtype = np . complex128 )
# left kronecker product corresponds to the correct basis ordering
for term in pauli_sum . terms :
term_hilbert =... |
def _grab_crl ( user_agent , url , timeout ) :
"""Fetches a CRL and parses it
: param user _ agent :
A unicode string of the user agent to use when fetching the URL
: param url :
A unicode string of the URL to fetch the CRL from
: param timeout :
The number of seconds after which an HTTP request should ... | request = Request ( url )
request . add_header ( 'Accept' , 'application/pkix-crl' )
request . add_header ( 'User-Agent' , user_agent )
response = urlopen ( request , None , timeout )
data = response . read ( )
if pem . detect ( data ) :
_ , _ , data = pem . unarmor ( data )
return crl . CertificateList . load ( da... |
def check_post_role ( self ) :
'''check the user role for docs .''' | priv_dic = { 'ADD' : False , 'EDIT' : False , 'DELETE' : False , 'ADMIN' : False }
if self . userinfo :
if self . userinfo . role [ 1 ] > '0' :
priv_dic [ 'ADD' ] = True
if self . userinfo . role [ 1 ] >= '1' :
priv_dic [ 'EDIT' ] = True
if self . userinfo . role [ 1 ] >= '3' :
priv_... |
def t_preproc_ID ( t ) :
r'[ _ A - Za - z ] +' | t . value = t . value . strip ( )
t . type = preprocessor . get ( t . value . lower ( ) , 'ID' )
return t |
def _get_last_node_for_prfx ( self , node , key_prfx , seen_prfx ) :
"""get last node for the given prefix , also update ` seen _ prfx ` to track the path already traversed
: param node : node in form of list , or BLANK _ NODE
: param key _ prfx : prefix to look for
: param seen _ prfx : prefix already seen ,... | node_type = self . _get_node_type ( node )
if node_type == NODE_TYPE_BLANK :
return BLANK_NODE
if node_type == NODE_TYPE_BRANCH : # already reach the expected node
if not key_prfx :
return node
sub_node = self . _decode_to_node ( node [ key_prfx [ 0 ] ] )
seen_prfx . append ( key_prfx [ 0 ] )
... |
def getContextsForExpression ( self , retina_name , body , get_fingerprint = None , start_index = 0 , max_results = 5 , sparsity = 1.0 ) :
"""Get semantic contexts for the input expression
Args :
retina _ name , str : The retina name ( required )
body , ExpressionOperation : The JSON encoded expression to be ... | resourcePath = '/expressions/contexts'
method = 'POST'
queryParams = { }
headerParams = { 'Accept' : 'Application/json' , 'Content-Type' : 'application/json' }
postData = None
queryParams [ 'retina_name' ] = retina_name
queryParams [ 'start_index' ] = start_index
queryParams [ 'max_results' ] = max_results
queryParams ... |
def add_children_to_node ( self , node ) :
"""Add children to etree . Element ` node ` .""" | if self . has_children :
for child_id in self . children :
child = self . runtime . get_block ( child_id )
self . runtime . add_block_as_child_node ( child , node ) |
def set_resource_value ( self , device_id , resource_path , resource_value , fix_path = True , timeout = None ) :
"""Set resource value for given resource path , on device .
Will block and wait for response to come through . Usage :
. . code - block : : python
try :
v = api . set _ resource _ value ( device... | self . ensure_notifications_thread ( )
return self . set_resource_value_async ( device_id , resource_path , resource_value ) . wait ( timeout ) |
def _generate_token ( self ) :
"""Create authentation to use with requests .""" | session = self . get_session ( )
url = self . __base_url ( 'magicBox.cgi?action=getMachineName' )
try : # try old basic method
auth = requests . auth . HTTPBasicAuth ( self . _user , self . _password )
req = session . get ( url , auth = auth , timeout = self . _timeout_default )
if not req . ok : # try new ... |
def unmatched_quotes_in_line ( text ) :
"""Return whether a string has open quotes .
This simply counts whether the number of quote characters of either
type in the string is odd .
Take from the IPython project ( in IPython / core / completer . py in v0.13)
Spyder team : Add some changes to deal with escape... | # We check " first , then ' , so complex cases with nested quotes will
# get the " to take precedence .
text = text . replace ( "\\'" , "" )
text = text . replace ( '\\"' , '' )
if text . count ( '"' ) % 2 :
return '"'
elif text . count ( "'" ) % 2 :
return "'"
else :
return '' |
def push_intercom_event_task ( obj_id ) :
"""Async : push _ intercom _ event _ task . delay ( event . id )""" | lock_id = "%s-push-intercom_event-%s" % ( settings . ENV_PREFIX , obj_id )
acquire_lock = lambda : cache . add ( lock_id , "true" , LOCK_EXPIRE )
# noqa : E731
release_lock = lambda : cache . delete ( lock_id )
# noqa : E731
if acquire_lock ( ) :
from aa_intercom . models import IntercomEvent
try :
inst... |
def serve ( self , app , conf ) :
"""A very simple approach for a WSGI server .""" | if self . args . reload :
try :
self . watch_and_spawn ( conf )
except ImportError :
print ( 'The `--reload` option requires `watchdog` to be ' 'installed.' )
print ( ' $ pip install watchdog' )
else :
self . _serve ( app , conf ) |
def _set_lastpage ( self ) :
"""Calculate value of class attribute ` ` last _ page ` ` .""" | self . last_page = ( len ( self . _page_data ) - 1 ) // self . screen . page_size |
def build_riskinputs ( self , kind ) :
""": param kind :
kind of hazard getter , can be ' poe ' or ' gmf '
: returns :
a list of RiskInputs objects , sorted by IMT .""" | logging . info ( 'Building risk inputs from %d realization(s)' , self . R )
imtls = self . oqparam . imtls
if not set ( self . oqparam . risk_imtls ) & set ( imtls ) :
rsk = ', ' . join ( self . oqparam . risk_imtls )
haz = ', ' . join ( imtls )
raise ValueError ( 'The IMTs in the risk models (%s) are disjo... |
def randbytes ( self ) :
"""- > # bytes result of bytes - encoded : func : gen _ rand _ str""" | return gen_rand_str ( 10 , 30 , use = self . random , keyspace = list ( self . keyspace ) ) . encode ( "utf-8" ) |
def _createIndexRti ( self , index , nodeName ) :
"""Auxiliary method that creates a PandasIndexRti .""" | return PandasIndexRti ( index = index , nodeName = nodeName , fileName = self . fileName , iconColor = self . _iconColor ) |
def get_assessment_form_for_create ( self , assessment_record_types ) :
"""Gets the assessment form for creating new assessments .
A new form should be requested for each create transaction .
arg : assessment _ record _ types ( osid . type . Type [ ] ) : array of
assessment record types to be included in the ... | # Implemented from template for
# osid . resource . ResourceAdminSession . get _ resource _ form _ for _ create _ template
for arg in assessment_record_types :
if not isinstance ( arg , ABCType ) :
raise errors . InvalidArgument ( 'one or more argument array elements is not a valid OSID Type' )
if assessmen... |
def run ( self ) :
"""Begin serving . Returns the bound port , or 0 for domain socket .""" | self . _listening_sock , self . _address = ( bind_domain_socket ( self . _address ) if self . _uds_path else bind_tcp_socket ( self . _address ) )
if self . _ssl :
certfile = os . path . join ( os . path . dirname ( __file__ ) , 'server.pem' )
self . _listening_sock = _ssl . wrap_socket ( self . _listening_sock... |
def _parse_ip_addr_show ( raw_result ) :
"""Parse the ' ip addr list dev ' command raw output .
: param str raw _ result : os raw result string .
: rtype : dict
: return : The parsed result of the show interface command in a dictionary of the form :
' os _ index ' : ' 0 ' ,
' dev ' : ' eth0 ' ,
' falgs ... | # does link exist ?
show_re = ( r'"(?P<dev>\S+)"\s+does not exist' )
re_result = search ( show_re , raw_result )
result = None
if not ( re_result ) : # match top two lines for serveral ' always there ' variables
show_re = ( r'\s*(?P<os_index>\d+):\s+(?P<dev>\S+):\s+<(?P<falgs_str>.*)?>.*?' r'mtu\s+(?P<mtu>\d+).+?st... |
def vtas2mach ( tas , h ) :
"""True airspeed ( tas ) to mach number conversion""" | a = vvsound ( h )
M = tas / a
return M |
def constq_debyetemp ( v , v0 , gamma0 , q , theta0 ) :
"""calculate Debye temperature for constant q
: param v : unit - cell volume in A ^ 3
: param v0 : unit - cell volume in A ^ 3 at 1 bar
: param gamma0 : Gruneisen parameter at 1 bar
: param q : logarithmic derivative of Gruneisen parameter
: param th... | gamma = constq_grun ( v , v0 , gamma0 , q )
if isuncertainties ( [ v , v0 , gamma0 , q , theta0 ] ) :
theta = theta0 * unp . exp ( ( gamma0 - gamma ) / q )
else :
theta = theta0 * np . exp ( ( gamma0 - gamma ) / q )
return theta |
def estimate_library_complexity ( df , algorithm = "RNA-seq" ) :
"""estimate library complexity from the number of reads vs .
number of unique start sites . returns " NA " if there are
not enough data points to fit the line""" | DEFAULT_CUTOFFS = { "RNA-seq" : ( 0.25 , 0.40 ) }
cutoffs = DEFAULT_CUTOFFS [ algorithm ]
if len ( df ) < 5 :
return { "unique_starts_per_read" : 'nan' , "complexity" : "NA" }
model = sm . ols ( formula = "starts ~ reads" , data = df )
fitted = model . fit ( )
slope = fitted . params [ "reads" ]
if slope <= cutoffs... |
def string_to_list ( input_string ) :
"""This function converts a string into a list using Python .
> > > string _ to _ list ( ' python program ' )
[ ' python ' , ' program ' ]
> > > string _ to _ list ( ' Data Analysis ' )
[ ' Data ' , ' Analysis ' ]
> > > string _ to _ list ( ' Hadoop Training ' )
[ '... | output_list = input_string . split ( ' ' )
return output_list |
def parse_date ( value ) :
"""Attempts to parse ` value ` into an instance of ` ` datetime . date ` ` . If
` value ` is ` ` None ` ` , this function will return ` ` None ` ` .
Args :
value : A timestamp . This can be a string , datetime . date , or
datetime . datetime value .""" | if not value :
return None
if isinstance ( value , datetime . date ) :
return value
return parse_datetime ( value ) . date ( ) |
def from_spacegroup ( cls , sg , lattice , species , coords , site_properties = None , coords_are_cartesian = False , tol = 1e-5 ) :
"""Generate a structure using a spacegroup . Note that only symmetrically
distinct species and coords should be provided . All equivalent sites
are generated from the spacegroup o... | from pymatgen . symmetry . groups import SpaceGroup
try :
i = int ( sg )
sgp = SpaceGroup . from_int_number ( i )
except ValueError :
sgp = SpaceGroup ( sg )
if isinstance ( lattice , Lattice ) :
latt = lattice
else :
latt = Lattice ( lattice )
if not sgp . is_compatible ( latt ) :
raise ValueEr... |
def keys ( ) :
"""List admin API keys .""" | for admin in current_app . config [ 'ADMIN_USERS' ] :
try :
db . get_db ( )
# init db on global app context
keys = ApiKey . find_by_user ( admin )
except Exception as e :
click . echo ( 'ERROR: {}' . format ( e ) )
else :
for key in keys :
click . echo ( '... |
def find_record ( self , model_class , record_id , reload = False ) :
"""Return a instance of model _ class from the API or the local cache .
Args :
model _ class ( : class : ` cinder _ data . model . CinderModel ` ) : A subclass of
: class : ` cinder _ data . model . CinderModel ` of your chosen model .
re... | cached_model = self . peek_record ( model_class , record_id )
if cached_model is not None and reload is False :
return cached_model
else :
return self . _get_record ( model_class , record_id ) |
def dict_union3 ( dict1 , dict2 , combine_op = op . add ) :
r"""Args :
dict1 ( dict ) :
dict2 ( dict ) :
combine _ op ( func ) : ( default = op . add )
Returns :
dict : mergedict _
CommandLine :
python - m utool . util _ dict - - exec - dict _ union3
Example :
> > > # ENABLE _ DOCTEST
> > > from... | keys1 = set ( dict1 . keys ( ) )
keys2 = set ( dict2 . keys ( ) )
# Combine common keys
keys3 = keys1 . intersection ( keys2 )
if len ( keys3 ) > 0 and combine_op is None :
raise AssertionError ( 'Can only combine disjoint dicts when combine_op is None' )
dict3 = { key : combine_op ( dict1 [ key ] , dict2 [ key ] )... |
def _check_callback ( callback ) :
"""Turns a callback that is potentially a class into a callable object .
Args :
callback ( object ) : An object that might be a class , method , or function .
if the object is a class , this creates an instance of it .
Raises :
ValueError : If an instance can ' t be crea... | # If the callback is a class , create an instance of it first
if inspect . isclass ( callback ) :
callback_object = callback ( )
if not callable ( callback_object ) :
raise ValueError ( "Callback must be a class that implements __call__ or a function." )
elif callable ( callback ) :
callback_object ... |
def predict ( self , X , cost_mat = None ) :
"""Predict class for X .
The predicted class of an input sample is computed as the class with
the highest mean predicted probability . If base estimators do not
implement a ` ` predict _ proba ` ` method , then it resorts to voting .
Parameters
X : { array - li... | # Check data
# X = check _ array ( X , accept _ sparse = [ ' csr ' , ' csc ' , ' coo ' ] ) # Dont in version 0.15
if self . n_features_ != X . shape [ 1 ] :
raise ValueError ( "Number of features of the model must " "match the input. Model n_features is {0} and " "input n_features is {1}." "" . format ( self . n_fe... |
def union ( self , other ) :
"""Return a new : class : ` DataFrame ` containing union of rows in this and another frame .
This is equivalent to ` UNION ALL ` in SQL . To do a SQL - style set union
( that does deduplication of elements ) , use this function followed by : func : ` distinct ` .
Also as standard ... | return DataFrame ( self . _jdf . union ( other . _jdf ) , self . sql_ctx ) |
def add_footerReference ( self , type_ , rId ) :
"""Return newly added CT _ HdrFtrRef element of * type _ * with * rId * .
The element tag is ` w : footerReference ` .""" | footerReference = self . _add_footerReference ( )
footerReference . type_ = type_
footerReference . rId = rId
return footerReference |
def _process_event ( self , event ) :
"""Extend event object with User and Channel objects""" | if event . get ( 'user' ) :
event . user = self . lookup_user ( event . get ( 'user' ) )
if event . get ( 'channel' ) :
event . channel = self . lookup_channel ( event . get ( 'channel' ) )
if self . user . id in event . mentions :
event . mentions_me = True
event . mentions = [ self . lookup_user ( uid ) f... |
def _update ( self ) :
"""Redraw the button ' s Surface object . Call this method when the button has changed appearance .""" | if self . customSurfaces :
self . surfaceNormal = pygame . transform . smoothscale ( self . origSurfaceNormal , self . _rect . size )
self . surfaceDown = pygame . transform . smoothscale ( self . origSurfaceDown , self . _rect . size )
self . surfaceHighlight = pygame . transform . smoothscale ( self . ori... |
def set_line_join ( self , line_join ) :
"""Set the current : ref : ` LINE _ JOIN ` within the cairo context .
As with the other stroke parameters ,
the current line cap style is examined by
: meth : ` stroke ` , : meth : ` stroke _ extents ` , and : meth : ` stroke _ to _ path ` ,
but does not have any eff... | cairo . cairo_set_line_join ( self . _pointer , line_join )
self . _check_status ( ) |
def is_type ( x , types , full = False ) :
"""Returns true if x is of type in types tuple
: param x :
: param types :
: param full :
: return :""" | types = types if isinstance ( types , tuple ) else ( types , )
ins = isinstance ( x , types )
sub = False
try :
sub = issubclass ( x , types )
except Exception :
pass
res = ins or sub
return res if not full else ( res , ins ) |
def _set_keys_for_save_query ( self , query ) :
"""Set the keys for a save update query .
: param query : A Builder instance
: type query : eloquent . orm . Builder
: return : The Builder instance
: rtype : eloquent . orm . Builder""" | query . where ( self . _morph_type , self . _morph_class )
return super ( MorphPivot , self ) . _set_keys_for_save_query ( query ) |
def calc_copulas ( self , output_file , model_names = ( "start-time" , "translation-x" , "translation-y" ) , label_columns = ( "Start_Time_Error" , "Translation_Error_X" , "Translation_Error_Y" ) ) :
"""Calculate a copula multivariate normal distribution from the training data for each group of ensemble members .
... | if len ( self . data [ 'train' ] ) == 0 :
self . load_data ( )
groups = self . data [ "train" ] [ "member" ] [ self . group_col ] . unique ( )
copulas = { }
label_columns = list ( label_columns )
for group in groups :
print ( group )
group_data = self . data [ "train" ] [ "total_group" ] . loc [ self . data... |
def create_db ( self , app ) :
"""Create a ZODB connection pool from the * app * configuration .""" | assert 'ZODB_STORAGE' in app . config , 'ZODB_STORAGE not configured'
storage = app . config [ 'ZODB_STORAGE' ]
if isinstance ( storage , basestring ) :
factory , dbargs = zodburi . resolve_uri ( storage )
elif isinstance ( storage , tuple ) :
factory , dbargs = storage
else :
factory , dbargs = storage , {... |
def values ( self , ** kwargs ) :
"""Get the view ' s values""" | result = yield self . get ( ** kwargs )
if not result [ 'rows' ] :
raise Return ( [ ] )
raise Return ( [ x [ 'value' ] for x in result [ 'rows' ] ] ) |
def print_summary ( self ) :
"""Print summary metrics of the annotation comparisons .""" | # True positives = matched reference samples
self . tp = len ( self . matched_ref_inds )
# False positives = extra test samples not matched
self . fp = self . n_test - self . tp
# False negatives = undetected reference samples
self . fn = self . n_ref - self . tp
# No tn attribute
self . specificity = self . tp / self ... |
def h ( tagName , * children , ** kwargs ) :
"""Takes an HTML Tag , children ( string , array , or another element ) , and
attributes
Examples :
> > > h ( ' div ' , [ h ( ' p ' , ' hey ' ) ] )
< div > < p > hey < / p > < / div >""" | attrs = { }
if 'attrs' in kwargs :
attrs = kwargs . pop ( 'attrs' )
attrs = attrs . copy ( )
attrs . update ( kwargs )
el = createComponent ( tagName )
return el ( children , ** attrs ) |
def _getitem ( self , index ) :
"""Get a single non - slice index .""" | row = self . _records [ index ]
if row is not None :
pass
elif self . is_attached ( ) : # need to handle negative indices manually
if index < 0 :
index = len ( self . _records ) + index
row = next ( ( decode_row ( line ) for i , line in self . _enum_lines ( ) if i == index ) , None )
if row is N... |
def Y ( self , value ) :
"""set phenotype""" | self . _N , self . _P = value . shape
self . _Y = value
self . clear_cache ( 'Ystar1' , 'Ystar' , 'Yhat' , 'LRLdiag_Yhat' , 'beta_grad' , 'Xstar_beta_grad' , 'Zstar' , 'DLZ' ) |
def stream ( self , model , position ) :
"""Create a : class : ` ~ bloop . stream . Stream ` that provides approximate chronological ordering .
. . code - block : : pycon
# Create a user so we have a record
> > > engine = Engine ( )
> > > user = User ( id = 3 , email = " user @ domain . com " )
> > > engi... | validate_not_abstract ( model )
if not model . Meta . stream or not model . Meta . stream . get ( "arn" ) :
raise InvalidStream ( "{!r} does not have a stream arn" . format ( model ) )
stream = Stream ( model = model , engine = self )
stream . move_to ( position = position )
return stream |
def match_uriinfo ( cls , info ) :
""": param info : an : py : class : ` ~ httpretty . core . URIInfo `
: returns : a 2 - item tuple : ( : py : class : ` ~ httpretty . core . URLMatcher ` , : py : class : ` ~ httpretty . core . URIInfo ` ) or ` ` ( None , [ ] ) ` `""" | items = sorted ( cls . _entries . items ( ) , key = lambda matcher_entries : matcher_entries [ 0 ] . priority , reverse = True , )
for matcher , value in items :
if matcher . matches ( info ) :
return ( matcher , info )
return ( None , [ ] ) |
async def execute ( self , query : str , * args , timeout : float = None ) -> str :
"""Execute an SQL command ( or commands ) .
This method can execute many SQL commands at once , when no arguments
are provided .
Example :
. . code - block : : pycon
> > > await con . execute ( ' ' '
. . . CREATE TABLE m... | self . _check_open ( )
if not args :
return await self . _protocol . query ( query , timeout )
_ , status , _ = await self . _execute ( query , args , 0 , timeout , True )
return status . decode ( ) |
def provision ( self , vm_name = None , provision_with = None ) :
'''Runs the provisioners defined in the Vagrantfile .
vm _ name : optional VM name string .
provision _ with : optional list of provisioners to enable .
e . g . [ ' shell ' , ' chef _ solo ' ]''' | prov_with_arg = None if provision_with is None else '--provision-with'
providers_arg = None if provision_with is None else ',' . join ( provision_with )
self . _call_vagrant_command ( [ 'provision' , vm_name , prov_with_arg , providers_arg ] ) |
def transformer_base_v3 ( ) :
"""Base parameters for Transformer model .""" | # Update parameters here , then occasionally cut a versioned set , e . g .
# transformer _ base _ v2.
hparams = transformer_base_v2 ( )
hparams . optimizer_adam_beta2 = 0.997
# New way of specifying learning rate schedule .
# Equivalent to previous version .
hparams . learning_rate_schedule = ( "constant*linear_warmup*... |
def toggle_template_selector ( self ) :
"""Slot for template selector elements behaviour .
. . versionadded : 4.3.0""" | if self . search_directory_radio . isChecked ( ) :
self . template_combo . setEnabled ( True )
else :
self . template_combo . setEnabled ( False )
if self . search_on_disk_radio . isChecked ( ) :
self . template_path . setEnabled ( True )
self . template_chooser . setEnabled ( True )
else :
self . t... |
async def _send_request ( self , request_type , payload ) :
"""Uses an executor to send an asynchronous ZMQ request to the
validator with the handler ' s Connection""" | try :
return await self . _connection . send ( message_type = request_type , message_content = payload , timeout = self . _timeout )
except DisconnectError :
LOGGER . warning ( 'Validator disconnected while waiting for response' )
raise errors . ValidatorDisconnected ( )
except asyncio . TimeoutError :
... |
def encode ( self ) :
"""Turn this report into a serialized bytearray that could be decoded with a call to decode""" | reading = self . visible_readings [ 0 ]
data = struct . pack ( "<BBHLLLL" , 0 , 0 , reading . stream , self . origin , self . sent_timestamp , reading . raw_time , reading . value )
return bytearray ( data ) |
def uninstall ( self , pkgname , * args , ** kwargs ) :
"""A context manager which allows uninstallation of packages from the virtualenv
: param str pkgname : The name of a package to uninstall
> > > venv = VirtualEnv ( " / path / to / venv / root " )
> > > with venv . uninstall ( " pytz " , auto _ confirm = ... | auto_confirm = kwargs . pop ( "auto_confirm" , True )
verbose = kwargs . pop ( "verbose" , False )
with self . activated ( ) :
pathset_base = self . get_monkeypatched_pathset ( )
dist = next ( iter ( filter ( lambda d : d . project_name == pkgname , self . get_working_set ( ) ) ) , None )
pathset = pathset_... |
def connect ( self , node , properties = None ) :
"""Connect a node
: param node :
: param properties : relationship properties
: return : True / rel instance""" | if not hasattr ( self . source , 'id' ) :
raise ValueError ( "Node has not been saved cannot connect!" )
if len ( self ) :
raise AttemptedCardinalityViolation ( "Node already has one relationship" )
else :
return super ( One , self ) . connect ( node , properties ) |
def set_category ( self , category ) :
"""Set package category
Args :
category : String of an existing category ' s name , or a
Category object .""" | # For some reason , packages only have the category name , not the
# ID .
if isinstance ( category , Category ) :
name = category . name
else :
name = category
self . find ( "category" ) . text = name |
def POST_zonefile ( self , path_info ) :
"""Publish a zonefile which has * already * been announced .
Return 200 and { ' status ' : True , ' servers ' : [ . . . ] } on success
Return 400 on invalid request , such as invalid JSON , JSON that doesn ' t match the schema , etc .
Return 502 on failure to replicate... | request_schema = { 'type' : 'object' , 'properties' : { 'zonefile' : { 'type' : 'string' , 'maxLength' : RPC_MAX_ZONEFILE_LEN } , 'zonefile_b64' : { 'type' : 'string' , 'pattern' : OP_BASE64_EMPTY_PATTERN , 'maxLength' : ( RPC_MAX_ZONEFILE_LEN * 4 ) / 3 + 1 , } } }
blockstackd_url = get_blockstackd_url ( )
zonefile_jso... |
def compute_diff_handle ( filename , old_line , code ) :
"""Uses the absolute line and ignores the callable / character offsets .
Used only in determining whether new issues are old issues .""" | key = "{filename}:{old_line}:{code}" . format ( filename = filename , old_line = old_line , code = code )
return BaseParser . compute_handle_from_key ( key ) |
def val_to_mrc ( code , val ) :
"""Convert one single ` val ` to MRC .
This function may be used for control fields in MARC records .
Args : ,
code ( str ) : Code of the field .
val ( str ) : Value of the field .
Returns :
str : Correctly padded MRC line with field .""" | code = str ( code )
if len ( code ) < 3 :
code += ( 3 - len ( code ) ) * " "
return "%s L %s" % ( code , val ) |
def _get_raw_objects ( self ) :
"""Helper function to populate the first page of raw objects for this tag .
This has the side effect of creating the ` ` _ raw _ objects ` ` attribute of
this object .""" | if not hasattr ( self , '_raw_objects' ) :
result = self . _client . get ( type ( self ) . api_endpoint , model = self )
# I want to cache this to avoid making duplicate requests , but I don ' t
# want it in the _ _ init _ _
self . _raw_objects = result
# pylint : disable = attribute - defined - outside... |
def login_password ( self , value ) :
"""Set the value of the login password field .""" | password = self . selenium . find_element ( * self . _password_input_locator )
password . clear ( )
password . send_keys ( value ) |
def startDataStoreMachine ( self , dataStoreItemName , machineName ) :
"""Starts the database instance running on the Data Store machine .
Inputs :
dataStoreItemName - name of the item to start
machineName - name of the machine to start on""" | url = self . _url + "/items/enterpriseDatabases/%s/machines/%s/start" % ( dataStoreItemName , machineName )
params = { "f" : "json" }
return self . _post ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) |
def from_scf_task ( cls , scf_task , ddk_tolerance = None , ph_tolerance = None , manager = None ) :
"""Build tasks for the computation of Born effective charges from a ground - state task .
Args :
scf _ task : ScfTask object .
ddk _ tolerance : tolerance used in the DDK run if with _ becs . None to use AbiPy... | new = cls ( manager = manager )
new . add_becs_from_scf_task ( scf_task , ddk_tolerance , ph_tolerance )
return new |
def minimize_ipopt ( fun , x0 , args = ( ) , kwargs = None , method = None , jac = None , hess = None , hessp = None , bounds = None , constraints = ( ) , tol = None , callback = None , options = None ) :
"""Minimize a function using ipopt . The call signature is exactly like for
` scipy . optimize . mimize ` . I... | if not SCIPY_INSTALLED :
raise ImportError ( 'Install SciPy to use the `minimize_ipopt` function.' )
_x0 = np . atleast_1d ( x0 )
problem = IpoptProblemWrapper ( fun , args = args , kwargs = kwargs , jac = jac , hess = hess , hessp = hessp , constraints = constraints )
lb , ub = get_bounds ( bounds )
cl , cu = get_... |
def authenticate_credentials ( self , payload ) :
"""Get or create an active user with the username contained in the payload .""" | username = payload . get ( 'preferred_username' ) or payload . get ( 'username' )
if username is None :
raise exceptions . AuthenticationFailed ( 'JWT must include a preferred_username or username claim!' )
else :
try :
user , __ = get_user_model ( ) . objects . get_or_create ( username = username )
... |
def upload_component ( component ) :
"""Upload a given component to pypi
The pypi username and password must either be specified in a ~ / . pypirc
file or in environment variables PYPI _ USER and PYPI _ PASS""" | if 'PYPI_USER' in os . environ and 'PYPI_PASS' in os . environ :
pypi_user = os . environ [ 'PYPI_USER' ]
pypi_pass = os . environ [ 'PYPI_PASS' ]
else :
pypi_user = None
pypi_pass = None
print ( "No PYPI user information in environment" )
comp = comp_names [ component ]
distpath = os . path . join ... |
def classifyParameters ( self ) :
"""Return ( arguments , options , outputs ) tuple . Together , the
three lists contain all parameters ( recursively fetched from
all parameter groups ) , classified into optional parameters ,
required ones ( with an index ) , and simple output parameters
( that would get wr... | arguments = [ ]
options = [ ]
outputs = [ ]
for parameter in self . parameters ( ) :
if parameter . channel == 'output' and not parameter . isExternalType ( ) :
outputs . append ( parameter )
elif parameter . index is not None :
arguments . append ( parameter )
if parameter . flag is not... |
def iter_issues ( self , milestone = None , state = None , assignee = None , mentioned = None , labels = None , sort = None , direction = None , since = None , number = - 1 , etag = None ) :
"""Iterate over issues on this repo based upon parameters passed .
. . versionchanged : : 0.9.0
The ` ` state ` ` paramet... | url = self . _build_url ( 'issues' , base_url = self . _api )
params = { 'assignee' : assignee , 'mentioned' : mentioned }
if milestone in ( '*' , 'none' ) or isinstance ( milestone , int ) :
params [ 'milestone' ] = milestone
self . _remove_none ( params )
params . update ( issue_params ( None , state , labels , s... |
def respond_fw_config ( self , msg ) :
"""Respond to a firmware config request .""" | ( req_fw_type , req_fw_ver , req_blocks , req_crc , bloader_ver ) = fw_hex_to_int ( msg . payload , 5 )
_LOGGER . debug ( 'Received firmware config request with firmware type %s, ' 'firmware version %s, %s blocks, CRC %s, bootloader %s' , req_fw_type , req_fw_ver , req_blocks , req_crc , bloader_ver )
fw_type , fw_ver ... |
def isexec ( path ) :
'''Check if given path points to an executable file .
: param path : file path
: type path : str
: return : True if executable , False otherwise
: rtype : bool''' | return os . path . isfile ( path ) and os . access ( path , os . X_OK ) |
def extract_colors ( filename_or_img , min_saturation = config . MIN_SATURATION , min_distance = config . MIN_DISTANCE , max_colors = config . MAX_COLORS , min_prominence = config . MIN_PROMINENCE , n_quantized = config . N_QUANTIZED ) :
"""Determine what the major colors are in the given image .""" | if Image . isImageType ( filename_or_img ) :
im = filename_or_img
else :
im = Image . open ( filename_or_img )
# get point color count
if im . mode != 'RGB' :
im = im . convert ( 'RGB' )
im = autocrop ( im , config . WHITE )
# assume white box
im = im . convert ( 'P' , palette = Image . ADAPTIVE , colors = ... |
def _create_decode_layer ( self ) :
"""Create the decoding layer of the network .
Returns
self""" | with tf . name_scope ( "decoder" ) :
activation = tf . add ( tf . matmul ( self . encode , tf . transpose ( self . W_ ) ) , self . bv_ )
if self . dec_act_func :
self . reconstruction = self . dec_act_func ( activation )
else :
self . reconstruction = activation
return self |
def submit_coroutine ( self , coro , loop ) :
"""Schedule and await a coroutine on the specified loop
The coroutine is wrapped and scheduled using
: func : ` asyncio . run _ coroutine _ threadsafe ` . While the coroutine is
" awaited " , the result is not available as method returns immediately .
Args :
c... | async def _do_call ( _coro ) :
with _IterationGuard ( self ) :
await _coro
asyncio . run_coroutine_threadsafe ( _do_call ( coro ) , loop = loop ) |
def parse_with_retrieved ( self , retrieved ) :
"""Parse output data folder , store results in database .
: param retrieved : a dictionary of retrieved nodes , where
the key is the link name
: returns : a tuple with two values ` ` ( bool , node _ list ) ` ` ,
where :
* ` ` bool ` ` : variable to tell if t... | success = False
node_list = [ ]
# Check that the retrieved folder is there
try :
out_folder = retrieved [ 'retrieved' ]
except KeyError :
self . logger . error ( "No retrieved folder found" )
return success , node_list
# Check the folder content is as expected
list_of_files = out_folder . get_folder_list ( ... |
def quadratic_2d ( data ) :
"""Compute the quadratic estimate of the centroid in a 2d - array .
Args :
data ( 2darray ) : two dimensional data array
Returns
center ( tuple ) : centroid estimate on the row and column directions ,
respectively""" | arg_data_max = np . argmax ( data )
i , j = np . unravel_index ( arg_data_max , data . shape )
z_ = data [ i - 1 : i + 2 , j - 1 : j + 2 ]
# our quadratic function is defined as
# f ( x , y | a , b , c , d , e , f ) : = a + b * x + c * y + d * x ^ 2 + e * xy + f * y ^ 2
# therefore , the best fit coeffiecients are give... |
def pb ( name , data , bucket_count = None , display_name = None , description = None ) :
"""Create a legacy histogram summary protobuf .
Arguments :
name : A unique name for the generated summary , including any desired
name scopes .
data : A ` np . array ` or array - like form of any shape . Must have typ... | # TODO ( nickfelt ) : remove on - demand imports once dep situation is fixed .
import tensorflow . compat . v1 as tf
if bucket_count is None :
bucket_count = summary_v2 . DEFAULT_BUCKET_COUNT
data = np . array ( data ) . flatten ( ) . astype ( float )
if data . size == 0 :
buckets = np . array ( [ ] ) . reshape... |
def create_relational ( cls , name , inst ) :
"""Creates a relational attribute .
: param name : the name of the attribute
: type name : str
: param inst : the structure of the relational attribute
: type inst : Instances""" | return Attribute ( javabridge . make_instance ( "weka/core/Attribute" , "(Ljava/lang/String;Lweka/core/Instances;)V" , name , inst . jobject ) ) |
def on_rabbitmq_channel_open ( self , channel ) :
"""Called when the RabbitMQ accepts the channel open request .
: param pika . channel . Channel channel : The channel opened with RabbitMQ""" | LOGGER . info ( 'Channel %i is opened for communication with RabbitMQ' , channel . channel_number )
self . _set_rabbitmq_channel ( channel )
self . _publish_deferred_messages ( ) |
def resample_image2d_flux ( image2d_orig , naxis1 , cdelt1 , crval1 , crpix1 , coeff ) :
"""Resample a 1D / 2D image using NAXIS1 , CDELT1 , CRVAL1 , and CRPIX1.
The same NAXIS1 , CDELT1 , CRVAL1 , and CRPIX1 are employed for all
the scans ( rows ) of the original ' image2d ' . The wavelength
calibrated outpu... | # duplicate input array , avoiding problems when using as input
# 1d numpy arrays with shape ( nchan , ) instead of a 2d numpy
# array with shape ( 1 , nchan )
if image2d_orig . ndim == 1 :
nscan = 1
nchan = image2d_orig . size
image2d = np . zeros ( ( nscan , nchan ) )
image2d [ 0 , : ] = np . copy ( i... |
def refresh ( self ) :
"""Re - query to update object with latest values . Return the object .
Any listing , such as the submissions on a subreddits top page , will
automatically be refreshed serverside . Refreshing a submission will
also refresh all its comments .
In the rare case of a comment being delete... | unique = self . reddit_session . _unique_count
# pylint : disable = W0212
self . reddit_session . _unique_count += 1
# pylint : disable = W0212
if isinstance ( self , Redditor ) :
other = Redditor ( self . reddit_session , self . _case_name , fetch = True , uniq = unique )
elif isinstance ( self , Comment ) :
s... |
def format_bytes_size ( val ) :
"""Take a number of bytes and convert it to a human readable number .
: param int val : The number of bytes to format .
: return : The size in a human readable format .
: rtype : str""" | if not val :
return '0 bytes'
for sz_name in [ 'bytes' , 'KB' , 'MB' , 'GB' , 'TB' , 'PB' , 'EB' ] :
if val < 1024.0 :
return "{0:.2f} {1}" . format ( val , sz_name )
val /= 1024.0
raise OverflowError ( ) |
def storage_set ( self , key , value ) :
"""Store a value for the module .""" | if not self . _module :
return
self . _storage_init ( )
module_name = self . _module . module_full_name
return self . _storage . storage_set ( module_name , key , value ) |
def process ( self , buff ) :
'''Process the input buffer . The buffer can contains all or a segment of the bytes from the complete message .
The function will buffer what will require extra bytes to be processed .
: param buff :''' | ( self . _stack , self . _memory , scstateidx , self . _state , tmpevents , self . _waitingforprop , self . _parentismap ) = process ( buff , self . create_parser_info ( ) , self . _deserializers ) ;
self . _scstate = self . scstatelist [ scstateidx - 1 ]
self . _events = tmpevents |
def process_fields ( self , field_names , depth ) :
'''The primary purpose of this function is to store the sql field list
and the depth to which we process .''' | # List of field names in correct order .
self . field_names = field_names
# number of fields .
self . num_fields = len ( field_names )
# Constrain depth .
if ( depth == 0 ) or ( depth >= self . num_fields ) :
self . depth = self . num_fields - 1
else :
self . depth = depth |
def handle_quit ( self , connection , event ) :
"""Store quit time for a nickname when it quits .""" | nickname = self . get_nickname ( event )
self . quit [ nickname ] = datetime . now ( )
del self . joined [ nickname ] |
def validate ( self ) :
"""Check if all mandatory keys exist in : attr : ` metainfo ` and are of expected
types
The necessary values are documented here :
| http : / / bittorrent . org / beps / bep _ 0003 . html
| https : / / wiki . theory . org / index . php / BitTorrentSpecification # Metainfo _ File _ St... | md = self . metainfo
info = md [ 'info' ]
# Check values shared by singlefile and multifile torrents
utils . assert_type ( md , ( 'info' , 'name' ) , ( str , ) , must_exist = True )
utils . assert_type ( md , ( 'info' , 'piece length' ) , ( int , ) , must_exist = True )
utils . assert_type ( md , ( 'info' , 'pieces' ) ... |
def split_on ( word : str , section : str ) -> Tuple [ str , str ] :
"""Given a string , split on a section , and return the two sections as a tuple .
: param word :
: param section :
: return :
> > > split _ on ( ' hamrye ' , ' ham ' )
( ' ham ' , ' rye ' )""" | return word [ : word . index ( section ) ] + section , word [ word . index ( section ) + len ( section ) : ] |
def strip_linebreaks ( s ) :
"""Strip excess line breaks from a string""" | return u"\n" . join ( [ c for c in s . split ( u'\n' ) if c ] ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.