signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def rename_snapshot ( self , path , oldsnapshotname , snapshotname , ** kwargs ) : """Rename a snapshot"""
response = self . _put ( path , 'RENAMESNAPSHOT' , oldsnapshotname = oldsnapshotname , snapshotname = snapshotname , ** kwargs ) assert not response . content
def publish ( self , message , exchange , routing_key , mandatory = None , immediate = None , headers = None ) : """Publish a message to a named exchange ."""
body , properties = message if headers : properties . headers = headers ret = self . channel . basic_publish ( body = body , properties = properties , exchange = exchange , routing_key = routing_key , mandatory = mandatory , immediate = immediate ) if mandatory or immediate : self . close ( )
def of_pyobj ( self , pyobj ) : """Use default hash method to return hash value of a piece of Python picklable object ."""
m = self . hash_algo ( ) m . update ( pickle . dumps ( pyobj , protocol = self . pk_protocol ) ) if self . return_int : return int ( m . hexdigest ( ) , 16 ) else : return m . hexdigest ( )
def _spawn_threads ( self ) : '''Internal method . Creates threads to handle low - level network receive .'''
for devname , pdev in self . _pcaps . items ( ) : t = threading . Thread ( target = LLNetReal . _low_level_dispatch , args = ( pdev , devname , self . _pktqueue ) ) t . start ( ) self . _threads . append ( t )
def register_custom_adapter ( cls , target_class , adapter ) : """: type target _ class : type : type adapter : JsonAdapter | type : rtype : None"""
class_name = target_class . __name__ if adapter . can_serialize ( ) : cls . _custom_serializers [ class_name ] = adapter if adapter . can_deserialize ( ) : cls . _custom_deserializers [ class_name ] = adapter
def escore ( self ) : """( property ) Returns the E - score associated with the result ."""
hg_pval_thresh = self . escore_pval_thresh or self . pval escore_tol = self . escore_tol or mhg_cython . get_default_tol ( ) es = mhg_cython . get_xlmhg_escore ( self . indices , self . N , self . K , self . X , self . L , hg_pval_thresh , escore_tol ) return es
def _get_time_bins ( index , freq , closed , label , base ) : """Obtain the bins and their respective labels for resampling operations . Parameters index : CFTimeIndex Index object to be resampled ( e . g . , CFTimeIndex named ' time ' ) . freq : xarray . coding . cftime _ offsets . BaseCFTimeOffset The o...
if not isinstance ( index , CFTimeIndex ) : raise TypeError ( 'index must be a CFTimeIndex, but got ' 'an instance of %r' % type ( index ) . __name__ ) if len ( index ) == 0 : datetime_bins = labels = CFTimeIndex ( data = [ ] , name = index . name ) return datetime_bins , labels first , last = _get_range_ed...
def version ( self ) : """Software version of the current repository"""
branches = self . branches ( ) if self . info [ 'branch' ] == branches . sandbox : try : return self . software_version ( ) except Exception as exc : raise utils . CommandError ( 'Could not obtain repo version, do you have a makefile ' 'with version entry?\n%s' % exc ) else : branch = self ....
def get_current_ip ( self ) : """Get the current IP Tor is using . : returns str : raises TorIpError"""
response = get ( ICANHAZIP , proxies = { "http" : self . local_http_proxy } ) if response . ok : return self . _get_response_text ( response ) raise TorIpError ( "Failed to get the current Tor IP" )
def cmd_web_report ( input_file , verbose , browser ) : """Uses Firefox or Chromium to take a screenshot of the websites . Makes a report that includes the HTTP headers . The expected format is one url per line . Creates a directory called ' report ' with the content inside . $ echo https : / / www . portan...
urls = input_file . read ( ) . decode ( ) . strip ( ) . split ( '\n' ) report_dir = Path ( 'report' ) try : report_dir . mkdir ( ) except Exception : pass report_file = report_dir / 'index.html' with report_file . open ( 'w' ) as outfile : outfile . write ( '<!doctype html>\n' ) outfile . write ( '<html...
def transitive_closure ( self ) : """Compute the transitive closure of the matrix ."""
data = [ [ 1 if j else 0 for j in i ] for i in self . data ] for k in range ( self . rows ) : for i in range ( self . rows ) : for j in range ( self . rows ) : if data [ i ] [ k ] and data [ k ] [ j ] : data [ i ] [ j ] = 1 return data
def runner ( self , fun , timeout = None , full_return = False , ** kwargs ) : '''Run ` runner modules < all - salt . runners > ` synchronously Wraps : py : meth : ` salt . runner . RunnerClient . cmd _ sync ` . Note that runner functions must be called using keyword arguments . Positional arguments are not s...
kwargs [ 'fun' ] = fun runner = salt . runner . RunnerClient ( self . opts ) return runner . cmd_sync ( kwargs , timeout = timeout , full_return = full_return )
def send_message ( self , messages , close_on_done = False ) : """Send a single message or batched message . : param messages : A message to send . This can either be a single instance of ` Message ` , or multiple messages wrapped in an instance of ` BatchMessage ` . : type message : ~ uamqp . message . Messa...
batch = messages . gather ( ) pending_batch = [ ] for message in batch : message . idle_time = self . _counter . get_current_ms ( ) self . _pending_messages . append ( message ) pending_batch . append ( message ) self . open ( ) running = True try : while running and any ( [ m for m in pending_batch if ...
def postponed_from_when ( self ) : """A string describing when the event was postponed from ( in the local time zone ) ."""
what = self . what if what : return _ ( "{what} from {when}" ) . format ( what = what , when = self . cancellationpage . when )
def query ( qname , rdtype = dns . rdatatype . A , rdclass = dns . rdataclass . IN , tcp = False , source = None , raise_on_no_answer = True , resolver = None ) : """Query nameservers to find the answer to the question . This is a convenience function that uses the default resolver object to make the query . ...
if resolver is None : resolver = get_default_resolver ( ) return resolver . query ( qname , rdtype , rdclass , tcp , source , raise_on_no_answer )
def create_multiple_droplets ( self , names , image , size , region , ssh_keys = None , backups = None , ipv6 = None , private_networking = None , user_data = None , ** kwargs ) : r"""Create multiple new droplets at once with the same image , size , etc . , differing only in name . All fields other than ` ` names...
data = { "names" : names , "image" : image . id if isinstance ( image , Image ) else image , "size" : str ( size ) , "region" : str ( region ) , } if ssh_keys is not None : data [ "ssh_keys" ] = [ k . _id if isinstance ( k , SSHKey ) else k for k in ssh_keys ] if backups is not None : data [ "backups" ] = backu...
def _joinOnAsPriv ( self , model , onIndex , whatAs ) : """Private method for handling joins ."""
if self . _join : raise Exception ( "Already joined with a table!" ) self . _join = model self . _joinedField = whatAs table = model . table self . _query = self . _query . eq_join ( onIndex , r . table ( table ) ) return self
def setup ( self , phase , entry_pressure = '' , pore_volume = '' , throat_volume = '' ) : r"""Set up the required parameters for the algorithm Parameters phase : OpenPNM Phase object The phase to be injected into the Network . The Phase must have the capillary entry pressure values for the system . entry...
self . settings [ 'phase' ] = phase . name if pore_volume : self . settings [ 'pore_volume' ] = pore_volume if throat_volume : self . settings [ 'throat_volume' ] = throat_volume if entry_pressure : self . settings [ 'entry_pressure' ] = entry_pressure # Setup arrays and info self [ 'throat.entry_pressure' ...
def update_processcount ( self , plist ) : """Update the global process count from the current processes list"""
# Update the maximum process ID ( pid ) number self . processcount [ 'pid_max' ] = self . pid_max # For each key in the processcount dict # count the number of processes with the same status for k in iterkeys ( self . processcount ) : self . processcount [ k ] = len ( list ( filter ( lambda v : v [ 'status' ] is k ...
def parse_instance ( self , global_params , region , reservation ) : """Parse a single EC2 instance : param global _ params : Parameters shared for all regions : param region : Name of the AWS region : param instance : Cluster"""
for i in reservation [ 'Instances' ] : instance = { } vpc_id = i [ 'VpcId' ] if 'VpcId' in i and i [ 'VpcId' ] else ec2_classic manage_dictionary ( self . vpcs , vpc_id , VPCConfig ( self . vpc_resource_types ) ) instance [ 'reservation_id' ] = reservation [ 'ReservationId' ] instance [ 'id' ] = i [...
def GetHostProcessorSpeed ( self ) : '''Retrieves the speed of the ESX system ' s physical CPU in MHz .'''
counter = c_uint ( ) ret = vmGuestLib . VMGuestLib_GetHostProcessorSpeed ( self . handle . value , byref ( counter ) ) if ret != VMGUESTLIB_ERROR_SUCCESS : raise VMGuestLibException ( ret ) return counter . value
def get_methods_vocabulary ( self , analysis_brain ) : """Returns a vocabulary with all the methods available for the passed in analysis , either those assigned to an instrument that are capable to perform the test ( option " Allow Entry of Results " ) and those assigned manually in the associated Analysis Se...
uids = analysis_brain . getAllowedMethodUIDs query = { 'portal_type' : 'Method' , 'is_active' : True , 'UID' : uids } brains = api . search ( query , 'bika_setup_catalog' ) if not brains : return [ { 'ResultValue' : '' , 'ResultText' : _ ( 'None' ) } ] return map ( lambda brain : { 'ResultValue' : brain . UID , 'Re...
def init ( ) : """Initializes the preprocessor"""
global OUTPUT global INCLUDED global CURRENT_DIR global ENABLED global INCLUDEPATH global IFDEFS global ID_TABLE global CURRENT_FILE global_ . FILENAME = '(stdin)' OUTPUT = '' INCLUDED = { } CURRENT_DIR = '' pwd = get_include_path ( ) INCLUDEPATH = [ os . path . join ( pwd , 'library' ) , os . path . join ( pwd , 'libr...
def parts ( ) : '''Returns the dictionary with the part as key and the contained book as indices .'''
parts = { 'Canon' : [ _ for _ in range ( 1 , 5 ) ] , 'Apostle' : [ 5 ] , 'Paul' : [ _ for _ in range ( 6 , 19 ) ] , 'General' : [ _ for _ in range ( 19 , 26 ) ] , 'Apocalypse' : [ 27 ] } return parts
def from_json ( json ) : """Creates a Track from a JSON file . No preprocessing is done . Arguments : json : map with the keys : name ( optional ) and segments . Return : A track instance"""
segments = [ Segment . from_json ( s ) for s in json [ 'segments' ] ] return Track ( json [ 'name' ] , segments ) . compute_metrics ( )
def visit_Call ( self , nodeCall ) : """Be invoked when visiting a node of function call . @ param node : currently visiting node"""
super ( PatternFinder , self ) . generic_visit ( nodeCall ) # Capture assignment like ' f = getattr ( . . . ) ' . if hasattr ( nodeCall . func , "func" ) : # In this case , the statement should be # ' f = getattr ( . . . ) ( ) ' . nodeCall = nodeCall . func # Make sure the function ' s name is ' getattr ' . if not ...
def get_widget_for ( self , fieldname ) : """Lookup the widget"""
field = self . context . getField ( fieldname ) if not field : return None return field . widget
def get_lat_lon ( self , exif_data ) : """Returns the latitude and longitude , if available , from the provided exif _ data ( obtained through get _ exif _ data above )"""
lat = None lon = None if "GPSInfo" in exif_data : gps_info = exif_data [ "GPSInfo" ] gps_latitude = self . _get_if_exist ( gps_info , "GPSLatitude" ) gps_latitude_ref = self . _get_if_exist ( gps_info , 'GPSLatitudeRef' ) gps_longitude = self . _get_if_exist ( gps_info , 'GPSLongitude' ) gps_longitu...
def get_matching ( content , match ) : """filters out lines that don ' t include match"""
if match != "" : lines = [ line for line in content . split ( "\n" ) if match in line ] content = "\n" . join ( lines ) return content
def facade ( projectmainfn , ** kwargs ) : # ( Callable [ [ None ] , None ] , Any ) - > None """Facade to simplify project setup that calls project main function Args : projectmainfn ( ( None ) - > None ) : main function of project * * kwargs : configuration parameters to pass to HDX Configuration class Ret...
# Setting up configuration site_url = Configuration . _create ( ** kwargs ) logger . info ( '--------------------------------------------------' ) logger . info ( '> Using HDX Python API Library %s' % Configuration . apiversion ) logger . info ( '> HDX Site: %s' % site_url ) UserAgent . user_agent = Configuration . rea...
def __prepare_config ( config , project_mapping , session_variables_set = None ) : """parse testcase / testsuite config ."""
# get config variables raw_config_variables = config . pop ( "variables" , { } ) raw_config_variables_mapping = utils . ensure_mapping_format ( raw_config_variables ) override_variables = utils . deepcopy_dict ( project_mapping . get ( "variables" , { } ) ) functions = project_mapping . get ( "functions" , { } ) # over...
def satisifesShapeOr ( cntxt : Context , n : Node , se : ShExJ . ShapeOr , _ : DebugContext ) -> bool : """Se is a ShapeOr and there is some shape expression se2 in shapeExprs such that satisfies ( n , se2 , G , m ) ."""
return any ( satisfies ( cntxt , n , se2 ) for se2 in se . shapeExprs )
def image_encoder ( image_feat , hparams , name = "image_encoder" , save_weights_to = None , make_image_summary = True ) : """A stack of self attention layers ."""
x = image_feat image_hidden_size = hparams . image_hidden_size or hparams . hidden_size image_filter_size = hparams . image_filter_size or hparams . filter_size with tf . variable_scope ( name ) : for layer in range ( hparams . num_encoder_layers or hparams . num_hidden_layers ) : with tf . variable_scope (...
def _process_name_or_alias_filter_directive ( filter_operation_info , location , context , parameters ) : """Return a Filter basic block that checks for a match against an Entity ' s name or alias . Args : filter _ operation _ info : FilterOperationInfo object , containing the directive and field info of the ...
filtered_field_type = filter_operation_info . field_type if isinstance ( filtered_field_type , GraphQLUnionType ) : raise GraphQLCompilationError ( u'Cannot apply "name_or_alias" to union type ' u'{}' . format ( filtered_field_type ) ) current_type_fields = filtered_field_type . fields name_field = current_type_fie...
def location ( self , x = None , y = None ) : """Return a context manager for temporarily moving the cursor . Move the cursor to a certain position on entry , let you print stuff there , then return the cursor to its original position : : term = Terminal ( ) with term . location ( 2 , 5 ) : print ( ' Hell...
# Save position and move to the requested column , row , or both : self . stream . write ( self . save ) if x is not None and y is not None : self . stream . write ( self . move ( y , x ) ) elif x is not None : self . stream . write ( self . move_x ( x ) ) elif y is not None : self . stream . write ( self ....
def changeGroupImageRemote ( self , image_url , thread_id = None ) : """Changes a thread image from a URL : param image _ url : URL of an image to upload and change : param thread _ id : User / Group ID to change image . See : ref : ` intro _ threads ` : raises : FBchatException if request failed"""
( image_id , mimetype ) , = self . _upload ( get_files_from_urls ( [ image_url ] ) ) return self . _changeGroupImage ( image_id , thread_id )
def run ( self ) : """Need to find any pre - existing vext contained in dependent packages and install them example : you create a setup . py with install _ requires [ " vext . gi " ] : - vext . gi gets installed using bdist _ egg - vext itself is now called with bdist _ egg and we end up here Vext now ...
logger . debug ( "vext InstallLib [started]" ) # Find packages that depend on vext and check for . vext files . . . logger . debug ( "find_vext_files" ) vext_files = self . find_vext_files ( ) logger . debug ( "manually_install_vext: " , vext_files ) self . manually_install_vext ( vext_files ) logger . debug ( "enable ...
def _handle_metadata ( self , node , scope , ctxt , stream ) : """Handle metadata for the node"""
self . _dlog ( "handling node metadata {}" . format ( node . metadata . keyvals ) ) keyvals = node . metadata . keyvals metadata_info = [ ] if "watch" in node . metadata . keyvals or "update" in keyvals : metadata_info . append ( self . _handle_watch_metadata ( node , scope , ctxt , stream ) ) if "packtype" in node...
def _submit ( self , body , future ) : """Enqueue a problem for submission to the server . This method is thread safe ."""
self . _submission_queue . put ( self . _submit . Message ( body , future ) )
def split_taf ( txt : str ) -> [ str ] : # type : ignore """Splits a TAF report into each distinct time period"""
lines = [ ] split = txt . split ( ) last_index = 0 for i , item in enumerate ( split ) : if starts_new_line ( item ) and i != 0 and not split [ i - 1 ] . startswith ( 'PROB' ) : lines . append ( ' ' . join ( split [ last_index : i ] ) ) last_index = i lines . append ( ' ' . join ( split [ last_index...
def _compute_primary_smooths ( self ) : """Compute fixed - span smooths with all of the default spans ."""
for span in DEFAULT_SPANS : smooth = smoother . perform_smooth ( self . x , self . y , span ) self . _primary_smooths . append ( smooth )
def get_loader ( vm_ , ** kwargs ) : '''Returns the information on the loader for a given vm : param vm _ : name of the domain : param connection : libvirt connection URI , overriding defaults : param username : username to connect with , overriding defaults : param password : password to connect with , ove...
conn = __get_conn ( ** kwargs ) loader = _get_loader ( _get_domain ( conn , vm_ ) ) conn . close ( ) return loader
def free_parameters ( self ) : """Returns a dictionary of free parameters for this source . We use the parameter path as the key because it ' s guaranteed to be unique , unlike the parameter name . : return :"""
free_parameters = collections . OrderedDict ( ) for component in self . _components . values ( ) : for par in component . shape . parameters . values ( ) : if par . free : free_parameters [ par . path ] = par for par in self . position . parameters . values ( ) : if par . free : free...
def _get_things ( self , method , thing , thing_type , params = None , cacheable = True ) : """Returns a list of the most played thing _ types by this thing ."""
limit = params . get ( "limit" , 1 ) seq = [ ] for node in _collect_nodes ( limit , self , self . ws_prefix + "." + method , cacheable , params ) : title = _extract ( node , "name" ) artist = _extract ( node , "name" , 1 ) playcount = _number ( _extract ( node , "playcount" ) ) seq . append ( TopItem ( ...
def stop_server ( self ) : """Stop receiving connections , wait for all tasks to end , and then terminate the server ."""
self . stop = True while self . task_count : time . sleep ( END_RESP ) self . terminate = True
def get_geometry_from_mp_symbol ( self , mp_symbol ) : """Returns the coordination geometry of the given mp _ symbol . : param mp _ symbol : The mp _ symbol of the coordination geometry ."""
for gg in self . cg_list : if gg . mp_symbol == mp_symbol : return gg raise LookupError ( 'No coordination geometry found with mp_symbol "{symbol}"' . format ( symbol = mp_symbol ) )
def _ParseValueData ( self , knowledge_base , value_data ) : """Parses Windows Registry value data for a preprocessing attribute . Args : knowledge _ base ( KnowledgeBase ) : to fill with preprocessing information . value _ data ( object ) : Windows Registry value data . Raises : errors . PreProcessFail :...
if not isinstance ( value_data , py2to3 . UNICODE_TYPE ) : raise errors . PreProcessFail ( 'Unsupported Windows Registry value type: {0:s} for ' 'artifact: {1:s}.' . format ( type ( value_data ) , self . ARTIFACT_DEFINITION_NAME ) ) if not knowledge_base . GetHostname ( ) : hostname_artifact = artifacts . Hostn...
def import_classes ( name , currmodule ) : # type : ( unicode , unicode ) - > Any """Import a class using its fully - qualified * name * ."""
target = None # import class or module using currmodule if currmodule : target = try_import ( currmodule + '.' + name ) # import class or module without currmodule if target is None : target = try_import ( name ) if target is None : raise InheritanceException ( 'Could not import class or module %r specified...
def _parse_request_arguments ( self , request ) : """Parses comma separated request arguments Args : request : A request that should contain ' inference _ address ' , ' model _ name ' , ' model _ version ' , ' model _ signature ' . Returns : A tuple of lists for model parameters"""
inference_addresses = request . args . get ( 'inference_address' ) . split ( ',' ) model_names = request . args . get ( 'model_name' ) . split ( ',' ) model_versions = request . args . get ( 'model_version' ) . split ( ',' ) model_signatures = request . args . get ( 'model_signature' ) . split ( ',' ) if len ( model_na...
def hide_button_span ( self , mode , file = sys . stdout ) : """: param int mode : 1 or 2 : param io . TextIOBase | io . StringIO file :"""
file . write ( "\033[83;%iu" % mode ) yield file . write ( "\033[83;0u" )
def get_post ( id , check_author = True ) : """Get a post and its author by id . Checks that the id exists and optionally that the current user is the author . : param id : id of post to get : param check _ author : require the current user to be the author : return : the post with author information : ...
post = Post . query . get_or_404 ( id , f"Post id {id} doesn't exist." ) if check_author and post . author != g . user : abort ( 403 ) return post
def make_association ( self , record ) : """contstruct the association : param record : : return : modeled association of genotype to mammalian phenotype"""
model = Model ( self . graph ) record [ 'relation' ] [ 'id' ] = self . resolve ( "has phenotype" ) # define the triple gene = record [ 'subject' ] [ 'id' ] relation = record [ 'relation' ] [ 'id' ] phenotype = record [ 'object' ] [ 'id' ] # instantiate the association g2p_assoc = Assoc ( self . graph , self . name , su...
def request_quotes ( tickers_list , selected_columns = [ '*' ] ) : """Request Yahoo Finance recent quotes . Returns quotes information from YQL . The columns to be requested are listed at selected _ columns . Check ` here < http : / / goo . gl / 8AROUD > ` _ for more information on YQL . > > > request _ quo...
__validate_list ( tickers_list ) __validate_list ( selected_columns ) query = 'select {cols} from yahoo.finance.quotes where symbol in ({vals})' query = query . format ( cols = ', ' . join ( selected_columns ) , vals = ', ' . join ( '"{0}"' . format ( s ) for s in tickers_list ) ) response = __yahoo_request ( query ) i...
def main ( ) : """Execute the converter using parameters provided on the command line"""
parser = argparse . ArgumentParser ( ) parser . add_argument ( '-o' , '--outfile' , metavar = 'output_file_path' , help = "Save calltree stats to <outfile>" ) parser . add_argument ( '-i' , '--infile' , metavar = 'input_file_path' , help = "Read Python stats from <infile>" ) parser . add_argument ( '-k' , '--kcachegrin...
def year ( self , value = None ) : """We do * NOT * know for what year we are converting so lets assume the year has 365 days ."""
if value is None : return self . day ( ) / 365 else : self . millisecond ( self . day ( value * 365 ) )
def match_url ( self , request ) : """match url determines if this is selected"""
matched = False if self . exact_url : if re . match ( "%s$" % ( self . url , ) , request . path ) : matched = True elif re . match ( "%s" % self . url , request . path ) : matched = True return matched
def fields ( self , new_fieldnames ) : """Overwrite all field names with new field names . Mass renaming ."""
if len ( new_fieldnames ) != len ( self . fields ) : raise Exception ( "Cannot replace fieldnames (len: %s) with list of " "incorrect length (len: %s)" % ( len ( new_fieldnames ) , len ( self . fields ) ) ) for old_name , new_name in izip ( self . fields , new_fieldnames ) : # use pop instead of ` del ` in case old...
def mitocompile ( args ) : """% prog mitcompile * . vcf . gz Extract information about deletions in vcf file ."""
from jcvi . formats . vcf import VcfLine from six . moves . urllib . parse import parse_qsl p = OptionParser ( mitocompile . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) vcfs = args print ( "\t" . join ( "vcf samplekey depth seqid pos alt svlen pe sr" ....
def on_download_to_activated ( self , menu_item ) : '''下载文件 / 目录到指定的文件夹里 .'''
tree_paths = self . iconview . get_selected_items ( ) if not tree_paths : return dialog = Gtk . FileChooserDialog ( _ ( 'Save to...' ) , self . app . window , Gtk . FileChooserAction . SELECT_FOLDER , ( Gtk . STOCK_CANCEL , Gtk . ResponseType . CANCEL , Gtk . STOCK_OK , Gtk . ResponseType . OK ) ) response = dialog...
def _pdf ( self , x , dist , cache ) : """Probability density function ."""
return evaluation . evaluate_density ( dist , numpy . arcsinh ( x ) , cache = cache ) / numpy . sqrt ( 1 + x * x )
def base_name_from_image ( image ) : """Extract the base name of the image to use as the ' algorithm name ' for the job . Args : image ( str ) : Image name . Returns : str : Algorithm name , as extracted from the image name ."""
m = re . match ( "^(.+/)?([^:/]+)(:[^:]+)?$" , image ) algo_name = m . group ( 2 ) if m else image return algo_name
def get ( self , roleId ) : """Get a specific role information"""
role = db . Role . find_one ( Role . role_id == roleId ) if not role : return self . make_response ( 'No such role found' , HTTP . NOT_FOUND ) return self . make_response ( { 'role' : role } )
def human_play ( w , i , grid ) : "Just ask for a move ."
plaint = '' prompt = whose_move ( grid ) + " move? [1-9] " while True : w . render_to_terminal ( w . array_from_text ( view ( grid ) + '\n\n' + plaint + prompt ) ) key = c = i . next ( ) try : move = int ( key ) except ValueError : pass else : if 1 <= move <= 9 : ...
def process_stencil ( cookbook , cookbook_name , template_pack , force_argument , stencil_set , stencil , written_files ) : """Process the stencil requested , writing any missing files as needed . The stencil named ' stencilset _ name ' should be one of templatepack ' s stencils ."""
# force can be passed on the command line or forced in a stencil ' s options force = force_argument or stencil [ 'options' ] . get ( 'force' , False ) stencil [ 'files' ] = stencil . get ( 'files' ) or { } files = { # files . keys ( ) are template paths , files . values ( ) are target paths # { path to template : rende...
def detect ( self , fstring , fname = None ) : """Have a stab at most files ."""
if fname is not None and '.' in fname : extension = fname . rsplit ( '.' , 1 ) [ 1 ] if extension in { 'pdf' , 'html' , 'xml' } : return False return True
def normalize ( input , case_mapping = protocol . DEFAULT_CASE_MAPPING ) : """Normalize input according to case mapping ."""
if case_mapping not in protocol . CASE_MAPPINGS : raise pydle . protocol . ProtocolViolation ( 'Unknown case mapping ({})' . format ( case_mapping ) ) input = input . lower ( ) if case_mapping in ( 'rfc1459' , 'rfc1459-strict' ) : input = input . replace ( '{' , '[' ) . replace ( '}' , ']' ) . replace ( '|' , '...
def _smooth_best_span_estimates ( self ) : """Apply a MID _ SPAN smooth to the best span estimates at each observation ."""
self . _smoothed_best_spans = smoother . perform_smooth ( self . x , self . _best_span_at_each_point , MID_SPAN )
def image_data ( Z , X = [ 0 , 1.0 ] , Y = [ 0 , 1.0 ] , aspect = 1.0 , zmin = None , zmax = None , clear = 1 , clabel = 'z' , autoformat = True , colormap = "Last Used" , shell_history = 0 , ** kwargs ) : """Generates an image plot . Parameters 2 - d array of z - values X = [ 0,1.0 ] , Y = [ 0,1.0] 1 - d a...
global _colormap # Set interpolation to something more relevant for every day science if not 'interpolation' in kwargs . keys ( ) : kwargs [ 'interpolation' ] = 'nearest' _pylab . ioff ( ) fig = _pylab . gcf ( ) if clear : fig . clear ( ) _pylab . axes ( ) # generate the 3d axes X = _n . array ( X ) Y = _n ...
def uninstall ( bld ) : '''removes the installed files'''
Options . commands [ 'install' ] = False Options . commands [ 'uninstall' ] = True Options . is_install = True bld . is_install = UNINSTALL try : def runnable_status ( self ) : return SKIP_ME setattr ( Task . Task , 'runnable_status_back' , Task . Task . runnable_status ) setattr ( Task . Task , 'ru...
def build ( self ) : """Builds the tree from the leaves that have been added . This function populates the tree from the leaves down non - recursively"""
self . order = MerkleTree . get_order ( len ( self . leaves ) ) n = 2 ** self . order self . nodes = [ b'' ] * 2 * n # populate lowest nodes with leaf hashes for j in range ( 0 , n ) : if ( j < len ( self . leaves ) ) : self . nodes [ j + n - 1 ] = self . leaves [ j ] . get_hash ( ) else : break...
def note_addition ( self , key , value ) : """Updates the change state to reflect the addition of a field . Detects previous changes and deletions of the field and acts accordingly ."""
# If we ' re adding a field we previously deleted , remove the deleted note . if key in self . _deleted : # If the key we ' re adding back has a different value , then it ' s a change if value != self . _deleted [ key ] : self . _previous [ key ] = self . _deleted [ key ] del self . _deleted [ key ] els...
def rollback ( self , revision ) : """Rollsback the currently deploy lambda code to a previous revision ."""
print ( "Rolling back.." ) self . zappa . rollback_lambda_function_version ( self . lambda_name , versions_back = revision ) print ( "Done!" )
def fetch ( reload : bool = False ) -> dict : """Returns a dictionary containing all of the available Cauldron commands currently registered . This data is cached for performance . Unless the reload argument is set to True , the command list will only be generated the first time this function is called . : ...
if len ( list ( COMMANDS . keys ( ) ) ) > 0 and not reload : return COMMANDS COMMANDS . clear ( ) for key in dir ( commands ) : e = getattr ( commands , key ) if e and hasattr ( e , 'NAME' ) and hasattr ( e , 'DESCRIPTION' ) : COMMANDS [ e . NAME ] = e return dict ( COMMANDS . items ( ) )
def decolorized_write ( self , fileobj : IO , msg : str ) -> None : """Write a string to a fileobject , stripping ANSI escape sequences if necessary Honor the current colors setting , which requires us to check whether the fileobject is a tty ."""
if self . colors . lower ( ) == constants . COLORS_NEVER . lower ( ) or ( self . colors . lower ( ) == constants . COLORS_TERMINAL . lower ( ) and not fileobj . isatty ( ) ) : msg = utils . strip_ansi ( msg ) fileobj . write ( msg )
def get_jobs ( self , job_id = None , params = None ) : """` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / ml - get - job . html > ` _ : arg job _ id : The ID of the jobs to fetch : arg allow _ no _ jobs : Whether to ignore if a wildcard expression matches no jobs . ( Th...
return self . transport . perform_request ( "GET" , _make_path ( "_ml" , "anomaly_detectors" , job_id ) , params = params )
def object_permission_set ( self ) : '''admins , users with team : admin for the team , and users with org : admin , team ' s organization have full access to teams . Users who are a member of the team , or are a member of the team ' s organization , have read access to the team .'''
return Or ( AllowAdmin , AllowObjectPermission ( 'team:admin' ) , AllowObjectPermission ( 'org:admin' , lambda t : t . organization_id ) , And ( AllowOnlySafeHttpMethod , Or ( ObjAttrTrue ( lambda r , t : t . users . filter ( pk = r . user . pk ) . exists ( ) ) , ObjAttrTrue ( lambda r , t : t . organization . users . ...
def get_float_time ( ) : '''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime ' s'''
t1 = time . time ( ) t2 = datetime . datetime . fromtimestamp ( t1 ) return time . mktime ( t2 . timetuple ( ) ) + 1e-6 * t2 . microsecond
def selected_classification ( self ) : """Obtain the classification selected by user . : returns : Metadata of the selected classification . : rtype : dict , None"""
item = self . lstClassifications . currentItem ( ) try : return definition ( item . data ( QtCore . Qt . UserRole ) ) except ( AttributeError , NameError ) : return None
def create_assessment ( self , assessment ) : """To create Assessment : param assessment : Assessment"""
raw_assessment = self . http . post ( '/Assessment' , assessment ) return Schemas . Assessment ( assessment = raw_assessment )
def make_frozen_stats_tree ( stats ) : """Makes a flat members tree of the given statistics . The statistics can be restored by : func : ` frozen _ stats _ from _ tree ` ."""
tree , stats_tree = [ ] , [ ( None , stats ) ] for x in itertools . count ( ) : try : parent_offset , _stats = stats_tree [ x ] except IndexError : break stats_tree . extend ( ( x , s ) for s in _stats ) members = ( _stats . name , _stats . filename , _stats . lineno , _stats . module , ...
def discrete ( cls , name , description = None , unit = '' , params = None , default = None , initial_status = None ) : """Instantiate a new discrete sensor object . Parameters name : str The name of the sensor . description : str A short description of the sensor . units : str The units of the sensor...
return cls ( cls . DISCRETE , name , description , unit , params , default , initial_status )
def table ( big_array ) : """Return a formatted table , generated from arrays representing columns . The function requires a 2 - dimensional array , where each array is a column of the table . This will be used to generate a formatted table in string format . The number of items in each columns does not need ...
number_of_columns = len ( big_array ) number_of_rows_in_column = [ len ( column ) for column in big_array ] max_cell_size = [ len ( max ( column , key = len ) ) for column in big_array ] table = [ ] # title row row_array = [ column [ 0 ] for column in big_array ] table . append ( table_row ( row_array , pad = max_cell_...
def request_time_facet ( field , time_filter , time_gap , time_limit = 100 ) : """time facet query builder : param field : map the query to this field . : param time _ limit : Non - 0 triggers time / date range faceting . This value is the maximum number of time ranges to return when a . time . gap is unspeci...
start , end = parse_datetime_range ( time_filter ) key_range_start = "f.{0}.facet.range.start" . format ( field ) key_range_end = "f.{0}.facet.range.end" . format ( field ) key_range_gap = "f.{0}.facet.range.gap" . format ( field ) key_range_mincount = "f.{0}.facet.mincount" . format ( field ) if time_gap : gap = g...
def truncate_repeated_single_step_traversals_in_sub_queries ( compound_match_query ) : """For each sub - query , remove one - step traversals that overlap a previous traversal location ."""
lowered_match_queries = [ ] for match_query in compound_match_query . match_queries : new_match_query = truncate_repeated_single_step_traversals ( match_query ) lowered_match_queries . append ( new_match_query ) return compound_match_query . _replace ( match_queries = lowered_match_queries )
def _base64ify ( data , chunksize = None ) : """Convert a binary string into its base64 encoding , broken up into chunks of I { chunksize } characters separated by a space . @ param data : the binary string @ type data : string @ param chunksize : the chunk size . Default is L { dns . rdata . _ base64 _ c...
if chunksize is None : chunksize = _base64_chunksize b64 = data . encode ( 'base64_codec' ) b64 = b64 . replace ( '\n' , '' ) l = len ( b64 ) if l > chunksize : chunks = [ ] i = 0 while i < l : chunks . append ( b64 [ i : i + chunksize ] ) i += chunksize b64 = ' ' . join ( chunks ) r...
def write_word_data ( self , address , register , value ) : """SMBus Write Word : i2c _ smbus _ write _ word _ data ( ) This is the opposite of the Read Word operation . 16 bits of data is written to a device , to the designated register that is specified through the Comm byte . S Addr Wr [ A ] Comm [ A ] D...
return self . smbus . write_word_data ( address , register , value )
def help_text ( self ) : """Return a string with all config keys and their descriptions ."""
result = [ ] for name in sorted ( self . _declarations . keys ( ) ) : result . append ( name ) result . append ( '-' * len ( name ) ) decl = self . _declarations [ name ] if decl . description : result . append ( decl . description . strip ( ) ) else : result . append ( '(no descript...
def parse_endpoint ( endpoint , identifier_type = None ) : """Convert an endpoint name into an ( operation , ns ) tuple ."""
# compute the operation parts = endpoint . split ( "." ) operation = Operation . from_name ( parts [ 1 ] ) # extract its parts matcher = match ( operation . endpoint_pattern , endpoint ) if not matcher : raise InternalServerError ( "Malformed operation endpoint: {}" . format ( endpoint ) ) kwargs = matcher . groupd...
def receive ( self , wallet , account , block , work = None ) : """Receive pending * * block * * for * * account * * in * * wallet * * . . enable _ control required : param wallet : Wallet of account to receive block for : type wallet : str : param account : Account to receive block for : type account : s...
wallet = self . _process_value ( wallet , 'wallet' ) account = self . _process_value ( account , 'account' ) block = self . _process_value ( block , 'block' ) payload = { "wallet" : wallet , "account" : account , "block" : block } if work : payload [ 'work' ] = self . _process_value ( work , 'work' ) resp = self . ...
def brightness ( self ) : """Return current brightness 0-255. For warm white return current led level . For RGB calculate the HSV and return the ' value ' ."""
if self . mode == "ww" : return int ( self . raw_state [ 9 ] ) else : _ , _ , v = colorsys . rgb_to_hsv ( * self . getRgb ( ) ) return v
def get_event_stream ( self ) : """Get the event stream associated with this WVA Note that this event stream is shared across all users of this WVA device as the WVA only supports a single event stream . : return : a new : class : ` WVAEventStream ` instance"""
if self . _event_stream is None : self . _event_stream = WVAEventStream ( self . _http_client ) return self . _event_stream
def generic_model ( cls , site_class , ** kwds ) : """Use generic model parameters based on site class . Parameters site _ class : str Site classification . Possible options are : * Geomatrix AB * Geomatrix CD * USGS AB * USGS CD * USGS A * USGS B * USGS C * USGS D See the report for definit...
p = dict ( cls . PARAMS [ site_class ] ) p . update ( kwds ) return cls ( ** p )
def _dispatch_send ( self , message ) : """Dispatch the different steps of sending"""
if self . dryrun : return message if not self . socket : raise GraphiteSendException ( "Socket was not created before send" ) sending_function = self . _send if self . _autoreconnect : sending_function = self . _send_and_reconnect try : if self . asynchronous and gevent : gevent . spawn ( sendin...
def crawl ( plugin ) : '''Performs a breadth - first crawl of all possible routes from the starting path . Will only visit a URL once , even if it is referenced multiple times in a plugin . Requires user interaction in between each fetch .'''
# TODO : use OrderedSet ? paths_visited = set ( ) paths_to_visit = set ( item . get_path ( ) for item in once ( plugin ) ) while paths_to_visit and continue_or_quit ( ) : path = paths_to_visit . pop ( ) paths_visited . add ( path ) # Run the new listitem patch_plugin ( plugin , path ) new_paths = se...
def _put_file_impacket ( local_path , path , share = 'C$' , conn = None , host = None , username = None , password = None ) : '''Wrapper around impacket . smbconnection . putFile ( ) that allows a file to be uploaded Example usage : import salt . utils . smb smb _ conn = salt . utils . smb . get _ conn ( ' ...
if conn is None : conn = get_conn ( host , username , password ) if conn is False : return False if hasattr ( local_path , 'read' ) : conn . putFile ( share , path , local_path ) return with salt . utils . files . fopen ( local_path , 'rb' ) as fh_ : conn . putFile ( share , path , fh_ . read )
def get_default_config ( self ) : """Return default config ."""
config = super ( SlonyCollector , self ) . get_default_config ( ) config . update ( { 'path' : 'postgres' , 'host' : 'localhost' , 'user' : 'postgres' , 'password' : 'postgres' , 'port' : 5432 , 'slony_node_string' : 'Node [0-9]+ - postgres@localhost' , 'method' : 'Threaded' , 'instances' : { } , } ) return config
def reformat_v09_trace ( raw_trace , max_lines = None ) : """reformat v09 trace simmilar to XRoar one and add CC and Memory - Information . Note : v09 traces contains the register info line one trace line later ! We reoder it as XRoar done : addr + Opcode with resulted registers"""
print ( ) print ( "Reformat v09 trace..." ) mem_info = SBC09MemInfo ( sys . stderr ) result = [ ] next_update = time . time ( ) + 1 old_line = None for line_no , line in enumerate ( raw_trace . splitlines ( ) ) : if max_lines is not None and line_no >= max_lines : msg = "max lines %i arraived -> Abort." % m...
def _from_pointer ( cls , pointer , incref ) : """Wrap an existing : c : type : ` cairo _ t * ` cdata pointer . : type incref : bool : param incref : Whether increase the : ref : ` reference count < refcounting > ` now . : return : A new : class : ` Context ` instance ."""
if pointer == ffi . NULL : raise ValueError ( 'Null pointer' ) if incref : cairo . cairo_reference ( pointer ) self = object . __new__ ( cls ) cls . _init_pointer ( self , pointer ) return self
def cleanup ( self ) : """Executes ` ansible - playbook ` against the cleanup playbook and returns None . : return : None"""
pb = self . _get_ansible_playbook ( self . playbooks . cleanup ) pb . execute ( )
def get_lines_from_file ( filename , lineno , context_lines , loader = None , module_name = None ) : """Returns context _ lines before and after lineno from file . Returns ( pre _ context _ lineno , pre _ context , context _ line , post _ context ) ."""
lineno = lineno - 1 lower_bound = max ( 0 , lineno - context_lines ) upper_bound = lineno + context_lines source = None if loader is not None and hasattr ( loader , "get_source" ) : result = get_source_lines_from_loader ( loader , module_name , lineno , lower_bound , upper_bound ) if result is not None : ...