signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def extant_file ( path ) :
"""Check if file exists with argparse""" | if not os . path . exists ( path ) :
raise argparse . ArgumentTypeError ( "{} does not exist" . format ( path ) )
return path |
def hmget ( self , * args ) :
"""This command on the model allow getting many instancehash fields with only
one redis call . You must pass hash name to retrieve as arguments .""" | if args and not any ( arg in self . _instancehash_fields for arg in args ) :
raise ValueError ( "Only InstanceHashField can be used here." )
return self . _call_command ( 'hmget' , args ) |
def flushing ( self ) :
"""Flush the current session , handling common errors .""" | try :
yield
self . session . flush ( )
except ( FlushError , IntegrityError ) as error :
error_message = str ( error )
# There ought to be a cleaner way to capture this condition
if "duplicate" in error_message :
raise DuplicateModelError ( error )
if "already exists" in error_message :
... |
def insert_data_frame ( col , df , int_col = None , binary_col = None , minimal_size = 5 ) :
"""Insert ` ` pandas . DataFrame ` ` .
: param col : : class : ` pymongo . collection . Collection ` instance .
: param df : : class : ` pandas . DataFrame ` instance .
: param int _ col : list of integer - type colum... | data = transform . to_dict_list_generic_type ( df , int_col = int_col , binary_col = binary_col )
smart_insert ( col , data , minimal_size ) |
def log_rmtree_error ( func , arg , exc_info ) :
"""Suited as onerror handler for ( sh ) util . rmtree ( ) that logs a warning .""" | logging . warning ( "Failure during '%s(%s)': %s" , func . __name__ , arg , exc_info [ 1 ] ) |
def _find_all_step_methods ( self ) :
"""Finds all _ step < n > methods where n is an integer in this class .""" | steps = ( [ method for method in dir ( self ) if callable ( getattr ( self , method ) ) and re . match ( r'_step\d+\d+.*' , method ) ] )
steps = sorted ( steps )
for step in steps :
self . _steps . append ( getattr ( self , step ) ) |
def get_user ( self , identified_with , identifier , req , resp , resource , uri_kwargs ) :
"""Get user object for given identifier .
Args :
identified _ with ( object ) : authentication middleware used
to identify the user .
identifier : middleware specifix user identifier ( string or tuple
in case of al... | stored_value = self . kv_store . get ( self . _get_storage_key ( identified_with , identifier ) )
if stored_value is not None :
user = self . serialization . loads ( stored_value . decode ( ) )
else :
user = None
return user |
def connect ( * , dsn , autocommit = False , ansi = False , timeout = 0 , loop = None , executor = None , echo = False , after_created = None , ** kwargs ) :
"""Accepts an ODBC connection string and returns a new Connection object .
The connection string can be passed as the string ` str ` , as a list of
keywor... | return _ContextManager ( _connect ( dsn = dsn , autocommit = autocommit , ansi = ansi , timeout = timeout , loop = loop , executor = executor , echo = echo , after_created = after_created , ** kwargs ) ) |
def cylinder ( target , throat_diameter = 'throat.diameter' ) :
r"""Calculate throat cross - sectional area for a cylindrical throat
Parameters
target : OpenPNM Object
The object which this model is associated with . This controls the
length of the calculated array , and also provides access to other
nece... | diams = target [ throat_diameter ]
value = _pi / 4 * ( diams ) ** 2
return value |
def validateExtractOptions ( options ) :
'''Check the validity of the option combinations for barcode extraction''' | if not options . pattern and not options . pattern2 :
if not options . read2_in :
U . error ( "Must supply --bc-pattern for single-end" )
else :
U . error ( "Must supply --bc-pattern and/or --bc-pattern2 " "if paired-end " )
if options . pattern2 :
if not options . read2_in :
U . err... |
def str_match ( arr , pat , case = True , flags = 0 , na = np . nan ) :
"""Determine if each string matches a regular expression .
Parameters
pat : str
Character sequence or regular expression .
case : bool , default True
If True , case sensitive .
flags : int , default 0 ( no flags )
re module flags ... | if not case :
flags |= re . IGNORECASE
regex = re . compile ( pat , flags = flags )
dtype = bool
f = lambda x : bool ( regex . match ( x ) )
return _na_map ( f , arr , na , dtype = dtype ) |
def get_all_parsers ( self , strict_type_matching : bool = False ) -> List [ Parser ] :
"""Returns the list of all parsers in order of relevance .
: return :""" | matching = self . find_all_matching_parsers ( strict = strict_type_matching ) [ 0 ]
# matching [ 1 ] ( approx match ) is supposed to be empty since we use a joker on type and a joker on ext : only
# exact and generic match should exist , no approx match
if len ( matching [ 1 ] ) > 0 :
raise Exception ( 'Internal er... |
def GenerateNetworkedConfigFile ( load_hook , normal_class_load_hook , normal_class_dump_hook , ** kwargs ) -> NetworkedConfigObject :
"""Generates a NetworkedConfigObject using the specified hooks .""" | def NetworkedConfigObjectGenerator ( url , safe_load : bool = True ) :
cfg = NetworkedConfigObject ( url = url , load_hook = load_hook , safe_load = safe_load , normal_class_load_hook = normal_class_load_hook , normal_class_dump_hook = normal_class_dump_hook )
return cfg
return NetworkedConfigObjectGenerator |
def delete_task ( self , task_name ) :
"""Deletes the named Task in this Job .""" | logger . debug ( 'Deleting task {0}' . format ( task_name ) )
if not self . state . allow_change_graph :
raise DagobahError ( "job's graph is immutable in its current state: %s" % self . state . status )
if task_name not in self . tasks :
raise DagobahError ( 'task %s does not exist' % task_name )
self . tasks ... |
def _stripe_object_to_record ( cls , data , current_ids = None , pending_relations = None ) :
"""This takes an object , as it is formatted in Stripe ' s current API for our object
type . In return , it provides a dict . The dict can be used to create a record or
to update a record
This function takes care of ... | manipulated_data = cls . _manipulate_stripe_object_hook ( data )
if "object" not in data :
raise ValueError ( "Stripe data has no `object` value. Aborting. %r" % ( data ) )
if not cls . is_valid_object ( data ) :
raise ValueError ( "Trying to fit a %r into %r. Aborting." % ( data [ "object" ] , cls . __name__ )... |
def _set_lim_and_transforms ( self ) :
"""Setup the key transforms for the axes .""" | # Most of the transforms are set up correctly by LambertAxes
LambertAxes . _set_lim_and_transforms ( self )
# Transform for latitude ticks . These are typically unused , but just
# in case we need them . . .
yaxis_stretch = Affine2D ( ) . scale ( 4 * self . horizon , 1.0 )
yaxis_stretch = yaxis_stretch . translate ( - ... |
def get_devices ( self ) :
"""Return a list of devices .
Deprecated , use get _ actors instead .""" | url = self . base_url + '/net/home_auto_query.lua'
response = self . session . get ( url , params = { 'sid' : self . sid , 'command' : 'AllOutletStates' , 'xhr' : 0 , } , timeout = 15 )
response . raise_for_status ( )
data = response . json ( )
count = int ( data [ "Outlet_count" ] )
devices = [ ]
for i in range ( 1 , ... |
def get_extver ( self ) :
"""Get the version for this extension .
Used when a name is given to multiple extensions""" | ver = self . _info [ 'extver' ]
if ver == 0 :
ver = self . _info [ 'hduver' ]
return ver |
def inc ( self , key , key_length = 0 ) :
"""Add value to key - value
Params :
< str > key
< int > value
< int > key _ length
Return :
< int > key _ value""" | if key_length < 1 :
key_length = len ( key )
val = self . add_method ( self , key , key_length , 1 )
if self . k :
self . _update ( key , val )
return val |
def on ( self , message , namespace = None ) :
"""Decorator to register a SocketIO event handler .
This decorator must be applied to SocketIO event handlers . Example : :
@ socketio . on ( ' my event ' , namespace = ' / chat ' )
def handle _ my _ custom _ event ( json ) :
print ( ' received json : ' + str (... | namespace = namespace or '/'
def decorator ( handler ) :
def _handler ( sid , * args ) :
return self . _handle_event ( handler , message , namespace , sid , * args )
if self . server :
self . server . on ( message , _handler , namespace = namespace )
else :
self . handlers . append (... |
def run_example ( example_name , environ ) :
"""Run an example module from zipline . examples .""" | mod = EXAMPLE_MODULES [ example_name ]
register_calendar ( "YAHOO" , get_calendar ( "NYSE" ) , force = True )
return run_algorithm ( initialize = getattr ( mod , 'initialize' , None ) , handle_data = getattr ( mod , 'handle_data' , None ) , before_trading_start = getattr ( mod , 'before_trading_start' , None ) , analyz... |
def current_arg_text ( self ) -> str :
"""Plain text part in the current argument , without any CQ codes .""" | if self . _current_arg_text is None :
self . _current_arg_text = Message ( self . current_arg ) . extract_plain_text ( )
return self . _current_arg_text |
def script ( script , interpreter = '' , suffix = '' , args = '' , ** kwargs ) :
'''Execute specified script using specified interpreter . This action accepts common
action arguments such as input , active , workdir , docker _ image and args . In particular ,
content of one or more files specified by option inp... | return SoS_ExecuteScript ( script , interpreter , suffix , args ) . run ( ** kwargs ) |
def hashsummary ( self ) :
"""Print a model summary - checksums of each layer parameters""" | children = list ( self . children ( ) )
result = [ ]
for child in children :
result . extend ( hashlib . sha256 ( x . detach ( ) . cpu ( ) . numpy ( ) . tobytes ( ) ) . hexdigest ( ) for x in child . parameters ( ) )
return result |
def get_injuries ( self , season , week ) :
"""Injuries by week""" | result = self . _method_call ( "Injuries/{season}/{week}" , "stats" , season = season , week = week )
return result |
def shrink ( self ) :
"""Shrink ca . 5 % of entries .""" | trim = int ( 0.05 * len ( self ) )
if trim :
items = super ( LFUCache , self ) . items ( )
# sorting function for items
keyfunc = lambda x : x [ 1 ] [ 0 ]
values = sorted ( items , key = keyfunc )
for item in values [ 0 : trim ] :
del self [ item [ 0 ] ] |
def snapshot_created ( name , ami_name , instance_name , wait_until_available = True , wait_timeout_seconds = 300 , ** kwargs ) :
'''Create a snapshot from the given instance
. . versionadded : : 2016.3.0''' | ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
if not __salt__ [ 'boto_ec2.create_image' ] ( ami_name = ami_name , instance_name = instance_name , ** kwargs ) :
ret [ 'comment' ] = 'Failed to create new AMI {ami_name}' . format ( ami_name = ami_name )
ret [ 'result' ] = False
r... |
async def stop_slaves ( self , timeout = 1 ) :
"""Stop all the slaves by sending a stop - message to their managers .
: param int timeout :
Timeout for connecting to each manager . If a connection can not
be made before the timeout expires , the resulting error for that
particular manager is logged , but th... | for addr in self . addrs :
try :
r_manager = await self . env . connect ( addr , timeout = timeout )
await r_manager . stop ( )
except :
self . _log ( logging . WARNING , "Could not stop {}" . format ( addr ) ) |
def set ( self , dict_name , key , value , priority = None ) :
'''Set a single value for a single key .
This requires a session lock .
: param str dict _ name : name of the dictionary to update
: param str key : key to update
: param str value : value to assign to ` key `
: param int priority : priority s... | if priority is not None :
priorities = { key : priority }
else :
priorities = None
self . update ( dict_name , { key : value } , priorities = priorities ) |
def run ( self ) :
"""Start json minimizer and exit when all json files were minimized .""" | for rel_path in sorted ( self . paths ) :
file_path = join ( self . data_dir , rel_path )
self . minify ( file_path )
after = self . size_of ( self . after_total )
before = self . size_of ( self . before_total )
saved = self . size_of ( self . before_total - self . after_total )
template = '\nTotal: ' '\033[92m... |
def parse_http_list ( s ) :
"""Parse lists as described by RFC 2068 Section 2.
In particular , parse comma - separated lists where the elements of
the list may include quoted - strings . A quoted - string could
contain a comma . A non - quoted string could have quotes in the
middle . Neither commas nor quot... | res = [ ]
part = ''
escape = quote = False
for cur in s :
if escape :
part += cur
escape = False
continue
if quote :
if cur == '\\' :
escape = True
continue
elif cur == '"' :
quote = False
part += cur
continue
if cur... |
def add_file_task ( self , dir_name = None ) :
'''添加上传任务 , 会弹出一个选择文件的对话框''' | file_dialog = Gtk . FileChooserDialog ( _ ( 'Choose Files..' ) , self . app . window , Gtk . FileChooserAction . OPEN , ( Gtk . STOCK_CANCEL , Gtk . ResponseType . CANCEL , Gtk . STOCK_OK , Gtk . ResponseType . OK ) )
file_dialog . set_modal ( True )
file_dialog . set_select_multiple ( True )
file_dialog . set_default_... |
def reset ( self ) :
"""Reset the tough connection .
If a reset is not possible , tries to reopen the connection .
It will not complain if the connection is already closed .""" | try :
self . _con . reset ( )
self . _transaction = False
self . _setsession ( )
self . _usage = 0
except Exception :
try :
self . reopen ( )
except Exception :
try :
self . rollback ( )
except Exception :
pass |
def union_update ( self , * others ) :
r"""Update the multiset , adding elements from all others using the maximum multiplicity .
> > > ms = Multiset ( ' aab ' )
> > > ms . union _ update ( ' bc ' )
> > > sorted ( ms )
[ ' a ' , ' a ' , ' b ' , ' c ' ]
You can also use the ` ` | = ` ` operator for the sam... | _elements = self . _elements
_total = self . _total
for other in map ( self . _as_mapping , others ) :
for element , multiplicity in other . items ( ) :
old_multiplicity = _elements . get ( element , 0 )
if multiplicity > old_multiplicity :
_elements [ element ] = multiplicity
... |
def saveVizGithub ( contents , ontouri ) :
"""DEPRECATED on 2016-11-16
Was working but had a dependecies on package ' uritemplate . py ' which caused problems at installation time""" | title = "Ontospy: ontology export"
readme = """This ontology documentation was automatically generated with Ontospy (https://github.com/lambdamusic/Ontospy).
The graph URI is: %s""" % str ( ontouri )
files = { 'index.html' : { 'content' : contents } , 'README.txt' : { 'content' : readme } , 'LICENSE.txt' : { 'content'... |
def _to_ascii ( s ) :
"""Converts given string to ascii ignoring non ascii .
Args :
s ( text or binary ) :
Returns :
str :""" | # TODO : Always use unicode within ambry .
from six import text_type , binary_type
if isinstance ( s , text_type ) :
ascii_ = s . encode ( 'ascii' , 'ignore' )
elif isinstance ( s , binary_type ) :
ascii_ = s . decode ( 'utf-8' ) . encode ( 'ascii' , 'ignore' )
else :
raise Exception ( 'Unknown text type - ... |
def generate_random_long ( signed = True ) :
"""Generates a random long integer ( 8 bytes ) , which is optionally signed""" | return int . from_bytes ( os . urandom ( 8 ) , signed = signed , byteorder = 'little' ) |
def send ( self , message ) :
"""Adds a message to the list , returning a fake ' ok ' response
: returns : A response message with ` ` ok = True ` `""" | for event in message . events :
self . events . append ( event )
reply = riemann_client . riemann_pb2 . Msg ( )
reply . ok = True
return reply |
def mavlink_packet ( self , m ) :
'''get time from mavlink ATTITUDE''' | if m . get_type ( ) == 'GLOBAL_POSITION_INT' :
if abs ( m . lat ) < 1000 and abs ( m . lon ) < 1000 :
return
self . vehicle_pos = VehiclePos ( m ) |
def from_config ( cls , shelf , obj , ** kwargs ) :
"""Construct a Recipe from a plain Python dictionary .
Most of the directives only support named ingredients , specified as
strings , and looked up on the shelf . But filters can be specified as
objects .
Additionally , each RecipeExtension can extract and... | def subdict ( d , keys ) :
new = { }
for k in keys :
if k in d :
new [ k ] = d [ k ]
return new
core_kwargs = subdict ( obj , recipe_schema [ 'schema' ] . keys ( ) )
core_kwargs = normalize_schema ( recipe_schema , core_kwargs )
core_kwargs [ 'filters' ] = [ parse_condition ( filter , sh... |
def append ( self , cell ) :
"""행에 cell을 붙입니다 .""" | assert isinstance ( cell , Cell )
super ( Row , self ) . append ( cell ) |
def moderate ( self , comment , content_object , request ) :
"""Determine whether a given comment on a given object should be
allowed to show up immediately , or should be marked non - public
and await approval .
Return ` ` True ` ` if the comment should be moderated ( marked
non - public ) , ` ` False ` ` ... | if self . auto_moderate_field and self . moderate_after is not None :
moderate_after_date = getattr ( content_object , self . auto_moderate_field )
if moderate_after_date is not None and self . _get_delta ( timezone . now ( ) , moderate_after_date ) . days >= self . moderate_after :
return True
return F... |
def mock_import ( do_not_mock = None , ** mock_kwargs ) :
"""Mocks import statements by ignoring ImportErrors
and replacing the missing module with a Mock .
: param str | unicode | list [ str | unicode ] do _ not _ mock : names of modules
that should exists , and an ImportError could be raised for .
: param... | do_not_mock = _to_list ( do_not_mock )
def try_import ( module_name , * args , ** kwargs ) :
try :
return _builtins_import ( module_name , * args , ** kwargs )
except : # intentionally catch all exceptions
if any ( ( _match ( module_name , prefix ) for prefix in do_not_mock ) ) : # This is a mod... |
def _action ( action = 'get' , search = None , one = True , force = False ) :
'''Multi action helper for start , stop , get , . . .''' | vms = { }
matched_vms = [ ]
client = salt . client . get_local_client ( __opts__ [ 'conf_file' ] )
# # lookup vms
try :
vmadm_args = { }
vmadm_args [ 'order' ] = 'uuid,alias,hostname,state'
if '=' in search :
vmadm_args [ 'search' ] = search
for cn in client . cmd_iter ( 'G@virtual:physical and ... |
def decode_buffer ( buffer : dict ) -> np . ndarray :
"""Translate a DataBuffer into a numpy array .
: param buffer : Dictionary with ' data ' byte array , ' dtype ' , and ' shape ' fields
: return : NumPy array of decoded data""" | buf = np . frombuffer ( buffer [ 'data' ] , dtype = buffer [ 'dtype' ] )
return buf . reshape ( buffer [ 'shape' ] ) |
def validate ( pfeed , * , as_df = True , include_warnings = True ) :
"""Check whether the given pfeed satisfies the ProtoFeed spec .
Parameters
pfeed : ProtoFeed
as _ df : boolean
If ` ` True ` ` , then return the resulting report as a DataFrame ;
otherwise return the result as a list
include _ warning... | problems = [ ]
# Check for invalid columns and check the required tables
checkers = [ 'check_frequencies' , 'check_meta' , 'check_service_windows' , 'check_shapes' , 'check_stops' , ]
for checker in checkers :
problems . extend ( globals ( ) [ checker ] ( pfeed , include_warnings = include_warnings ) )
return gt . ... |
def ColorWithLightness ( self , lightness ) :
'''Create a new instance based on this one with a new lightness value .
Parameters :
: lightness :
The lightness of the new color [ 0 . . . 1 ] .
Returns :
A grapefruit . Color instance .
> > > Color . NewFromHsl ( 30 , 1 , 0.5 ) . ColorWithLightness ( 0.25)... | h , s , l = self . __hsl
return Color ( ( h , s , lightness ) , 'hsl' , self . __a , self . __wref ) |
def email ( self ) :
"""Shortcut property for finding the e - mail address or bot URL .""" | if "profile" in self . _raw :
email = self . _raw [ "profile" ] . get ( "email" )
elif "bot_url" in self . _raw :
email = self . _raw [ "bot_url" ]
else :
email = None
if not email :
logging . debug ( "No email found for %s" , self . _raw . get ( "name" ) )
return email |
def baldwinsoc_winners ( self , profile ) :
"""Returns an integer list that represents all possible winners of a profile under baldwin rule .
: ivar Profile profile : A Profile object that represents an election profile .""" | ordering = profile . getOrderVectors ( )
m = profile . numCands
prefcounts = profile . getPreferenceCounts ( )
if min ( ordering [ 0 ] ) == 0 :
startstate = set ( range ( m ) )
else :
startstate = set ( range ( 1 , m + 1 ) )
wmg = self . getWmg2 ( prefcounts , ordering , startstate , normalize = False )
known_w... |
def find_first_tag ( tags , entity_type , after_index = - 1 ) :
"""Searches tags for entity type after given index
Args :
tags ( list ) : a list of tags with entity types to be compaired too entity _ type
entity _ type ( str ) : This is he entity type to be looking for in tags
after _ index ( int ) : the st... | for tag in tags :
for entity in tag . get ( 'entities' ) :
for v , t in entity . get ( 'data' ) :
if t . lower ( ) == entity_type . lower ( ) and tag . get ( 'start_token' , 0 ) > after_index :
return tag , v , entity . get ( 'confidence' )
return None , None , None |
def count ( self , level = None ) :
"""Return number of non - NA / null observations in the Series .
Parameters
level : int or level name , default None
If the axis is a MultiIndex ( hierarchical ) , count along a
particular level , collapsing into a smaller Series .
Returns
int or Series ( if level spe... | if level is None :
return notna ( com . values_from_object ( self ) ) . sum ( )
if isinstance ( level , str ) :
level = self . index . _get_level_number ( level )
lev = self . index . levels [ level ]
level_codes = np . array ( self . index . codes [ level ] , subok = False , copy = True )
mask = level_codes ==... |
def split_input ( cls , mapper_spec ) :
"""Returns a list of shard _ count input _ spec _ shards for input _ spec .
Args :
mapper _ spec : The mapper specification to split from . Must contain
' blob _ keys ' parameter with one or more blob keys .
Returns :
A list of BlobstoreInputReaders corresponding to... | params = _get_params ( mapper_spec )
blob_keys = params [ cls . BLOB_KEYS_PARAM ]
if isinstance ( blob_keys , basestring ) : # This is a mechanism to allow multiple blob keys ( which do not contain
# commas ) in a single string . It may go away .
blob_keys = blob_keys . split ( "," )
blob_sizes = { }
for blob_key i... |
def unique_id ( self ) :
"""Generates a tuple that uniquely identifies a ` Monomer ` in an ` Assembly ` .
Notes
The unique _ id will uniquely identify each monomer within a polymer .
If each polymer in an assembly has a distinct id , it will uniquely
identify each monomer within the assembly .
The hetero ... | if self . is_hetero :
if self . mol_code == 'HOH' :
hetero_flag = 'W'
else :
hetero_flag = 'H_{0}' . format ( self . mol_code )
else :
hetero_flag = ' '
return self . ampal_parent . id , ( hetero_flag , self . id , self . insertion_code ) |
def setLocalityGroups ( self , login , tableName , groups ) :
"""Parameters :
- login
- tableName
- groups""" | self . send_setLocalityGroups ( login , tableName , groups )
self . recv_setLocalityGroups ( ) |
def param_sweep ( model , sequences , param_grid , n_jobs = 1 , verbose = 0 ) :
"""Fit a series of models over a range of parameters .
Parameters
model : msmbuilder . BaseEstimator
An * instance * of an estimator to be used
to fit data .
sequences : list of array - like
List of sequences , or a single s... | if isinstance ( param_grid , dict ) :
param_grid = ParameterGrid ( param_grid )
elif not isinstance ( param_grid , ParameterGrid ) :
raise ValueError ( "param_grid must be a dict or ParamaterGrid instance" )
# iterable with ( model , sequence ) as items
iter_args = ( ( clone ( model ) . set_params ( ** params )... |
def _get_param_values ( self , name ) :
"""Return the parameter by name as stored on the protocol
agent payload . This loads the data from the local cache
versus having to query the SMC for each parameter .
: param str name : name of param
: rtype : dict""" | for param in self . data . get ( 'paParameters' , [ ] ) :
for _pa_parameter , values in param . items ( ) :
if values . get ( 'name' ) == name :
return values |
def output ( self , value ) :
"""SPL output port assignment expression .
Arguments :
value ( str ) : SPL expression used for an output assignment . This can be a string , a constant , or an : py : class : ` Expression ` .
Returns :
Expression : Output assignment expression that is valid as a the context of ... | return super ( Source , self ) . output ( self . stream , value ) |
def set_basic_params ( self , count = None , thunder_lock = None , lock_engine = None ) :
""": param int count : Create the specified number of shared locks .
: param bool thunder _ lock : Serialize accept ( ) usage ( if possible )
Could improve performance on Linux with robust pthread mutexes .
http : / / uw... | self . _set ( 'thunder-lock' , thunder_lock , cast = bool )
self . _set ( 'lock-engine' , lock_engine )
self . _set ( 'locks' , count )
return self . _section |
def apply_config ( self , config ) :
"""Takes the given config dictionary and sets the hosts and base _ path
attributes .
If the kazoo client connection is established , its hosts list is
updated to the newly configured value .""" | self . hosts = config [ "hosts" ]
old_base_path = self . base_path
self . base_path = config [ "path" ]
if not self . connected . is_set ( ) :
return
logger . debug ( "Setting ZK hosts to %s" , self . hosts )
self . client . set_hosts ( "," . join ( self . hosts ) )
if old_base_path and old_base_path != self . base... |
def _random_id ( self , size = 16 , chars = string . ascii_uppercase + string . digits ) :
"""Generates a random id based on ` size ` and ` chars ` variable .
By default it will generate a 16 character long string based on
ascii uppercase letters and digits .""" | return '' . join ( random . choice ( chars ) for _ in range ( size ) ) |
def package ( self ) :
"""Find a package name from a build task ' s parameters .
: returns : name of the package this build task is building .
: raises : ValueError if we could not parse this tasks ' s request params .""" | if self . method == 'buildNotification' :
return self . params [ 1 ] [ 'name' ]
if self . method in ( 'createImage' , 'image' , 'livecd' ) :
return self . params [ 0 ]
if self . method == 'indirectionimage' :
return self . params [ 0 ] [ 'name' ]
# params [ 0 ] is the source URL for these tasks :
if self . ... |
def change ( properties , feature , value = None ) :
"""Returns a modified version of properties with all values of the
given feature replaced by the given value .
If ' value ' is None the feature will be removed .""" | assert is_iterable_typed ( properties , basestring )
assert isinstance ( feature , basestring )
assert isinstance ( value , ( basestring , type ( None ) ) )
result = [ ]
feature = add_grist ( feature )
for p in properties :
if get_grist ( p ) == feature :
if value :
result . append ( replace_gri... |
def calc_naturalremotedischarge_v1 ( self ) :
"""Try to estimate the natural discharge of a cross section far downstream
based on the last few simulation steps .
Required control parameter :
| NmbLogEntries |
Required log sequences :
| LoggedTotalRemoteDischarge |
| LoggedOutflow |
Calculated flux seq... | con = self . parameters . control . fastaccess
flu = self . sequences . fluxes . fastaccess
log = self . sequences . logs . fastaccess
flu . naturalremotedischarge = 0.
for idx in range ( con . nmblogentries ) :
flu . naturalremotedischarge += ( log . loggedtotalremotedischarge [ idx ] - log . loggedoutflow [ idx ]... |
def _hash_of_file ( path , algorithm ) :
"""Return the hash digest of a file .""" | with open ( path , 'rb' ) as archive :
hash = hashlib . new ( algorithm )
for chunk in read_chunks ( archive ) :
hash . update ( chunk )
return hash . hexdigest ( ) |
def fields ( self ) :
'''Return a tuple of ordered fields for this : class : ` ColumnTS ` .''' | key = self . id + ':fields'
encoding = self . client . encoding
return tuple ( sorted ( ( f . decode ( encoding ) for f in self . client . smembers ( key ) ) ) ) |
def flush_all ( self , time = 0 ) :
"""Send a command to server flush | delete all keys .
: param time : Time to wait until flush in seconds .
: type time : int
: return : True in case of success , False in case of failure
: rtype : bool""" | returns = [ ]
for server in self . servers :
returns . append ( server . flush_all ( time ) )
return any ( returns ) |
def add_filter ( self , filter_values ) :
"""Improve the original one to deal with OR cases .""" | field = self . _params [ 'field' ]
# Build a ` AND ` query on values wihtout the OR operator .
# and a ` OR ` query for each value containing the OR operator .
filters = [ Q ( 'bool' , should = [ Q ( 'term' , ** { field : v } ) for v in value . split ( OR_SEPARATOR ) ] ) if OR_SEPARATOR in value else Q ( 'term' , ** { ... |
def auto_doc ( tool , nco_self ) :
"""Generate the _ _ doc _ _ string of the decorated function by calling the nco help command
: param tool :
: param nco _ self :
: return :""" | def desc ( func ) :
func . __doc__ = nco_self . call ( [ tool , "--help" ] ) . get ( "stdout" )
return func
return desc |
def add_to_category ( self , category , name , action ) :
"""Adds given action to given category .
: param category : Category to store the action .
: type category : unicode
: param name : Action name .
: type name : unicode
: param action : Action object .
: type action : QAction
: return : Method s... | category = self . get_category ( category , vivify = True )
if not isinstance ( category , dict ) :
return False
category [ name ] = action
LOGGER . debug ( "> Added '{0}' action to '{1}' category!" . format ( category , name ) )
return True |
def symlink ( source , target , isfile = True ) :
"""Creates a symlink at target * file * pointing to source .
: arg isfile : when True , if symlinking is disabled in the global config , the file
is copied instead with fortpy . utility . copyfile ; otherwise fortpy . utility . copy
is used and the target is c... | from fortpy . code import config
from os import path
if config . symlink :
from os import symlink , remove
if path . isfile ( target ) or path . islink ( target ) :
remove ( target )
elif path . isdir ( target ) :
msg . warn ( "Cannot auto-delete directory '{}' for symlinking." . format ( ta... |
def send_message ( self , message ) :
"""Send a message to Storm via stdout .""" | if not isinstance ( message , dict ) :
logger = self . logger if self . logger else log
logger . error ( "%s.%d attempted to send a non dict message to Storm: " "%r" , self . component_name , self . pid , message , )
return
self . serializer . send_message ( message ) |
def formation_energy ( self , chemical_potentials = None , fermi_level = 0 ) :
"""Computes the formation energy for a defect taking into account a given chemical potential and fermi _ level""" | chemical_potentials = chemical_potentials if chemical_potentials else { }
chempot_correction = sum ( [ chem_pot * ( self . bulk_structure . composition [ el ] - self . defect . defect_composition [ el ] ) for el , chem_pot in chemical_potentials . items ( ) ] )
formation_energy = self . energy + chempot_correction
if "... |
def single ( self ) :
"""Return the associated node .
: return : node""" | nodes = super ( One , self ) . all ( )
if nodes :
if len ( nodes ) == 1 :
return nodes [ 0 ]
else :
raise CardinalityViolation ( self , len ( nodes ) )
else :
raise CardinalityViolation ( self , 'none' ) |
def add_sender_info ( self , sender_txhash , nulldata_vin_outpoint , sender_out_data ) :
"""Record sender information in our block info .
@ sender _ txhash : txid of the sender
@ nulldata _ vin _ outpoint : the ' vout ' index from the nulldata tx input that this transaction funded""" | assert sender_txhash in self . sender_info . keys ( ) , "Missing sender info for %s" % sender_txhash
assert nulldata_vin_outpoint in self . sender_info [ sender_txhash ] , "Missing outpoint %s for sender %s" % ( nulldata_vin_outpoint , sender_txhash )
block_hash = self . sender_info [ sender_txhash ] [ nulldata_vin_out... |
def shared ( self ) -> typing . Union [ None , SharedCache ] :
"""The shared display object associated with this project .""" | return self . _project . shared if self . _project else None |
def compare_and_set ( self , oldval , newval ) :
'''Given ` oldval ` and ` newval ` , sets the atom ' s value to ` newval ` if and
only if ` oldval ` is the atom ' s current value . Returns ` True ` upon
success , otherwise ` False ` .
: param oldval : The old expected value .
: param newval : The new value... | ret = self . _state . compare_and_set ( oldval , newval )
if ret :
self . notify_watches ( oldval , newval )
return ret |
def _bake_script ( script ) :
"""Takes a script element and bakes it in only if it contains a remote resource""" | if "src" in script . attrs :
if re . match ( "https?://" , script [ "src" ] ) :
script_data = _load_url ( script [ "src" ] ) . read ( )
else :
script_data = _load_file ( script [ "src" ] ) . read ( )
script . clear ( )
if USING_PYTHON2 :
script . string = "\n" + script_data + "\n... |
def set_shutter_level ( self , level = 0.0 ) :
"""sets the shutter level
Args :
level ( float ) : the new level of the shutter . 0.0 = open , 1.0 = closed
Returns :
the result of the _ restCall""" | data = { "channelIndex" : 1 , "deviceId" : self . id , "shutterLevel" : level }
return self . _restCall ( "device/control/setShutterLevel" , body = json . dumps ( data ) ) |
def set_event_tags ( self , id , ** kwargs ) : # noqa : E501
"""Set all tags associated with a specific event # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . set _ event _ tags ( ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . set_event_tags_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . set_event_tags_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def get_ry0_distance ( self , mesh ) :
"""For each point determine the corresponding Ry0 distance using the GC2
configuration .
See : meth : ` superclass method
< . base . BaseSurface . get _ ry0 _ distance > `
for spec of input and result values .""" | # If the GC2 calculations have already been computed ( by invoking Ry0
# first ) and the mesh is identical then class has GC2 attributes
# already pre - calculated
if not self . tmp_mesh or ( self . tmp_mesh == mesh ) : # If that ' s not the case , or the mesh is different then
# re - compute GC2 configuration
self... |
def bearer_auth ( ) :
"""Prompts the user for authorization using bearer authentication .
tags :
- Auth
parameters :
- in : header
name : Authorization
schema :
type : string
produces :
- application / json
responses :
200:
description : Sucessful authentication .
401:
description : Unsu... | authorization = request . headers . get ( "Authorization" )
if not ( authorization and authorization . startswith ( "Bearer " ) ) :
response = app . make_response ( "" )
response . headers [ "WWW-Authenticate" ] = "Bearer"
response . status_code = 401
return response
slice_start = len ( "Bearer " )
toke... |
def create_similar_image ( self , content , width , height ) :
"""Create a new image surface that is as compatible as possible
for uploading to and the use in conjunction with this surface .
However , this surface can still be used like any normal image surface .
Initially the surface contents are all 0
( t... | return Surface . _from_pointer ( cairo . cairo_surface_create_similar_image ( self . _pointer , content , width , height ) , incref = False ) |
def run_process ( self , process ) :
"""Runs a single action .""" | message = u'#{bright}'
message += u'{} ' . format ( str ( process ) [ : 68 ] ) . ljust ( 69 , '.' )
stashed = False
if self . unstaged_changes and not self . include_unstaged_changes :
out , err , code = self . git . stash ( keep_index = True , quiet = True )
stashed = code == 0
try :
result = process ( fil... |
def rescorer ( self , rescorer ) :
"""Returns a new QuerySet with a set rescorer .""" | clone = self . _clone ( )
clone . _rescorer = rescorer
return clone |
def execute_state_machine_from_path ( self , state_machine = None , path = None , start_state_path = None , wait_for_execution_finished = True ) :
"""A helper function to start an arbitrary state machine at a given path .
: param path : The path where the state machine resides
: param start _ state _ path : The... | import rafcon . core . singleton
from rafcon . core . storage import storage
rafcon . core . singleton . library_manager . initialize ( )
if not state_machine :
state_machine = storage . load_state_machine_from_path ( path )
rafcon . core . singleton . state_machine_manager . add_state_machine ( state_machine )... |
def cond_int ( self , conkey ) :
"""Return the trailing number from cond if any , as an int . If no
trailing number , return the string conkey as is .
This is used for sorting the conditions properly even when
passing the number 10 . The name of this function could be
improved since it might return a string... | m = re . match ( self . numrx , conkey )
if not m :
return conkey
return int ( m . group ( 1 ) ) |
def matrixplot ( adata , var_names , groupby = None , use_raw = None , log = False , num_categories = 7 , figsize = None , dendrogram = False , gene_symbols = None , var_group_positions = None , var_group_labels = None , var_group_rotation = None , layer = None , standard_scale = None , swap_axes = False , show = None ... | if use_raw is None and adata . raw is not None :
use_raw = True
if isinstance ( var_names , str ) :
var_names = [ var_names ]
categories , obs_tidy = _prepare_dataframe ( adata , var_names , groupby , use_raw , log , num_categories , gene_symbols = gene_symbols , layer = layer )
if groupby is None or len ( cate... |
def _flush ( self ) :
"""Purges the buffer and commits all pending values into the estimator .""" | self . _buffer . sort ( )
self . _replace_batch ( )
self . _buffer = [ ]
self . _compress ( ) |
def parse_filters ( self , vt_filter ) :
"""Parse a string containing one or more filters
and return a list of filters
Arguments :
vt _ filter ( string ) : String containing filters separated with
semicolon .
Return :
List with filters . Each filters is a list with 3 elements
e . g . [ arg , operator ... | filter_list = vt_filter . split ( ';' )
filters = list ( )
for single_filter in filter_list :
filter_aux = re . split ( '(\W)' , single_filter , 1 )
if len ( filter_aux ) < 3 :
raise OSPDError ( "Invalid number of argument in the filter" , "get_vts" )
_element , _oper , _val = filter_aux
if _ele... |
def render_compressed_output ( self , package , package_name , package_type ) :
"""Render HTML for using the package ' s output file .
Subclasses can override this method to provide custom behavior for
rendering the output file .""" | method = getattr ( self , 'render_{0}' . format ( package_type ) )
return method ( package , package . output_filename ) |
def DataCopyWithOverlay ( self , dcmfilelist , out_dir , overlays ) :
"""Function make 3D data from dicom file slices
: dcmfilelist list of sorted . dcm files
: overlays dictionary of binary overlays . { 1 : np . array ( [ . . . ] ) , 3 : . . . }
: out _ dir output directory""" | dcmlist = dcmfilelist
# data3d = [ ]
for i in range ( len ( dcmlist ) ) :
onefile = dcmlist [ i ]
logger . info ( onefile )
data = dicom . read_file ( onefile )
for i_overlay in overlays . keys ( ) :
overlay3d = overlays [ i_overlay ]
data = self . encode_overlay_slice ( data , overlay3d... |
def execute ( self , input_data ) :
'''yara worker execute method''' | raw_bytes = input_data [ 'sample' ] [ 'raw_bytes' ]
matches = self . rules . match_data ( raw_bytes )
# The matches data is organized in the following way
# { ' filename1 ' : [ match _ list ] , ' filename2 ' : [ match _ list ] }
# match _ list = list of match
# match = { ' meta ' : { ' description ' : ' blah } , tags =... |
def put ( self , id , name , description , command_to_run , environment_variables , required_arguments , required_arguments_default_values , logs_path , results_path , container_image , container_type , extra_data_to_put = None , ) :
"""Updates a task type on the saltant server .
Args :
id ( int ) : The ID of t... | # Add in extra data specific to container task types
if extra_data_to_put is None :
extra_data_to_put = { }
extra_data_to_put . update ( { "logs_path" : logs_path , "results_path" : results_path , "container_image" : container_image , "container_type" : container_type , } )
# Call the parent create function
return ... |
def setup ( self , level = None , log_file = None , json = None ) :
'''Load everything up . Note that any arg here will override both
default and custom settings
@ param level : the log level
@ param log _ file : boolean t / f whether to log to a file , else stdout
@ param json : boolean t / f whether to wr... | self . settings = self . wrapper . load ( self . settings_name )
my_level = level if level else self . settings [ 'LOG_LEVEL' ]
# negate because logger wants True for std out
my_output = not log_file if log_file else self . settings [ 'LOG_STDOUT' ]
my_json = json if json else self . settings [ 'LOG_JSON' ]
self . logg... |
def list_zones ( self , max_results = None , page_token = None ) :
"""List zones for the project associated with this client .
See
https : / / cloud . google . com / dns / api / v1 / managedZones / list
: type max _ results : int
: param max _ results : maximum number of zones to return , If not
passed , ... | path = "/projects/%s/managedZones" % ( self . project , )
return page_iterator . HTTPIterator ( client = self , api_request = self . _connection . api_request , path = path , item_to_value = _item_to_zone , items_key = "managedZones" , page_token = page_token , max_results = max_results , ) |
def convert_time ( time ) :
"""Convert a time string into 24 - hour time .""" | split_time = time . split ( )
try : # Get rid of period in a . m . / p . m .
am_pm = split_time [ 1 ] . replace ( '.' , '' )
time_str = '{0} {1}' . format ( split_time [ 0 ] , am_pm )
except IndexError :
return time
try :
time_obj = datetime . strptime ( time_str , '%I:%M %p' )
except ValueError :
t... |
def url_unquote_plus ( s , charset = 'utf-8' , errors = 'replace' ) :
"""URL decode a single string with the given decoding and decode
a " + " to whitespace .
Per default encoding errors are ignored . If you want a different behavior
you can set ` errors ` to ` ` ' replace ' ` ` or ` ` ' strict ' ` ` . In str... | if isinstance ( s , unicode ) :
s = s . encode ( charset )
return _decode_unicode ( _unquote_plus ( s ) , charset , errors ) |
def _parse_attributes ( self , attributes ) :
"""Ensure compliance with the spec ' s attributes section
Specifically , the attributes object of the single resource
object . This contains the key / values to be mapped to the
model .
: param attributes :
dict JSON API attributes object""" | link = 'jsonapi.org/format/#document-resource-object-attributes'
if not isinstance ( attributes , dict ) :
self . fail ( 'The JSON API resource object attributes key MUST ' 'be a hash.' , link )
elif 'id' in attributes or 'type' in attributes :
self . fail ( 'A field name of `id` or `type` is not allowed in ' '... |
def declare_backward_dependency ( self , out_grad , in_data , out_data ) :
"""Declare dependencies of this operator for backward pass .
Parameters
out _ grad : list of int
ids of out _ grad blobs .
in _ data : list of int
ids of in _ data blobs .
out _ data : list of int
ids of out _ data blobs .
Re... | deps = [ ]
if self . need_top_grad ( ) :
deps . extend ( out_grad )
deps . extend ( in_data )
deps . extend ( out_data )
return deps |
def _set_gradebook_view ( self , session ) :
"""Sets the underlying gradebook view to match current view""" | if self . _gradebook_view == COMPARATIVE :
try :
session . use_comparative_gradebook_view ( )
except AttributeError :
pass
else :
try :
session . use_plenary_gradebook_view ( )
except AttributeError :
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.