signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def write_tar ( src_fs , # type : FS
file , # type : Union [ Text , BinaryIO ]
compression = None , # type : Optional [ Text ]
encoding = "utf-8" , # type : Text
walker = None , # type : Optional [ Walker ]
) : # type : ( . . . ) - > None
"""Write the contents of a filesystem to a tar file .
Arguments :
file ( ... | type_map = { ResourceType . block_special_file : tarfile . BLKTYPE , ResourceType . character : tarfile . CHRTYPE , ResourceType . directory : tarfile . DIRTYPE , ResourceType . fifo : tarfile . FIFOTYPE , ResourceType . file : tarfile . REGTYPE , ResourceType . socket : tarfile . AREGTYPE , # no type for socket
Resour... |
def down ( self , point ) :
"""Set initial cursor window coordinates and pick constrain - axis .""" | self . _vdown = arcball_map_to_sphere ( point , self . _center , self . _radius )
self . _qdown = self . _qpre = self . _qnow
if self . _constrain and self . _axes is not None :
self . _axis = arcball_nearest_axis ( self . _vdown , self . _axes )
self . _vdown = arcball_constrain_to_axis ( self . _vdown , self ... |
def run_thread ( self , usnap = .2 , daemon = True ) :
"""run thread with data""" | # self . stream _ data ( ) # Unless other changes are made this would limit to localhost only .
try :
gps3_data_thread = Thread ( target = self . unpack_data , args = { usnap : usnap } , daemon = daemon )
except TypeError : # threading . Thread ( ) only accepts daemon argument in Python 3.3
gps3_data_thread = T... |
def is_reserved_ip ( self , ip ) :
"""Check if the given ip address is in a reserved ipv4 address space .
: param ip : ip address
: return : boolean""" | theip = ipaddress ( ip )
for res in self . _reserved_netmasks :
if theip in ipnetwork ( res ) :
return True
return False |
def rpc_export ( rpc_method_name , sync = False ) :
"""Export a function or plugin method as a msgpack - rpc request handler .""" | def dec ( f ) :
f . _nvim_rpc_method_name = rpc_method_name
f . _nvim_rpc_sync = sync
f . _nvim_bind = True
f . _nvim_prefix_plugin_path = False
return f
return dec |
def sender ( self ) :
""": returns : A : class : ` ~ okcupyd . profile . Profile ` instance belonging
to the sender of this message .""" | return ( self . _message_thread . user_profile if 'from_me' in self . _message_element . attrib [ 'class' ] else self . _message_thread . correspondent_profile ) |
def sort_magic_data ( magic_data , sort_name ) :
'''Sort magic _ data by header ( like er _ specimen _ name for example )''' | magic_data_sorted = { }
for rec in magic_data :
name = rec [ sort_name ]
if name not in list ( magic_data_sorted . keys ( ) ) :
magic_data_sorted [ name ] = [ ]
magic_data_sorted [ name ] . append ( rec )
return magic_data_sorted |
def _PrintSessionsOverview ( self , storage_reader ) :
"""Prints a sessions overview .
Args :
storage _ reader ( StorageReader ) : storage reader .""" | table_view = views . ViewsFactory . GetTableView ( self . _views_format_type , title = 'Sessions' )
for session in storage_reader . GetSessions ( ) :
start_time = timelib . Timestamp . CopyToIsoFormat ( session . start_time )
session_identifier = uuid . UUID ( hex = session . identifier )
session_identifier... |
def generate_api_gateway ( ) :
"""Create the Blockade API Gateway REST service .""" | logger . debug ( "[#] Setting up the API Gateway" )
client = boto3 . client ( 'apigateway' , region_name = PRIMARY_REGION )
matches = [ x for x in client . get_rest_apis ( ) . get ( 'items' , list ( ) ) if x [ 'name' ] == API_GATEWAY ]
if len ( matches ) > 0 :
logger . debug ( "[#] API Gateway already setup" )
... |
def append ( self , entry ) :
"""Append an entry to self""" | if not self . is_appendable ( entry ) :
raise ValueError ( 'entry not appendable' )
self . data += entry . data |
def p_expr ( self , p ) :
"""expr : assignment _ expr
| expr COMMA assignment _ expr""" | if len ( p ) == 2 :
p [ 0 ] = p [ 1 ]
else :
p [ 0 ] = ast . Comma ( left = p [ 1 ] , right = p [ 3 ] ) |
def get_view_names ( engine : Engine ) -> List [ str ] :
"""Returns a list of database view names from the : class : ` Engine ` .""" | insp = Inspector . from_engine ( engine )
return insp . get_view_names ( ) |
def transformToNative ( obj ) :
"""Turn a recurring Component into a RecurringComponent .""" | if not obj . isNative :
object . __setattr__ ( obj , '__class__' , RecurringComponent )
obj . isNative = True
return obj |
def from_date ( self , value : date ) -> datetime :
"""Initializes from the given date value""" | assert isinstance ( value , date )
# self . value = datetime . combine ( value , time . min )
self . value = datetime ( value . year , value . month , value . day )
return self . value |
def exists ( self , pattern , ** match_kwargs ) :
"""Check if image exists in screen
Returns :
If exists , return FindPoint , or
return None if result . confidence < self . image _ match _ threshold""" | ret = self . match ( pattern , ** match_kwargs )
if ret is None :
return None
if not ret . matched :
return None
return ret |
def get_task_cls ( cls , name ) :
"""Returns an unambiguous class or raises an exception .""" | task_cls = cls . _get_reg ( ) . get ( name )
if not task_cls :
raise TaskClassNotFoundException ( cls . _missing_task_msg ( name ) )
if task_cls == cls . AMBIGUOUS_CLASS :
raise TaskClassAmbigiousException ( 'Task %r is ambiguous' % name )
return task_cls |
def main ( args = sys . argv ) :
"""main entry point for the manifest CLI""" | if len ( args ) < 2 :
return usage ( "Command expected" )
command = args [ 1 ]
rest = args [ 2 : ]
if "create" . startswith ( command ) :
return cli_create ( rest )
elif "query" . startswith ( command ) :
return cli_query ( rest )
elif "verify" . startswith ( command ) :
return cli_verify ( rest )
else ... |
async def queryone ( self , stmt , * args ) :
"""Query for exactly one result .
Raises NoResultError if there are no results , or ValueError if
there are more than one .""" | results = await self . query ( stmt , * args )
if len ( results ) == 0 :
raise NoResultError ( )
elif len ( results ) > 1 :
raise ValueError ( "Expected 1 result, got %d" % len ( results ) )
return results [ 0 ] |
def clear_terminal ( self ) :
"""Reimplement ShellBaseWidget method""" | self . clear ( )
self . new_prompt ( self . interpreter . p2 if self . interpreter . more else self . interpreter . p1 ) |
def _reduce_opacity ( self ) :
"""Reduce opacity for watermark image .""" | if self . image . mode != 'RGBA' :
image = self . image . convert ( 'RGBA' )
else :
image = self . image . copy ( )
alpha = image . split ( ) [ 3 ]
alpha = ImageEnhance . Brightness ( alpha ) . enhance ( self . opacity )
image . putalpha ( alpha )
self . image = image |
def rms ( self , stride = 1 ) :
"""Calculate the root - mean - square value of this ` TimeSeries `
once per stride .
Parameters
stride : ` float `
stride ( seconds ) between RMS calculations
Returns
rms : ` TimeSeries `
a new ` TimeSeries ` containing the RMS value with dt = stride""" | stridesamp = int ( stride * self . sample_rate . value )
nsteps = int ( self . size // stridesamp )
# stride through TimeSeries , recording RMS
data = numpy . zeros ( nsteps )
for step in range ( nsteps ) : # find step TimeSeries
idx = int ( stridesamp * step )
idx_end = idx + stridesamp
stepseries = self [... |
def provideObjectsToLearn ( self , objectNames = None ) :
"""Returns the objects in a canonical format to be sent to an experiment .
The returned format is a a dictionary where the keys are object names , and
values are lists of sensations , each sensation being a mapping from
cortical column index to a pair ... | if objectNames is None :
objectNames = self . objects . keys ( )
objects = { }
for name in objectNames :
objects [ name ] = [ self . _getSDRPairs ( [ pair ] * self . numColumns ) for pair in self . objects [ name ] ]
self . _checkObjectsToLearn ( objects )
return objects |
def register ( ) :
"""Return dictionary of tranform factories""" | registry = { key : bake_html ( key ) for key in ( 'css' , 'css-all' , 'tag' , 'text' ) }
registry [ 'xpath' ] = bake_parametrized ( xpath_selector , select_all = False )
registry [ 'xpath-all' ] = bake_parametrized ( xpath_selector , select_all = True )
return registry |
def encode_sentences ( sentences , vocab = None , invalid_label = - 1 , invalid_key = '\n' , start_label = 0 , unknown_token = None ) :
"""Encode sentences and ( optionally ) build a mapping
from string tokens to integer indices . Unknown keys
will be added to vocabulary .
Parameters
sentences : list of lis... | idx = start_label
if vocab is None :
vocab = { invalid_key : invalid_label }
new_vocab = True
else :
new_vocab = False
res = [ ]
for sent in sentences :
coded = [ ]
for word in sent :
if word not in vocab :
assert ( new_vocab or unknown_token ) , "Unknown token %s" % word
... |
def cancel ( self , block = True ) :
"""Cancel a call to consume ( ) happening in another thread
This could take up to DashiConnection . consumer _ timeout to complete .
@ param block : if True , waits until the consumer has returned""" | if self . _consumer :
self . _consumer . cancel ( block = block ) |
def date ( self ) -> Optional [ DateHeader ] :
"""The ` ` Date ` ` header .""" | try :
return cast ( DateHeader , self [ b'date' ] [ 0 ] )
except ( KeyError , IndexError ) :
return None |
def map_with_slider ( h3 : HistogramND , * , show_zero : bool = True , show_values : bool = False , ** kwargs ) -> dict :
"""Heatmap showing slice in first two dimensions , third dimension represented as a slider .
Parameters""" | vega = _create_figure ( kwargs )
values_arr = get_data ( h3 , kwargs . pop ( "density" , None ) , kwargs . pop ( "cumulative" , None ) )
values = values_arr . tolist ( )
value_format = get_value_format ( kwargs . pop ( "value_format" , None ) )
_add_title ( h3 , vega , kwargs )
_create_scales ( h3 , vega , kwargs )
_cr... |
def _handle_uniqueness ( self ) :
"""Checks marked as unique and unique _ together fields of the Model at each
creation and update , and if it violates the uniqueness raises IntegrityError .
First , looks at the fields which marked as " unique " . If Model ' s unique fields
did not change , it means that ther... | def _getattr ( u ) :
try :
return self . _field_values [ u ]
except KeyError :
return getattr ( self , u )
if self . _uniques :
for u in self . _uniques :
val = _getattr ( u )
changed_fields = self . changed_fields ( from_db = True )
if self . exist and not ( u in cha... |
def defaults ( self ) :
"""Reset the chart options and style to defaults""" | self . chart_style = { }
self . chart_opts = { }
self . style ( "color" , "#30A2DA" )
self . width ( 900 )
self . height ( 250 ) |
def get_location ( self ) :
"""Return the absolute location of this widget on the Screen , taking into account the
current state of the Frame that is displaying it and any label offsets of the Widget .
: returns : A tuple of the form ( < X coordinate > , < Y coordinate > ) .""" | origin = self . _frame . canvas . origin
return ( self . _x + origin [ 0 ] + self . _offset , self . _y + origin [ 1 ] - self . _frame . canvas . start_line ) |
def increase_writes_in_units ( current_provisioning , units , max_provisioned_writes , consumed_write_units_percent , log_tag ) :
"""Increase the current _ provisioning with units units
: type current _ provisioning : int
: param current _ provisioning : The current provisioning
: type units : int
: param u... | units = int ( units )
current_provisioning = float ( current_provisioning )
consumed_write_units_percent = float ( consumed_write_units_percent )
consumption_based_current_provisioning = int ( math . ceil ( current_provisioning * ( consumed_write_units_percent / 100 ) ) )
if consumption_based_current_provisioning > cur... |
def get_identity ( user ) :
"""Create an identity for a given user instance .
Primarily useful for testing .""" | identity = Identity ( user . id )
if hasattr ( user , 'id' ) :
identity . provides . add ( UserNeed ( user . id ) )
for role in getattr ( user , 'roles' , [ ] ) :
identity . provides . add ( RoleNeed ( role . name ) )
identity . user = user
return identity |
def lookup_class_name ( name , context , depth = 3 ) :
"""given a table name in the form ` schema _ name ` . ` table _ name ` , find its class in the context .
: param name : ` schema _ name ` . ` table _ name `
: param context : dictionary representing the namespace
: param depth : search depth into imported... | # breadth - first search
nodes = [ dict ( context = context , context_name = '' , depth = depth ) ]
while nodes :
node = nodes . pop ( 0 )
for member_name , member in node [ 'context' ] . items ( ) :
if not member_name . startswith ( '_' ) : # skip IPython ' s implicit variables
if inspect .... |
def _option ( value ) :
'''Look up the value for an option .''' | if value in __opts__ :
return __opts__ [ value ]
master_opts = __pillar__ . get ( 'master' , { } )
if value in master_opts :
return master_opts [ value ]
if value in __pillar__ :
return __pillar__ [ value ] |
def _concat_nbest_translations ( translations : List [ Translation ] , stop_ids : Set [ int ] , length_penalty : LengthPenalty , brevity_penalty : Optional [ BrevityPenalty ] = None ) -> Translation :
"""Combines nbest translations through concatenation .
: param translations : A list of translations ( sequence s... | expanded_translations = ( _expand_nbest_translation ( translation ) for translation in translations )
concatenated_translations = [ ]
# type : List [ Translation ]
for translations_to_concat in zip ( * expanded_translations ) :
concatenated_translations . append ( _concat_translations ( translations = list ( transl... |
def __is_valid_type ( self , typ , typlist ) :
"""Check if type is valid based on input type list
" string " is special because it can be used for stringlist
: param typ : the type to check
: param typlist : the list of type to check
: return : True on success , False otherwise""" | typ_is_str = typ == "string"
str_list_in_typlist = "stringlist" in typlist
return typ in typlist or ( typ_is_str and str_list_in_typlist ) |
def update ( self , other = None , ** kwargs ) :
"""Set metadata values from the given iterable ` other ` and kwargs .
Behavior is like ` dict . update ` : If ` other ` has a ` ` keys ` ` method ,
they are looped over and ` ` self [ key ] ` ` is assigned ` ` other [ key ] ` ` .
Else , ` ` other ` ` is an iter... | def _set ( key , value ) :
if key in _ATTR2FIELD and value :
self . set ( self . _convert_name ( key ) , value )
if not other : # other is None or empty container
pass
elif hasattr ( other , 'keys' ) :
for k in other . keys ( ) :
_set ( k , other [ k ] )
else :
for k , v in other :
... |
def metric ( self , name , count , elapsed ) :
"""A metric function that writes a single CSV file
: arg str name : name of the metric
: arg int count : number of items
: arg float elapsed : time in seconds""" | if name is None :
warnings . warn ( "Ignoring unnamed metric" , stacklevel = 3 )
return
with self . lock :
self . writer . writerow ( ( name , count , "%f" % elapsed ) ) |
def relation_ ( self , table , origin_field , search_field , destination_field = None , id_field = "id" ) :
"""Returns a DataSwim instance with a column filled from a relation foreign key""" | df = self . _relation ( table , origin_field , search_field , destination_field , id_field )
return self . _duplicate_ ( df ) |
def _should_use_fr_error_handler ( self ) :
"""Determine if error should be handled with FR or default Flask
The goal is to return Flask error handlers for non - FR - related routes ,
and FR errors ( with the correct media type ) for FR endpoints . This
method currently handles 404 and 405 errors .
: return... | adapter = current_app . create_url_adapter ( request )
try :
adapter . match ( )
except MethodNotAllowed as e : # Check if the other HTTP methods at this url would hit the Api
valid_route_method = e . valid_methods [ 0 ]
rule , _ = adapter . match ( method = valid_route_method , return_rule = True )
ret... |
def explore_show_head ( self , uri , check_headers = None ) :
"""Do HEAD on uri and show infomation .
Will also check headers against any values specified in
check _ headers .""" | print ( "HEAD %s" % ( uri ) )
if ( re . match ( r'^\w+:' , uri ) ) : # Looks like a URI
response = requests . head ( uri )
else : # Mock up response if we have a local file
response = self . head_on_file ( uri )
print ( " status: %s" % ( response . status_code ) )
if ( response . status_code == '200' ) : # pri... |
def program_unit_name ( line : str ) -> str :
"""Given a line that starts a program unit , i . e . , a program , module ,
subprogram , or function , this function returns the name associated
with that program unit .""" | match = RE_PGM_UNIT_START . match ( line )
assert match != None
return match . group ( 2 ) |
def num_pages ( self ) :
"""Returns the total number of pages .""" | if self . count == 0 and not self . allow_empty_first_page :
return 0
hits = max ( 1 , self . count - self . orphans )
return int ( ceil ( hits / float ( self . per_page ) ) ) |
def draw_hist ( self , metric , title = "" ) :
"""Draw a series of histograms of the selected keys over different
training steps .""" | # TODO : assert isinstance ( list ( values . values ( ) ) [ 0 ] , np . ndarray )
rows = 1
cols = 1
limit = 10
# max steps to show
# We need a 3D projection Subplot , so ignore the one provided to
# as an create a new one .
ax = self . figure . add_subplot ( self . gs , projection = "3d" )
ax . view_init ( 30 , - 80 )
#... |
def get_digest ( self ) :
"""return int uuid number for digest
: rtype : int
: return : digest""" | a , b = struct . unpack ( '>QQ' , self . digest )
return ( a << 64 ) | b |
def logout_oauth2 ( self ) :
'''Logout for given Oauth2 bearer token''' | url = "https://api.robinhood.com/oauth2/revoke_token/"
data = { "client_id" : CLIENT_ID , "token" : self . refresh_token , }
res = self . post ( url , payload = data )
if res is None :
self . account_id = None
self . account_url = None
self . access_token = None
self . refresh_token = None
self . mf... |
def compute_venn2_subsets ( a , b ) :
'''Given two set or Counter objects , computes the sizes of ( a & ~ b , b & ~ a , a & b ) .
Returns the result as a tuple .
> > > compute _ venn2 _ subsets ( set ( [ 1,2,3,4 ] ) , set ( [ 2,3,4,5,6 ] ) )
(1 , 2 , 3)
> > > compute _ venn2 _ subsets ( Counter ( [ 1,2,3,4 ... | if not ( type ( a ) == type ( b ) ) :
raise ValueError ( "Both arguments must be of the same type" )
set_size = len if type ( a ) != Counter else lambda x : sum ( x . values ( ) )
# We cannot use len to compute the cardinality of a Counter
return ( set_size ( a - b ) , set_size ( b - a ) , set_size ( a & b ) ) |
def EvalGeneric ( self , hashers = None ) :
"""Causes the entire file to be hashed by the given hash functions .
This sets up a ' finger ' for fingerprinting , where the entire file
is passed through a pre - defined ( or user defined ) set of hash functions .
Args :
hashers : An iterable of hash classes ( e... | if hashers is None :
hashers = Fingerprinter . GENERIC_HASH_CLASSES
hashfuncs = [ x ( ) for x in hashers ]
finger = Finger ( hashfuncs , [ Range ( 0 , self . filelength ) ] , { 'name' : 'generic' } )
self . fingers . append ( finger )
return True |
def get_ngroups ( self , field = None ) :
'''Returns ngroups count if it was specified in the query , otherwise ValueError .
If grouping on more than one field , provide the field argument to specify which count you are looking for .''' | field = field if field else self . _determine_group_field ( field )
if 'ngroups' in self . data [ 'grouped' ] [ field ] :
return self . data [ 'grouped' ] [ field ] [ 'ngroups' ]
raise ValueError ( "ngroups not found in response. specify group.ngroups in the query." ) |
def _remove_api_url_from_link ( link ) :
'''Remove the API URL from the link if it is there''' | if link . startswith ( _api_url ( ) ) :
link = link [ len ( _api_url ( ) ) : ]
if link . startswith ( _api_url ( mirror = True ) ) :
link = link [ len ( _api_url ( mirror = True ) ) : ]
return link |
def cloneQuery ( self , limit = _noItem , sort = _noItem ) :
"""Clone the original query which this distinct query wraps , and return a new
wrapper around that clone .""" | newq = self . query . cloneQuery ( limit = limit , sort = sort )
return self . __class__ ( newq ) |
def sample_group ( sid , groups ) :
"""Iterate through all categories in an OrderedDict and return category name if SampleID
present in that category .
: type sid : str
: param sid : SampleID from dataset .
: type groups : OrderedDict
: param groups : Returned dict from phylotoast . util . gather _ catego... | for name in groups :
if sid in groups [ name ] . sids :
return name |
def update ( self , other ) :
"""Update the collection with items from * other * . Accepts other
: class : ` SortedSetBase ` instances , dictionaries mapping members to
numeric scores , or sequences of ` ` ( member , score ) ` ` tuples .""" | def update_trans ( pipe ) :
other_items = method ( pipe = pipe ) if use_redis else method ( )
pipe . multi ( )
for member , score in other_items :
pipe . zadd ( self . key , { self . _pickle ( member ) : float ( score ) } )
watches = [ ]
if self . _same_redis ( other , RedisCollection ) :
use_re... |
def _record_app_data ( self , data ) :
"""Parse raw metadata output for a single application
The usual output is :
ApplicationName RevisionNumber
ApplicationName ROOT _ Version
ApplicationName KM3NET
ApplicationName . / command / line - - arguments - - which - - can
contain
also
multiple lines
and... | name , revision = data [ 0 ] . split ( )
root_version = data [ 1 ] . split ( ) [ 1 ]
command = b'\n' . join ( data [ 3 : ] ) . split ( b'\n' + name + b' Linux' ) [ 0 ]
self . meta . append ( { 'application_name' : np . string_ ( name ) , 'revision' : np . string_ ( revision ) , 'root_version' : np . string_ ( root_vers... |
def ints ( self , qlist ) :
"""Converts a sequence of pegasus _ index node labels into
linear _ index node labels , preserving order
Parameters
qlist : sequence of ints
The pegasus _ index node labels
Returns
rlist : iterable of tuples
The linear _ lindex node lables corresponding to qlist""" | m , m1 = self . args
return ( ( ( m * u + w ) * 12 + k ) * m1 + z for ( u , w , k , z ) in qlist ) |
def read_namespaced_role_binding ( self , name , namespace , ** kwargs ) : # noqa : E501
"""read _ namespaced _ role _ binding # noqa : E501
read the specified RoleBinding # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = T... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . read_namespaced_role_binding_with_http_info ( name , namespace , ** kwargs )
# noqa : E501
else :
( data ) = self . read_namespaced_role_binding_with_http_info ( name , namespace , ** kwargs )
# noqa : E501
re... |
def update_item ( self , table_name , key , attribute_updates , expected = None , return_values = None , object_hook = None ) :
"""Edits an existing item ' s attributes . You can perform a conditional
update ( insert a new attribute name - value pair if it doesn ' t exist ,
or replace an existing name - value p... | data = { 'TableName' : table_name , 'Key' : key , 'AttributeUpdates' : attribute_updates }
if expected :
data [ 'Expected' ] = expected
if return_values :
data [ 'ReturnValues' ] = return_values
json_input = json . dumps ( data )
return self . make_request ( 'UpdateItem' , json_input , object_hook = object_hook... |
def deserialize_frame ( stream , header , verifier = None ) :
"""Deserializes a frame from a body .
: param stream : Source data stream
: type stream : io . BytesIO
: param header : Deserialized header
: type header : aws _ encryption _ sdk . structures . MessageHeader
: param verifier : Signature verifie... | _LOGGER . debug ( "Starting frame deserialization" )
frame_data = { }
final_frame = False
( sequence_number , ) = unpack_values ( ">I" , stream , verifier )
if sequence_number == SequenceIdentifier . SEQUENCE_NUMBER_END . value :
_LOGGER . debug ( "Deserializing final frame" )
( sequence_number , ) = unpack_val... |
def zip ( self , * items ) :
"""Zip the collection together with one or more arrays .
: param items : The items to zip
: type items : list
: rtype : Collection""" | return self . __class__ ( list ( zip ( self . items , * items ) ) ) |
def match ( tgt , delimiter = DEFAULT_TARGET_DELIM , opts = None ) :
'''Matches a grain based on regex''' | if not opts :
opts = __opts__
log . debug ( 'grains pcre target: %s' , tgt )
if delimiter not in tgt :
log . error ( 'Got insufficient arguments for grains pcre match ' 'statement from master' )
return False
return salt . utils . data . subdict_match ( opts [ 'grains' ] , tgt , delimiter = delimiter , regex... |
def Validate ( self , problems = default_problem_reporter ) :
"""Validate attribute values and this object ' s internal consistency .
Returns :
True iff all validation checks passed .""" | found_problem = False
found_problem = ( ( not util . ValidateRequiredFieldsAreNotEmpty ( self , self . _REQUIRED_FIELD_NAMES , problems ) ) or found_problem )
found_problem = self . ValidateAgencyUrl ( problems ) or found_problem
found_problem = self . ValidateAgencyLang ( problems ) or found_problem
found_problem = se... |
def infer_struct ( value : Mapping [ str , GenericAny ] ) -> Struct :
"""Infer the : class : ` ~ ibis . expr . datatypes . Struct ` type of ` value ` .""" | if not value :
raise TypeError ( 'Empty struct type not supported' )
return Struct ( list ( value . keys ( ) ) , list ( map ( infer , value . values ( ) ) ) ) |
def lgammln ( xx ) :
"""Returns the gamma function of xx .
Gamma ( z ) = Integral ( 0 , infinity ) of t ^ ( z - 1 ) exp ( - t ) dt .
( Adapted from : Numerical Recipies in C . )
Usage : lgammln ( xx )""" | coeff = [ 76.18009173 , - 86.50532033 , 24.01409822 , - 1.231739516 , 0.120858003e-2 , - 0.536382e-5 ]
x = xx - 1.0
tmp = x + 5.5
tmp = tmp - ( x + 0.5 ) * math . log ( tmp )
ser = 1.0
for j in range ( len ( coeff ) ) :
x = x + 1
ser = ser + coeff [ j ] / x
return - tmp + math . log ( 2.50662827465 * ser ) |
def stop ( self ) :
"""Stop the primitive manager .""" | for p in self . primitives [ : ] :
p . stop ( )
StoppableLoopThread . stop ( self ) |
def SecurityCheck ( self , func , request , * args , ** kwargs ) :
"""A decorator applied to protected web handlers .""" | request . user = self . username
request . token = access_control . ACLToken ( username = "Testing" , reason = "Just a test" )
return func ( request , * args , ** kwargs ) |
def sponsor_menu ( root_menu , menu = "sponsors" , label = _ ( "Sponsors" ) , sponsors_item = _ ( "Our sponsors" ) , packages_item = _ ( "Sponsorship packages" ) ) :
"""Add sponsor menu links .""" | root_menu . add_menu ( menu , label , items = [ ] )
for sponsor in ( Sponsor . objects . all ( ) . order_by ( 'packages' , 'order' , 'id' ) . prefetch_related ( 'packages' ) ) :
symbols = sponsor . symbols ( )
if symbols :
item_name = u"» %s %s" % ( sponsor . name , symbols )
else :
item_nam... |
def image_get_by_alias ( alias , remote_addr = None , cert = None , key = None , verify_cert = True , _raw = False ) :
'''Get an image by an alias
alias :
The alias of the image to retrieve
remote _ addr :
An URL to a remote Server , you also have to give cert and key if
you provide remote _ addr and its ... | client = pylxd_client_get ( remote_addr , cert , key , verify_cert )
image = None
try :
image = client . images . get_by_alias ( alias )
except pylxd . exceptions . LXDAPIException :
raise SaltInvocationError ( 'Image with alias \'{0}\' not found' . format ( alias ) )
if _raw :
return image
return _pylxd_mo... |
def _set_value ( self , value ) :
"""Called by a Job object to tell the result is ready , and
provides the value of this result . The object will become
ready and successful . The collector ' s notify _ ready ( ) method
will be called , and the callback method too""" | assert not self . ready ( )
self . _data = value
self . _success = True
self . _event . set ( )
if self . _collector is not None :
self . _collector . notify_ready ( self )
if self . _callback is not None :
try :
self . _callback ( value )
except :
traceback . print_exc ( ) |
def convert ( ** kwargs ) :
"""EXAMPLE DOCSTRING for function ( you would usually put the discription here )
Parameters
user : colon delimited list of analysts ( default : " " )
magfile : input magnetometer file ( required )
Returns
type - Tuple : ( True or False indicating if conversion was sucessful , m... | # get parameters from kwargs . get ( parameter _ name , default _ value )
user = kwargs . get ( 'user' , '' )
magfile = kwargs . get ( 'magfile' )
# do any extra formating you need to variables here
# open magfile to start reading data
try :
infile = open ( magfile , 'r' )
except Exception as ex :
print ( ( "ba... |
def sato ( target , mol_weight = 'pore.molecular_weight' , boiling_temperature = 'pore.boiling_point' , temperature = 'pore.temperature' , critical_temperature = 'pore.critical_temperature' ) :
r"""Uses Sato et al . model to estimate thermal conductivity for pure liquids
from first principles at conditions of int... | T = target [ temperature ]
Tc = target [ critical_temperature ]
MW = target [ mol_weight ]
Tbr = target [ boiling_temperature ] / Tc
Tr = T / Tc
value = ( 1.11 / ( ( MW * 1e3 ) ** 0.5 ) ) * ( 3 + 20 * ( 1 - Tr ) ** ( 2 / 3 ) ) / ( 3 + 20 * ( 1 - Tbr ) ** ( 2 / 3 ) )
return value |
def enable_wrapper ( cls , enable , new_class ) :
"""Wrap the enable method to call pre and post enable signals and update
module status""" | def _wrapped ( self , * args , ** kwargs ) :
if not self . installed :
raise AssertionError ( 'Module %s cannot be enabled' ', you should install it first' % self . verbose_name )
if self . enabled :
raise AssertionError ( 'Module %s is already enabled' % self . verbose_name )
logger . info ... |
def replace_table_rate_shipping_by_id ( cls , table_rate_shipping_id , table_rate_shipping , ** kwargs ) :
"""Replace TableRateShipping
Replace all attributes of TableRateShipping
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _replace_table_rate_shipping_by_id_with_http_info ( table_rate_shipping_id , table_rate_shipping , ** kwargs )
else :
( data ) = cls . _replace_table_rate_shipping_by_id_with_http_info ( table_rate_shipping_id , table_rate_shi... |
def validate ( self , value ) :
"""Abstract method , check if a value is correct ( type ) .
Should raise : class : ` TypeError ` if the type the validation fail .
: param value : the value to validate
: return : the given value ( that may have been converted )""" | for validator in self . validators :
errors = [ ]
try :
validator ( value )
except ValidationError as err :
errors . append ( err )
if errors :
raise ValidationError ( errors )
return value |
def createProduct ( self , powerups ) :
"""Create a new L { Product } instance which confers the given
powerups .
@ type powerups : C { list } of powerup item types
@ rtype : L { Product }
@ return : The new product instance .""" | types = [ qual ( powerup ) . decode ( 'ascii' ) for powerup in powerups ]
for p in self . store . parent . query ( Product ) :
for t in types :
if t in p . types :
raise ValueError ( "%s is already included in a Product" % ( t , ) )
return Product ( store = self . store . parent , types = types ... |
def tRNAscan ( args ) :
"""% prog tRNAscan all . trna > all . trna . gff3
Convert tRNAscan - SE output into gff3 format .
Sequence tRNA Bounds tRNA Anti Intron Bounds Cove
Name tRNA # Begin End Type Codon Begin End Score
23231 1 335355 335440 Tyr GTA 335392 335404 69.21
23231 2 1076190 1076270 Leu AAG 0 0... | from jcvi . formats . gff import sort
p = OptionParser ( tRNAscan . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
trnaout , = args
gffout = trnaout + ".gff3"
fp = open ( trnaout )
fw = open ( gffout , "w" )
next ( fp )
next ( fp )
row = next ( fp )
asse... |
def _import_attr_n_module ( module_name , attr ) :
"""From the given ` ` module _ name ` ` import
the value for ` ` attr ` ` ( attribute ) .""" | __import__ ( module_name )
module = sys . modules [ module_name ]
attr = getattr ( module , attr )
return attr , module |
def size ( array ) :
"""Return a human - readable description of the number of bytes required
to store the data of the given array .
For example : :
> > > array . nbytes
1400000
> > biggus . size ( array )
'13.35 MiB '
Parameters
array : array - like object
The array object must provide an ` nbyte... | nbytes = array . nbytes
if nbytes < ( 1 << 10 ) :
size = '{} B' . format ( nbytes )
elif nbytes < ( 1 << 20 ) :
size = '{:.02f} KiB' . format ( nbytes / ( 1 << 10 ) )
elif nbytes < ( 1 << 30 ) :
size = '{:.02f} MiB' . format ( nbytes / ( 1 << 20 ) )
elif nbytes < ( 1 << 40 ) :
size = '{:.02f} GiB' . for... |
def connect ( self ) :
"""Create internal connection to AMQP service .""" | logging . info ( "Connecting to {} with user {}." . format ( self . host , self . username ) )
credentials = pika . PlainCredentials ( self . username , self . password )
connection_params = pika . ConnectionParameters ( host = self . host , credentials = credentials , heartbeat_interval = self . heartbeat_interval )
s... |
def refresh ( * modules : typing . Union [ str , types . ModuleType ] , recursive : bool = False , force : bool = False ) -> bool :
"""Checks the specified module or modules for changes and reloads them if
they have been changed since the module was first imported or last
refreshed .
: param modules :
One o... | out = [ ]
for module in modules :
out . append ( reload_module ( module , recursive , force ) )
return any ( out ) |
def bins ( self ) :
"""Bins in the wider format ( as edge pairs )
Returns
bins : np . ndarray
shape = ( bin _ count , 2)""" | if self . _bins is None :
self . _bins = make_bin_array ( self . numpy_bins )
return self . _bins |
def validate_response ( self , resp ) :
"""Validates resp against expected return type for this function .
Raises RpcException if the response is invalid .""" | ok , msg = self . contract . validate ( self . returns , self . returns . is_array , resp )
if not ok :
vals = ( self . full_name , str ( resp ) , msg )
msg = "Function '%s' invalid response: '%s'. %s" % vals
raise RpcException ( ERR_INVALID_RESP , msg ) |
def gradient ( self , mu , dist ) :
"""derivative of the link function wrt mu
Parameters
mu : array - like of legth n
dist : Distribution instance
Returns
grad : np . array of length n""" | return dist . levels / ( mu * ( dist . levels - mu ) ) |
def in6_cidr2mask ( m ) :
"""Return the mask ( bitstring ) associated with provided length
value . For instance if function is called on 48 , return value is
' \xff \xff \xff \xff \xff \xff \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 ' .""" | if m > 128 or m < 0 :
raise Kamene_Exception ( "value provided to in6_cidr2mask outside [0, 128] domain (%d)" % m )
t = [ ]
for i in range ( 0 , 4 ) :
t . append ( max ( 0 , 2 ** 32 - 2 ** ( 32 - min ( 32 , m ) ) ) )
m -= 32
return b"" . join ( [ struct . pack ( '!I' , i ) for i in t ] ) |
def _designspace_locations ( self , designspace ) :
"""Map font filenames to their locations in a designspace .""" | maps = [ ]
for elements in ( designspace . sources , designspace . instances ) :
location_map = { }
for element in elements :
path = _normpath ( element . path )
location_map [ path ] = element . location
maps . append ( location_map )
return maps |
def convert_value ( self , value ) :
"""Convert value to float . If value is a string , ensure that the first
character is the same as symbol ie . the value is in the currency this
formatter is representing .""" | if isinstance ( value , str ) :
assert value . startswith ( self . symbol ) , "Currency does not start with " + self . symbol
value = value . lstrip ( self . symbol )
return super ( ) . convert_value ( value ) |
def set_viewlimits ( self , axes = None ) :
"""update xy limits of a plot""" | if axes is None :
axes = self . axes
xmin , xmax , ymin , ymax = self . data_range
if len ( self . conf . zoom_lims ) > 1 :
zlims = self . conf . zoom_lims [ - 1 ]
if axes in zlims :
xmin , xmax , ymin , ymax = zlims [ axes ]
xmin = max ( self . data_range [ 0 ] , xmin )
xmax = min ( self . data_ran... |
def load_to_array ( self , keys ) :
"""This loads the data contained in the catalogue into a numpy array . The
method works only for float data
: param keys :
A list of keys to be uploaded into the array
: type list :""" | # Preallocate the numpy array
data = np . empty ( ( len ( self . data [ keys [ 0 ] ] ) , len ( keys ) ) )
for i in range ( 0 , len ( self . data [ keys [ 0 ] ] ) ) :
for j , key in enumerate ( keys ) :
data [ i , j ] = self . data [ key ] [ i ]
return data |
def iterator ( self , envelope ) :
""": meth : ` WMessengerOnionSessionFlowProto . iterator ` implementation""" | for pair in self . __pairs :
if pair . comparator ( ) . match ( envelope ) is True :
return pair . flow ( ) . iterator ( envelope )
if self . __default_flow is not None :
return self . __default_flow . iterator ( envelope ) |
def _build_gecos ( gecos_dict ) :
'''Accepts a dictionary entry containing GECOS field names and their values ,
and returns a full GECOS comment string , to be used with usermod .''' | return '{0},{1},{2},{3}' . format ( gecos_dict . get ( 'fullname' , '' ) , gecos_dict . get ( 'roomnumber' , '' ) , gecos_dict . get ( 'workphone' , '' ) , gecos_dict . get ( 'homephone' , '' ) ) |
def format_out_of_country_calling_number ( numobj , region_calling_from ) :
"""Formats a phone number for out - of - country dialing purposes .
If no region _ calling _ from is supplied , we format the number in its
INTERNATIONAL format . If the country calling code is the same as that of
the region where the... | if not _is_valid_region_code ( region_calling_from ) :
return format_number ( numobj , PhoneNumberFormat . INTERNATIONAL )
country_code = numobj . country_code
nsn = national_significant_number ( numobj )
if not _has_valid_country_calling_code ( country_code ) :
return nsn
if country_code == _NANPA_COUNTRY_CODE... |
def update_cookies ( self , cookies : Optional [ LooseCookies ] ) -> None :
"""Update request cookies header .""" | if not cookies :
return
c = SimpleCookie ( )
if hdrs . COOKIE in self . headers :
c . load ( self . headers . get ( hdrs . COOKIE , '' ) )
del self . headers [ hdrs . COOKIE ]
if isinstance ( cookies , Mapping ) :
iter_cookies = cookies . items ( )
else :
iter_cookies = cookies
# type : ignore
f... |
def expandvars ( s , vars = None ) :
"""Perform variable substitution on the given string
Supported syntax :
* $ VARIABLE
* $ { VARIABLE }
* $ { # VARIABLE }
* $ { VARIABLE : - default }
: param s : message to expand
: type s : str
: param vars : dictionary of variables . Default is ` ` os . environ... | tpl = TemplateWithDefaults ( s )
return tpl . substitute ( vars or os . environ ) |
def __parse_organizations ( self , stream ) :
"""Parse GrimoireLab organizations .
The GrimoireLab organizations format is a YAML element stored
under the " organizations " key . The next example shows the
structure of the document :
- organizations :
Bitergia :
- bitergia . com
- support . bitergia .... | if not stream :
return
yaml_file = self . __load_yml ( stream )
try :
for element in yaml_file :
name = self . __encode ( element [ 'organization' ] )
if not name :
error = "Empty organization name"
msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error }
... |
def constraint ( self , n = - 1 , fid = 0 ) :
"""Obtain the set of orthogonal equations that make the solution of
the rank deficient normal equations possible .
: param fid : the id of the sub - fitter ( numerical )""" | c = self . _getval ( "constr" , fid )
if n < 0 or n > self . deficiency ( fid ) :
return c
else :
raise RuntimeError ( "Not yet implemented" ) |
def fix_string_case ( text ) :
"""Converts case - insensitive characters to lower case
Case - sensitive characters as defined in config . AVRO _ CASESENSITIVES
retain their case , but others are converted to their lowercase
equivalents . The result is a string with phonetic - compatible case
which will the ... | fixed = [ ]
for i in text :
if is_case_sensitive ( i ) :
fixed . append ( i )
else :
fixed . append ( i . lower ( ) )
return '' . join ( fixed ) |
def fetchone ( self ) :
"""fetch a single row . a lock object is used to assure that a single
record will be fetched and all housekeeping done properly in a
multithreaded environment .
as getting a block is currently synchronous , this also protects
against multiple block requests ( but does not protect aga... | self . _cursorLock . acquire ( )
# if there are available records in current block ,
# return one and advance counter
if self . _currentBlock is not None and self . _currentRecordNum < len ( self . _currentBlock ) :
x = self . _currentRecordNum
self . _currentRecordNum += 1
self . _cursorLock . release ( )
... |
def _ellipsoids_bootstrap_expand ( args ) :
"""Internal method used to compute the expansion factor ( s ) for a collection
of bounding ellipsoids using bootstrapping .""" | # Unzipping .
points , pointvol , vol_dec , vol_check = args
rstate = np . random
# Resampling .
npoints , ndim = points . shape
idxs = rstate . randint ( npoints , size = npoints )
# resample
idx_in = np . unique ( idxs )
# selected objects
sel = np . ones ( npoints , dtype = 'bool' )
sel [ idx_in ] = False
idx_out = ... |
def clean_time ( time_string ) :
"""Return a datetime from the Amazon - provided datetime string""" | # Get a timezone - aware datetime object from the string
time = dateutil . parser . parse ( time_string )
if not settings . USE_TZ : # If timezone support is not active , convert the time to UTC and
# remove the timezone field
time = time . astimezone ( timezone . utc ) . replace ( tzinfo = None )
return time |
def count ( self , * args , ** kw ) :
"""Counts whether the memoized value has already been
set ( a hit ) or not ( a miss ) .""" | obj = args [ 0 ]
if self . method_name in obj . _memo :
self . hit = self . hit + 1
else :
self . miss = self . miss + 1 |
def get_user ( self , id ) :
"""Returns details about the user for the given id .
Use get _ user _ by _ email ( ) or get _ user _ by _ username ( ) for help
identifiying the id .""" | self . assert_has_permission ( 'scim.read' )
return self . _get ( self . uri + '/Users/%s' % ( id ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.