signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def email ( self , subject , text_body , html_body = None , sender = None , ** kwargs ) : # type : ( str , str , Optional [ str ] , Optional [ str ] , Any ) - > None """Emails a user . Args : subject ( str ) : Email subject text _ body ( str ) : Plain text email body html _ body ( str ) : HTML email body ...
self . configuration . emailer ( ) . send ( [ self . data [ 'email' ] ] , subject , text_body , html_body = html_body , sender = sender , ** kwargs )
def ko_json ( queryset , field_names = None , name = None , safe = False ) : """Given a QuerySet , return just the serialized representation based on the knockout _ fields . Useful for middleware / APIs . Convenience method around ko _ data ."""
return ko_data ( queryset , field_names , name , safe , return_json = True )
def _setup_model_loss ( self , lr ) : """Setup loss and optimizer for PyTorch model ."""
# Setup loss if not hasattr ( self , "loss" ) : self . loss = SoftCrossEntropyLoss ( ) # Setup optimizer if not hasattr ( self , "optimizer" ) : self . optimizer = optim . Adam ( self . parameters ( ) , lr = lr )
def delete_multiple ( self , ids = None , messages = None ) : """Execute an HTTP request to delete messages from queue . Arguments : ids - - A list of messages id to be deleted from the queue . messages - - Response to message reserving ."""
url = "queues/%s/messages" % self . name items = None if ids is None and messages is None : raise Exception ( 'Please, specify at least one parameter.' ) if ids is not None : items = [ { 'id' : item } for item in ids ] if messages is not None : items = [ { 'id' : item [ 'id' ] , 'reservation_id' : item [ 'r...
def ancestors ( self ) : """Get a list of ancestors . @ return : A list of ancestors . @ rtype : [ L { Element } , . . ]"""
ancestors = [ ] p = self . parent while p is not None : ancestors . append ( p ) p = p . parent return ancestors
def udf ( f = None , returnType = StringType ( ) ) : """Creates a user defined function ( UDF ) . . . note : : The user - defined functions are considered deterministic by default . Due to optimization , duplicate invocations may be eliminated or the function may even be invoked more times than it is present ...
# The following table shows most of Python data and SQL type conversions in normal UDFs that # are not yet visible to the user . Some of behaviors are buggy and might be changed in the near # future . The table might have to be eventually documented externally . # Please see SPARK - 25666 ' s PR to see the codes in ord...
def observe_command ( command , ** kwargs ) : """Executes the given command and captures the output without any output to the console : param str | list command : : kwargs : * ` shell ` ( ` ` bool ` ` = False ) - - * ` timeout ` ( ` ` int ` ` = 15 ) - - Timeout in seconds * ` stdin ` ( ` ` * ` ` = None ) ...
shell = kwargs . get ( 'shell' , False ) timeout = kwargs . get ( 'timeout' , 15 ) stdin = kwargs . get ( 'stdin' , subprocess . PIPE ) stdout = kwargs . get ( 'stdout' , subprocess . PIPE ) stderr = kwargs . get ( 'stderr' , subprocess . PIPE ) cwd = kwargs . get ( 'cwd' , None ) kwargs . update ( shell = shell ) kwar...
def plot ( self ) : """The plot object , see [ Pyplot ] [ 1 ] . If one does not exist , it will be created first with [ ` add _ subplot ` ] [ 2 ] . [1 ] : http : / / matplotlib . org / api / pyplot _ api . html [2 ] : http : / / matplotlib . org / api / figure _ api . html # matplotlib . figure . Figure . add...
if not hasattr ( self , '_plot' ) : plot = self . figure . add_subplot ( 111 ) pointspace = self . fit . pointspace ( num = self . options [ 'points' ] ) if any ( v is not None for v in self . fit . data . error ) : plot_data = plot . errorbar self . options [ 'data' ] [ 'xerr' ] = self . fi...
def map2rpn ( map , obj ) : """Convert a Mongodb - like dictionary to a RPN list of operands and operators . Reverse Polish notation ( RPN ) is a mathematical notation in which every operator follows all of its operands , e . g . 3 - 4 + 5 - - > 3 4 - 5 + > > > d = { 2.0 : { ' $ eq ' : 1.0 } } > > > asser...
rpn = [ ] for k , v in map . items ( ) : if k in _ALL_OPS : if isinstance ( v , collections . abc . Mapping ) : # e . g " $ not " : { " $ gt " : " one " } # print ( " in op _ vmap " , k , v ) values = map2rpn ( v , obj ) rpn . extend ( values ) rpn . append ( k ) ...
def wiftohex ( wifkey ) : '''Returns a tuple of : (64 - char hex key , 2 - char hex prefix for key , if it was compressed )'''
iscompressed = False wifkey = normalize_input ( wifkey ) assert len ( wifkey ) == 50 or len ( wifkey ) == 51 or len ( wifkey ) == 52 for c in wifkey : if c not in b58_digits : raise Exception ( "Not WIF" ) key = b58d ( wifkey ) prefix , key = key [ : 2 ] , key [ 2 : ] if len ( key ) == 66 : assert key [...
def daemon_status ( self ) : """Displays the load status of a service . : rtype : dict"""
url = self . _build_url ( constants . DAEMON_STATUS_ENDPOINT ) json = self . client . get ( url , timeout = self . timeout ) return json
def send ( self , subname , value , timestamp = None ) : '''Send the data to statsd via self . connection : keyword subname : The subname to report the data to ( appended to the client name ) : type subname : str : keyword value : The raw value to send'''
if timestamp is None : ts = int ( dt . datetime . now ( ) . strftime ( "%s" ) ) else : ts = timestamp name = self . _get_name ( self . name , subname ) self . logger . info ( '%s: %s %s' % ( name , value , ts ) ) return statsd . Client . _send ( self , { name : '%s|r|%s' % ( value , ts ) } )
def add_constant ( self , stream , value ) : """Store a constant value for use in this sensor graph . Constant assignments occur after all sensor graph nodes have been allocated since they must be propogated to all appropriate virtual stream walkers . Args : stream ( DataStream ) : The constant stream to ...
if stream in self . constant_database : raise ArgumentError ( "Attempted to set the same constant twice" , stream = stream , old_value = self . constant_database [ stream ] , new_value = value ) self . constant_database [ stream ] = value
def __print_namespace_help ( self , session , namespace , cmd_name = None ) : """Prints the documentation of all the commands in the given name space , or only of the given command : param session : Session Handler : param namespace : Name space of the command : param cmd _ name : Name of the command to sho...
session . write_line ( "=== Name space '{0}' ===" , namespace ) # Get all commands in this name space if cmd_name is None : names = [ command for command in self . _commands [ namespace ] ] names . sort ( ) else : names = [ cmd_name ] first_cmd = True for command in names : if not first_cmd : # Print an...
def update_release ( self , release , project , release_id ) : """UpdateRelease . [ Preview API ] Update a complete release object . : param : class : ` < Release > < azure . devops . v5_1 . release . models . Release > ` release : Release object for update . : param str project : Project ID or project name ...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if release_id is not None : route_values [ 'releaseId' ] = self . _serialize . url ( 'release_id' , release_id , 'int' ) content = self . _serialize . body ( release , 'Release' ) res...
def _default ( self , obj : object ) : """Return a serializable version of obj . Overrides JsonObj _ default method : param obj : Object to be serialized : return : Serialized version of obj"""
return None if obj is JSGNull else obj . val if type ( obj ) is AnyType else JSGObject . _strip_nones ( obj . __dict__ ) if isinstance ( obj , JsonObj ) else cast ( JSGString , obj ) . val if issubclass ( type ( obj ) , JSGString ) else str ( obj )
def check_call_out ( command ) : """Run the given command ( with shell = False ) and return the output as a string . Strip the output of enclosing whitespace . If the return code is non - zero , throw GitInvocationError ."""
# start external command process p = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) # get outputs out , _ = p . communicate ( ) # throw exception if process failed if p . returncode != 0 : raise GitInvocationError , 'failed to run "%s"' % " " . join ( command ) return out ....
def add_priorfactor ( self , ** kwargs ) : """Adds given values to priorfactors If given keyword exists already , error will be raised to use : func : ` EclipsePopulation . change _ prior ` instead ."""
for kw in kwargs : if kw in self . priorfactors : logging . error ( '%s already in prior factors for %s. use change_prior function instead.' % ( kw , self . model ) ) continue else : self . priorfactors [ kw ] = kwargs [ kw ] logging . info ( '%s added to prior factors for %s' %...
def update ( self , ignore_warnings = None ) : """Update this app _ profile . . . note : : Update any or all of the following values : ` ` routing _ policy _ type ` ` ` ` description ` ` ` ` cluster _ id ` ` ` ` allow _ transactional _ writes ` `"""
update_mask_pb = field_mask_pb2 . FieldMask ( ) if self . description is not None : update_mask_pb . paths . append ( "description" ) if self . routing_policy_type == RoutingPolicyType . ANY : update_mask_pb . paths . append ( "multi_cluster_routing_use_any" ) else : update_mask_pb . paths . append ( "singl...
def parse_statement ( self ) : """Parse a single statement ."""
token = self . stream . current if token . type != 'name' : self . fail ( 'tag name expected' , token . lineno ) self . _tag_stack . append ( token . value ) pop_tag = True try : if token . value in _statement_keywords : return getattr ( self , 'parse_' + self . stream . current . value ) ( ) if tok...
def read ( self , timeout = None ) : '''Read from the transport . If no data is available , should return None . If timeout > 0 , will only block for ` timeout ` seconds .'''
# If currently locked , another greenlet is trying to read , so yield # control and then return none . Required if a Connection is configured # to be synchronous , a sync callback is trying to read , and there ' s # another read loop running read _ frames . Without it , the run loop will # release the lock but then imm...
def get_marked_up_list ( self , tokensource ) : """an updated version of pygments . formatter . format _ unencoded"""
# import ipdb ; ipdb . set _ trace ( ) source = self . _format_lines ( tokensource ) if self . hl_lines : source = self . _highlight_lines ( source ) if not self . nowrap : if self . linenos == 2 : source = self . _wrap_inlinelinenos ( source ) if self . lineanchors : source = self . _wrap_l...
def _make_login ( self ) : """Private method that makes login"""
login_url = '{}data/v1/session/login?user={}&pass={}&sid={}' . format ( self . base_url , self . username , self . password , self . _parse_session_id ( self . _session_info ) ) self . _session_info = get_json ( login_url )
def branches_containing ( commit ) : """Return a list of branches conatining that commit"""
lines = run ( 'branch --contains %s' % commit ) . splitlines ( ) return [ l . lstrip ( '* ' ) for l in lines ]
def invitation_accepted ( event ) : """When an invitation is accepted , add the user to the team"""
request = getRequest ( ) storage = get_storage ( ) if event . token_id not in storage : return ws_uid , username = storage [ event . token_id ] storage [ event . token_id ] acl_users = api . portal . get_tool ( 'acl_users' ) acl_users . updateCredentials ( request , request . response , username , None ) catalog = ...
def current ( cls , service , port ) : """Returns a Node instance representing the current service node . Collects the host and IP information for the current machine and the port information from the given service ."""
host = socket . getfqdn ( ) return cls ( host = host , ip = socket . gethostbyname ( host ) , port = port , metadata = service . metadata )
def absent ( name , region = None , key = None , keyid = None , profile = None ) : '''Ensure a pipeline with the service _ name does not exist name Name of the service to ensure a data pipeline does not exist for . region Region to connect to . key Secret key to be used . keyid Access key to be used...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } result_pipeline_id = __salt__ [ 'boto_datapipeline.pipeline_id_from_name' ] ( name , region = region , key = key , keyid = keyid , profile = profile , ) if 'error' not in result_pipeline_id : pipeline_id = result_pipeline_id [ 'result' ] ...
def super_lm_moe ( ) : """Add mixture of experts with ~ 1B params ."""
hparams = super_lm_base ( ) hparams . layers = ( ( "n,att,m,d,a," "n,moe,m,d,a," ) * 4 + "n,ffn,d" ) hparams . moe_num_experts = 32 hparams . moe_hidden_sizes = "1024" return hparams
def write_oplog_progress ( self ) : """Writes oplog progress to file provided by user"""
if self . oplog_checkpoint is None : return None with self . oplog_progress as oplog_prog : oplog_dict = oplog_prog . get_dict ( ) items = [ [ name , util . bson_ts_to_long ( oplog_dict [ name ] ) ] for name in oplog_dict ] if not items : return # write to temp file backup_file = self . oplog_checkpoint + "...
def serialize ( self , raw = False ) : '''Encode the private part of the key in a base64 format by default , but when raw is True it will return hex encoded bytes . @ return : bytes'''
if raw : return self . _key . encode ( ) return self . _key . encode ( nacl . encoding . Base64Encoder )
def split_tokens ( self ) : """Split string into tokens ( lazy ) ."""
if not self . _split_tokens_calculated : # split into items ( whitespace split ) self . _split_tokens = self . _line_str . split ( ) self . _split_tokens_calculated = True return self . _split_tokens
def _find_from_file ( full_doc , from_file_keyword ) : """Finds a line in < full _ doc > like < from _ file _ keyword > < colon > < path > and return path"""
path = None for line in full_doc . splitlines ( ) : if from_file_keyword in line : parts = line . strip ( ) . split ( ':' ) if len ( parts ) == 2 and parts [ 0 ] . strip ( ) == from_file_keyword : path = parts [ 1 ] . strip ( ) break return path
def _local_coverage ( reader , features , read_strand = None , fragment_size = None , shift_width = 0 , bins = None , use_score = False , accumulate = True , preserve_total = False , method = None , function = "mean" , zero_inf = True , zero_nan = True , processes = None , stranded = True , verbose = False ) : """R...
# bigWig files are handled differently , so we need to know if we ' re working # with one ; raise exeception if a kwarg was supplied that ' s not supported . if isinstance ( reader , filetype_adapters . BigWigAdapter ) : is_bigwig = True defaults = ( ( 'read_strand' , read_strand , None ) , ( 'fragment_size' , ...
def iterShapes ( self ) : """Serves up shapes in a shapefile as an iterator . Useful for handling large shapefiles ."""
shp = self . __getFileObj ( self . shp ) shp . seek ( 0 , 2 ) self . shpLength = shp . tell ( ) shp . seek ( 100 ) while shp . tell ( ) < self . shpLength : yield self . __shape ( )
def _entryChanged ( self , entry ) : """This is called when a log entry is changed"""
# resave the log self . purrer . save ( ) # redo entry item if entry . tw_item : number = entry . tw_item . _ientry entry . tw_item = None self . etw . takeTopLevelItem ( number ) if number : after = self . etw . topLevelItem ( number - 1 ) else : after = None self . _addEntryIte...
def build ( self ) : """Create and start up the internal workers ."""
# If there ' s no output tube , it means that this stage # is at the end of a fork ( hasn ' t been linked to any stage downstream ) . # Therefore , create one output tube . if not self . _output_tubes : self . _output_tubes . append ( self . _worker_class . getTubeClass ( ) ( ) ) self . _worker_class . assemble ( s...
def set_idle_priority ( pid = None ) : """Puts a process in the idle io priority class . If pid is omitted , applies to the current process ."""
if pid is None : pid = os . getpid ( ) lib . ioprio_set ( lib . IOPRIO_WHO_PROCESS , pid , lib . IOPRIO_PRIO_VALUE ( lib . IOPRIO_CLASS_IDLE , 0 ) )
def pixelFormat ( self ) : """Returns a string representing the pixel format of the video stream . e . g . yuv420p . Returns none is it is not a video stream ."""
f = None if self . isVideo ( ) : if self . __dict__ [ 'pix_fmt' ] : f = self . __dict__ [ 'pix_fmt' ] return f
def _cast ( self , _input , _output ) : """Transforms a pair of input / output into the real slim shoutput . : param _ input : Bag : param _ output : mixed : return : Bag"""
if isenvelope ( _output ) : _output , _flags , _options = _output . unfold ( ) else : _flags , _options = [ ] , { } if len ( _flags ) : # TODO : parse flags to check constraints are respected ( like not modified alone , etc . ) if F_NOT_MODIFIED in _flags : return _input if F_INHERIT in _flags :...
def present ( name , ** kwargs ) : '''Ensure a job is present in the schedule name The unique name that is given to the scheduled job . seconds The scheduled job will be executed after the specified number of seconds have passed . minutes The scheduled job will be executed after the specified number...
ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : [ ] } current_schedule = __salt__ [ 'schedule.list' ] ( show_all = True , return_yaml = False ) if name in current_schedule : new_item = __salt__ [ 'schedule.build_schedule_item' ] ( name , ** kwargs ) # See if the new _ item is valid i...
def get_service_state ( self , service_id : str ) -> str : """Get the state of the service . Only the manager nodes can retrieve service state Args : service _ id ( str ) : Service id Returns : str , state of the service"""
# Get service service = self . _client . services . get ( service_id ) # Get the state of the service for service_task in service . tasks ( ) : service_state = service_task [ 'DesiredState' ] return service_state
def diff ( ctx , branch ) : """Determine which tests intersect a git diff ."""
diff = GitDiffReporter ( branch ) regions = diff . changed_intervals ( ) _report_from_regions ( regions , ctx . obj , file_factory = diff . old_file )
def build ( self , builder ) : """Build XML by appending to builder"""
params = dict ( OID = self . oid , Name = self . name ) if self . unit_dictionary_name : params [ "mdsol:UnitDictionaryName" ] = self . unit_dictionary_name for suffix in [ "A" , "B" , "C" , "K" ] : val = getattr ( self , "constant_{0}" . format ( suffix . lower ( ) ) ) params [ "mdsol:Constant{0}" . format...
def register_client ( provider_info , redirect_uris ) : """This function registers a new client with the specified OpenID Provider , and then returns the regitered client ID and other information . : param provider _ info : The contents of the discovery endpoint as specified by the OpenID Connect Discovery 1....
client_type = check_redirect_uris ( redirect_uris ) submit_info = { 'redirect_uris' : redirect_uris , 'application_type' : client_type , 'token_endpoint_auth_method' : 'client_secret_post' } headers = { 'Content-type' : 'application/json' } resp , content = httplib2 . Http ( ) . request ( provider_info [ 'registration_...
def run ( self , module , options ) : """Run the operator . : param module : The target module path . : type module : ` ` str ` ` : param options : Any runtime options . : type options : ` ` dict ` ` : return : The operator results . : rtype : ` ` dict ` `"""
logger . debug ( "Running CC harvester" ) results = { } for filename , details in dict ( self . harvester . results ) . items ( ) : results [ filename ] = { } total = 0 # running CC total for instance in details : if isinstance ( instance , Class ) : i = self . _dict_from_class ( ins...
def convert_tuple_to_integer ( numbers ) : """This function transforms a tuple of positive integers into a single integer . > > > convert _ tuple _ to _ integer ( ( 1 , 2 , 3 ) ) 123 > > > convert _ tuple _ to _ integer ( ( 4 , 5 , 6 ) ) 456 > > > convert _ tuple _ to _ integer ( ( 5 , 6 , 7 ) ) 567"""
converted_number = int ( '' . join ( str ( num ) for num in numbers ) ) return converted_number
def add_user ( self , user , ** kwargs ) : """Add a user to this team ."""
if isinstance ( user , User ) : user = user [ 'id' ] assert isinstance ( user , six . string_types ) endpoint = '{0}/{1}/users/{2}' . format ( self . endpoint , self [ 'id' ] , user , ) result = self . request ( 'PUT' , endpoint = endpoint , query_params = kwargs ) return result
def _verify ( self , request , return_payload = False , verify = True , raise_missing = False , request_args = None , request_kwargs = None , * args , ** kwargs ) : """Verify that a request object is authenticated ."""
try : token = self . _get_token ( request ) is_valid = True reason = None except ( exceptions . MissingAuthorizationCookie , exceptions . MissingAuthorizationQueryArg , exceptions . MissingAuthorizationHeader , ) as e : token = None is_valid = False reason = list ( e . args ) status = e . st...
def update_hosts ( self , host_names ) : """Primarily for puppet - unity use . Update the hosts for the lun if needed . : param host _ names : specify the new hosts which access the LUN ."""
if self . host_access : curr_hosts = [ access . host . name for access in self . host_access ] else : curr_hosts = [ ] if set ( curr_hosts ) == set ( host_names ) : log . info ( 'Hosts for updating is equal to current hosts, ' 'skip modification.' ) return None new_hosts = [ UnityHostList . get ( cli = ...
def _parse_nexus_vni_range ( self , tunnel_range ) : """Raise an exception for invalid tunnel range or malformed range ."""
for ident in tunnel_range : if not self . _is_valid_nexus_vni ( ident ) : raise exc . NetworkTunnelRangeError ( tunnel_range = tunnel_range , error = _ ( "%(id)s is not a valid Nexus VNI value." ) % { 'id' : ident } ) if tunnel_range [ 1 ] < tunnel_range [ 0 ] : raise exc . NetworkTunnelRangeError ( tun...
def _normalize_images ( self ) : """normalizes image filenames by prepending ' File : ' if needed"""
if 'image' not in self . data : return for img in self . data [ 'image' ] : fname = img [ 'file' ] . replace ( '_' , ' ' ) fstart = fname . startswith ( 'File:' ) istart = fname . startswith ( 'Image:' ) if not fstart and not istart : fname = 'File:' + fname img [ 'orig' ] = img [ 'f...
def get_read_format ( cls , source , args , kwargs ) : """Determine the read format for a given input source"""
ctx = None if isinstance ( source , FILE_LIKE ) : fileobj = source filepath = source . name if hasattr ( source , 'name' ) else None else : filepath = source try : ctx = get_readable_fileobj ( filepath , encoding = 'binary' ) fileobj = ctx . __enter__ ( ) # pylint : disable = no ...
def create_data_descriptor ( self , is_sequence : bool , collection_dimension_count : int , datum_dimension_count : int ) -> DataAndMetadata . DataDescriptor : """Create a data descriptor . : param is _ sequence : whether the descriptor describes a sequence of data . : param collection _ dimension _ count : the...
return DataAndMetadata . DataDescriptor ( is_sequence , collection_dimension_count , datum_dimension_count )
def get_weights_as_images ( weights_npy , width , height , outdir = 'img/' , n_images = 10 , img_type = 'grey' ) : """Create and save the weights of the hidden units as images . : param weights _ npy : path to the weights . npy file : param width : width of the images : param height : height of the images :...
weights = np . load ( weights_npy ) perm = np . random . permutation ( weights . shape [ 1 ] ) [ : n_images ] for p in perm : w = np . array ( [ i [ p ] for i in weights ] ) image_path = outdir + 'w_{}.png' . format ( p ) gen_image ( w , width , height , image_path , img_type )
async def fetch_guild ( self , guild_id ) : """| coro | Retrieves a : class : ` . Guild ` from an ID . . . note : : Using this , you will not receive : attr : ` . Guild . channels ` , : class : ` . Guild . members ` , : attr : ` . Member . activity ` and : attr : ` . Member . voice ` per : class : ` . Membe...
data = await self . http . get_guild ( guild_id ) return Guild ( data = data , state = self . _connection )
def gettext ( ui_file_path ) : """Let you use gettext instead of the Qt tools for l18n"""
with open ( ui_file_path , 'r' ) as fin : content = fin . read ( ) # replace ` ` _ translate ( " context " , ` ` by ` ` _ ( ` ` content = re . sub ( r'_translate\(".*",\s' , '_(' , content ) content = content . replace ( ' _translate = QtCore.QCoreApplication.translate' , '' ) with open ( ui_file_path , 'w' ...
def get_processor ( self , processor_type : Type [ P ] ) -> P : """Get a Processor instance , by type . This method returns a Processor instance by type . This could be useful in certain situations , such as wanting to call a method on a Processor , from within another Processor . : param processor _ type :...
for processor in self . _processors : if type ( processor ) == processor_type : return processor
def locations_to_cache ( locations , latest = False ) : """Return a cumulative cache file build from the list of locations Parameters locations : list A list of strings containing files , globs , or cache files used to build a combined lal cache file object . latest : Optional , { False , Boolean } Only...
cum_cache = lal . Cache ( ) for source in locations : flist = glob . glob ( source ) if latest : def relaxed_getctime ( fn ) : # when building a cache from a directory of temporary # low - latency frames , files might disappear between # the glob ( ) and getctime ( ) calls tr...
def new_backup ( self , src ) : """Create a new backup file allocation"""
backup_id_file = p . join ( self . backup_dir , '.bk_idx' ) backup_num = file_or_default ( backup_id_file , 1 , int ) backup_name = str ( backup_num ) + "_" + os . path . basename ( src ) backup_num += 1 file_put_contents ( backup_id_file , str ( backup_num ) ) return p . join ( self . backup_dir , backup_name )
def permission_required ( perm , queryset_or_model = None , login_url = None , raise_exception = False ) : """Permission check decorator for classbased / functional generic view This decorator works as class , method or function decorator without any modification . DO NOT use ` ` method _ decorator ` ` or wha...
# convert model to queryset if queryset_or_model and issubclass ( queryset_or_model , Model ) : queryset_or_model = queryset_or_model . _default_manager . all ( ) def wrapper ( class_or_method ) : if inspect . isclass ( class_or_method ) : from permission . decorators . classbase import permission_requi...
def start ( self , blocking = False ) : """Start the interface : param blocking : Should the call block until stop ( ) is called ( default : False ) : type blocking : bool : rtype : None"""
self . debug ( "()" ) # Start the plugins for plugin in self . plugins : try : # Inject self into plugin plugin . controller = self plugin . start ( blocking = False ) except : self . exception ( u"Failed to start plugin {}" . format ( plugin . name ) ) raise PluginStartException...
def get_default ( cls , category ) : """Get the default value of a given category ."""
value = cls . _DEFAULTS [ category ] if not value or not isinstance ( value , list ) : return value return value [ 0 ]
def route_method ( method_name , extra_part = False ) : """Custom handler routing decorator . Signs a web handler callable with the http method as attribute . Args : method _ name ( str ) : HTTP method name ( i . e GET , POST ) extra _ part ( bool ) : Indicates if wrapped callable name should be a part of...
def wrapper ( callable_obj ) : if method_name . lower ( ) not in DEFAULT_ROUTES : raise HandlerHTTPMethodError ( 'Invalid http method in method: {}' . format ( method_name ) ) callable_obj . http_method = method_name . upper ( ) callable_obj . url_extra_part = callable_obj . __name__ if extra_part e...
def calc_inuz_v1 ( self ) : """Accumulate the total inflow into the upper zone layer . Required control parameters : | NmbZones | | ZoneType | Required derived parameters : | RelLandZoneArea | Required fluxes sequences : | CF | Calculated flux sequence : | InUZ | Basic equation : : math : ` In...
con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess flu . inuz = 0. for k in range ( con . nmbzones ) : if con . zonetype [ k ] != ILAKE : flu . inuz += der . rellandzonearea [ k ] * ( flu . r [ k ] - flu . cf [ k ] )
def listdir ( directory ) : """Returns list of nested files and directories for local directory by path : param directory : absolute or relative path to local directory : return : list nested of file or directory names"""
file_names = list ( ) for filename in os . listdir ( directory ) : file_path = os . path . join ( directory , filename ) if os . path . isdir ( file_path ) : filename = f'{filename}{os.path.sep}' file_names . append ( filename ) return file_names
def retrieve_log_trace ( self , filename = None , dir = None ) : """Retrieves the application log and trace files of the job and saves them as a compressed tar file . An existing file with the same name will be overwritten . Args : filename ( str ) : name of the created tar file . Defaults to ` job _ < id >...
if hasattr ( self , "applicationLogTrace" ) and self . applicationLogTrace is not None : logger . debug ( "Retrieving application logs from: " + self . applicationLogTrace ) if not filename : filename = _file_name ( 'job' , self . id , '.tar.gz' ) return self . rest_client . _retrieve_file ( self . ...
def json_register ( self ) : '''The first char of ' code ' stands for the different field . '1 ' for user _ name '2 ' for user _ email '3 ' for user _ pass '4 ' for user _ role The seconde char of ' code ' stands for different status . '1 ' for invalide '2 ' for already exists .'''
# user _ create _ status = { ' success ' : False , ' code ' : ' 00 ' } post_data = self . get_post_data ( ) user_create_status = self . __check_valid ( post_data ) if not user_create_status [ 'success' ] : return json . dump ( user_create_status , self ) form = SumForm ( self . request . arguments ) if form . valid...
def create_initialized_contract_account ( self , contract_code , storage ) -> None : """Creates a new contract account , based on the contract code and storage provided The contract code only includes the runtime contract bytecode . : param contract _ code : Runtime bytecode for the contract : param storage...
# TODO : Add type hints new_account = Account ( self . _generate_new_address ( ) , code = contract_code , balance = 0 ) new_account . storage = storage self . _put_account ( new_account )
def remove_actor ( self , actor , reset_camera = False ) : """Removes an actor from the Renderer . Parameters actor : vtk . vtkActor Actor that has previously added to the Renderer . reset _ camera : bool , optional Resets camera so all actors can be seen . Returns success : bool True when actor rem...
name = None if isinstance ( actor , str ) : name = actor keys = list ( self . _actors . keys ( ) ) names = [ ] for k in keys : if k . startswith ( '{}-' . format ( name ) ) : names . append ( k ) if len ( names ) > 0 : self . remove_actor ( names , reset_camera = reset_ca...
def do_complete ( self , code , cursor_pos ) : """Method called on autocompletion requests"""
self . _klog . info ( "{%s}" , code [ cursor_pos : cursor_pos + 10 ] ) token , start = token_at_cursor ( code , cursor_pos ) tkn_low = token . lower ( ) if is_magic ( token , start , code ) : matches = [ k for k in magics . keys ( ) if k . startswith ( tkn_low ) ] else : matches = [ sparql_names [ k ] for k in ...
def submit_report ( self , report ) : """Submits a report . * If ` ` report . is _ enclave ` ` is ` ` True ` ` , then the report will be submitted to the enclaves identified by ` ` report . enclaves ` ` ; if that field is ` ` None ` ` , then the enclave IDs registered with this | TruStar | object will be used...
# make distribution type default to " enclave " if report . is_enclave is None : report . is_enclave = True if report . enclave_ids is None : # use configured enclave _ ids by default if distribution type is ENCLAVE if report . is_enclave : report . enclave_ids = self . enclave_ids # if distribution...
def resume ( self ) : """Resumes the thread execution . @ rtype : int @ return : Suspend count . If zero , the thread is running ."""
hThread = self . get_handle ( win32 . THREAD_SUSPEND_RESUME ) return win32 . ResumeThread ( hThread )
def group_paragraphs ( indent_paragraphs ) : '''Group paragraphs so that more indented paragraphs become children of less indented paragraphs .'''
# The tree consists of tuples of the form ( indent , [ children ] ) where the # children may be strings or other tuples root = Node ( 0 , [ ] , None ) current_node = root previous_indent = - 1 for indent , lines in indent_paragraphs : if indent > previous_indent : current_node = create_child_node ( current_...
def get_controller_info_records ( self ) : """Get the info records for all the controller objects in the manager . New info records for each controller object are created for every call so the latest info is included . Returns : List of records . ControllerInfoRecord objects . Each opject conatins the inf...
info_records = [ ] for controller_module_name in self . _controller_objects . keys ( ) : with expects . expect_no_raises ( 'Failed to collect controller info from %s' % controller_module_name ) : record = self . _create_controller_info_record ( controller_module_name ) if record : info_r...
def incr ( self , conn , key , increment = 1 ) : """Command is used to change data for some item in - place , incrementing it . The data for the item is treated as decimal representation of a 64 - bit unsigned integer . : param key : ` ` bytes ` ` , is the key of the item the client wishes to change : par...
assert self . _validate_key ( key ) resp = yield from self . _incr_decr ( conn , b'incr' , key , increment ) return resp
def load_from_string ( self , content , container , ** kwargs ) : """Load config from given string ' cnf _ content ' . : param content : Config content string : param container : callble to make a container object later : param kwargs : optional keyword parameters to be sanitized : : dict : return : Dict - ...
return self . load_from_stream ( anyconfig . compat . StringIO ( content ) , container , ** kwargs )
def secgroup_delete ( name , profile = None , ** kwargs ) : '''Delete a secgroup to nova ( nova secgroup - delete ) CLI Example : . . code - block : : bash salt ' * ' nova . secgroup _ delete mygroup'''
conn = _auth ( profile , ** kwargs ) return conn . secgroup_delete ( name )
def set_to_restart ( self , instance ) : """Put an instance to the restart queue : param instance : instance to restart : type instance : object : return : None"""
self . to_restart . append ( instance ) if instance . is_external : instance . proc = None
def set_logger ( self , logger ) : """subscribe to fortran log messages"""
# we don ' t expect anything back try : self . library . set_logger . restype = None except AttributeError : logger . warn ( "Tried to set logger but method is not implemented in %s" , self . engine ) return # as an argument we need a pointer to a fortran log func . . . self . library . set_logger . argtype...
def NewFont ( familyName = None , styleName = None , showInterface = True ) : """Create a new font . * * familyName * * will be assigned to ` ` font . info . familyName ` ` and * * styleName * * will be assigned to ` ` font . info . styleName ` ` . These are optional and default to ` ` None ` ` . If * * showI...
return dispatcher [ "NewFont" ] ( familyName = familyName , styleName = styleName , showInterface = showInterface )
def filterMsgs ( self , wrappedMsgs : deque ) -> deque : """Filters messages by view number so that only the messages that have the current view number are retained . : param wrappedMsgs : the messages to filter"""
filtered = deque ( ) while wrappedMsgs : wrappedMsg = wrappedMsgs . popleft ( ) msg , sender = wrappedMsg if hasattr ( msg , f . VIEW_NO . nm ) : reqViewNo = getattr ( msg , f . VIEW_NO . nm ) if reqViewNo == self . viewNo : filtered . append ( wrappedMsg ) else : ...
def variables ( self ) -> tuple : """Variables ."""
try : assert self . _variables is not None except ( AssertionError , AttributeError ) : self . _variables = [ self [ n ] for n in self . variable_names ] finally : return tuple ( self . _variables )
def filter_kwargs ( _function , * args , ** kwargs ) : """Given a function and args and keyword args to pass to it , call the function but using only the keyword arguments which it accepts . This is equivalent to redefining the function with an additional \ * \ * kwargs to accept slop keyword args . If the ...
if has_kwargs ( _function ) : return _function ( * args , ** kwargs ) # Get the list of function arguments func_code = six . get_function_code ( _function ) function_args = func_code . co_varnames [ : func_code . co_argcount ] # Construct a dict of those kwargs which appear in the function filtered_kwargs = { } for...
def end ( self ) : """This method must be called after the operation returns . Note that this method is not to be invoked by the user ; it is invoked by the implementation of the : class : ` ~ zhmcclient . Session ` class . If the statistics keeper holding this time statistics is enabled , this method takes...
if self . keeper . enabled : if self . _begin_time is None : raise RuntimeError ( "end() called without preceding begin()" ) dt = time . time ( ) - self . _begin_time self . _begin_time = None self . _count += 1 self . _sum += dt if dt > self . _max : self . _max = dt if dt <...
def generate_rpcs ( self , address ) : """Generate the RPCs needed to stream this config variable to a tile . Args : address ( int ) : The address of the tile that we should stream to . Returns : list of tuples : A list of argument tuples for each RPC . These tuples can be passed to EmulatedDevice . rpc t...
rpc_list = [ ] for offset in range ( 2 , len ( self . data ) , 16 ) : rpc = ( address , rpcs . SET_CONFIG_VARIABLE , self . var_id , offset - 2 , self . data [ offset : offset + 16 ] ) rpc_list . append ( rpc ) return rpc_list
def getAttribute ( self , attr : str ) -> _AttrValueType : """Get attribute of this node as string format . If this node does not have ` ` attr ` ` , return None ."""
if attr == 'class' : if self . classList : return self . classList . toString ( ) return None attr_node = self . getAttributeNode ( attr ) if attr_node is None : return None return attr_node . value
def get_wordlist ( stanzas ) : """Get an iterable of all final words in all stanzas"""
return sorted ( list ( set ( ) . union ( * [ stanza . words for stanza in stanzas ] ) ) )
def cli ( ctx , stage ) : """listen to push requests for src and pull requests from target ( experimental )"""
if not ctx . bubble : ctx . say_yellow ( 'There is no bubble present, will not listen' ) raise click . Abort ( ) SRC = None if stage in STAGES : try : SRC = ctx . cfg . CFG [ stage ] . SOURCE except KeyError : pass if not SRC : ctx . say_red ( 'There is no SOURCE in stage:' + stage )...
def count ( cls , iterable ) : """Returns the number of items in an iterable ."""
iterable = iter ( iterable ) count = 0 while True : try : next ( iterable ) except StopIteration : break count += 1 return count
def _collect_data ( self ) : """Returns a list of all the data gathered from the engine iterable ."""
all_data = [ ] for line in self . engine . run_engine ( ) : logging . debug ( "Adding {} to all_data" . format ( line ) ) all_data . append ( line . copy ( ) ) logging . debug ( "all_data is now {}" . format ( all_data ) ) return all_data
def symmetry_looking ( x , param ) : """Boolean variable denoting if the distribution of x * looks symmetric * . This is the case if . . math : : | mean ( X ) - median ( X ) | < r * ( max ( X ) - min ( X ) ) : param x : the time series to calculate the feature of : type x : numpy . ndarray : param r : the...
if not isinstance ( x , ( np . ndarray , pd . Series ) ) : x = np . asarray ( x ) mean_median_difference = np . abs ( np . mean ( x ) - np . median ( x ) ) max_min_difference = np . max ( x ) - np . min ( x ) return [ ( "r_{}" . format ( r [ "r" ] ) , mean_median_difference < ( r [ "r" ] * max_min_difference ) ) fo...
def path_to_pattern ( path , metadata = None ) : """Remove source information from path when using chaching Returns None if path is not str Parameters path : str Path to data optionally containing format _ strings metadata : dict , optional Extra arguments to the class , contains any cache information ...
if not isinstance ( path , str ) : return pattern = path if metadata : cache = metadata . get ( 'cache' ) if cache : regex = next ( c . get ( 'regex' ) for c in cache if c . get ( 'argkey' ) == 'urlpath' ) pattern = pattern . split ( regex ) [ - 1 ] return pattern
def done ( self , result ) : """save the geometry before dialog is close to restore it later"""
self . _geometry = self . geometry ( ) QtWidgets . QDialog . done ( self , result )
def json_to_entity ( tc_data , value_fields , resource_type , resource_type_parent ) : """Convert ThreatConnect JSON response to a TCEntityArray . . . Attention : : This method is subject to frequent changes . Args : tc _ data ( dictionary ) : Array of data returned from TC API call . value _ fields ( list ...
if not isinstance ( tc_data , list ) : tc_data = [ tc_data ] entity_array = [ ] for d in tc_data : entity = { 'id' : d . get ( 'id' ) , 'webLink' : d . get ( 'webLink' ) } # value values = [ ] if 'summary' in d : values . append ( d . get ( 'summary' ) ) else : for field in value...
def remove_callback ( self , signal_name , callback ) : """: meth : ` . WSignalSourceProto . remove _ callback ` implementation"""
try : self . __direct_callbacks [ signal_name ] . remove ( callback ) except KeyError : raise ValueError ( 'Signal "%s" does not have the specified callback' % signal_name )
def is_training_name ( name ) : """* * Guess * * if this variable is only used in training . Only used internally to avoid too many logging . Do not use it ."""
# TODO : maybe simply check against TRAINABLE _ VARIABLES and MODEL _ VARIABLES ? # TODO or use get _ slot _ names ( ) name = get_op_tensor_name ( name ) [ 0 ] if name . endswith ( '/Adam' ) or name . endswith ( '/Adam_1' ) : return True if name . endswith ( '/Momentum' ) : return True if name . endswith ( '/Ad...
def _pop_digits ( char_list ) : """Pop consecutive digits from the front of list and return them Pops any and all consecutive digits from the start of the provided character list and returns them as a list of string digits . Operates on ( and possibly alters ) the passed list . : param list char _ list : a ...
logger . debug ( '_pop_digits(%s)' , char_list ) digits = [ ] while len ( char_list ) != 0 and char_list [ 0 ] . isdigit ( ) : digits . append ( char_list . pop ( 0 ) ) logger . debug ( 'got digits: %s' , digits ) logger . debug ( 'updated char list: %s' , char_list ) return digits
def ensure_dict_key ( in_dict , keys , delimiter = DEFAULT_TARGET_DELIM , ordered_dict = False ) : '''Ensures that in _ dict contains the series of recursive keys defined in keys . : param dict in _ dict : The dict to work with . : param str keys : The delimited string with one or more keys . : param str deli...
if delimiter in keys : a_keys = keys . split ( delimiter ) else : a_keys = [ keys ] dict_pointer = in_dict while a_keys : current_key = a_keys . pop ( 0 ) if current_key not in dict_pointer or not isinstance ( dict_pointer [ current_key ] , dict ) : dict_pointer [ current_key ] = OrderedDict ( )...
def file_query_size ( self , path , follow_symlinks ) : """Queries the size of a regular file in the guest . in path of type str Path to the file which size is requested . Guest path style . in follow _ symlinks of type bool It @ c true , symbolic links in the final path component will be followed to thei...
if not isinstance ( path , basestring ) : raise TypeError ( "path can only be an instance of type basestring" ) if not isinstance ( follow_symlinks , bool ) : raise TypeError ( "follow_symlinks can only be an instance of type bool" ) size = self . _call ( "fileQuerySize" , in_p = [ path , follow_symlinks ] ) re...
def radio_field ( * args , ** kwargs ) : '''Get a password'''
radio_field = wtforms . RadioField ( * args , ** kwargs ) radio_field . input_type = 'radio_field' return radio_field