signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _authenticate ( self ) : """run any request against the API just to make sure the credentials are valid : return bool : success status : raises Exception : on error"""
opts = { 'domain' : self . _domain } opts . update ( self . _auth ) response = self . _api . domain . info ( opts ) self . _validate_response ( response = response , message = 'Failed to authenticate' ) # set to fake id to pass tests , inwx doesn ' t work on domain id but # uses domain names for identification self . d...
def auth ( self , code = "" , refresh_token = "" ) : """Authenticates user and retrieves ( and refreshes ) access token : param code : code provided after redirect ( authorization _ code only ) : param refresh _ token : the refresh _ token to update access _ token without authorization"""
if refresh_token : try : self . oauth . request_token ( grant_type = "refresh_token" , refresh_token = refresh_token ) self . refresh_token = self . oauth . refresh_token except HTTPError as e : if e . code == 401 : raise DeviantartError ( "Unauthorized: Please check your cre...
def get_data ( self , create = False ) : """Get dict stored for current running task . Return ` None ` or an empty dict if no data was found depending on the ` create ` argument value . : param create : if argument is ` True ` , create empty dict for task , default : ` False `"""
task = asyncio_current_task ( loop = self . loop ) if task : task_id = id ( task ) if create and task_id not in self . data : self . data [ task_id ] = { } task . add_done_callback ( self . del_data ) return self . data . get ( task_id ) return None
def can_create_submission ( self , user = None ) : '''Central access control for submitting things related to assignments .'''
if user : # Super users , course owners and tutors should be able to test their validations # before the submission is officially possible . # They should also be able to submit after the deadline . if user . is_superuser or user is self . course . owner or self . course . tutors . filter ( pk = user . pk ) . exist...
def dimension ( self ) : """output dimension"""
if self . C00 is None : # no data yet if isinstance ( self . dim , int ) : # return user choice warnings . warn ( 'Returning user-input for dimension, since this model has not yet been estimated.' ) return self . dim raise RuntimeError ( 'Please call set_model_params prior using this method.' ) ...
def add ( self , p , q ) : """perform elliptic curve addition"""
if p . iszero ( ) : return q if q . iszero ( ) : return p lft = 0 # calculate the slope of the intersection line if p == q : if p . y == 0 : return self . zero ( ) lft = ( 3 * p . x ** 2 + self . a ) / ( 2 * p . y ) elif p . x == q . x : return self . zero ( ) else : lft = ( p . y - q . ...
def request ( self , method , path , options = None , payload = None , heartbeater = None , retry_count = 0 ) : """Make a request to the Service Registry API . @ param method : HTTP method ( ' POST ' , ' GET ' , etc . ) . @ type method : C { str } @ param path : Path to be appended to base URL ( ' / sessions ...
def _request ( authHeaders , options , payload , heartbeater , retry_count ) : tenantId = authHeaders [ 'X-Tenant-Id' ] requestUrl = self . baseUrl + tenantId + path if options : requestUrl += '?' + urlencode ( options ) payload = StringProducer ( json . dumps ( payload ) ) if payload else None ...
def is_human ( data , builds = None ) : """Check if human , optionally with build number , search by name or extra GL contigs ."""
def has_build37_contigs ( data ) : for contig in ref . file_contigs ( dd . get_ref_file ( data ) ) : if contig . name . startswith ( "GL" ) or contig . name . find ( "_gl" ) >= 0 : if contig . name in naming . GMAP [ "hg19" ] or contig . name in naming . GMAP [ "GRCh37" ] : retur...
def AddBookkeepingOperators ( model ) : """This adds a few bookkeeping operators that we can inspect later . These operators do not affect the training procedure : they only collect statistics and prints them to file or to logs ."""
# Print basically prints out the content of the blob . to _ file = 1 routes the # printed output to a file . The file is going to be stored under # root _ folder / [ blob name ] model . Print ( 'accuracy' , [ ] , to_file = 1 ) model . Print ( 'loss' , [ ] , to_file = 1 ) # Summarizes the parameters . Different from Pri...
def refine ( args ) : """% prog refine breakpoints . bed gaps . bed Find gaps within or near breakpoint region . For breakpoint regions with no gaps , there are two options : - Break in the middle of the region - Break at the closest gap ( - - closest )"""
p = OptionParser ( refine . __doc__ ) p . add_option ( "--closest" , default = False , action = "store_true" , help = "In case of no gaps, use closest [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) breakpointsbed , gapsbed = args ncols = len...
def _getFeedContent ( self , url , excludeRead = False , continuation = None , loadLimit = 20 , since = None , until = None ) : """A list of items ( from a feed , a category or from URLs made with SPECIAL _ ITEMS _ URL ) Returns a dict with : param id : ( str , feed ' s id ) : param continuation : ( str , to ...
parameters = { } if excludeRead : parameters [ 'xt' ] = 'user/-/state/com.google/read' if continuation : parameters [ 'c' ] = continuation parameters [ 'n' ] = loadLimit if since : parameters [ 'ot' ] = since if until : parameters [ 'nt' ] = until contentJson = self . httpGet ( url , parameters ) return...
def add_to_environment ( self , environment ) : """Add the router to the given environment ."""
self . _env = environment . _env self . _userdata = ffi . new_handle ( self ) ENVIRONMENT_DATA [ self . _env ] . routers [ self . name ] = self lib . EnvAddRouterWithContext ( self . _env , self . _name . encode ( ) , self . _priority , lib . query_function , lib . print_function , lib . getc_function , lib . ungetc_fu...
def ppo_tiny_world_model ( ) : """Atari parameters with world model as policy ."""
hparams = ppo_original_params ( ) hparams . policy_network = "next_frame_basic_deterministic" hparams_keys = hparams . values ( ) . keys ( ) video_hparams = basic_deterministic_params . next_frame_tiny ( ) for ( name , value ) in six . iteritems ( video_hparams . values ( ) ) : if name in hparams_keys : hpa...
def inferObjects ( self , bodyPlacement , maxTouches = 2 ) : """Touch each object with multiple sensors twice . : returns : dict mapping the number of touches required to the number of objects that took that many touches to be uniquely inferred . The ' None ' key is reserved for objects not recognized after `...
for monitor in self . monitors . itervalues ( ) : monitor . afterBodyWorldLocationChanged ( bodyPlacement ) numTouchesRequired = collections . defaultdict ( int ) for objectName , objectFeatures in self . objects . iteritems ( ) : self . reset ( ) objectPlacement = self . objectPlacements [ objectName ] ...
def update_shared_file ( self , sharekey = None , title = None , description = None ) : """Update the editable details ( just the title and description ) of a SharedFile . Args : sharekey ( str ) : Sharekey of the SharedFile to update . title ( Optional [ str ] ) : Title of the SharedFile . description ( ...
if not sharekey : raise Exception ( "You must specify a sharekey for the sharedfile" "you wish to update." ) if not ( title or description ) : raise Exception ( "You must specify a title or description." ) post_data = { } if title : post_data [ 'title' ] = title if description : post_data [ 'description...
def set_var ( var , value ) : '''Set a variable in the make . conf Return a dict containing the new value for variable : : { ' < variable > ' : { ' old ' : ' < old - value > ' , ' new ' : ' < new - value > ' } } CLI Example : . . code - block : : bash salt ' * ' makeconf . set _ var ' LINGUAS ' ' en ' '...
makeconf = _get_makeconf ( ) old_value = get_var ( var ) # If var already in file , replace its value if old_value is not None : __salt__ [ 'file.sed' ] ( makeconf , '^{0}=.*' . format ( var ) , '{0}="{1}"' . format ( var , value ) ) else : _add_var ( var , value ) new_value = get_var ( var ) return { var : { '...
def load_metrics ( event_dir , epoch ) : """Loads metrics for this epoch if they have already been written . This reads the entire event file but it ' s small with just per - epoch metrics . Args : event _ dir : TODO ( koz4k ) : Document this . epoch : TODO ( koz4k ) : Document this . Returns : metrics ...
metrics = { } for filename in tf . gfile . ListDirectory ( event_dir ) : path = os . path . join ( event_dir , filename ) for event in tf . train . summary_iterator ( path ) : if event . step == epoch and event . HasField ( "summary" ) : value = event . summary . value [ 0 ] metr...
def fill_n ( self , values , weights = None , dropna : bool = True , columns : bool = False ) : """Add more values at once . Parameters values : array _ like Values to add . Can be array of shape ( count , ndim ) or array of shape ( ndim , count ) [ use columns = True ] or something convertible to it we...
values = np . asarray ( values ) if values . ndim != 2 : raise RuntimeError ( "Expecting 2D array of values." ) if columns : values = values . T if values . shape [ 1 ] != self . ndim : raise RuntimeError ( "Expecting array with {0} columns" . format ( self . ndim ) ) if dropna : values = values [ ~ np ...
def _split_regions ( chrom , start , end ) : """Split regions longer than 100kb into smaller sections ."""
window_size = 1e5 if end - start < window_size * 5 : return [ ( chrom , start , end ) ] else : out = [ ] for r in pybedtools . BedTool ( ) . window_maker ( w = window_size , b = pybedtools . BedTool ( "%s\t%s\t%s" % ( chrom , start , end ) , from_string = True ) ) : out . append ( ( r . chrom , r . ...
def pdfdump ( self , filename = None , ** kargs ) : """pdfdump ( filename = None , layer _ shift = 0 , rebuild = 1) Creates a PDF file describing a packet . If filename is not provided a temporary file is created and xpdf is called . : param filename : the file ' s filename"""
from scapy . config import conf from scapy . utils import get_temp_file , ContextManagerSubprocess canvas = self . canvas_dump ( ** kargs ) if filename is None : fname = get_temp_file ( autoext = kargs . get ( "suffix" , ".pdf" ) ) canvas . writePDFfile ( fname ) if WINDOWS and conf . prog . pdfreader is No...
def run_encoder ( self , param_dict , encoder_dict ) : """run the encoder on a supplied param _ dict"""
X_dict = { } Xcol_dict = { } # put each column of X in Xbycol _ dict Xbycol_dict = { } for key in encoder_dict : if ( key != 'twoway' ) and ( key != 'threeway' ) and ( key != 'trimmed_columns' ) : encoder = encoder_dict [ key ] param_values = param_dict [ key ] Xsub , names = encoder ( key ,...
def kv_format_dict ( d , keys = None , separator = DEFAULT_SEPARATOR ) : """Formats the given dictionary ` ` d ` ` . For more details see : func : ` kv _ format ` . : param collections . Mapping d : Dictionary containing values to format . : param collections . Iterable keys : List of keys to extract from...
return _format_pairs ( dump_dict ( d , keys ) , separator = separator )
def _get_attr_list ( self , attr ) : """Return user ' s attribute / attributes"""
a = self . _attrs . get ( attr ) if not a : return [ ] if type ( a ) is list : r = [ i . decode ( 'utf-8' , 'ignore' ) for i in a ] else : r = [ a . decode ( 'utf-8' , 'ignore' ) ] return r
def find_old_vidyo_rooms ( max_room_event_age ) : """Finds all Vidyo rooms that are : - linked to no events - linked only to events whose start date precedes today - max _ room _ event _ age days"""
recently_used = ( db . session . query ( VCRoom . id ) . filter ( VCRoom . type == 'vidyo' , Event . end_dt > ( now_utc ( ) - timedelta ( days = max_room_event_age ) ) ) . join ( VCRoom . events ) . join ( VCRoomEventAssociation . event ) . group_by ( VCRoom . id ) ) # non - deleted rooms with no recent associations re...
def vendorize ( vendor_requirements ) : """This is the main entry point for vendorizing requirements . It expects a list of tuples that should contain the name of the library and the version . For example , a library ` ` foo ` ` with version ` ` 0.0.1 ` ` would look like : : vendor _ requirements = [ ( ' ...
for library in vendor_requirements : if len ( library ) == 2 : name , version = library cmd = None elif len ( library ) == 3 : # a possible cmd we need to run name , version , cmd = library vendor_library ( name , version , cmd )
def validate_trail_settings ( self , ct , aws_region , trail ) : """Validates logging , SNS and S3 settings for the global trail . Has the capability to : - start logging for the trail - create SNS topics & queues - configure or modify a S3 bucket for logging"""
self . log . debug ( 'Validating trail {}/{}/{}' . format ( self . account . account_name , aws_region , trail [ 'Name' ] ) ) status = ct . get_trail_status ( Name = trail [ 'Name' ] ) if not status [ 'IsLogging' ] : self . log . warning ( 'Logging is disabled for {}/{}/{}' . format ( self . account . account_name ...
def enum_to_yaml ( cls : Type [ T_EnumToYAML ] , representer : Representer , data : T_EnumToYAML ) -> ruamel . yaml . nodes . ScalarNode : """Encodes YAML representation . This is a mixin method for writing enum values to YAML . It needs to be added to the enum as a classmethod . See the module docstring for fu...
return representer . represent_scalar ( f"!{cls.__name__}" , f"{str(data)}" )
def get_default_ref ( repo ) : """Return a ` github . GitRef ` object for the HEAD of the default branch . Parameters repo : github . Repository . Repository repo to get default branch head ref from Returns head : : class : ` github . GitRef ` instance Raises github . RateLimitExceededException code...
assert isinstance ( repo , github . Repository . Repository ) , type ( repo ) # XXX this probably should be resolved via repos . yaml default_branch = repo . default_branch default_branch_ref = "heads/{ref}" . format ( ref = default_branch ) # if accessing the default branch fails something is seriously wrong . . . try...
def __collect_trace_data ( self , request , response , error , latency ) : """Collects the tracing data from the given parameters . : param request : The Flask request . : param response : The flask response . : param error : The error occurred if any . : param latency : The time elapsed to process the requ...
data = OrderedDict ( ) data [ 'latency' ] = latency . elapsed data [ 'request_method' ] = request . environ [ 'REQUEST_METHOD' ] data [ 'request_url' ] = request . url data [ 'request_headers' ] = request . headers body = request . get_data ( as_text = True ) if body : data [ 'request_body' ] = body if response : ...
def comparable ( self ) : """str : comparable representation of the path specification ."""
string_parts = [ ] string_parts . append ( 'table name: {0:s}' . format ( self . table_name ) ) string_parts . append ( 'column name: {0:s}' . format ( self . column_name ) ) if self . row_condition is not None : row_condition_string = ' ' . join ( [ '{0!s}' . format ( value ) for value in self . row_condition ] ) ...
def get_body ( self ) : '''Get the response Body : returns Body : A Body object containing the response .'''
if self . _body is None : resp = self . _dispatcher . _dispatch ( self . request ) self . _body = self . _create_body ( resp ) return self . _body
def gen_weights ( self , f_target ) : """Generate a set of weights over the basis functions such that the target forcing term trajectory is matched . f _ target np . array : the desired forcing term trajectory"""
# calculate x and psi x_track = self . cs . rollout ( ) psi_track = self . gen_psi ( x_track ) # efficiently calculate weights for BFs using weighted linear regression self . w = np . zeros ( ( self . dmps , self . bfs ) ) for d in range ( self . dmps ) : # spatial scaling term k = 1. # ( self . goal [ d ] - se...
def first ( self , predicate = None ) : '''The first element in a sequence ( optionally satisfying a predicate ) . If the predicate is omitted or is None this query returns the first element in the sequence ; otherwise , it returns the first element in the sequence for which the predicate evaluates to True . ...
if self . closed ( ) : raise ValueError ( "Attempt to call first() on a closed Queryable." ) return self . _first ( ) if predicate is None else self . _first_predicate ( predicate )
def run_reducer ( self , stdin = sys . stdin , stdout = sys . stdout ) : """Run the reducer on the hadoop node ."""
self . init_hadoop ( ) self . init_reducer ( ) outputs = self . _reduce_input ( self . internal_reader ( ( line [ : - 1 ] for line in stdin ) ) , self . reducer , self . final_reducer ) self . writer ( outputs , stdout )
def pad2d ( data , padding ) : """Pad array This method pads an input numpy array with zeros in all directions . Parameters data : np . ndarray Input data array ( at least 2D ) padding : int , tuple Amount of padding in x and y directions , respectively Returns np . ndarray padded data Notes Adj...
data = np . array ( data ) if isinstance ( padding , int ) : padding = np . array ( [ padding ] ) elif isinstance ( padding , ( tuple , list ) ) : padding = np . array ( padding ) elif isinstance ( padding , np . ndarray ) : pass else : raise ValueError ( 'Padding must be an integer or a tuple (or list,...
def friendly_format ( self ) : """Serialize to a format more suitable for displaying to end users ."""
if self . description is not None : msg = self . description else : msg = 'errorCode: {} / detailCode: {}' . format ( self . errorCode , self . detailCode ) return self . _fmt ( self . name , msg )
def parse ( self , sentence ) : """Parse raw sentence into ConllSentence Parameters sentence : list a list of ( word , tag ) tuples Returns ConllSentence ConllSentence object"""
words = np . zeros ( ( len ( sentence ) + 1 , 1 ) , np . int32 ) tags = np . zeros ( ( len ( sentence ) + 1 , 1 ) , np . int32 ) words [ 0 , 0 ] = ParserVocabulary . ROOT tags [ 0 , 0 ] = ParserVocabulary . ROOT vocab = self . _vocab for i , ( word , tag ) in enumerate ( sentence ) : words [ i + 1 , 0 ] , tags [ i ...
def _get_attachments ( self , id ) : """Retrieve a list of attachments associated with this Xero object ."""
uri = '/' . join ( [ self . base_url , self . name , id , 'Attachments' ] ) + '/' return uri , { } , 'get' , None , None , False
def get_images ( self , limit = None ) : """Return all of the images associated with the user ."""
url = ( self . _imgur . _base_url + "/3/account/{0}/" "images/{1}" . format ( self . name , '{}' ) ) resp = self . _imgur . _send_request ( url , limit = limit ) return [ Image ( img , self . _imgur ) for img in resp ]
def render_issue ( self , description = '' , traceback = '' ) : """Render issue before sending it to Github"""
# Get component versions versions = get_versions ( ) # Get git revision for development version revision = '' if versions [ 'revision' ] : revision = versions [ 'revision' ] # Make a description header in case no description is supplied if not description : description = "### What steps reproduce the problem?" ...
def retry ( ExceptionToCheck , tries = 3 , delay = 1 , backoff = 1 ) : """Retry calling the decorated function using an exponential backoff . http : / / www . saltycrane . com / blog / 2009/11 / trying - out - retry - decorator - python / original from : http : / / wiki . python . org / moin / PythonDecoratorLi...
def deco_retry ( f ) : @ functools . wraps ( f ) def f_retry ( * args , ** kwargs ) : mtries , mdelay = tries , delay while mtries > 1 : try : return f ( * args , ** kwargs ) except ExceptionToCheck : time . sleep ( mdelay ) ...
def add_ip_address ( list_name , item_name ) : '''Add an IP address to an IP address list . list _ name ( str ) : The name of the specific policy IP address list to append to . item _ name ( str ) : The IP address to append to the list . CLI Example : . . code - block : : bash salt ' * ' bluecoat _ sslv ....
payload = { "jsonrpc" : "2.0" , "id" : "ID0" , "method" : "add_policy_ip_addresses" , "params" : [ list_name , { "item_name" : item_name } ] } response = __proxy__ [ 'bluecoat_sslv.call' ] ( payload , True ) return _validate_change_result ( response )
def _get_application ( self , subdomain ) : """Return a WSGI application for subdomain . The subdomain is passed to the create _ application constructor as a keyword argument . : param subdomain : Subdomain to get or create an application with"""
with self . lock : app = self . instances . get ( subdomain ) if app is None : app = self . create_application ( subdomain = subdomain ) self . instances [ subdomain ] = app return app
def add ( self , * args , ** kwargs ) : """Add Cookie objects by their names , or create new ones under specified names . Any unnamed arguments are interpreted as existing cookies , and are added under the value in their . name attribute . With keyword arguments , the key is interpreted as the cookie name a...
# Only the first one is accessible through the main interface , # others accessible through get _ all ( all _ cookies ) . for cookie in args : self . all_cookies . append ( cookie ) if cookie . name in self : continue self [ cookie . name ] = cookie for key , value in kwargs . items ( ) : cookie...
def log_entry_encode ( self , id , num_logs , last_log_num , time_utc , size ) : '''Reply to LOG _ REQUEST _ LIST id : Log id ( uint16 _ t ) num _ logs : Total number of logs ( uint16 _ t ) last _ log _ num : High log number ( uint16 _ t ) time _ utc : UTC timestamp of log in seconds since 1970 , or 0 if no...
return MAVLink_log_entry_message ( id , num_logs , last_log_num , time_utc , size )
def _autodetect_std ( self , cmd = "" , search_patterns = None , re_flags = re . I , priority = 99 ) : """Standard method to try to auto - detect the device type . This method will be called for each device _ type present in SSH _ MAPPER _ BASE dict ( ' dispatch ' key ) . It will attempt to send a command and m...
invalid_responses = [ r"% Invalid input detected" , r"syntax error, expecting" , r"Error: Unrecognized command" , r"%Error" , r"command not found" , r"Syntax Error: unexpected argument" , ] if not cmd or not search_patterns : return 0 try : # _ send _ command _ wrapper will use already cached results if available ...
def center_end ( r , window_size ) : """Center a region on its end and expand it to window _ size bases . : return : the new region ."""
res = copy . copy ( r ) res . start = res . end - window_size / 2 res . end = res . start + window_size return res
def create ( cls , cli , src_resource_id , dst_resource_id , max_time_out_of_sync , name = None , members = None , auto_initiate = None , hourly_snap_replication_policy = None , daily_snap_replication_policy = None , replicate_existing_snaps = None , remote_system = None , src_spa_interface = None , src_spb_interface =...
req_body = cli . make_body ( srcResourceId = src_resource_id , dstResourceId = dst_resource_id , maxTimeOutOfSync = max_time_out_of_sync , members = members , autoInitiate = auto_initiate , name = name , hourlySnapReplicationPolicy = hourly_snap_replication_policy , dailySnapReplicationPolicy = daily_snap_replication_p...
def active_vectors_info ( self ) : """Return the active scalar ' s field and name : [ field , name ]"""
if not hasattr ( self , '_active_vectors_info' ) : self . _active_vectors_info = [ POINT_DATA_FIELD , None ] # field and name _ , name = self . _active_vectors_info # rare error where scalar name isn ' t a valid scalar if name not in self . point_arrays : if name not in self . cell_arrays : name = N...
def tree_to_dot ( tree : BubbleTree , dotfile : str = None , render : bool = False ) : """Write in dotfile a graph equivalent to those depicted in bubble file See http : / / graphviz . readthedocs . io / en / latest / examples . html # cluster - py for graphviz API"""
graph = tree_to_graph ( tree ) path = None if dotfile : # first save the dot file . path = graph . save ( dotfile ) if render : # secondly , show it . # As the dot file is known by the Graph object , # it will be placed around the dot file . graph . view ( ) return path
def _record_count ( self ) : """Get number of records in file . This is maybe suboptimal because we have to seek to the end of the file . Side effect : returns file position to record _ start ."""
self . filepath_or_buffer . seek ( 0 , 2 ) total_records_length = ( self . filepath_or_buffer . tell ( ) - self . record_start ) if total_records_length % 80 != 0 : warnings . warn ( "xport file may be corrupted" ) if self . record_length > 80 : self . filepath_or_buffer . seek ( self . record_start ) retur...
def fromobj ( obj ) : """Creates an OID object from the pointer to ASN1 _ OBJECT c structure . This method intended for internal use for submodules which deal with libcrypto ASN1 parsing functions , such as x509 or CMS"""
nid = libcrypto . OBJ_obj2nid ( obj ) if nid == 0 : buf = create_string_buffer ( 80 ) dotted_len = libcrypto . OBJ_obj2txt ( buf , 80 , obj , 1 ) dotted = buf [ : dotted_len ] oid = create ( dotted , dotted , dotted ) else : oid = Oid ( nid ) return oid
def get_readme ( ) : 'Get the long description from the README file'
here = path . abspath ( path . dirname ( __file__ ) ) with open ( path . join ( here , 'README.rst' ) , encoding = 'utf-8' ) as my_fd : result = my_fd . read ( ) return result
def writeSwarmDescription ( self , csvPath , outPath , predictedField = None , swarmParams = None ) : """Writes swarm description file ( JSON ) . : param csvPath : path to CSV data : param outPath : absolute or relative file path to write swarm JSON file : param predictedField : ( string ) : param swarmPara...
if self . _confluence is None : raise Exception ( "Missing Confluence! Cannot attempt operation requiring " "data without first loading the data." ) if predictedField is None : predictedField = self . _predictedField fields = self . _createFieldDescription ( ) swarmDesc = createSwarmDescription ( fields , csvPa...
def transfer ( cls , inputs , recipients , asset_id , metadata = None ) : """A simple way to generate a ` TRANSFER ` transaction . Note : Different cases for threshold conditions : Combining multiple ` inputs ` with an arbitrary number of ` recipients ` can yield interesting cases for the creation of thre...
if not isinstance ( inputs , list ) : raise TypeError ( '`inputs` must be a list instance' ) if len ( inputs ) == 0 : raise ValueError ( '`inputs` must contain at least one item' ) if not isinstance ( recipients , list ) : raise TypeError ( '`recipients` must be a list instance' ) if len ( recipients ) == 0...
def set_ytick_suffix ( self , suffix ) : """Set ticks for the y - axis . : param suffix : string added after each tick . If the value is ` degree ` or ` precent ` the corresponding symbols will be added ."""
if suffix == 'degree' : suffix = r'^\circ' elif suffix == 'percent' : suffix = r'\%' self . ticks [ 'ysuffix' ] = suffix
def _check_linux ( self , instance ) : """_ check _ linux can be run inside a container and still collects the network metrics from the host For that procfs _ path can be set to something like " / host / proc " When a custom procfs _ path is set , the collect _ connection _ state option is ignored"""
proc_location = self . agentConfig . get ( 'procfs_path' , '/proc' ) . rstrip ( '/' ) custom_tags = instance . get ( 'tags' , [ ] ) if Platform . is_containerized ( ) and proc_location != "/proc" : proc_location = "%s/1" % proc_location if self . _is_collect_cx_state_runnable ( proc_location ) : try : s...
def get_kba_values ( kb_name , searchname = "" , searchtype = "s" ) : """Return an array of values " authority file " type = just values . : param kb _ name : name of kb : param searchname : get these values , according to searchtype : param searchtype : s = substring , e = exact , , sw = startswith"""
if searchtype == 's' and searchname : searchname = '%' + searchname + '%' if searchtype == 'sw' and searchname : # startswith searchname = searchname + '%' if not searchname : searchname = '%' query = db . session . query ( models . KnwKBRVAL ) . join ( models . KnwKB ) . filter ( models . KnwKBRVAL . m_val...
def check_result ( running , recurse = False , highstate = None ) : '''Check the total return value of the run and determine if the running dict has any issues'''
if not isinstance ( running , dict ) : return False if not running : return False ret = True for state_id , state_result in six . iteritems ( running ) : expected_type = dict # The _ _ extend _ _ state is a list if "__extend__" == state_id : expected_type = list if not recurse and not is...
def _readtoken ( self , name , pos , length ) : """Reads a token from the bitstring and returns the result ."""
if length is not None and int ( length ) > self . length - pos : raise ReadError ( "Reading off the end of the data. " "Tried to read {0} bits when only {1} available." . format ( int ( length ) , self . length - pos ) ) try : val = name_to_read [ name ] ( self , length , pos ) return val , pos + length exc...
def edit_message_media ( self , chat_id : Union [ int , str ] , message_id : int , media : InputMedia , reply_markup : "pyrogram.InlineKeyboardMarkup" = None ) -> "pyrogram.Message" : """Use this method to edit audio , document , photo , or video messages . If a message is a part of a message album , then it can ...
style = self . html if media . parse_mode . lower ( ) == "html" else self . markdown caption = media . caption if isinstance ( media , InputMediaPhoto ) : if os . path . exists ( media . media ) : media = self . send ( functions . messages . UploadMedia ( peer = self . resolve_peer ( chat_id ) , media = typ...
def send_query ( self , query ) : '''This method is called by the tasks . It is redirected to the submodule .'''
if self . __switched_on : return self . __solr_server_connector . send_query ( query ) else : msg = 'Not sending query' LOGGER . debug ( msg ) raise esgfpid . exceptions . SolrSwitchedOff ( msg )
def open ( filename , frame = 'unspecified' ) : """Creates a NormalCloudImage from a file . Parameters filename : : obj : ` str ` The file to load the data from . Must be one of . png , . jpg , . npy , or . npz . frame : : obj : ` str ` A string representing the frame of reference in which the new image...
data = Image . load_data ( filename ) return NormalCloudImage ( data , frame )
def push_external_commands ( self , commands ) : """Send a HTTP request to the satellite ( POST / r _ un _ external _ commands ) to send the external commands to the satellite : param results : Results list to send : type results : list : return : True on success , False on failure : rtype : bool"""
logger . debug ( "Pushing %d external commands" , len ( commands ) ) return self . con . post ( '_run_external_commands' , { 'cmds' : commands } , wait = True )
def p_iteration_statement_1 ( self , p ) : """iteration _ statement : DO statement WHILE LPAREN expr RPAREN SEMI | DO statement WHILE LPAREN expr RPAREN AUTOSEMI"""
p [ 0 ] = self . asttypes . DoWhile ( predicate = p [ 5 ] , statement = p [ 2 ] ) p [ 0 ] . setpos ( p )
def get_sphinx_doc ( self , name , depth = None , exclude = None , width = 72 , error = False , raised = False , no_comment = False , ) : r"""Return an exception list marked up in ` reStructuredText ` _ . : param name : Name of the callable ( method , function or class property ) to generate exceptions document...
# pylint : disable = R0101 , R0204 , R0912 , R0915 , R0916 if depth and ( ( not isinstance ( depth , int ) ) or ( isinstance ( depth , int ) and ( depth < 0 ) ) ) : raise RuntimeError ( "Argument `depth` is not valid" ) if exclude and ( ( not isinstance ( exclude , list ) ) or ( isinstance ( exclude , list ) and an...
def get_dummy_dataloader ( dataloader , target_shape ) : """Return a dummy data loader which returns a fixed data batch of target shape"""
data_iter = enumerate ( dataloader ) _ , data_batch = next ( data_iter ) logging . debug ( 'Searching target batch shape: %s' , target_shape ) while data_batch [ 0 ] . shape != target_shape : logging . debug ( 'Skip batch with shape %s' , data_batch [ 0 ] . shape ) _ , data_batch = next ( data_iter ) logging . ...
def libvlc_video_get_chapter_description ( p_mi , i_title ) : '''Get the description of available chapters for specific title . @ param p _ mi : the media player . @ param i _ title : selected title . @ return : list containing description of available chapter for title i _ title .'''
f = _Cfunctions . get ( 'libvlc_video_get_chapter_description' , None ) or _Cfunction ( 'libvlc_video_get_chapter_description' , ( ( 1 , ) , ( 1 , ) , ) , None , ctypes . POINTER ( TrackDescription ) , MediaPlayer , ctypes . c_int ) return f ( p_mi , i_title )
def _to_json_type ( obj , classkey = None ) : """Recursively convert the object instance into a valid JSON type ."""
if isinstance ( obj , dict ) : data = { } for ( k , v ) in obj . items ( ) : data [ k ] = _to_json_type ( v , classkey ) return data elif hasattr ( obj , "_ast" ) : return _to_json_type ( obj . _ast ( ) ) elif hasattr ( obj , "__iter__" ) : return [ _to_json_type ( v , classkey ) for v in ob...
def get_parameter_value_from_file_names ( files , parameters = None , unique = False , sort = True ) : """Takes a list of files , searches for the parameter name in the file name and returns a ordered dict with the file name in the first dimension and the corresponding parameter value in the second . The file n...
# unique = False logging . debug ( 'Get the parameter: ' + str ( parameters ) + ' values from the file names of ' + str ( len ( files ) ) + ' files' ) files_dict = collections . OrderedDict ( ) if parameters is None : # special case , no parameter defined return files_dict if isinstance ( parameters , basestring ) ...
def _getMethodNamePrefix ( self , node ) : """Return the prefix of this method based on sibling methods . @ param node : the current node"""
targetName = node . name for sibling in node . parent . nodes_of_class ( type ( node ) ) : if sibling is node : # We are on the same node in parent so we skip it . continue prefix = self . _getCommonStart ( targetName , sibling . name ) if not prefix . rstrip ( '_' ) : # We ignore prefixes which are...
def update ( self , actions = values . unset ) : """Update the TaskActionsInstance : param dict actions : The JSON string that specifies the actions that instruct the Assistant on how to perform the task : returns : Updated TaskActionsInstance : rtype : twilio . rest . autopilot . v1 . assistant . task . task...
return self . _proxy . update ( actions = actions , )
def create ( model , count , * args , ** kwargs ) : '''Create * count * instances of * model * using the either an appropiate autofixture that was : ref : ` registry < registry > ` or fall back to the default : class : ` AutoFixture ` class . * model * can be a model class or its string representation ( e . g...
from . compat import get_model if isinstance ( model , string_types ) : model = get_model ( * model . split ( '.' , 1 ) ) if model in REGISTRY : autofixture_class = REGISTRY [ model ] else : autofixture_class = AutoFixture # Get keyword arguments that the create _ one method accepts and pass them # into cre...
def remove ( self , name ) : '''Remove a column of data . Args : name ( str ) : name of the column to remove Returns : None . . note : : If the column name does not exist , a warning is issued .'''
try : del self . data [ name ] except ( ValueError , KeyError ) : import warnings warnings . warn ( "Unable to find column '%s' in data source" % name )
def get_property ( self , name ) : """Gets the given property of the element . : Args : - name - Name of the property to retrieve . : Usage : text _ length = target _ element . get _ property ( " text _ length " )"""
try : return self . _execute ( Command . GET_ELEMENT_PROPERTY , { "name" : name } ) [ "value" ] except WebDriverException : # if we hit an end point that doesnt understand getElementProperty lets fake it return self . parent . execute_script ( 'return arguments[0][arguments[1]]' , self , name )
def _sensoryComputeLearningMode ( self , anchorInput ) : """Associate this location with a sensory input . Subsequently , anchorInput will activate the current location during anchor ( ) . @ param anchorInput ( numpy array ) A sensory input . This will often come from a feature - location pair layer ."""
overlaps = self . connections . computeActivity ( anchorInput , self . connectedPermanence ) activeSegments = np . where ( overlaps >= self . activationThreshold ) [ 0 ] potentialOverlaps = self . connections . computeActivity ( anchorInput ) matchingSegments = np . where ( potentialOverlaps >= self . learningThreshold...
def has_bom ( self , f ) : """Check for UTF8 , UTF16 , and UTF32 BOMs ."""
content = f . read ( 4 ) encoding = None m = RE_UTF_BOM . match ( content ) if m is not None : if m . group ( 1 ) : encoding = 'utf-8-sig' elif m . group ( 2 ) : encoding = 'utf-32' elif m . group ( 3 ) : encoding = 'utf-32' elif m . group ( 4 ) : encoding = 'utf-16' ...
def _split_rules ( rules ) : '''Split rules with combined grants into individual rules . Amazon returns a set of rules with the same protocol , from and to ports together as a single rule with a set of grants . Authorizing and revoking rules , however , is done as a split set of rules . This function splits t...
split = [ ] for rule in rules : ip_protocol = rule . get ( 'ip_protocol' ) to_port = rule . get ( 'to_port' ) from_port = rule . get ( 'from_port' ) grants = rule . get ( 'grants' ) for grant in grants : _rule = { 'ip_protocol' : ip_protocol , 'to_port' : to_port , 'from_port' : from_port } ...
def get_parameters ( tp ) : """Return type parameters of a parameterizable type as a tuple in lexicographic order . Parameterizable types are generic types , unions , tuple types and callable types . Examples : : get _ parameters ( int ) = = ( ) get _ parameters ( Generic ) = = ( ) get _ parameters ( Unio...
if NEW_TYPING : if ( isinstance ( tp , _GenericAlias ) or isinstance ( tp , type ) and issubclass ( tp , Generic ) and tp is not Generic ) : return tp . __parameters__ return ( ) if ( is_generic_type ( tp ) or is_union_type ( tp ) or is_callable_type ( tp ) or is_tuple_type ( tp ) ) : return tp . __...
def _get_array ( val , shape , default = None , dtype = np . float64 ) : """Ensure an object is an array with the specified shape ."""
assert val is not None or default is not None if hasattr ( val , '__len__' ) and len ( val ) == 0 : # pragma : no cover val = None # Do nothing if the array is already correct . if ( isinstance ( val , np . ndarray ) and val . shape == shape and val . dtype == dtype ) : return val out = np . zeros ( shape , dty...
def make_symbolic ( self , name , addr , length = None ) : """Replaces ` length ` bytes starting at ` addr ` with a symbolic variable named name . Adds a constraint equaling that symbolic variable to the value previously at ` addr ` , and returns the variable ."""
l . debug ( "making %s bytes symbolic" , length ) if isinstance ( addr , str ) : addr , length = self . state . arch . registers [ addr ] else : if length is None : raise Exception ( "Unspecified length!" ) r = self . load ( addr , length ) v = self . get_unconstrained_bytes ( name , r . size ( ) ) self...
def get_directory_list_doc ( self , configs ) : """JSON dict description of a protorpc . remote . Service in list format . Args : configs : Either a single dict or a list of dicts containing the service configurations to list . Returns : dict , The directory list document as a JSON dict ."""
if not isinstance ( configs , ( tuple , list ) ) : configs = [ configs ] util . check_list_type ( configs , dict , 'configs' , allow_none = False ) return self . __directory_list_descriptor ( configs )
def rectangles_from_histogram ( H ) : """Largest Rectangular Area in a Histogram : param H : histogram table : returns : area , left , height , right , rect . is [ 0 , height ] * [ left , right ) : complexity : linear"""
best = ( float ( '-inf' ) , 0 , 0 , 0 ) S = [ ] H2 = H + [ float ( '-inf' ) ] # extra element to empty the queue for right in range ( len ( H2 ) ) : x = H2 [ right ] left = right while len ( S ) > 0 and S [ - 1 ] [ 1 ] >= x : left , height = S . pop ( ) # first element is area of candidate ...
def remapOpenCv ( im , coords ) : """Remap an image using OpenCV . See : func : ` remap ` for parameters ."""
# required for older OpenCV versions im = np . require ( im , im . dtype , 'C' ) return cv2 . remap ( im , coords , None , cv2 . INTER_LANCZOS4 )
def get_user_properties ( self ) : """Return the properties of the User"""
user = self . context . getUser ( ) # No User linked , nothing to do if user is None : return { } out = { } plone_user = user . getUser ( ) userid = plone_user . getId ( ) for sheet in plone_user . listPropertysheets ( ) : ps = plone_user . getPropertysheet ( sheet ) out . update ( dict ( ps . propertyItems...
def contains_as_type ( self , value_type , value ) : """Checks if this array contains a value . The check before comparison converts elements and the value to type specified by type code . : param value _ type : a type code that defines a type to convert values before comparison : param value : a value to be ...
typed_value = TypeConverter . to_nullable_type ( value_type , value ) for element in self : typed_element = TypeConverter . to_type ( value_type , element ) if typed_value == None and typed_element == None : return True if typed_value == None or typed_element == None : continue if typed_...
def req_withdraw ( self , address , amount , currency , fee = 0 , addr_tag = "" ) : """申请提现虚拟币 : param address _ id : : param amount : : param currency : btc , ltc , bcc , eth , etc . . . ( 火币Pro支持的币种 ) : param fee : : param addr - tag : : return : { " status " : " ok " , " data " : 700"""
params = { 'address' : address , 'amount' : amount , 'currency' : currency , 'fee' : fee , 'addr-tag' : addr_tag } path = '/v1/dw/withdraw/api/create' def _wrapper ( _func ) : @ wraps ( _func ) def handle ( ) : _func ( api_key_post ( params , path ) ) return handle return _wrapper
def get_true_capacity ( self ) : """Get the capacity for the scheduled activity , taking into account activity defaults and overrides ."""
c = self . capacity if c is not None : return c else : if self . rooms . count ( ) == 0 and self . activity . default_capacity : # use activity - level override return self . activity . default_capacity rooms = self . get_true_rooms ( ) return EighthRoom . total_capacity_of_rooms ( rooms )
def click_text ( self , text , exact_match = False ) : """Click text identified by ` ` text ` ` . By default tries to click first text involves given ` ` text ` ` , if you would like to click exactly matching text , then set ` ` exact _ match ` ` to ` True ` . If there are multiple use of ` ` text ` ` and you...
self . _element_find_by_text ( text , exact_match ) . click ( )
def rmdir_p ( self ) : """Like : meth : ` rmdir ` , but does not raise an exception if the directory is not empty or does not exist ."""
suppressed = FileNotFoundError , FileExistsError , DirectoryNotEmpty with contextlib . suppress ( suppressed ) : with DirectoryNotEmpty . translate ( ) : self . rmdir ( ) return self
def delete_lambda_deprecated ( awsclient , function_name , s3_event_sources = [ ] , time_event_sources = [ ] , delete_logs = False ) : # FIXME : mutable default arguments ! """Deprecated : please use delete _ lambda ! : param awsclient : : param function _ name : : param s3 _ event _ sources : : param time ...
unwire_deprecated ( awsclient , function_name , s3_event_sources = s3_event_sources , time_event_sources = time_event_sources , alias_name = ALIAS_NAME ) client_lambda = awsclient . get_client ( 'lambda' ) response = client_lambda . delete_function ( FunctionName = function_name ) if delete_logs : log_group_name = ...
def is_subclass ( o , bases ) : """Similar to the ` ` issubclass ` ` builtin , but does not raise a ` ` TypeError ` ` if either ` ` o ` ` or ` ` bases ` ` is not an instance of ` ` type ` ` . Example : : > > > is _ subclass ( IOError , Exception ) True > > > is _ subclass ( Exception , None ) False > ...
try : return _issubclass ( o , bases ) except TypeError : pass if not isinstance ( o , type ) : return False if not isinstance ( bases , tuple ) : return False bases = tuple ( b for b in bases if isinstance ( b , type ) ) return _issubclass ( o , bases )
def prune ( args ) : """% prog prune best . edges Prune overlap graph ."""
from collections import defaultdict p = OptionParser ( prune . __doc__ ) add_graph_options ( p ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) bestedges , = args G = read_graph ( bestedges , maxerr = opts . maxerr ) reads_to_ctgs = parse_ctgs ( bestedges , opts ....
def validate ( self ) : """Applies all defined validation to the current state of the object , and raises an error if they are not all met . Raises : ValidationError : if validations do not pass"""
missing = self . missing_property_names ( ) if len ( missing ) > 0 : raise validators . ValidationError ( "'{0}' are required attributes for {1}" . format ( missing , self . __class__ . __name__ ) ) for prop , val in six . iteritems ( self . _properties ) : if val is None : continue if isinstance ( ...
async def get_alarms ( self ) : """Get alarms for a Netdata instance ."""
url = '{}{}' . format ( self . base_url , self . endpoint ) try : with async_timeout . timeout ( 5 , loop = self . _loop ) : response = await self . _session . get ( url ) _LOGGER . debug ( "Response from Netdata: %s" , response . status ) data = await response . text ( ) _LOGGER . debug ( data ...
def status_mute ( self , id ) : """Mute notifications for a status . Returns a ` toot dict ` _ with the now muted status"""
id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/mute' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
def _generic_signal_handler ( self , signal_type ) : """Function for handling both SIGTERM and SIGINT"""
print ( "</pre>" ) message = "Got " + signal_type + ". Failing gracefully..." self . timestamp ( message ) self . fail_pipeline ( KeyboardInterrupt ( signal_type ) , dynamic_recover = True ) sys . exit ( 1 )
def auth_complete ( self ) : """Whether the authentication handshake is complete during connection initialization . : rtype : bool"""
timeout = False auth_in_progress = False if self . _connection . cbs : timeout , auth_in_progress = self . _auth . handle_token ( ) if timeout is None and auth_in_progress is None : _logger . debug ( "No work done." ) return False if timeout : raise compat . TimeoutException ( "Authorization...
def footer_length ( header ) : """Calculates the ciphertext message footer length , given a complete header . : param header : Complete message header object : type header : aws _ encryption _ sdk . structures . MessageHeader : rtype : int"""
footer_length = 0 if header . algorithm . signing_algorithm_info is not None : footer_length += 2 # Signature Length footer_length += header . algorithm . signature_len # Signature return footer_length
async def create_task ( app : web . Application , coro : Coroutine , * args , ** kwargs ) -> asyncio . Task : """Convenience function for calling ` TaskScheduler . create ( coro ) ` This will use the default ` TaskScheduler ` to create a new background task . Example : import asyncio from datetime import da...
return await get_scheduler ( app ) . create ( coro , * args , ** kwargs )