signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def generate_default_schema ( output ) :
"""Get default schema for fake PII""" | original_path = os . path . join ( os . path . dirname ( __file__ ) , 'data' , 'randomnames-schema.json' )
shutil . copyfile ( original_path , output ) |
def render ( self , template = None , additional = None ) :
"""Render single model to its html representation .
You may set template path in render function argument ,
or model ' s variable named ' template _ path ' ,
or get default name : $ app _ label $ / models / $ model _ name $ . html
Settings :
* MO... | template_path = template or self . get_template_path ( )
template_vars = { 'model' : self }
if additional :
template_vars . update ( additional )
rendered = render_to_string ( template_path , template_vars )
return mark_safe ( rendered ) |
def guess_payload_class ( self , payload ) :
"""ISOTP encodes the frame type in the first nibble of a frame .""" | t = ( orb ( payload [ 0 ] ) & 0xf0 ) >> 4
if t == 0 :
return ISOTP_SF
elif t == 1 :
return ISOTP_FF
elif t == 2 :
return ISOTP_CF
else :
return ISOTP_FC |
def midi_inputs ( self ) :
""": return : A list of MIDI input : class : ` Ports ` .""" | return self . client . get_ports ( is_midi = True , is_physical = True , is_input = True ) |
def main ( ) :
"""This is the main body of the process that does the work .
Summary :
- load the raw data
- read in rules list
- create log events for AIKIF according to rules [ map ]
- create new facts / reports based on rules [ report ]
OUTPUT =
AIKIF mapping : Date _ of _ transaction = > event
AI... | print ( 'AIKIF example: Processing Finance data\n' )
data = read_bank_statements ( 'your_statement.csv' )
print ( data )
maps = load_column_maps ( )
rules = load_rules ( )
for m in maps :
print ( 'AIKIF mapping : ' + m [ 0 ] + ' => ' + m [ 1 ] )
for rule in rules : # print ( rule )
if rule [ 0 ] == 'agg' :
... |
def uuid_from_kronos_time ( time , _type = UUIDType . RANDOM ) :
"""Generate a UUID with the specified time .
If ` lowest ` is true , return the lexicographically first UUID for the specified
time .""" | return timeuuid_from_time ( int ( time ) + UUID_TIME_OFFSET , type = _type ) |
def grant_user_permission ( self , id , ** kwargs ) : # noqa : E501
"""Grants a specific user permission # 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 . grant _ user _ permission ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . grant_user_permission_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . grant_user_permission_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def get_nodes ( self , path ) :
"""Returns combined ` ` DirNode ` ` and ` ` FileNode ` ` objects list representing
state of changeset at the given ` ` path ` ` . If node at the given ` ` path ` `
is not instance of ` ` DirNode ` ` , ChangesetError would be raised .""" | if self . _get_kind ( path ) != NodeKind . DIR :
raise ChangesetError ( "Directory does not exist for revision %s at " " '%s'" % ( self . revision , path ) )
path = self . _fix_path ( path )
filenodes = [ FileNode ( f , changeset = self ) for f in self . _file_paths if os . path . dirname ( f ) == path ]
dirs = pat... |
def set_offchain_reveal_state ( transfers_pair : List [ MediationPairState ] , payee_address : Address , ) -> None :
"""Set the state of a transfer * sent * to a payee .""" | for pair in transfers_pair :
if pair . payee_address == payee_address :
pair . payee_state = 'payee_secret_revealed' |
def dimension ( self , name , copy = True ) :
"""Returns the requested : class : ` ~ hypercube . dims . Dimension ` object
Parameters
name : str
Name of the : class : ` ~ hypercube . dims . Dimension ` object
copy : boolean
Returns a copy of the : class : ` ~ hypercube . dims . Dimension ` object if True ... | try :
return create_dimension ( name , self . _dims [ name ] ) if copy else self . _dims [ name ]
except KeyError :
raise KeyError ( "Dimension '{n}' is not registered " "on this cube" . format ( n = name ) ) , None , sys . exc_info ( ) [ 2 ] |
def append ( self , tweet ) :
"""Add a tweet to the end of the list .""" | c = self . connection . cursor ( )
last_tweet = c . execute ( "SELECT tweet from tweetlist where label='last_tweet'" ) . next ( ) [ 0 ]
c . execute ( "INSERT INTO tweets(message, previous_tweet, next_tweet) VALUES (?,?,NULL)" , ( tweet , last_tweet ) )
tweet_id = c . lastrowid
# Set the current tweet as the last tweet... |
def plot_time_elapsed ( filename , elapsed = False , unit = 's' , plot_kwargs = None ) :
'''Plot series data from MonitorTimeElapsed output text file .
Args :
filename ( str ) : Path to * . series . txt file produced by : obj : ` ~ nnabla . MonitorSeries ` class .
elapsed ( bool ) : If ` ` True ` ` , it plots... | import matplotlib . pyplot as plt
if plot_kwargs is None :
plot_kwargs = { }
data_column = 3 if elapsed else 1
data = np . genfromtxt ( filename , dtype = 'i8,f4' , usecols = ( 0 , data_column ) , names = [ 'k' , 'v' ] )
index = data [ 'k' ]
values = data [ 'v' ]
if unit == 's' :
pass
elif unit == 'm' :
val... |
def custom_prefix_lax ( instance ) :
"""Ensure custom content follows lenient naming style conventions
for forward - compatibility .""" | for error in chain ( custom_object_prefix_lax ( instance ) , custom_property_prefix_lax ( instance ) , custom_observable_object_prefix_lax ( instance ) , custom_object_extension_prefix_lax ( instance ) , custom_observable_properties_prefix_lax ( instance ) ) :
yield error |
def login ( self ) :
"""Login and get a valid session ID .""" | try :
( sid , challenge ) = self . _login_request ( )
if sid == '0000000000000000' :
secret = self . _create_login_secret ( challenge , self . _password )
( sid2 , challenge ) = self . _login_request ( username = self . _user , secret = secret )
if sid2 == '0000000000000000' :
... |
def _load_resources ( self ) :
"""Load all the native goldman resources .
The route or API endpoint will be automatically determined
based on the resource object instance passed in .
INFO : Only our Model based resources are supported when
auto - generating API endpoints .""" | for resource in self . RESOURCES :
if isinstance ( resource , goldman . ModelsResource ) :
route = '/%s' % resource . rtype
elif isinstance ( resource , goldman . ModelResource ) :
route = '/%s/{rid}' % resource . rtype
elif isinstance ( resource , goldman . RelatedResource ) :
route... |
def store ( self , response ) :
"""Store response in cache , skipping if code is forbidden .
: param requests . Response response : HTTP response""" | if response . status_code not in CACHE_CODES :
return
now = datetime . datetime . now ( )
self . data [ response . url ] = { 'date' : now , 'response' : response , }
logger . info ( 'Stored response in cache' )
self . _reduce_age ( now )
self . _reduce_count ( ) |
def getSystemIps ( ) :
"""will not return the localhost one""" | IPs = [ ]
for interface in NetInfo . getSystemIfs ( ) :
if not interface . startswith ( 'lo' ) :
ip = netinfo . get_ip ( interface )
IPs . append ( ip )
return IPs |
def get_aggregate_by_id ( self , tx_id : str ) -> ScheduledTxAggregate :
"""Creates an aggregate for single entity""" | tran = self . get_by_id ( tx_id )
return self . get_aggregate_for ( tran ) |
def listdir ( self , folder_id = '0' , type_filter = None , offset = None , limit = None , ** listdir_kwz ) :
'''Return a list of objects in the specified folder _ id .
limit is passed to the API , so might be used as optimization .
None means " fetch all items , with several requests , if necessary " .
type ... | res = yield super ( txBox , self ) . listdir ( folder_id = folder_id , offset = offset , limit = limit if limit is not None else 900 , ** listdir_kwz )
lst = res [ 'entries' ]
if limit is None : # treat it as " no limit " , using several requests to fetch all items
while res [ 'total_count' ] > res [ 'offset' ] + r... |
def split_string_into_words ( input_str : str ) -> list :
"""This function takes a string of words separated by either commas or spaces as input .
It then splits the string into individual words and returns them as a list .
Example :
split _ string _ into _ words ( " Hi , my name is John " ) - > [ " Hi " , " ... | if not input_str :
return [ ]
word_list = [ ]
modified_str = input_str . replace ( ',' , ' ' )
word_list = modified_str . split ( )
return word_list |
def _make_settings ( args , application , settings , STATIC_ROOT , MEDIA_ROOT ) :
"""Setup the Django settings
: param args : docopt arguments
: param default _ settings : default Django settings
: param settings : Django settings module
: param STATIC _ ROOT : static root directory
: param MEDIA _ ROOT :... | import dj_database_url
from . default_settings import get_default_settings , get_boilerplates_settings
try :
extra_settings_file = args . get ( '--extra-settings' )
if not extra_settings_file :
extra_settings_file = HELPER_FILE
if extra_settings_file [ - 3 : ] != '.py' :
filename , __ = os .... |
def harvest_openaire_projects ( source = None , setspec = None ) :
"""Harvest grants from OpenAIRE and store as authority records .""" | loader = LocalOAIRELoader ( source = source ) if source else RemoteOAIRELoader ( setspec = setspec )
for grant_json in loader . iter_grants ( ) :
register_grant . delay ( grant_json ) |
def upload_directory ( self , directory , bucket , key , transfer_config = None , subscribers = None ) :
'''upload a directory using Aspera''' | check_io_access ( directory , os . R_OK )
return self . _queue_task ( bucket , [ FilePair ( key , directory ) ] , transfer_config , subscribers , enumAsperaDirection . SEND ) |
def _write_file ( folder , filename , data ) :
'''Writes a file to disk''' | path = os . path . join ( folder , filename )
if not os . path . exists ( folder ) :
msg = '{0} cannot be written. {1} does not exist' . format ( filename , folder )
log . error ( msg )
raise AttributeError ( six . text_type ( msg ) )
with salt . utils . files . fopen ( path , 'w' ) as fp_ :
fp_ . write... |
def update ( self , obj_id , is_public = NotUpdated , is_protected = NotUpdated ) :
"""Update a Job Execution .""" | data = { }
self . _copy_if_updated ( data , is_public = is_public , is_protected = is_protected )
return self . _patch ( '/job-executions/%s' % obj_id , data ) |
def cached_property ( prop ) :
"""A replacement for the property decorator that will only compute the
attribute ' s value on the first call and serve a cached copy from
then on .""" | def cache_wrapper ( self ) :
if not hasattr ( self , "_cache" ) :
self . _cache = { }
if prop . __name__ not in self . _cache :
return_value = prop ( self )
if isgenerator ( return_value ) :
return_value = tuple ( return_value )
self . _cache [ prop . __name__ ] = ret... |
def send ( self , conn ) :
'''Send the message on the given connection .
Args :
conn ( WebSocketHandler ) : a WebSocketHandler to send messages
Returns :
int : number of bytes sent''' | if conn is None :
raise ValueError ( "Cannot send to connection None" )
with ( yield conn . write_lock . acquire ( ) ) :
sent = 0
yield conn . write_message ( self . header_json , locked = False )
sent += len ( self . header_json )
# uncomment this to make it a lot easier to reproduce lock - related... |
def main ( ) :
"""NAME
plot _ magmap . py
DESCRIPTION
makes a color contour map of desired field model
SYNTAX
plot _ magmap . py [ command line options ]
OPTIONS
- h prints help and quits
- f FILE specify field model file with format : l m g h
- fmt [ pdf , eps , svg , png ] specify format for out... | cmap = 'RdYlBu'
date = 2016.
if not ccrs :
print ( "-W- You must intstall the cartopy module to run plot_magmap.py" )
sys . exit ( )
dir_path = '.'
lincr = 1
# level increment for contours
if '-WD' in sys . argv :
ind = sys . argv . index ( '-WD' )
dir_path = sys . argv [ ind + 1 ]
if '-h' in sys . argv... |
def _verify_validator ( self , validator , path ) :
"""Verifies that a given validator associated with the field at the given path is legitimate .""" | # Validator should be a function
if not callable ( validator ) :
raise SchemaFormatException ( "Invalid validations for {}" , path )
# Validator should accept a single argument
( args , varargs , keywords , defaults ) = getargspec ( validator )
if len ( args ) != 1 :
raise SchemaFormatException ( "Invalid valid... |
def stopword_remove ( self , items , threshold = False ) :
"""Remove stopwords from either tokens ( items = " tokens " )
or stems ( items = " stems " )""" | def remove ( tokens ) :
return [ t for t in tokens if t not in self . stopwords ]
if items == 'tokens' :
self . tokens = list ( map ( remove , self . tokens ) )
elif items == 'stems' :
self . stems = list ( map ( remove , self . stems ) )
else :
raise ValueError ( "Items must be either \'tokens\' or \'s... |
def locate ( desktop_filename_or_name ) :
'''Locate a . desktop from the standard locations .
Find the path to the . desktop file of a given . desktop filename or application name .
Standard locations :
- ` ` ~ / . local / share / applications / ` `
- ` ` / usr / share / applications ` `
Args :
desktop ... | paths = [ os . path . expanduser ( '~/.local/share/applications' ) , '/usr/share/applications' ]
result = [ ]
for path in paths :
for file in os . listdir ( path ) :
if desktop_filename_or_name in file . split ( '.' ) or desktop_filename_or_name == file : # Example : org . gnome . gedit
result .... |
def gradients_X ( self , dL_dK , X , X2 , target ) :
"""Derivative of the covariance matrix with respect to X""" | self . _K_computations ( X , X2 )
arg = self . _K_poly_arg
if X2 is None :
target += 2 * self . weight_variance * self . degree * self . variance * ( ( ( X [ None , : , : ] ) ) * ( arg ** ( self . degree - 1 ) ) [ : , : , None ] * dL_dK [ : , : , None ] ) . sum ( 1 )
else :
target += self . weight_variance * se... |
def findsource ( object ) :
"""Return the entire source file and starting line number for an object .
The argument may be a module , class , method , function , traceback , frame ,
or code object . The source code is returned as a list of all the lines
in the file and the line number indexes a line in that li... | try :
file = open ( getsourcefile ( object ) )
except ( TypeError , IOError ) :
raise IOError , 'could not get source code'
lines = file . readlines ( )
file . close ( )
if ismodule ( object ) :
return lines , 0
if isclass ( object ) :
name = object . __name__
pat = re . compile ( r'^\s*class\s*' + ... |
def redfearn ( lat , lon , false_easting = None , false_northing = None , zone = None , central_meridian = None , scale_factor = None ) :
"""Compute UTM projection using Redfearn ' s formula
lat , lon is latitude and longitude in decimal degrees
If false easting and northing are specified they will override
t... | from math import pi , sqrt , sin , cos , tan
# GDA Specifications
a = 6378137.0
# Semi major axis
inverse_flattening = 298.257222101
# 1 / f
if scale_factor is None :
K0 = 0.9996
# Central scale factor
else :
K0 = scale_factor
# print ( ' scale ' , K0)
zone_width = 6
# Degrees
longitude_of_central_meridian_... |
def request ( self , host , handler , request_body , verbose ) :
'''Send xml - rpc request using proxy''' | # We get a traceback if we don ' t have this attribute :
self . verbose = verbose
url = 'http://' + host + handler
request = urllib2 . Request ( url )
request . add_data ( request_body )
# Note : ' Host ' and ' Content - Length ' are added automatically
request . add_header ( 'User-Agent' , self . user_agent )
request ... |
def between ( value , min = None , max = None ) :
"""Validate that a number is between minimum and / or maximum value .
This will work with any comparable type , such as floats , decimals and dates
not just integers .
This validator is originally based on ` WTForms NumberRange validator ` _ .
. . _ WTForms ... | if min is None and max is None :
raise AssertionError ( 'At least one of `min` or `max` must be specified.' )
if min is None :
min = Min
if max is None :
max = Max
try :
min_gt_max = min > max
except TypeError :
min_gt_max = max < min
if min_gt_max :
raise AssertionError ( '`min` cannot be more ... |
def delete ( user_id ) :
'''Delele the user in the database by ` user _ id ` .''' | try :
del_count = TabMember . delete ( ) . where ( TabMember . uid == user_id )
del_count . execute ( )
return True
except :
return False |
def _read ( self , directory , filename , session , path , name , extension , spatial , spatialReferenceID , replaceParamFile ) :
"""Storm Pipe Network File Read from File Method""" | # Set file extension property
self . fileExtension = extension
# Dictionary of keywords / cards and parse function names
KEYWORDS = { 'CONNECT' : spc . connectChunk , 'SJUNC' : spc . sjuncChunk , 'SLINK' : spc . slinkChunk }
sjuncs = [ ]
slinks = [ ]
connections = [ ]
# Parse file into chunks associated with keywords /... |
def run_trial ( self , trial_id = 0 ) :
"""Run a single trial of the simulation
Parameters
trial _ id : int""" | # Set - up trial environment and graph
self . env = NetworkEnvironment ( self . G . copy ( ) , initial_time = 0 , ** self . environment_params )
# self . G = self . initial _ topology . copy ( )
# self . trial _ params = deepcopy ( self . global _ params )
# Set up agents on nodes
print ( 'Setting up agents...' )
self ... |
def map_values ( self , func ) :
""": param func :
: type func : T - > U
: rtype : TDict [ U ]
Usage :
> > > TDict ( k1 = 1 , k2 = 2 , k3 = 3 ) . map _ values ( lambda x : x * 2 ) = = {
. . . " k1 " : 2,
. . . " k2 " : 4,
. . . " k3 " : 6
True""" | return TDict ( { k : func ( v ) for k , v in self . items ( ) } ) |
def collect_filtered_models ( discard , * input_values ) :
'''Collect a duplicate - free list of all other Bokeh models referred to by
this model , or by any of its references , etc , unless filtered - out by the
provided callable .
Iterate over ` ` input _ values ` ` and descend through their structure
col... | ids = set ( [ ] )
collected = [ ]
queued = [ ]
def queue_one ( obj ) :
if obj . id not in ids and not ( callable ( discard ) and discard ( obj ) ) :
queued . append ( obj )
for value in input_values :
_visit_value_and_its_immediate_references ( value , queue_one )
while queued :
obj = queued . pop (... |
def visit_class ( rec , cls , op ) : # type : ( Any , Iterable , Union [ Callable [ . . . , Any ] , partial [ Any ] ] ) - > None
"""Apply a function to with " class " in cls .""" | if isinstance ( rec , MutableMapping ) :
if "class" in rec and rec . get ( "class" ) in cls :
op ( rec )
for d in rec :
visit_class ( rec [ d ] , cls , op )
if isinstance ( rec , MutableSequence ) :
for d in rec :
visit_class ( d , cls , op ) |
def clear ( self ) :
"""Removes all child widgets .""" | layout = self . layout ( )
for index in reversed ( range ( layout . count ( ) ) ) :
item = layout . takeAt ( index )
try :
item . widget ( ) . deleteLater ( )
except AttributeError :
item = None |
def get_area ( self ) :
"""Calculate area of bounding box .""" | return ( self . p2 . x - self . p1 . x ) * ( self . p2 . y - self . p1 . y ) |
def read_tree ( input , schema ) :
'''Read a tree from a string or file
Args :
` ` input ` ` ( ` ` str ` ` ) : Either a tree string , a path to a tree file ( plain - text or gzipped ) , or a DendroPy Tree object
` ` schema ` ` ( ` ` str ` ` ) : The schema of ` ` input ` ` ( DendroPy , Newick , NeXML , or Nexu... | schema_to_function = { 'dendropy' : read_tree_dendropy , 'newick' : read_tree_newick , 'nexml' : read_tree_nexml , 'nexus' : read_tree_nexus }
if schema . lower ( ) not in schema_to_function :
raise ValueError ( "Invalid schema: %s (valid options: %s)" % ( schema , ', ' . join ( sorted ( schema_to_function . keys (... |
def _iter_matches ( self , input_match , subject_graph , one_match , level = 0 ) :
"""Given an onset for a match , iterate over all completions of that match
This iterator works recursively . At each level the match is extended
with a new set of relations based on vertices in the pattern graph
that are at a d... | self . print_debug ( "ENTERING _ITER_MATCHES" , 1 )
self . print_debug ( "input_match: %s" % input_match )
# A ) collect the new edges in the pattern graph and the subject graph
# to extend the match .
# Note that the edges are ordered . edge [ 0 ] is always in the match .
# edge [ 1 ] is never in the match . The const... |
def p_postfix_expr ( self , p ) :
"""postfix _ expr : left _ hand _ side _ expr
| left _ hand _ side _ expr PLUSPLUS
| left _ hand _ side _ expr MINUSMINUS""" | if len ( p ) == 2 :
p [ 0 ] = p [ 1 ]
else :
p [ 0 ] = self . asttypes . PostfixExpr ( op = p [ 2 ] , value = p [ 1 ] )
p [ 0 ] . setpos ( p , 2 ) |
def _expect_inline_link ( text , start ) :
"""( link _ dest " link _ title " )""" | if start >= len ( text ) or text [ start ] != '(' :
return None
i = start + 1
m = patterns . whitespace . match ( text , i )
if m :
i = m . end ( )
m = patterns . link_dest_1 . match ( text , i )
if m :
link_dest = m . start ( ) , m . end ( ) , m . group ( )
i = m . end ( )
else :
open_num = 0
e... |
def _copy_from_to ( from_file , to_file ) :
"""A very rough and ready copy from / to function .""" | with pelican_open ( from_file ) as text_in :
encoding = 'utf-8'
with open ( to_file , 'w' , encoding = encoding ) as text_out :
text_out . write ( text_in )
logger . info ( 'Writing %s' , to_file ) |
def _check_requirements ( self ) :
"""Check if VPCS is available with the correct version .""" | path = self . _vpcs_path ( )
if not path :
raise VPCSError ( "No path to a VPCS executable has been set" )
# This raise an error if ubridge is not available
self . ubridge_path
if not os . path . isfile ( path ) :
raise VPCSError ( "VPCS program '{}' is not accessible" . format ( path ) )
if not os . access ( p... |
def validate_isosceles_triangle ( a , b , c ) :
"""This function checks whether a triangle with provided sides is an isosceles triangle . An isosceles triangle is a
triangle that has two sides of equal length .
Args :
a , b , c : The lengths of the sides of a triangle .
Returns :
Boolean : True if the tri... | return a == b or b == c or c == a |
def read ( input_taxonomy_io ) :
'''Parse in a taxonomy from the given I / O .
Parameters
input _ taxonomy _ io : io
an open io object that is iterable . This stream is neither opened
nor closed by this method
Returns
A GreenGenesTaxonomy instance with the taxonomy parsed in
Raises
DuplicateTaxonomy... | tax = { }
for line in input_taxonomy_io :
if len ( line . strip ( ) ) == 0 :
continue
# ignore empty lines
splits = line . split ( "\t" )
if len ( splits ) != 2 :
raise MalformedGreenGenesTaxonomyException ( "Unexpected number of tab-separated fields found in taxonomy file, on line %... |
def _dbc_decorate_namespace ( bases : List [ type ] , namespace : MutableMapping [ str , Any ] ) -> None :
"""Collect invariants , preconditions and postconditions from the bases and decorate all the methods .
Instance methods are simply replaced with the decorated function / Properties , class methods and static... | _collapse_invariants ( bases = bases , namespace = namespace )
for key , value in namespace . items ( ) :
if inspect . isfunction ( value ) or isinstance ( value , ( staticmethod , classmethod ) ) :
_decorate_namespace_function ( bases = bases , namespace = namespace , key = key )
elif isinstance ( valu... |
def reference_preprocessing ( job , samples , config ) :
"""Spawn the jobs that create index and dict file for reference
: param JobFunctionWrappingJob job : passed automatically by Toil
: param Namespace config : Argparse Namespace object containing argument inputs
: param list [ list ] samples : A nested li... | job . fileStore . logToMaster ( 'Processed reference files' )
config . fai = job . addChildJobFn ( run_samtools_faidx , config . reference ) . rv ( )
config . dict = job . addChildJobFn ( run_picard_create_sequence_dictionary , config . reference ) . rv ( )
job . addFollowOnJobFn ( map_job , download_sample , samples ,... |
def _utc_float ( self ) :
"""Return UTC as a floating point Julian date .""" | tai = self . tai
leap_dates = self . ts . leap_dates
leap_offsets = self . ts . leap_offsets
leap_reverse_dates = leap_dates + leap_offsets / DAY_S
i = searchsorted ( leap_reverse_dates , tai , 'right' )
return tai - leap_offsets [ i ] / DAY_S |
def create_component ( self , name , project , description = None , leadUserName = None , assigneeType = None , isAssigneeTypeValid = False , ) :
"""Create a component inside a project and return a Resource for it .
: param name : name of the component
: type name : str
: param project : key of the project to... | data = { 'name' : name , 'project' : project , 'isAssigneeTypeValid' : isAssigneeTypeValid }
if description is not None :
data [ 'description' ] = description
if leadUserName is not None :
data [ 'leadUserName' ] = leadUserName
if assigneeType is not None :
data [ 'assigneeType' ] = assigneeType
url = self ... |
def get_arsc_info ( arscobj ) :
"""Return a string containing all resources packages ordered by packagename , locale and type .
: param arscobj : : class : ` ~ ARSCParser `
: return : a string""" | buff = ""
for package in arscobj . get_packages_names ( ) :
buff += package + ":\n"
for locale in arscobj . get_locales ( package ) :
buff += "\t" + repr ( locale ) + ":\n"
for ttype in arscobj . get_types ( package , locale ) :
buff += "\t\t" + ttype + ":\n"
try :
... |
def del_instance ( self , obj ) :
"""Remove any stored instance methods that belong to an object
Args :
obj : The instance object to remove""" | to_remove = set ( )
for wrkey , _obj in self . iter_instances ( ) :
if obj is _obj :
to_remove . add ( wrkey )
for wrkey in to_remove :
del self [ wrkey ] |
def coalescence_waiting_times ( self , backward = True ) :
'''Generator over the waiting times of successive coalescence events
Args :
` ` backward ` ` ( ` ` bool ` ` ) : ` ` True ` ` to go backward in time ( i . e . , leaves to root ) , otherwise ` ` False ` `''' | if not isinstance ( backward , bool ) :
raise TypeError ( "backward must be a bool" )
times = list ( ) ;
lowest_leaf_dist = float ( '-inf' )
for n , d in self . distances_from_root ( ) :
if len ( n . children ) > 1 :
times . append ( d )
elif len ( n . children ) == 0 and d > lowest_leaf_dist :
... |
def str_to_date ( self ) :
"""Returns the date attribute as a date object .
: returns : Date of the status if it exists .
: rtype : date or NoneType""" | if hasattr ( self , 'date' ) :
return date ( * list ( map ( int , self . date . split ( '-' ) ) ) )
else :
return None |
def validate ( self ) :
"""Ensure that all fields ' values are valid and that non - nullable fields are present .""" | for field_name , field_obj in self . _fields . items ( ) :
value = field_obj . __get__ ( self , self . __class__ )
if value is None and field_obj . null is False :
raise ValidationError ( 'Non-nullable field {0} is set to None' . format ( field_name ) )
elif value is None and field_obj . null is Tru... |
def wishart_pairwise_pvals ( self , axis = 0 ) :
"""Return matrices of column - comparison p - values as list of numpy . ndarrays .
Square , symmetric matrix along * axis * of pairwise p - values for the
null hypothesis that col [ i ] = col [ j ] for each pair of columns .
* axis * ( int ) : axis along which ... | return [ slice_ . wishart_pairwise_pvals ( axis = axis ) for slice_ in self . slices ] |
def set_root_logger ( root_log_level , log_path = None ) :
"""Set the root logger ' pypyr ' . Do this before you do anything else .
Run once and only once at initialization .""" | handlers = [ ]
console_handler = logging . StreamHandler ( )
handlers . append ( console_handler )
if log_path :
file_handler = logging . FileHandler ( log_path )
handlers . append ( file_handler )
set_logging_config ( root_log_level , handlers = handlers )
root_logger = logging . getLogger ( "pypyr" )
root_log... |
def read ( cls , five9 , external_id ) :
"""Return a record singleton for the ID .
Args :
five9 ( five9 . Five9 ) : The authenticated Five9 remote .
external _ id ( mixed ) : The identified on Five9 . This should be the
value that is in the ` ` _ _ uid _ field _ _ ` ` field on the record .
Returns :
Bas... | results = cls . search ( five9 , { cls . __uid_field__ : external_id } )
if not results :
return None
return results [ 0 ] |
def _secondary_min ( self ) :
"""Getter for the minimum series value""" | return ( self . secondary_range [ 0 ] if ( self . secondary_range and self . secondary_range [ 0 ] is not None ) else ( min ( self . _secondary_values ) if self . _secondary_values else None ) ) |
def infographic_header_element ( impact_function_name , feature , parent ) :
"""Get a formatted infographic header sentence for an impact function .
For instance :
* infographic _ header _ element ( ' flood ' ) - > ' Estimated impact of a flood '""" | _ = feature , parent
# NOQA
string_format = infographic_header [ 'string_format' ]
if impact_function_name :
header = string_format . format ( impact_function_name = impact_function_name )
return header . capitalize ( )
return None |
def _pad ( self , text ) :
"""Pad the text .""" | top_bottom = ( "\n" * self . _padding ) + " "
right_left = " " * self . _padding * self . PAD_WIDTH
return top_bottom + right_left + text + right_left + top_bottom |
def M200 ( self , Rs , rho0 , c ) :
"""M ( R _ 200 ) calculation for NFW profile
: param Rs : scale radius
: type Rs : float
: param rho0 : density normalization ( characteristic density )
: type rho0 : float
: param c : concentration
: type c : float [ 4,40]
: return : M ( R _ 200 ) density""" | return 4 * np . pi * rho0 * Rs ** 3 * ( np . log ( 1. + c ) - c / ( 1. + c ) ) |
def _get_batch ( self ) :
"""Load data / label from dataset""" | batch_data = mx . nd . zeros ( ( self . batch_size , 3 , self . _data_shape [ 0 ] , self . _data_shape [ 1 ] ) )
batch_label = [ ]
for i in range ( self . batch_size ) :
if ( self . _current + i ) >= self . _size :
if not self . is_train :
continue
# use padding from middle in each epoch... |
def cleanup_containers ( self , include_initial = False , exclude = None , raise_on_error = False , list_only = False ) :
"""Finds all stopped containers and removes them ; by default does not remove containers that have never been
started .
: param include _ initial : Consider containers that have never been s... | exclude_names = set ( exclude or ( ) )
def _stopped_containers ( ) :
for container in self . containers ( all = True ) :
c_names = [ name [ 1 : ] for name in container [ 'Names' ] or ( ) if name . find ( '/' , 2 ) ]
c_status = container [ 'Status' ]
if ( ( ( include_initial and c_status == '... |
def quit ( self ) :
"""This will terminate ( with SIGTERM ) the underlying Tor process .
: returns : a Deferred that callback ( ) ' s ( with None ) when the
process has actually exited .""" | try :
self . transport . signalProcess ( 'TERM' )
d = Deferred ( )
self . _on_exit . append ( d )
except error . ProcessExitedAlready :
self . transport . loseConnection ( )
d = succeed ( None )
except Exception :
d = fail ( )
return d |
def validate_array ( datum , schema , parent_ns = None , raise_errors = True ) :
"""Check that the data list values all match schema [ ' items ' ] .
Parameters
datum : Any
Data being validated
schema : dict
Schema
parent _ ns : str
parent namespace
raise _ errors : bool
If true , raises Validation... | return ( isinstance ( datum , Sequence ) and not is_str ( datum ) and all ( validate ( datum = d , schema = schema [ 'items' ] , field = parent_ns , raise_errors = raise_errors ) for d in datum ) ) |
def create ( cls , resource_id , * , account_id , properties = None , tags = None , location = None , auto_add = True , auto_commit = False ) :
"""Creates a new Resource object with the properties and tags provided
Args :
resource _ id ( str ) : Unique identifier for the resource object
account _ id ( int ) :... | if cls . get ( resource_id ) :
raise ResourceException ( 'Resource {} already exists' . format ( resource_id ) )
res = Resource ( )
res . resource_id = resource_id
res . account_id = account_id
res . location = location
res . resource_type_id = ResourceType . get ( cls . resource_type ) . resource_type_id
if proper... |
def _finalize_upload ( self ) :
"""Finalizes the upload on the API server .""" | from sevenbridges . models . file import File
try :
response = self . _api . post ( self . _URL [ 'upload_complete' ] . format ( upload_id = self . _upload_id ) ) . json ( )
self . _result = File ( api = self . _api , ** response )
self . _status = TransferState . COMPLETED
except SbgError as e :
self .... |
def encode ( i , * , width = - 1 ) :
"""Encodes a nonnegative integer into syncsafe format
When width > 0 , then len ( result ) = = width
When width < 0 , then len ( result ) > = abs ( width )""" | if i < 0 :
raise ValueError ( "value is negative" )
assert width != 0
data = bytearray ( )
while i :
data . append ( i & 127 )
i >>= 7
if width > 0 and len ( data ) > width :
raise ValueError ( "Integer too large" )
if len ( data ) < abs ( width ) :
data . extend ( [ 0 ] * ( abs ( width ) - len ( da... |
def inserted_hs_indices ( self , prune = False ) :
"""Get indices of the inserted H & S ( for formatting purposes ) .""" | if self . ndim == 2 and prune : # If pruning is applied , we need to subtract from the H & S indes
# the number of pruned rows ( cols ) that come before that index .
pruning_bases = [ self . _pruning_base ( axis = i , hs_dims = [ 0 , 1 ] ) for i in [ 1 , 0 ] ]
pruning_bases = [ base if base . ndim == 1 else np ... |
def client_receives_binary ( self , name = None , timeout = None , label = None ) :
"""Receive raw binary message .
If client ` name ` is not given , uses the latest client . Optional message
` label ` is shown on logs .
Examples :
| $ { binary } = | Client receives binary |
| $ { binary } = | Client rece... | client , name = self . _clients . get_with_name ( name )
msg = client . receive ( timeout = timeout )
self . _register_receive ( client , label , name )
return msg |
def get ( policy_class = None , return_full_policy_names = True , hierarchical_return = False , adml_language = 'en-US' , return_not_configured = False ) :
'''Get a policy value
Args :
policy _ class ( str ) :
Some policies are both user and computer , by default all policies
will be pulled , but this can b... | vals = { }
modal_returns = { }
_policydata = _policy_info ( )
if policy_class is None or policy_class . lower ( ) == 'both' :
policy_class = _policydata . policies . keys ( )
elif policy_class . lower ( ) not in [ z . lower ( ) for z in _policydata . policies . keys ( ) ] :
msg = 'The policy_class {0} is not an... |
def GetInput ( self ) :
"""Yield client urns .""" | clients = GetAllClients ( token = self . token )
logging . debug ( "Got %d clients" , len ( clients ) )
return clients |
def make_title ( self , chan , cycle , stage , evt_type ) :
"""Make a title for plots , etc .""" | cyc_str = None
if cycle is not None :
cyc_str = [ str ( c [ 2 ] ) for c in cycle ]
cyc_str [ 0 ] = 'cycle ' + cyc_str [ 0 ]
title = [ ' + ' . join ( [ str ( x ) for x in y ] ) for y in [ chan , cyc_str , stage , evt_type ] if y is not None ]
return ', ' . join ( title ) |
def radius_of_gyration ( neurite ) :
'''Calculate and return radius of gyration of a given neurite .''' | centre_mass = neurite_centre_of_mass ( neurite )
sum_sqr_distance = 0
N = 0
dist_sqr = [ distance_sqr ( centre_mass , s ) for s in nm . iter_segments ( neurite ) ]
sum_sqr_distance = np . sum ( dist_sqr )
N = len ( dist_sqr )
return np . sqrt ( sum_sqr_distance / N ) |
def remove ( self , index ) :
'''Return new tree with index removed .''' | newtree = LookupTree ( )
newtree . root = _remove_down ( self . root , index , 0 )
return newtree |
def _retranslate ( seq ) :
'''Retranslates a nucleotide sequence following refinement .
Input is a Pair sequence ( basically a dict of MongoDB output ) .''' | if len ( seq [ 'vdj_nt' ] ) % 3 != 0 :
trunc = len ( seq [ 'vdj_nt' ] ) % 3
seq [ 'vdj_nt' ] = seq [ 'vdj_nt' ] [ : - trunc ]
seq [ 'vdj_aa' ] = Seq ( seq [ 'vdj_nt' ] , generic_dna ) . translate ( ) |
def EnqueueBreakpointUpdate ( self , breakpoint ) :
"""Asynchronously updates the specified breakpoint on the backend .
This function returns immediately . The worker thread is actually doing
all the work . The worker thread is responsible to retry the transmission
in case of transient errors .
Args :
bre... | with self . _transmission_thread_startup_lock :
if self . _transmission_thread is None :
self . _transmission_thread = threading . Thread ( target = self . _TransmissionThreadProc )
self . _transmission_thread . name = 'Cloud Debugger transmission thread'
self . _transmission_thread . daemon... |
def execute ( query , data = None ) :
"""Execute an arbitrary SQL query given by query , returning any
results as a list of OrderedDicts . A list of values can be supplied as an ,
additional argument , which will be substituted into question marks in the
query .""" | connection = _State . connection ( )
_State . new_transaction ( )
if data is None :
data = [ ]
result = connection . execute ( query , data )
_State . table = None
_State . metadata = None
try :
del _State . table_pending
except AttributeError :
pass
if not result . returns_rows :
return { u'data' : [ ]... |
def get_theme ( ) :
'''Checks system for theme information .
First checks for the environment variable COLORFGBG .
Next , queries terminal , supported on Windows and xterm , perhaps others .
See notes on get _ color ( ) .
Returns :
str , None : ' dark ' , ' light ' , None if no information .''' | theme = None
log . debug ( 'COLORFGBG: %s' , env . COLORFGBG )
if env . COLORFGBG :
FG , _ , BG = env . COLORFGBG . partition ( ';' )
theme = 'dark' if BG < '8' else 'light'
# background wins
else :
if os_name == 'nt' :
from . windows import get_color as _get_color
# avoid Unbound Local
... |
def get_data_file_names_from_scan_base ( scan_base , filter_str = [ '_analyzed.h5' , '_interpreted.h5' , '_cut.h5' , '_result.h5' , '_hists.h5' ] , sort_by_time = True , meta_data_v2 = True ) :
"""Generate a list of . h5 files which have a similar file name .
Parameters
scan _ base : list , string
List of str... | data_files = [ ]
if scan_base is None :
return data_files
if isinstance ( scan_base , basestring ) :
scan_base = [ scan_base ]
for scan_base_str in scan_base :
if '.h5' == os . path . splitext ( scan_base_str ) [ 1 ] :
data_files . append ( scan_base_str )
else :
data_files . extend ( gl... |
def distinguished_name_list_exists ( name , items ) :
'''Ensures that a distinguished name list exists with the items provided .
name : The name of the module function to execute .
name ( str ) : The name of the distinguished names list .
items ( list ) : A list of items to ensure exist on the distinguished n... | ret = _default_ret ( name )
req_change = False
try :
existing_lists = __salt__ [ 'bluecoat_sslv.get_distinguished_name_lists' ] ( )
if name not in existing_lists :
__salt__ [ 'bluecoat_sslv.add_distinguished_name_list' ] ( name )
req_change = True
list_members = __salt__ [ 'bluecoat_sslv.get... |
def send_packet ( self , pk , expected_reply = ( ) , resend = False , timeout = 0.2 ) :
"""Send a packet through the link interface .
pk - - Packet to send
expect _ answer - - True if a packet from the Crazyflie is expected to
be sent back , otherwise false""" | self . _send_lock . acquire ( )
if self . link is not None :
if len ( expected_reply ) > 0 and not resend and self . link . needs_resending :
pattern = ( pk . header , ) + expected_reply
logger . debug ( 'Sending packet and expecting the %s pattern back' , pattern )
new_timer = Timer ( timeo... |
def add_row ( self , list_or_dict , key = None ) :
"""Adds a list or dict as a row in the FVM data structure
: param str key : key used when rows is a dict rather than an array
: param list _ or _ dict : a feature list or dict""" | if isinstance ( list_or_dict , list ) :
self . _add_list_row ( list_or_dict , key )
else :
self . _add_dict_row ( list_or_dict , key ) |
def context_changed ( self , context ) :
""": type context : dict""" | self . _image . set_cmap ( context [ 'colormap' ] )
self . _image . set_clim ( context [ 'min' ] , context [ 'max' ] )
self . _image . set_interpolation ( context [ 'interpolation' ] )
self . _update_indicators ( context )
self . _set_view_limits ( )
if self . _model . index_direction is not SliceDirection . depth :
... |
def remove_duplicates ( errors ) :
"""Filter duplicates from given error ' s list .""" | passed = defaultdict ( list )
for error in errors :
key = error . linter , error . number
if key in DUPLICATES :
if key in passed [ error . lnum ] :
continue
passed [ error . lnum ] = DUPLICATES [ key ]
yield error |
def trajectories ( self , M , N , start = None , stop = None ) :
"""Generates M trajectories , each of length N , starting from state s
Parameters
M : int
number of trajectories
N : int
trajectory length
start : int , optional , default = None
starting state . If not given , will sample from the stati... | trajs = [ self . trajectory ( N , start = start , stop = stop ) for _ in range ( M ) ]
return trajs |
def _add_warp_ctc_loss ( pred , seq_len , num_label , label ) :
"""Adds Symbol . contrib . ctc _ loss on top of pred symbol and returns the resulting symbol""" | label = mx . sym . Reshape ( data = label , shape = ( - 1 , ) )
label = mx . sym . Cast ( data = label , dtype = 'int32' )
return mx . sym . WarpCTC ( data = pred , label = label , label_length = num_label , input_length = seq_len ) |
def generate_item_urls ( self ) :
"""Return dict with identifier / URL pairs for the dataset items .""" | item_urls = { }
for i in self . dataset . identifiers :
relpath = self . dataset . item_properties ( i ) [ "relpath" ]
url = self . generate_url ( "data/" + relpath )
item_urls [ i ] = url
return item_urls |
def _checkTypeSchemaConsistency ( self , actualType , onDiskSchema ) :
"""Called for all known types at database startup : make sure that what we
know ( in memory ) about this type agrees with what is stored about this
type in the database .
@ param actualType : A L { MetaItem } instance which is associated w... | # make sure that both the runtime and the database both know about this
# type ; if they don ' t both know , we can ' t check that their views are
# consistent
try :
inMemorySchema = _inMemorySchemaCache [ actualType ]
except KeyError :
inMemorySchema = _inMemorySchemaCache [ actualType ] = [ ( storedAttribute ... |
def cache_result ( default_size = settings . AVATAR_DEFAULT_SIZE ) :
"""Decorator to cache the result of functions that take a ` ` user ` ` and a
` ` size ` ` value .""" | if not settings . AVATAR_CACHE_ENABLED :
def decorator ( func ) :
return func
return decorator
def decorator ( func ) :
def cached_func ( user , size = None , ** kwargs ) :
prefix = func . __name__
cached_funcs . add ( prefix )
key = get_cache_key ( user , size or default_siz... |
def add_flow_exception ( exc ) :
"""Add an exception that should not be logged .
The argument must be a subclass of Exception .""" | global _flow_exceptions
if not isinstance ( exc , type ) or not issubclass ( exc , Exception ) :
raise TypeError ( 'Expected an Exception subclass, got %r' % ( exc , ) )
as_set = set ( _flow_exceptions )
as_set . add ( exc )
_flow_exceptions = tuple ( as_set ) |
def _did_receive_response ( self , connection ) :
"""Receive a response from the connection""" | if connection . has_timeouted :
bambou_logger . info ( "NURESTConnection has timeout." )
return
has_callbacks = connection . has_callbacks ( )
should_post = not has_callbacks
if connection . handle_response_for_connection ( should_post = should_post ) and has_callbacks :
callback = connection . callbacks [ ... |
def __finish_initializing ( self ) :
"""Handle any initialization after arguments & config has been parsed .""" | if self . args . debug or self . args . trace : # Set the console ( StreamHandler ) to allow debug statements .
if self . args . debug :
self . console . setLevel ( logging . DEBUG )
self . console . setFormatter ( logging . Formatter ( '[%(levelname)s] %(asctime)s %(name)s - %(message)s' ) )
# Set ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.