signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _wrap_users ( users , request ) : """Returns a list with the given list of users and / or the currently logged in user , if the list contains the magic item SELF ."""
result = set ( ) for u in users : if u is SELF and is_authenticated ( request ) : result . add ( request . user . get_username ( ) ) else : result . add ( u ) return result
def new ( self , fn_input , fn_name , name = None , tags = None , properties = None , details = None , instance_type = None , depends_on = None , ** kwargs ) : ''': param fn _ input : Function input : type fn _ input : dict : param fn _ name : Name of the function to be called : type fn _ name : string : pa...
final_depends_on = [ ] if depends_on is not None : if isinstance ( depends_on , list ) : for item in depends_on : if isinstance ( item , DXJob ) or isinstance ( item , DXDataObject ) : if item . get_id ( ) is None : raise DXError ( 'A dxpy handler given in dep...
def iso_string_to_python_datetime ( isostring : str ) -> Optional [ datetime . datetime ] : """Takes an ISO - 8601 string and returns a ` ` datetime ` ` ."""
if not isostring : return None # if you parse ( ) an empty string , you get today ' s date return dateutil . parser . parse ( isostring )
def _save_table ( self , raw = False , cls = None , force_insert = False , force_update = False , using = None , update_fields = None , ) : """Overwrites model ' s ` ` _ save _ table ` ` method to save translations after instance has been saved ( required to retrieve the object ID for ` ` Translation ` ` model ...
updated = super ( ModelMixin , self ) . _save_table ( raw = raw , cls = cls , force_insert = force_insert , force_update = force_update , using = using , update_fields = update_fields , ) self . _linguist . decider . objects . save_translations ( [ self ] ) return updated
def list_reference_bases ( self , id_ , start = 0 , end = None ) : """Returns an iterator over the bases from the server in the form of consecutive strings . This command does not conform to the patterns of the other search and get requests , and is implemented differently ."""
request = protocol . ListReferenceBasesRequest ( ) request . start = pb . int ( start ) request . end = pb . int ( end ) request . reference_id = id_ not_done = True # TODO We should probably use a StringIO here to make string buffering # a bit more efficient . bases_list = [ ] while not_done : response = self . _r...
def _set_trusted_key ( self , v , load = False ) : """Setter method for trusted _ key , mapped from YANG variable / ntp / trusted _ key ( trust - key ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ trusted _ key is considered as a private method . Backends looking t...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = TypedListType ( allowed_type = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'1 .. 65535'...
def get_default_config ( self ) : """Override SNMPCollector . get _ default _ config method to provide default _ config for the SNMPInterfaceCollector"""
default_config = super ( SNMPInterfaceCollector , self ) . get_default_config ( ) default_config [ 'path' ] = 'interface' default_config [ 'byte_unit' ] = [ 'bit' , 'byte' ] return default_config
def update_transients ( self , add_names , remove_names , * class_build_args , ** class_build_kwargs ) : """Adds transients ( service , topic , etc ) named in add _ names if they are not exposed in resolved _ dict and removes transients named in remove _ names if they are exposed in resolved _ dict This method ...
# Important : no effect if names is empty list . only return empty . functional style . added = [ ] removed = [ ] for tst_name in [ tst for tst in add_names if tst not in self . transients . keys ( ) ] : try : ttype = self . transient_type_resolver ( tst_name ) # should return None if error - TODO :...
def reset_user_db ( self , comment = None ) : """Executes a Send Reset LDAP User DB Request operation on this node . : param str comment : comment to audit : raises NodeCommandFailed : failure resetting db : return : None"""
self . make_request ( NodeCommandFailed , method = 'update' , resource = 'reset_user_db' , params = { 'comment' : comment } )
def page_from_image ( input_file ) : """Create ` OcrdPage < / . . / . . / ocrd _ models / ocrd _ models . ocrd _ page . html > ` _ from an ` OcrdFile < / . . / . . / ocrd _ models / ocrd _ models . ocrd _ file . html > ` _ representing an image ( i . e . should have ` ` mimetype ` ` starting with ` ` image / ` ...
if input_file . local_filename is None : raise Exception ( "input_file must have 'local_filename' property" ) exif = exif_from_filename ( input_file . local_filename ) now = datetime . now ( ) return PcGtsType ( Metadata = MetadataType ( Creator = "OCR-D/core %s" % VERSION , Created = now , LastChange = now ) , Pag...
def undo ( config = 'root' , files = None , num_pre = None , num_post = None ) : '''Undo all file changes that happened between num _ pre and num _ post , leaving the files into the state of num _ pre . . . warning : : If one of the files has changes after num _ post , they will be overwritten The snapshots...
pre , post = _get_num_interval ( config , num_pre , num_post ) changes = status ( config , pre , post ) changed = set ( changes . keys ( ) ) requested = set ( files or changed ) if not requested . issubset ( changed ) : raise CommandExecutionError ( 'Given file list contains files that are not present' 'in the chan...
def _get_version_mode ( self , mode = None ) : """Return a VersionMode for a mode name . When the mode is None , we are working with the ' base ' mode ."""
version_mode = self . _version_modes . get ( mode ) if not version_mode : version_mode = self . _version_modes [ mode ] = VersionMode ( name = mode ) return version_mode
def _do_search ( self ) : """Perform the mlt call , then convert that raw format into a SearchResults instance and return it ."""
if self . _results_cache is None : response = self . raw ( ) results = self . to_python ( response . get ( 'hits' , { } ) . get ( 'hits' , [ ] ) ) self . _results_cache = DictSearchResults ( self . type , response , results , None ) return self . _results_cache
def import_modname ( modname ) : r"""Args : modname ( str ) : module name Returns : module : module CommandLine : python - m utool . util _ import - - test - import _ modname Example : > > > # ENABLE _ DOCTEST > > > from utool . util _ import import * # NOQA > > > modname _ list = [ > > > ' utoo...
# The _ _ import _ _ statment is weird if util_inject . PRINT_INJECT_ORDER : if modname not in sys . modules : util_inject . noinject ( modname , N = 2 , via = 'ut.import_modname' ) if '.' in modname : fromlist = modname . split ( '.' ) [ - 1 ] fromlist_ = list ( map ( str , fromlist ) ) # needs...
def get_unread_forums ( self , user ) : """Returns the list of unread forums for the given user ."""
return self . get_unread_forums_from_list ( user , self . perm_handler . get_readable_forums ( Forum . objects . all ( ) , user ) )
def sort_func ( self , key ) : """Used to sort keys when writing Entry to JSON format . Should be supplemented / overridden by inheriting classes ."""
if key == self . _KEYS . SCHEMA : return 'aaa' if key == self . _KEYS . NAME : return 'aab' if key == self . _KEYS . SOURCES : return 'aac' if key == self . _KEYS . ALIAS : return 'aad' if key == self . _KEYS . MODELS : return 'aae' if key == self . _KEYS . PHOTOMETRY : return 'zzy' if key == se...
def uri_to_kwargs ( uri ) : """Return a URI as kwargs for connecting to PostgreSQL with psycopg2, applying default values for non - specified areas of the URI . : param str uri : The connection URI : rtype : dict"""
parsed = urlparse ( uri ) default_user = get_current_user ( ) password = unquote ( parsed . password ) if parsed . password else None kwargs = { 'host' : parsed . hostname , 'port' : parsed . port , 'dbname' : parsed . path [ 1 : ] or default_user , 'user' : parsed . username or default_user , 'password' : password } v...
def mrc_header_from_params ( shape , dtype , kind , ** kwargs ) : """Create a minimal MRC2014 header from the given parameters . Parameters shape : 3 - sequence of ints 3D shape of the stored data . The values are used as ` ` ' nx ' , ' ny ' , ' nz ' ` ` header entries , in this order . Note that this is ...
# Positional args shape = [ int ( n ) for n in shape ] kind , kind_in = str ( kind ) . lower ( ) , kind if kind not in ( 'volume' , 'projections' ) : raise ValueError ( "`kind '{}' not understood" . format ( kind_in ) ) # Keyword args extent = kwargs . pop ( 'extent' , shape ) axis_order = kwargs . pop ( 'axis_orde...
def hook_symbol ( self , symbol_name , simproc , kwargs = None , replace = None ) : """Resolve a dependency in a binary . Looks up the address of the given symbol , and then hooks that address . If the symbol was not available in the loaded libraries , this address may be provided by the CLE externs object . ...
if type ( symbol_name ) is not int : sym = self . loader . find_symbol ( symbol_name ) if sym is None : # it could be a previously unresolved weak symbol . . ? new_sym = None for reloc in self . loader . find_relevant_relocations ( symbol_name ) : if not reloc . symbol . is_weak : ...
def docker_list ( registry_pass ) : # type : ( str ) - > None """List docker images stored in the remote registry . Args : registry _ pass ( str ) : Remote docker registry password ."""
registry = conf . get ( 'docker.registry' , None ) if registry is None : log . err ( "You must define docker.registry conf variable to list images" ) sys . exit ( - 1 ) registry_user = conf . get ( 'docker.registry_user' , None ) if registry_user is None : registry_user = click . prompt ( "Username" ) rc = ...
def initialize_notebook ( ) : """Initialize the IPython notebook display elements"""
try : from IPython . core . display import display , HTML except ImportError : print ( "IPython Notebook could not be loaded." ) # Thanks to @ jakevdp : # https : / / github . com / jakevdp / mpld3 / blob / master / mpld3 / _ display . py # L85 load_lib = """ function vct_load_lib(url, callback)...
def readBimFile ( basefilename ) : """Helper fuinction that reads bim files"""
# read bim file bim_fn = basefilename + '.bim' rv = SP . loadtxt ( bim_fn , delimiter = '\t' , usecols = ( 0 , 3 ) , dtype = int ) return rv
def create ( self , ** kwargs ) : """Custom creation logic to handle edge cases This shouldn ' t be needed , but ASM has a tendency to raise various errors that are painful to handle from a customer point - of - view The error itself are described in their exception handler To address these failure , we try...
for x in range ( 0 , 30 ) : try : return self . _create ( ** kwargs ) except iControlUnexpectedHTTPError as ex : if self . _check_exception ( ex ) : continue else : raise
def _write ( self , cmd , * datas ) : """Helper function to simplify writing ."""
cmd = Command ( write = cmd ) cmd . write ( self . _transport , self . _protocol , * datas )
def _get_datasets ( dataset_ids ) : """Get all the datasets in a list of dataset IDS . This must be done in chunks of 999, as sqlite can only handle ' in ' with < 1000 elements ."""
dataset_dict = { } datasets = [ ] if len ( dataset_ids ) > qry_in_threshold : idx = 0 extent = qry_in_threshold while idx < len ( dataset_ids ) : log . info ( "Querying %s datasets" , len ( dataset_ids [ idx : extent ] ) ) rs = db . DBSession . query ( Dataset ) . filter ( Dataset . id . in_...
def GetDataStream ( self , name , case_sensitive = True ) : """Retrieves a data stream by name . Args : name ( str ) : name of the data stream . case _ sensitive ( Optional [ bool ] ) : True if the name is case sensitive . Returns : DataStream : a data stream or None if not available . Raises : ValueE...
if not isinstance ( name , py2to3 . STRING_TYPES ) : raise ValueError ( 'Name is not a string.' ) name_lower = name . lower ( ) matching_data_stream = None for data_stream in self . _GetDataStreams ( ) : if data_stream . name == name : return data_stream if not case_sensitive and data_stream . name ...
def label_count ( self , label_list_ids = None ) : """Return a dictionary containing the number of times , every label - value in this corpus is occurring . Args : label _ list _ ids ( list ) : If not None , only labels from label - lists with an id contained in this list are considered . Returns : dict :...
count = collections . defaultdict ( int ) for utterance in self . utterances . values ( ) : for label_value , utt_count in utterance . label_count ( label_list_ids = label_list_ids ) . items ( ) : count [ label_value ] += utt_count return count
def converge ( f , step , tol , max_h ) : """simple newton iteration based convergence function"""
g = f ( 0 ) dx = 10000 h = step while ( dx > tol ) : g2 = f ( h ) dx = abs ( g - g2 ) g = g2 h += step if h > max_h : raise Exception ( "Did not converge before {}" . format ( h ) ) return g
def __raise ( self , * args ) : """Ensures that the Widget stays on top of the parent stack forcing the redraw . : param \ * args : Arguments . : type \ * args : \ *"""
children = self . parent ( ) . children ( ) . remove ( self ) if children : self . stackUnder ( children [ - 1 ] ) else : self . lower ( ) self . raise_ ( )
def zip_source_model ( ssmLT , archive_zip = '' , log = logging . info ) : """Zip the source model files starting from the smmLT . xml file"""
basedir = os . path . dirname ( ssmLT ) if os . path . basename ( ssmLT ) != 'ssmLT.xml' : orig = ssmLT ssmLT = os . path . join ( basedir , 'ssmLT.xml' ) with open ( ssmLT , 'wb' ) as f : f . write ( open ( orig , 'rb' ) . read ( ) ) archive_zip = archive_zip or os . path . join ( basedir , 'ssmLT....
def get_assessments_offered_for_assessment ( self , assessment_id ) : """Gets an ` ` AssessmentOfferedList ` ` by the given assessment . In plenary mode , the returned list contains all known assessments offered or an error results . Otherwise , the returned list may contain only those assessments offered tha...
# Implemented from template for # osid . learning . ActivityLookupSession . get _ activities _ for _ objective _ template # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'assessment' , collection = 'AssessmentOffered' , runtime = self . _runtime ) result = collection . fin...
def list_firewall_policies ( self , retrieve_all = True , ** _params ) : """Fetches a list of all firewall policies for a project ."""
# Pass filters in " params " argument to do _ request return self . list ( 'firewall_policies' , self . firewall_policies_path , retrieve_all , ** _params )
def store ( self , value , l , dir_only ) : """Group patterns by literals and potential magic patterns ."""
if l and value in ( b'' , '' ) : return globstar = value in ( b'**' , '**' ) and self . globstar magic = self . is_magic ( value ) if magic : value = compile ( value , self . flags ) l . append ( WcGlob ( value , magic , globstar , dir_only , False ) )
def get_current_url ( ) : """Return the current URL including the query string as a relative path . If the app uses subdomains , return an absolute path"""
if current_app . config . get ( 'SERVER_NAME' ) and ( # Check current hostname against server name , ignoring port numbers , if any ( split on ' : ' ) request . environ [ 'HTTP_HOST' ] . split ( ':' , 1 ) [ 0 ] != current_app . config [ 'SERVER_NAME' ] . split ( ':' , 1 ) [ 0 ] ) : return request . url url = url_fo...
def start ( name , call = None ) : '''Start a VM in Linode . name The name of the VM to start . CLI Example : . . code - block : : bash salt - cloud - a stop vm _ name'''
if call != 'action' : raise SaltCloudException ( 'The start action must be called with -a or --action.' ) node_id = get_linode_id_from_name ( name ) node = get_linode ( kwargs = { 'linode_id' : node_id } ) if node [ 'STATUS' ] == 1 : return { 'success' : True , 'action' : 'start' , 'state' : 'Running' , 'msg' :...
def myRank ( grade , badFormat , year , length ) : '''rank of candidateNumber in year Arguments : grade { int } - - a weighted average for a specific candidate number and year badFormat { dict } - - candNumber : [ results for candidate ] year { int } - - year you are in length { int } - - length of each r...
return int ( sorted ( everyonesAverage ( year , badFormat , length ) , reverse = True ) . index ( grade ) + 1 )
def send_to_room ( self , message , room_name ) : """Sends a given message to a given room"""
room = self . get_room ( room_name ) if room is not None : room . send_message ( message )
def init_app ( self , app ) : """Initialise the formatter with app - specific values from ` ` app ` ` ’ s configuration"""
if self . __inited : return config = app . config . get ( 'FLASK_LOGGING_EXTRAS' , { } ) blueprint_config = config . get ( 'BLUEPRINT' , { } ) self . bp_var = blueprint_config . get ( 'FORMAT_NAME' , 'blueprint' ) self . bp_app = blueprint_config . get ( 'APP_BLUEPRINT' , '<app>' ) self . bp_noreq = blueprint_confi...
def diff_missed_lines ( self , filename ) : """Return a list of 2 - element tuples ` ( lineno , is _ new ) ` for the given file ` filename ` where ` lineno ` is a missed line number and ` is _ new ` indicates whether the missed line was introduced ( True ) or removed ( False ) ."""
line_changed = [ ] for line in self . file_source ( filename ) : if line . status is not None : is_new = not line . status line_changed . append ( ( line . number , is_new ) ) return line_changed
def _fromJSON ( cls , jsonobject ) : """Generates a new instance of : class : ` maspy . core . MzmlProduct ` from a decoded JSON object ( as generated by : func : ` maspy . core . MzmlProduct . _ reprJSON ( ) ` ) . : param jsonobject : decoded JSON object : returns : a new instance of : class : ` MzmlProduc...
isolationWindow = [ tuple ( param ) for param in jsonobject ] return cls ( isolationWindow )
def _render_parts ( self , header_parts ) : """Helper function to format and quote a single header . Useful for single headers that are composed of multiple items . E . g . , ' Content - Disposition ' fields . : param header _ parts : A sequence of ( k , v ) tuples or a : class : ` dict ` of ( k , v ) to fo...
parts = [ ] iterable = header_parts if isinstance ( header_parts , dict ) : iterable = header_parts . items ( ) for name , value in iterable : if value is not None : parts . append ( self . _render_part ( name , value ) ) return '; ' . join ( parts )
def get_management_commands ( settings ) : """Find registered managemend commands and return their classes as a : class : ` dict ` . Keys are names of the management command and values are classes of the management command ."""
app_commands = getattr ( settings , 'MANAGEMENT_COMMANDS' , ( ) ) commands = { } for name in itertools . chain ( SHELTER_MANAGEMENT_COMMANDS , app_commands ) : command_obj = import_object ( name ) if not issubclass ( command_obj , BaseCommand ) : raise ValueError ( "'%s' is not subclass of the BaseComma...
def execute_pubsub ( self , command , * channels ) : """Executes Redis ( p ) subscribe / ( p ) unsubscribe commands . ConnectionsPool picks separate connection for pub / sub and uses it until explicitly closed or disconnected ( unsubscribing from all channels / patterns will leave connection locked for pub ...
conn , address = self . get_connection ( command ) if conn is not None : return conn . execute_pubsub ( command , * channels ) else : return self . _wait_execute_pubsub ( address , command , channels , { } )
def iou_binary ( preds , labels , EMPTY = 1. , ignore = None , per_image = True ) : """IoU for foreground class binary : 1 foreground , 0 background"""
if not per_image : preds , labels = ( preds , ) , ( labels , ) ious = [ ] for pred , label in zip ( preds , labels ) : intersection = ( ( label == 1 ) & ( pred == 1 ) ) . sum ( ) union = ( ( label == 1 ) | ( ( pred == 1 ) & ( label != ignore ) ) ) . sum ( ) if not union : iou = EMPTY else : ...
def _get_size ( self ) -> Tuple [ int , int ] : """Return the ( width , height ) for this Image . Returns : Tuple [ int , int ] : The ( width , height ) of this Image"""
w = ffi . new ( "int *" ) h = ffi . new ( "int *" ) lib . TCOD_image_get_size ( self . image_c , w , h ) return w [ 0 ] , h [ 0 ]
def handle ( self , connection_id , message_content ) : """Handles parsing incoming requests , and wrapping the final response . Args : connection _ id ( str ) : ZMQ identity sent over ZMQ socket message _ content ( bytes ) : Byte encoded request protobuf to be parsed Returns : HandlerResult : result to b...
try : request = self . _request_proto ( ) request . ParseFromString ( message_content ) except DecodeError : LOGGER . info ( 'Protobuf %s failed to deserialize' , request ) return self . _wrap_result ( self . _status . INTERNAL_ERROR ) try : response = self . _respond ( request ) except _ResponseFai...
def __load_settings_from_file ( self ) : """Loads settings info from the settings json file : returns : True if the settings info is valid : rtype : boolean"""
filename = self . get_base_path ( ) + 'settings.json' if not exists ( filename ) : raise OneLogin_Saml2_Error ( 'Settings file not found: %s' , OneLogin_Saml2_Error . SETTINGS_FILE_NOT_FOUND , filename ) # In the php toolkit instead of being a json file it is a php file and # it is directly included json_data = ope...
def random_host_extinction ( log , sampleNumber , extinctionType , extinctionConstant , hostExtinctionDistributions , plot = False ) : """* Generate a Numpy array of random host extinctions * * * Key Arguments : * * - ` ` log ` ` - - logger - ` ` sampleNumber ` ` - - the sample number , i . e . array size -...
# # # # # # > IMPORTS # # # # # # # STANDARD LIB # # # # THIRD PARTY # # import numpy as np # # LOCAL APPLICATION # # # # # # # # > VARIABLE SETTINGS # # # # # # # # # # # > ACTION ( S ) # # # # # # xxx come back here and add in the random extinctions generation - - will # need to account for what type of SN we have # ...
def _load_lsm_data ( self , data_var , conversion_factor = 1 , calc_4d_method = None , calc_4d_dim = None , time_step = None ) : """This extracts the LSM data from a folder of netcdf files"""
data = self . xd . lsm . getvar ( data_var , yslice = self . yslice , xslice = self . xslice , calc_4d_method = calc_4d_method , calc_4d_dim = calc_4d_dim ) if isinstance ( time_step , datetime ) : data = data . loc [ { self . lsm_time_dim : [ pd . to_datetime ( time_step ) ] } ] elif time_step is not None : da...
def bitop ( self , operation , dest , * keys ) : """Perform a bitwise operation using ` ` operation ` ` between ` ` keys ` ` and store the result in ` ` dest ` ` ."""
return self . execute_command ( 'BITOP' , operation , dest , * keys )
def draw_annulus ( self , center , inner_radius , outer_radius , array , value , mode = "set" ) : """Draws an annulus of specified radius on the input array and fills it with specified value : param center : a tuple for the center of the annulus : type center : tuple ( x , y ) : param inner _ radius : how man...
if mode == "add" : self . draw_circle ( center , outer_radius , array , value ) self . draw_circle ( center , inner_radius , array , - value ) elif mode == "set" : ri , ci , existing = self . draw_circle ( center , inner_radius , array , - value ) self . draw_circle ( center , outer_radius , array , val...
def to_title_caps ( underscore_case ) : r"""Args : underscore _ case ( ? ) : Returns : str : title _ str CommandLine : python - m utool . util _ str - - exec - to _ title _ caps Example : > > > # DISABLE _ DOCTEST > > > from utool . util _ str import * # NOQA > > > underscore _ case = ' the _ foo ...
words = underscore_case . split ( '_' ) words2 = [ word [ 0 ] . upper ( ) + word [ 1 : ] for count , word in enumerate ( words ) ] title_str = ' ' . join ( words2 ) return title_str
def transport_param ( image ) : """Parse DockerImage info into skopeo parameter : param image : DockerImage : return : string . skopeo parameter specifying image"""
transports = { SkopeoTransport . CONTAINERS_STORAGE : "containers-storage:" , SkopeoTransport . DIRECTORY : "dir:" , SkopeoTransport . DOCKER : "docker://" , SkopeoTransport . DOCKER_ARCHIVE : "docker-archive" , SkopeoTransport . DOCKER_DAEMON : "docker-daemon:" , SkopeoTransport . OCI : "oci:" , SkopeoTransport . OSTR...
def hr_avg ( self ) : """Average heart rate of the workout"""
hr_data = self . hr_values ( ) return int ( sum ( hr_data ) / len ( hr_data ) )
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'batches' ) and self . batches is not None : _dict [ 'batches' ] = [ x . _to_dict ( ) for x in self . batches ] return _dict
def kms_key_policy ( ) : """Creates a key policy for use of a KMS Key ."""
statements = [ ] statements . extend ( kms_key_root_statements ( ) ) return Policy ( Version = "2012-10-17" , Id = "root-account-access" , Statement = statements )
def _yield_children ( rec ) : # type : ( dr . DirectoryRecord ) - > Generator '''An internal function to gather and yield all of the children of a Directory Record . Parameters : rec - The Directory Record to get all of the children from ( must be a directory ) Yields : Children of this Directory Record...
if not rec . is_dir ( ) : raise pycdlibexception . PyCdlibInvalidInput ( 'Record is not a directory!' ) last = b'' for child in rec . children : # Check to see if the filename of this child is the same as the # last one , and if so , skip the child . This can happen if we # have very large files with more than one ...
def clear ( self ) : """Empties DEPQ . Performance : O ( 1)"""
with self . lock : self . data . clear ( ) self . items . clear ( )
def context ( self ) : """Get the context ."""
stats = status_codes_by_date_stats ( ) attacks_data = [ { 'type' : 'line' , 'zIndex' : 9 , 'name' : _ ( 'Attacks' ) , 'data' : [ ( v [ 0 ] , v [ 1 ] [ 'attacks' ] ) for v in stats ] } ] codes_data = [ { 'zIndex' : 4 , 'name' : '2xx' , 'data' : [ ( v [ 0 ] , v [ 1 ] [ 200 ] ) for v in stats ] } , { 'zIndex' : 5 , 'name'...
def secp256r1 ( ) : """create the secp256r1 curve"""
GFp = FiniteField ( int ( "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF" , 16 ) ) ec = EllipticCurve ( GFp , 115792089210356248762697446949407573530086143415290314195533631308867097853948 , 41058363725152142129326129780047268409114441015993725554835256314039467401291 ) # return ECDSA ( GFp , ec . po...
def init_app ( self , app ) : """Initialize the APScheduler with a Flask application instance ."""
self . app = app self . app . apscheduler = self self . _load_config ( ) self . _load_jobs ( ) if self . api_enabled : self . _load_api ( )
def run ( self , packets ) : """Run automatically . Positional arguments : * packets - - list < dict > , list of packet dicts to be reassembled"""
for packet in packets : frag_check ( packet , protocol = self . protocol ) info = Info ( packet ) self . reassembly ( info ) self . _newflg = True
def QueryPermissions ( self , user_link , query , options = None ) : """Queries permissions for a user . : param str user _ link : The link to the user entity . : param ( str or dict ) query : : param dict options : The request options for the request . : return : Query Iterable of Permissions . : r...
if options is None : options = { } path = base . GetPathFromLink ( user_link , 'permissions' ) user_id = base . GetResourceIdOrFullNameFromLink ( user_link ) def fetch_fn ( options ) : return self . __QueryFeed ( path , 'permissions' , user_id , lambda r : r [ 'Permissions' ] , lambda _ , b : b , query , option...
def policy_exists ( vhost , name , runas = None ) : '''Return whether the policy exists based on rabbitmqctl list _ policies . Reference : http : / / www . rabbitmq . com / ha . html CLI Example : . . code - block : : bash salt ' * ' rabbitmq . policy _ exists / HA'''
if runas is None and not salt . utils . platform . is_windows ( ) : runas = salt . utils . user . get_user ( ) policies = list_policies ( runas = runas ) return bool ( vhost in policies and name in policies [ vhost ] )
def split_tarball_path ( path ) : '''split _ tarball _ path ( path ) yields a tuple ( tarball , p ) in which tarball is the path to the tarball referenced by path and p is the internal path that followed that tarball . If no tarball is included in the path , then ( None , path ) is returned . If no internal pat...
lpath = path . lower ( ) for e in tarball_endings : if lpath . endswith ( e ) : return ( path , '' ) ee = e + ':' if ee not in lpath : continue spl = path . split ( ee ) tarball = spl [ 0 ] + e p = ee . join ( spl [ 1 : ] ) return ( tarball , p ) return ( None , path )
def as_graph_queue ( self , manifest , limit_to = None ) : """Returns a queue over nodes in the graph that tracks progress of dependecies ."""
if limit_to is None : graph_nodes = self . graph . nodes ( ) else : graph_nodes = limit_to new_graph = _subset_graph ( self . graph , graph_nodes ) return GraphQueue ( new_graph , manifest )
def retry ( exception_cls , max_tries = 10 , sleep = 0.05 ) : """Decorator for retrying a function if it throws an exception . : param exception _ cls : an exception type or a parenthesized tuple of exception types : param max _ tries : maximum number of times this function can be executed . Must be at least 1....
assert max_tries > 0 def with_max_retries_call ( delegate ) : for i in xrange ( 0 , max_tries ) : try : return delegate ( ) except exception_cls : if i + 1 == max_tries : raise time . sleep ( sleep ) def outer ( fn ) : is_generator = inspect . ...
def __get_return_value_withargs ( self , index_list , * args , ** kwargs ) : """Pre - conditions : (1 ) The user has created a stub and specified the stub behaviour (2 ) The user has called the stub function with the specified " args " and " kwargs " (3 ) One or more ' withArgs ' conditions were applicable in...
c = self . _conditions args_list = self . _wrapper . args_list kwargs_list = self . _wrapper . kwargs_list # indices with an arg and oncall have higher priority and should be checked first indices_with_oncall = [ i for i in reversed ( index_list ) if c [ "oncall" ] [ i ] ] # if there are any combined withArgs + onCall ...
def create_property ( name , ptype ) : """Creates a custom property with a getter that performs computing functionality ( if available ) and raise a type error if setting with the wrong type . Note : By default , the setter attempts to convert the object to the correct type ; a type error is raised if thi...
pname = '_' + name def getter ( self ) : # This will be where the data is store ( e . g . self . _ name ) # This is the default property " getter " for container data objects . # If the property value is None , this function will check for a # convenience method with the signature , self . compute _ name ( ) and call #...
def next_page ( self ) : """Next page Uses query object to fetch next slice of items unless on last page in which case does nothing"""
if self . is_last_page ( ) : return False self . page += 1 self . items = self . fetch_items ( ) return True
def clean ( self , value ) : """Propagate to list elements ."""
value = super ( ListField , self ) . clean ( value ) if value is not None : return map ( self . itemspec . clean , value )
def dirty ( self ) : '''The set of instances in this : class : ` Session ` which have been modified .'''
return frozenset ( chain ( * tuple ( ( sm . dirty for sm in itervalues ( self . _models ) ) ) ) )
def field_or_value ( clause ) : """For a clause that could be a field or value , create the right one and return it"""
if hasattr ( clause , "getName" ) and clause . getName ( ) != "field" : return Value ( resolve ( clause ) ) else : return Field ( clause )
def remove_this_predicateAnchor ( self , predAnch_id ) : """Removes the predicate anchor for the given predicate anchor identifier @ type predAnch _ id : string @ param predAnch _ id : the predicate anchor identifier to be removed"""
for predAnch in self . get_predicateAnchors ( ) : if predAnch . get_id ( ) == predAnch_id : self . node . remove ( predAnch . get_node ( ) ) break
def mode ( inlist ) : """Returns a list of the modal ( most common ) score ( s ) in the passed list . If there is more than one such score , all are returned . The bin - count for the mode ( s ) is also returned . Usage : lmode ( inlist ) Returns : bin - count for mode ( s ) , a list of modal value ( s )"""
scores = pstat . unique ( inlist ) scores . sort ( ) freq = [ ] for item in scores : freq . append ( inlist . count ( item ) ) maxfreq = max ( freq ) mode = [ ] stillmore = 1 while stillmore : try : indx = freq . index ( maxfreq ) mode . append ( scores [ indx ] ) del freq [ indx ] ...
def _ssh_state ( chunks , st_kwargs , kwargs , test = False ) : '''Function to run a state with the given chunk via salt - ssh'''
file_refs = salt . client . ssh . state . lowstate_file_refs ( chunks , _merge_extra_filerefs ( kwargs . get ( 'extra_filerefs' , '' ) , __opts__ . get ( 'extra_filerefs' , '' ) ) ) # Create the tar containing the state pkg and relevant files . trans_tar = salt . client . ssh . state . prep_trans_tar ( __context__ [ 'f...
def vpn_connections ( self ) : """Instance depends on the API version : * 2018-04-01 : : class : ` VpnConnectionsOperations < azure . mgmt . network . v2018_04_01 . operations . VpnConnectionsOperations > `"""
api_version = self . _get_api_version ( 'vpn_connections' ) if api_version == '2018-04-01' : from . v2018_04_01 . operations import VpnConnectionsOperations as OperationClass else : raise NotImplementedError ( "APIVersion {} is not available" . format ( api_version ) ) return OperationClass ( self . _client , s...
def add_parent ( self , parent ) : """Adds self as child of parent , then adds parent ."""
parent . add_child ( self ) self . parent = parent return parent
def del_all_svc_comments ( self , service ) : """Delete all service comments Format of the line that triggers function call : : DEL _ ALL _ SVC _ COMMENTS ; < host _ name > ; < service _ description > : param service : service to edit : type service : alignak . objects . service . Service : return : None"...
comments = list ( service . comments . keys ( ) ) for uuid in comments : service . del_comment ( uuid ) self . send_an_element ( service . get_update_status_brok ( ) )
def positive ( data ) : r"""Positivity operator This method preserves only the positive coefficients of the input data , all negative coefficients are set to zero Parameters data : int , float , list , tuple or np . ndarray Input data Returns int or float , or np . ndarray array with only positive coe...
if not isinstance ( data , ( int , float , list , tuple , np . ndarray ) ) : raise TypeError ( 'Invalid data type, input must be `int`, `float`, ' '`list`, `tuple` or `np.ndarray`.' ) def pos_thresh ( data ) : return data * ( data > 0 ) def pos_recursive ( data ) : data = np . array ( data ) if not data...
def parse_single_report ( file_obj ) : """Take a filename , parse the data assuming it ' s a flagstat file Returns a dictionary { ' lineName _ pass ' : value , ' lineName _ fail ' : value }"""
parsed_data = { } re_groups = [ 'passed' , 'failed' , 'passed_pct' , 'failed_pct' ] for k , r in flagstat_regexes . items ( ) : r_search = re . search ( r , file_obj , re . MULTILINE ) if r_search : for i , j in enumerate ( re_groups ) : try : key = "{}_{}" . format ( k , j )...
def get_canonical_encoding_name ( name ) : # type : ( str ) - > str """Given an encoding name , get the canonical name from a codec lookup . : param str name : The name of the codec to lookup : return : The canonical version of the codec name : rtype : str"""
import codecs try : codec = codecs . lookup ( name ) except LookupError : return name else : return codec . name
def ArgList ( args , lparen = LParen ( ) , rparen = RParen ( ) ) : """A parenthesised argument list , used by Call ( )"""
node = Node ( syms . trailer , [ lparen . clone ( ) , rparen . clone ( ) ] ) if args : node . insert_child ( 1 , Node ( syms . arglist , args ) ) return node
def registerViewType ( self , cls , window = None ) : """Registers the inputed widget class as a potential view class . If the optional window argument is supplied , then the registerToWindow method will be called for the class . : param cls | < subclass of XView > window | < QMainWindow > | | < QDialog > | | N...
if ( not cls in self . _viewTypes ) : self . _viewTypes . append ( cls ) if ( window ) : cls . registerToWindow ( window )
def paragraph_ends ( self ) : """The end positions of ` ` paragraphs ` ` layer elements ."""
if not self . is_tagged ( PARAGRAPHS ) : self . tokenize_paragraphs ( ) return self . ends ( PARAGRAPHS )
def _query ( self , query_str , query_args = None , ** query_options ) : """* * query _ options - - dict ignore _ result - - boolean - - true to not attempt to fetch results fetchone - - boolean - - true to only fetch one result count _ result - - boolean - - true to return the int count of rows affected"""
ret = True # http : / / stackoverflow . com / questions / 6739355 / dictcursor - doesnt - seem - to - work - under - psycopg2 connection = query_options . get ( 'connection' , None ) with self . connection ( connection ) as connection : cur = connection . cursor ( ) ignore_result = query_options . get ( 'ignore...
def getAlgorithmInstance ( self , layer = "L2" , column = 0 ) : """Returns an instance of the underlying algorithm . For example , layer = L2 and column = 1 could return the actual instance of ColumnPooler that is responsible for column 1."""
assert ( ( column >= 0 ) and ( column < self . numColumns ) ) , ( "Column number not " "in valid range" ) if layer == "L2" : return self . L2Columns [ column ] . getAlgorithmInstance ( ) elif layer == "L4" : return self . L4Columns [ column ] . getAlgorithmInstance ( ) else : raise Exception ( "Invalid laye...
def _get_ssl_attribute ( value , mapping , default_value , warning_message ) : """Get the TLS attribute based on the compatibility mapping . If no valid attribute can be found , fall - back on default and display a warning . : param str value : : param dict mapping : Dictionary based mapping : param defau...
for key in mapping : if not key . endswith ( value . lower ( ) ) : continue return mapping [ key ] LOGGER . warning ( warning_message , value ) return default_value
def _poll_vq_single ( self , dname , use_devmode , ddresp ) : """Initiate a view query for a view located in a design document : param ddresp : The design document to poll ( as JSON ) : return : True if successful , False if no views ."""
vname = None query = None v_mr = ddresp . get ( 'views' , { } ) v_spatial = ddresp . get ( 'spatial' , { } ) if v_mr : vname = single_dict_key ( v_mr ) query = Query ( ) elif v_spatial : vname = single_dict_key ( v_spatial ) query = SpatialQuery ( ) if not vname : return False query . stale = STALE_...
def hash ( self ) : """Return md5 hash for current dataset ."""
if self . _hash is None : m = hashlib . new ( 'md5' ) if self . _preprocessor is None : # generate hash from numpy array m . update ( numpy_buffer ( self . _X_train ) ) m . update ( numpy_buffer ( self . _y_train ) ) if self . _X_test is not None : m . update ( numpy_buffer (...
def generate_script ( self ) : """Create the SGE script that will run the jobs in the JobGroup , with the passed arguments ."""
self . script = "" # Holds the script string total = 1 # total number of jobs in this group # for now , SGE _ TASK _ ID becomes TASK _ ID , but we base it at zero self . script += """let "TASK_ID=$SGE_TASK_ID - 1"\n""" # build the array definitions ; force ordering for Python3.5 tests for key in sorted ( self . argumen...
def dendrite_filter ( n ) : '''Select only dendrites'''
return n . type == NeuriteType . basal_dendrite or n . type == NeuriteType . apical_dendrite
def _rename_file ( self , line = "" ) : """Rename an ontology 2016-04-11 : not a direct command anymore"""
if not self . all_ontologies : self . _help_nofiles ( ) else : out = [ ] for each in self . all_ontologies : if line in each : out += [ each ] choice = self . _selectFromList ( out , line ) if choice : fullpath = self . LOCAL_MODELS + "/" + choice print ( fullpath...
def ensure_contexted ( func ) : """This decorator ensure that an instance of the Evtx class is used within a context statement . That is , that the ` with ` statement is used , or ` _ _ enter _ _ ( ) ` and ` _ _ exit _ _ ( ) ` are called explicitly ."""
@ wraps ( func ) def wrapped ( self , * args , ** kwargs ) : if self . _buf is None : raise TypeError ( "An Evtx object must be used with" " a context (see the `with` statement)." ) else : return func ( self , * args , ** kwargs ) return wrapped
def check_versions ( self , conn ) : """: param conn : a DB API 2 connection : returns : a message with the versions that will be applied or None"""
scripts = self . read_scripts ( skip_versions = self . get_db_versions ( conn ) ) versions = [ s [ 'version' ] for s in scripts ] if versions : return ( 'Your database is not updated. You can update it by ' 'running oq engine --upgrade-db which will process the ' 'following new versions: %s' % versions )
def find_ss_regions ( dssp_residues ) : """Separates parsed DSSP data into groups of secondary structure . Notes Example : all residues in a single helix / loop / strand will be gathered into a list , then the next secondary structure element will be gathered into a separate list , and so on . Parameters ...
loops = [ ' ' , 'B' , 'S' , 'T' ] current_ele = None fragment = [ ] fragments = [ ] first = True for ele in dssp_residues : if first : first = False fragment . append ( ele ) elif current_ele in loops : if ele [ 1 ] in loops : fragment . append ( ele ) else : ...
def encodeRNAStructure ( seq_vec , maxlen = None , seq_align = "start" , W = 240 , L = 160 , U = 1 , tmpdir = "/tmp/RNAplfold/" ) : """Compute RNA secondary structure with RNAplfold implemented in Kazan et al 2010 , [ doi ] ( https : / / doi . org / 10.1371 / journal . pcbi . 1000832 ) . # Note Secondary stru...
# extend the tmpdir with uuid string to allow for parallel execution tmpdir = tmpdir + "/" + str ( uuid4 ( ) ) + "/" if not isinstance ( seq_vec , list ) : seq_vec = seq_vec . tolist ( ) if not os . path . exists ( tmpdir ) : os . makedirs ( tmpdir ) fasta_path = tmpdir + "/input.fasta" write_fasta ( fasta_path...
def _import_module ( name , package = 'vlfd' , warn = True , prefix = '_py_' , ignore = '_' ) : """Try import all public attributes from module into global namespace . Existing attributes with name clashes are renamed with prefix . Attributes starting with underscore are ignored by default . Return True on su...
import warnings from importlib import import_module try : try : module = import_module ( name ) except ImportError : module = import_module ( '.' + name , package = package ) except ImportError : if warn : warnings . warn ( "failed to import module %s" % name ) else : for attr in...
def get ( self , name ) : """Get the resource URI for a specified resource name . If an entry for the specified resource name does not exist in the Name - URI cache , the cache is refreshed from the HMC with all resources of the manager holding this cache . If an entry for the specified resource name still ...
self . auto_invalidate ( ) try : return self . _uris [ name ] except KeyError : self . refresh ( ) try : return self . _uris [ name ] except KeyError : raise NotFound ( { self . _manager . _name_prop : name } , self . _manager )
def owner_to ( dbname , ownername , user = None , host = None , port = None , password = None , runas = None ) : '''Set the owner of all schemas , functions , tables , views and sequences to the given username . CLI Example : . . code - block : : bash salt ' * ' postgres . owner _ to ' dbname ' ' username '...
sqlfile = tempfile . NamedTemporaryFile ( ) sqlfile . write ( 'begin;\n' ) sqlfile . write ( 'alter database "{0}" owner to "{1}";\n' . format ( dbname , ownername ) ) queries = ( # schemas ( 'alter schema {n} owner to {owner};' , 'select quote_ident(schema_name) as n from ' 'information_schema.schemata;' ) , # tables ...