signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def reset ( self ) : """Reset the estimates of mean and variance . Resets the full state of this class . Returns : Operation ."""
with tf . name_scope ( self . _name + '/reset' ) : return tf . group ( self . _count . assign ( 0 ) , self . _mean . assign ( tf . zeros_like ( self . _mean ) ) , self . _var_sum . assign ( tf . zeros_like ( self . _var_sum ) ) )
def _send_offset_fetch_request ( self , partitions ) : """Fetch the committed offsets for a set of partitions . This is a non - blocking call . The returned future can be polled to get the actual offsets returned from the broker . Arguments : partitions ( list of TopicPartition ) : the partitions to fetch ...
assert self . config [ 'api_version' ] >= ( 0 , 8 , 1 ) , 'Unsupported Broker API' assert all ( map ( lambda k : isinstance ( k , TopicPartition ) , partitions ) ) if not partitions : return Future ( ) . success ( { } ) node_id = self . coordinator ( ) if node_id is None : return Future ( ) . failure ( Errors ....
def compile ( self , source , path = None ) : """Compile source to a ready to run template . : param source : The template to compile - should be a unicode string : return : A template function ready to execute"""
container = self . _generate_code ( source ) def make_module_name ( name , suffix = None ) : output = 'pybars._templates.%s' % name if suffix : output += '_%s' % suffix return output if not path : path = '_template' generate_name = True else : path = path . replace ( '\\' , '/' ) pat...
def convert ( cls , content , input_format , output_format ) : """Convert transcript ` content ` from ` input _ format ` to ` output _ format ` . Arguments : content : Transcript content byte - stream . input _ format : Input transcript format . output _ format : Output transcript format . Accepted input ...
assert input_format in ( 'srt' , 'sjson' ) assert output_format in ( 'srt' , 'sjson' ) # Decode the content with utf - 8 - sig which will also # skip byte order mark ( BOM ) character if found . content = content . decode ( 'utf-8-sig' ) if input_format == output_format : return content if input_format == 'srt' : ...
def parse ( self , channel_id , payload ) : '''Parse a header frame for a channel given a Reader payload .'''
class_id = payload . read_short ( ) weight = payload . read_short ( ) size = payload . read_longlong ( ) properties = { } # The AMQP spec is overly - complex when it comes to handling header # frames . The spec says that in addition to the first 16bit field , # additional ones can follow which / may / then be in the pr...
def randmatrix ( m , n , random_seed = None ) : """Creates an m x n matrix of random values drawn using the Xavier Glorot method ."""
val = np . sqrt ( 6.0 / ( m + n ) ) np . random . seed ( random_seed ) return np . random . uniform ( - val , val , size = ( m , n ) )
def cli ( ctx , transcript = { } , suppress_history = False , suppress_events = False , organism = "" , sequence = "" ) : """[ UNTESTED ] Add a transcript to a feature Output : A standard apollo feature dictionary ( { " features " : [ { . . . } ] } )"""
return ctx . gi . annotations . add_transcript ( transcript = transcript , suppress_history = suppress_history , suppress_events = suppress_events , organism = organism , sequence = sequence )
def last_updated ( self ) : '''Return the last _ updated time of the current request item : return : A DateTime object : rettype : datetetime . datetime'''
key = self . get_key_from_request ( ) max_age = self . get_max_age ( ) if max_age == 0 : return datetime . fromtimestamp ( Storage . start_time ) ttl = self . get_storage ( ) . ttl ( key ) if ttl >= 0 : return datetime . now ( ) - timedelta ( seconds = ( max_age - ttl ) ) if ttl == - 1 : # Per Redis docs : - 1 ...
def local_run ( ) : """Whether we should hit GCS dev appserver stub ."""
server_software = os . environ . get ( 'SERVER_SOFTWARE' ) if server_software is None : return True if 'remote_api' in server_software : return False if server_software . startswith ( ( 'Development' , 'testutil' ) ) : return True return False
def team_districts ( self , team ) : """Get districts a team has competed in . : param team : Team to get data on . : return : List of District objects ."""
return [ District ( raw ) for raw in self . _get ( 'team/%s/districts' % self . team_key ( team ) ) ]
def get_bel_stmts ( self , filter = False ) : """Get relevant statements from the BEL large corpus . Performs a series of neighborhood queries and then takes the union of all the statements . Because the query process can take a long time for large gene lists , the resulting list of statements are cached in a...
if self . basename is not None : bel_stmt_path = '%s_bel_stmts.pkl' % self . basename # Check for cached BEL stmt file if self . basename is not None and os . path . isfile ( bel_stmt_path ) : logger . info ( "Loading BEL statements from %s" % bel_stmt_path ) with open ( bel_stmt_path , 'rb' ) as f : ...
def get_service ( self , bundle , reference ) : # type : ( Any , ServiceReference ) - > Any """Retrieves the service corresponding to the given reference : param bundle : The bundle requiring the service : param reference : A service reference : return : The requested service : raise BundleException : The s...
with self . __svc_lock : if reference . is_factory ( ) : return self . __get_service_from_factory ( bundle , reference ) # Be sure to have the instance try : service = self . __svc_registry [ reference ] # Indicate the dependency imports = self . __bundle_imports . setdefault...
def hill_i ( self , x , threshold = 0.1 , power = 2 ) : """Inhibiting hill function . Is equivalent to 1 - hill _ a ( self , x , power , threshold ) ."""
x_pow = np . power ( x , power ) threshold_pow = np . power ( threshold , power ) return threshold_pow / ( x_pow + threshold_pow )
def produce_fake_hash ( x ) : """Produce random , binary features , totally irrespective of the content of x , but in the same shape as x ."""
h = np . random . binomial ( 1 , 0.5 , ( x . shape [ 0 ] , 1024 ) ) packed = np . packbits ( h , axis = - 1 ) . view ( np . uint64 ) return zounds . ArrayWithUnits ( packed , [ x . dimensions [ 0 ] , zounds . IdentityDimension ( ) ] )
def register ( self , src , trg , trg_mask = None , src_mask = None ) : """Implementation of pair - wise registration using thunder - registration For more information on the model estimation , refer to https : / / github . com / thunder - project / thunder - registration This function takes two 2D single chann...
# Initialise instance of CrossCorr object ccreg = registration . CrossCorr ( ) # padding _ value = 0 # Compute translation between pair of images model = ccreg . fit ( src , reference = trg ) # Get translation as an array translation = [ - x for x in model . toarray ( ) . tolist ( ) [ 0 ] ] # Fill in transformation mat...
def handleImplicitCheck ( self ) : """Checkboxes are hidden when inside of a RadioGroup as a selection of the Radio button is an implicit selection of the Checkbox . As such , we have to manually " check " any checkbox as needed ."""
for button , widget in zip ( self . radioButtons , self . widgets ) : if isinstance ( widget , CheckBox ) : if button . GetValue ( ) : # checked widget . setValue ( True ) else : widget . setValue ( False )
def get_top_albums ( self , limit = None , cacheable = True ) : """Returns a list of the top albums ."""
params = self . _get_params ( ) if limit : params [ "limit" ] = limit return self . _get_things ( "getTopAlbums" , "album" , Album , params , cacheable )
def loads ( self , msg , encoding = None , raw = False ) : '''Run the correct loads serialization format : param encoding : Useful for Python 3 support . If the msgpack data was encoded using " use _ bin _ type = True " , this will differentiate between the ' bytes ' type and the ' str ' type by decoding co...
try : def ext_type_decoder ( code , data ) : if code == 78 : data = salt . utils . stringutils . to_unicode ( data ) return datetime . datetime . strptime ( data , '%Y%m%dT%H:%M:%S.%f' ) return data gc . disable ( ) # performance optimization for msgpack if msgpac...
def _get_example_values ( self , route : str , annotation : ResourceAnnotation ) -> Dict [ str , Any ] : """Gets example values for all properties in the annotation ' s schema . : param route : The route to get example values for . : type route : werkzeug . routing . Rule for a flask api . : param annotation ...
defined_values = self . defined_example_values . get ( ( annotation . http_method . lower ( ) , str ( route ) ) ) if defined_values and not defined_values [ 'update' ] : return defined_values [ 'values' ] # If we defined a req _ obj _ type for the logic , use that type ' s # example values instead of the annotated ...
def check_validation_level ( validation_level ) : """Validate the given validation level : type validation _ level : ` ` int ` ` : param validation _ level : validation level ( see : class : ` hl7apy . consts . VALIDATION _ LEVEL ` ) : raises : : exc : ` hl7apy . exceptions . UnknownValidationLevel ` if the g...
if validation_level not in ( VALIDATION_LEVEL . QUIET , VALIDATION_LEVEL . STRICT , VALIDATION_LEVEL . TOLERANT ) : raise UnknownValidationLevel
def result ( self ) -> workflow . IntervalGeneratorType : """Generate intervals indicating the valid sentences ."""
config = cast ( SentenceSegementationConfig , self . config ) index = - 1 labels = None while True : # 1 . Find the start of the sentence . start = - 1 while True : # Check the ` ` labels ` ` generated from step ( 2 ) . if labels is None : # https : / / www . python . org / dev / peps / pep - 0479/ ...
async def destroy_attachment ( self , a : Attachment ) : """destroy a match attachment | methcoro | Args : a : the attachment you want to destroy Raises : APIException"""
await self . connection ( 'DELETE' , 'tournaments/{}/matches/{}/attachments/{}' . format ( self . _tournament_id , self . _id , a . _id ) ) if a in self . attachments : self . attachments . remove ( a )
def Overlay_highlightNode ( self , highlightConfig , ** kwargs ) : """Function path : Overlay . highlightNode Domain : Overlay Method name : highlightNode Parameters : Required arguments : ' highlightConfig ' ( type : HighlightConfig ) - > A descriptor for the highlight appearance . Optional arguments :...
expected = [ 'nodeId' , 'backendNodeId' , 'objectId' ] passed_keys = list ( kwargs . keys ( ) ) assert all ( [ ( key in expected ) for key in passed_keys ] ) , "Allowed kwargs are ['nodeId', 'backendNodeId', 'objectId']. Passed kwargs: %s" % passed_keys subdom_funcs = self . synchronous_command ( 'Overlay.highlightNode...
def attach_run_command ( cmd ) : """Run a command when attaching Please do not call directly , this will execvp the command . This is to be used in conjunction with the attach method of a container ."""
if isinstance ( cmd , tuple ) : return _lxc . attach_run_command ( cmd ) elif isinstance ( cmd , list ) : return _lxc . attach_run_command ( ( cmd [ 0 ] , cmd ) ) else : return _lxc . attach_run_command ( ( cmd , [ cmd ] ) )
def _xml_tag_filter ( s : str , strip_namespaces : bool ) -> str : """Returns tag name and optionally strips namespaces . : param el : Element : param strip _ namespaces : Strip namespace prefix : return : str"""
if strip_namespaces : ns_end = s . find ( '}' ) if ns_end != - 1 : s = s [ ns_end + 1 : ] else : ns_end = s . find ( ':' ) if ns_end != - 1 : s = s [ ns_end + 1 : ] return s
def ensure_newline ( self , n ) : """Make sure there are ' n ' line breaks at the end ."""
assert n >= 0 text = self . _output . getvalue ( ) . rstrip ( '\n' ) if not text : return self . _output = StringIO ( ) self . _output . write ( text ) self . _output . write ( '\n' * n ) text = self . _output . getvalue ( ) assert text [ - n - 1 ] != '\n' assert text [ - n : ] == '\n' * n
def fd_to_td ( htilde , delta_t = None , left_window = None , right_window = None , left_beta = 8 , right_beta = 8 ) : """Converts a FD waveform to TD . A window can optionally be applied using ` ` fd _ taper ` ` to the left or right side of the waveform before being converted to the time domain . Parameters ...
if left_window is not None : start , end = left_window htilde = fd_taper ( htilde , start , end , side = 'left' , beta = left_beta ) if right_window is not None : start , end = right_window htilde = fd_taper ( htilde , start , end , side = 'right' , beta = right_beta ) return htilde . to_timeseries ( de...
def fasta_stats ( self ) : """Parse the lengths of all contigs for each sample , as well as the total GC %"""
for sample in self . metadata : # Initialise variables to store appropriate values parsed from contig records contig_lengths = list ( ) fasta_sequence = str ( ) for contig , record in sample [ self . analysistype ] . record_dict . items ( ) : # Append the length of the contig to the list contig_leng...
def _set_error_handler_callbacks ( self , app ) : """Sets the error handler callbacks used by this extension"""
@ app . errorhandler ( NoAuthorizationError ) def handle_auth_error ( e ) : return self . _unauthorized_callback ( str ( e ) ) @ app . errorhandler ( CSRFError ) def handle_csrf_error ( e ) : return self . _unauthorized_callback ( str ( e ) ) @ app . errorhandler ( ExpiredSignatureError ) def handle_expired_err...
def set_defaults ( self , default_config_params ) : """Set default values from specified ConfigParams and returns a new ConfigParams object . : param default _ config _ params : ConfigMap with default parameter values . : return : a new ConfigParams object ."""
map = StringValueMap . from_maps ( default_config_params , self ) return ConfigParams ( map )
def publish ( self , topic , message ) : """Publish an MQTT message to a topic ."""
self . connect ( ) log . info ( 'publish {}' . format ( message ) ) self . client . publish ( topic , message )
def show ( self , rows : int = 5 , dataframe : pd . DataFrame = None ) -> pd . DataFrame : """Display info about the dataframe : param rows : number of rows to show , defaults to 5 : param rows : int , optional : param dataframe : a pandas dataframe , defaults to None : param dataframe : pd . DataFrame , op...
try : if dataframe is not None : df = dataframe else : df = self . df if df is None : self . warning ( "Dataframe is empty: nothing to show" ) return num = len ( df . columns . values ) except Exception as e : self . err ( e , self . show , "Can not show dataframe" ) ...
def bootstrap ( ) : '''Patches the ' site ' module such that the bootstrap functions for registering the post import hook callback functions are called as the last thing done when initialising the Python interpreter . This function would normally be called from the special ' . pth ' file .'''
global _patched if _patched : return _patched = True # We want to do our real work as the very last thing in the ' site ' # module when it is being imported so that the module search path is # initialised properly . What is the last thing executed depends on # whether the ' usercustomize ' module support is enabled...
def get_authorization_session_for_vault ( self , vault_id ) : """Gets an ` ` AuthorizationSession ` ` which is responsible for performing authorization checks for the given vault . arg : vault _ id ( osid . id . Id ) : the ` ` Id ` ` of the vault return : ( osid . authorization . AuthorizationSession ) - ` ` an...
if not self . supports_authorization ( ) : raise errors . Unimplemented ( ) # Also include check to see if the catalog Id is found otherwise raise errors . NotFound # pylint : disable = no - member return sessions . AuthorizationSession ( vault_id , runtime = self . _runtime )
def gevent_start ( self ) : """Helper method to start the node for gevent - based applications ."""
import gevent import gevent . select self . _poller_greenlet = gevent . spawn ( self . poll ) self . _select = gevent . select . select self . heartbeat ( ) self . update ( )
def Run ( self , unused_arg ) : """This kills us with no cleanups ."""
logging . debug ( "Disabling service" ) win32serviceutil . ChangeServiceConfig ( None , config . CONFIG [ "Nanny.service_name" ] , startType = win32service . SERVICE_DISABLED ) svc_config = QueryService ( config . CONFIG [ "Nanny.service_name" ] ) if svc_config [ 1 ] == win32service . SERVICE_DISABLED : logging . i...
def add_where_when ( voevent , coords , obs_time , observatory_location , allow_tz_naive_datetime = False ) : """Add details of an observation to the WhereWhen section . We Args : voevent ( : class : ` Voevent ` ) : Root node of a VOEvent etree . coords ( : class : ` . Position2D ` ) : Sky co - ordinates of...
# . . todo : : Implement TimeError using datetime . timedelta if obs_time . tzinfo is not None : utc_naive_obs_time = obs_time . astimezone ( pytz . utc ) . replace ( tzinfo = None ) elif not allow_tz_naive_datetime : raise ValueError ( "Datetime passed without tzinfo, cannot be sure if it is really a " "UTC ti...
def _normalize_abmn ( abmn ) : """return a normalized version of abmn"""
abmn_2d = np . atleast_2d ( abmn ) abmn_normalized = np . hstack ( ( np . sort ( abmn_2d [ : , 0 : 2 ] , axis = 1 ) , np . sort ( abmn_2d [ : , 2 : 4 ] , axis = 1 ) , ) ) return abmn_normalized
def apply ( query , replacements = None , vars = None , allow_io = False , libs = ( "stdcore" , "stdmath" ) ) : """Run ' query ' on ' vars ' and return the result ( s ) . Arguments : query : A query object or string with the query . replacements : Built - time parameters to the query , either as dict or as ...
if vars is None : vars = { } if allow_io : libs = list ( libs ) libs . append ( "stdio" ) query = q . Query ( query , params = replacements ) stdcore_included = False for lib in libs : if lib == "stdcore" : stdcore_included = True # ' solve ' always includes this automatically - we don '...
def hold_sync ( self ) : """Hold syncing any state until the outermost context manager exits"""
if self . _holding_sync is True : yield else : try : self . _holding_sync = True yield finally : self . _holding_sync = False self . send_state ( self . _states_to_send ) self . _states_to_send . clear ( )
def _initialize ( self , * args , ** kwargs ) : """Initiaize the mapping matcher with constructor arguments ."""
self . items = None self . keys = None self . values = None if args : if len ( args ) != 2 : raise TypeError ( "expected exactly two positional arguments, " "got %s" % len ( args ) ) if kwargs : raise TypeError ( "expected positional or keyword arguments, not both" ) # got positional argumen...
def time_since ( self , mtype ) : '''return the time since the last message of type mtype was received'''
if not mtype in self . messages : return time . time ( ) - self . start_time return time . time ( ) - self . messages [ mtype ] . _timestamp
def dequeue ( self ) -> Tuple [ int , TItem ] : """Removes and returns an item from the priority queue . Returns : A tuple whose first element is the priority of the dequeued item and whose second element is the dequeued item . Raises : ValueError : The queue is empty ."""
if self . _len == 0 : raise ValueError ( 'BucketPriorityQueue is empty.' ) # Drop empty buckets at the front of the queue . while self . _buckets and not self . _buckets [ 0 ] : self . _buckets . pop ( 0 ) self . _offset += 1 # Pull item out of the front bucket . item = self . _buckets [ 0 ] . pop ( 0 ) pri...
def file ( input_file , light = False ) : """Import colorscheme from json file ."""
util . create_dir ( os . path . join ( CONF_DIR , "colorschemes/light/" ) ) util . create_dir ( os . path . join ( CONF_DIR , "colorschemes/dark/" ) ) theme_name = "." . join ( ( input_file , "json" ) ) bri = "light" if light else "dark" user_theme_file = os . path . join ( CONF_DIR , "colorschemes" , bri , theme_name ...
def parseDoc ( self , doc_str , format = "xml" ) : """Parse a OAI - ORE Resource Maps document . See Also : ` ` rdflib . ConjunctiveGraph . parse ` ` for documentation on arguments ."""
self . parse ( data = doc_str , format = format ) self . _ore_initialized = True return self
def _get_log_file ( self , handler ) : '''Generate log file path for a given handler Args : handler : The handler configuration dictionary for which a log file path should be generated .'''
if 'file_name_pattern' not in handler : filename = '%Y-%m-%d-%H-%M-%S-{name}.pcap' else : filename = handler [ 'file_name_pattern' ] log_file = handler [ 'log_dir' ] if 'path' in handler : log_file = os . path . join ( log_file , handler [ 'path' ] , filename ) else : log_file = os . path . join ( log_f...
def requestAttribute ( self , attrib : Attribute , sender ) : """Used to get a raw attribute from Sovrin : param attrib : attribute to add : return : number of pending txns"""
self . _attributes [ attrib . key ( ) ] = attrib req = attrib . getRequest ( sender ) if req : return self . prepReq ( req , key = attrib . key ( ) )
def matrix_to_points ( matrix , pitch , origin ) : """Convert an ( n , m , p ) matrix into a set of points for each voxel center . Parameters matrix : ( n , m , p ) bool , voxel matrix pitch : float , what pitch was the voxel matrix computed with origin : ( 3 , ) float , what is the origin of the voxel matr...
indices = np . column_stack ( np . nonzero ( matrix ) ) points = indices_to_points ( indices = indices , pitch = pitch , origin = origin ) return points
def predict_and_complete ( self , i , to_scan , columns , transitives ) : """The core Earley Predictor and Completer . At each stage of the input , we handling any completed items ( things that matched on the last cycle ) and use those to predict what should come next in the input stream . The completions and...
# Held Completions ( H in E . Scotts paper ) . node_cache = { } held_completions = { } column = columns [ i ] # R ( items ) = Ei ( column . items ) items = deque ( column ) while items : item = items . pop ( ) # remove an element , A say , from R # # # The Earley completer if item . is_complete : # # # ...
def sets ( self , values ) : """Set list of sets ."""
# if cache server is configured , save sets list if self . cache : self . cache . set ( self . app . config [ 'OAISERVER_CACHE_KEY' ] , values )
def setData ( self , data , setName = None ) : """Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names . Args : data : The dataframe containing the data to be assigned . setName : The name of the set to which the indices values of the DataFrame are to be a...
if not isinstance ( data , DataFrame ) : if pd is not None and isinstance ( data , pd . DataFrame ) : data = DataFrame . fromPandas ( data ) if setName is None : lock_and_call ( lambda : self . _impl . setData ( data . _impl ) , self . _lock ) else : lock_and_call ( lambda : self . _impl . setData (...
def load ( prefix , epoch , ctx = None , ** kwargs ) : """Load model checkpoint from file . Parameters prefix : str Prefix of model name . epoch : int epoch number of model we would like to load . ctx : Context or list of Context , optional The device context of training and prediction . kwargs : di...
symbol , arg_params , aux_params = load_checkpoint ( prefix , epoch ) return FeedForward ( symbol , ctx = ctx , arg_params = arg_params , aux_params = aux_params , begin_epoch = epoch , ** kwargs )
def erase_code_breakpoint ( self , dwProcessId , address ) : """Erases the code breakpoint at the given address . @ see : L { define _ code _ breakpoint } , L { has _ code _ breakpoint } , L { get _ code _ breakpoint } , L { enable _ code _ breakpoint } , L { enable _ one _ shot _ code _ breakpoint } , ...
bp = self . get_code_breakpoint ( dwProcessId , address ) if not bp . is_disabled ( ) : self . disable_code_breakpoint ( dwProcessId , address ) del self . __codeBP [ ( dwProcessId , address ) ]
def crop ( self , min , max ) : """Crop a region by removing coordinates outside bounds . Follows normal slice indexing conventions . Parameters min : tuple Minimum or starting bounds for each axis . max : tuple Maximum or ending bounds for each axis ."""
new = [ c for c in self . coordinates if all ( c >= min ) and all ( c < max ) ] return one ( new )
def store ( self , result , filename , pretty = True ) : """Write a result to the given file . Parameters result : memote . MemoteResult The dictionary structure of results . filename : str or pathlib . Path Store results directly to the given filename . pretty : bool , optional Whether ( default ) or...
LOGGER . info ( "Storing result in '%s'." , filename ) if filename . endswith ( ".gz" ) : with gzip . open ( filename , "wb" ) as file_handle : file_handle . write ( jsonify ( result , pretty = pretty ) . encode ( "utf-8" ) ) else : with open ( filename , "w" , encoding = "utf-8" ) as file_handle : ...
def is_undirected ( matrix ) : """Determine if the matrix reprensents a directed graph : param matrix : The matrix to tested : returns : boolean"""
if isspmatrix ( matrix ) : return sparse_allclose ( matrix , matrix . transpose ( ) ) return np . allclose ( matrix , matrix . T )
def config_dict_to_string ( dictionary ) : """Convert a given config dictionary : : dictionary [ key _ 1 ] = value _ 1 dictionary [ key _ 2 ] = value _ 2 dictionary [ key _ n ] = value _ n into the corresponding string : : key _ 1 = value _ 1 | key _ 2 = value _ 2 | . . . | key _ n = value _ n : param d...
parameters = [ ] for key in dictionary : parameters . append ( u"%s%s%s" % ( key , gc . CONFIG_STRING_ASSIGNMENT_SYMBOL , dictionary [ key ] ) ) return gc . CONFIG_STRING_SEPARATOR_SYMBOL . join ( parameters )
def check_info_validity ( self ) : """ValueError if cache differs at all from source data layer with an excepton for volume _ size which prints a warning ."""
cache_info = self . get_json ( 'info' ) if not cache_info : return fresh_info = self . vol . _fetch_info ( ) mismatch_error = ValueError ( """ Data layer info file differs from cache. Please check whether this change invalidates your cache. If VALID do one of: 1) Manually delete the cache ...
def tptnfpfn_chi ( * args , ** kwargs ) : """Calculate Chi from True Positive ( tp ) , True Negative ( tn ) , False Positive / Negative counts . Assumes that the random variable being measured is continuous rather than discrete . Reference : https : / / en . wikipedia . org / wiki / Matthews _ correlation _ c...
tp , tn , fp , fn = args_tptnfpfn ( * args , ** kwargs ) return tptnfpfn_mcc ( tp = tp , tn = tn , fp = fp , fn = fn ) ** 2. * ( tp + tn + fp + fn )
def set_insn ( self , insn ) : """Set a new raw buffer to disassemble : param insn : the buffer : type insn : string"""
self . insn = insn self . size = len ( self . insn )
def check_new_version_available ( this_version ) : """Checks if a newer version of Zappa is available . Returns True is updateable , else False ."""
import requests pypi_url = 'https://pypi.python.org/pypi/Zappa/json' resp = requests . get ( pypi_url , timeout = 1.5 ) top_version = resp . json ( ) [ 'info' ] [ 'version' ] return this_version != top_version
def users_forgot_password ( self , email , ** kwargs ) : """Send email to reset your password ."""
return self . __call_api_post ( 'users.forgotPassword' , email = email , data = kwargs )
def reply ( self , reply_comment ) : """Reply to the Message . Notes : HTML can be inserted in the string and will be interpreted properly by Outlook . Args : reply _ comment : String message to send with email ."""
payload = '{ "Comment": "' + reply_comment + '"}' endpoint = 'https://outlook.office.com/api/v2.0/me/messages/' + self . message_id + '/reply' self . _make_api_call ( 'post' , endpoint , data = payload )
def to_int ( self , number , default = 0 ) : """Returns an integer"""
try : return int ( number ) except ( KeyError , ValueError ) : return self . to_int ( default , 0 )
def hv_mv_station_load ( network ) : """Checks for over - loading of HV / MV station . Parameters network : : class : ` ~ . grid . network . Network ` Returns : pandas : ` pandas . DataFrame < dataframe > ` Dataframe containing over - loaded HV / MV stations , their apparent power at maximal over - load...
crit_stations = pd . DataFrame ( ) crit_stations = _station_load ( network , network . mv_grid . station , crit_stations ) if not crit_stations . empty : logger . debug ( '==> HV/MV station has load issues.' ) else : logger . debug ( '==> No HV/MV station load issues.' ) return crit_stations
def send_config_set ( self , config_commands = None , exit_config_mode = True , delay_factor = 1 , max_loops = 150 , strip_prompt = False , strip_command = False , config_mode_command = None , ) : """Send configuration commands down the SSH channel . config _ commands is an iterable containing all of the configur...
delay_factor = self . select_delay_factor ( delay_factor ) if config_commands is None : return "" elif isinstance ( config_commands , string_types ) : config_commands = ( config_commands , ) if not hasattr ( config_commands , "__iter__" ) : raise ValueError ( "Invalid argument passed into send_config_set" )...
def CheckDependencies ( verbose_output = True ) : """Checks the availability of the dependencies . Args : verbose _ output ( Optional [ bool ] ) : True if output should be verbose . Returns : bool : True if the dependencies are available , False otherwise ."""
print ( 'Checking availability and versions of dependencies.' ) check_result = True for module_name , version_tuple in sorted ( PYTHON_DEPENDENCIES . items ( ) ) : if not _CheckPythonModule ( module_name , version_tuple [ 0 ] , version_tuple [ 1 ] , is_required = version_tuple [ 3 ] , maximum_version = version_tupl...
def main ( ) : """Get arguments and call the execution function"""
# if less than required arguments , use the defaults if len ( sys . argv ) < 8 : print ( "Usage: %s server_url username password namespace classname " "max_open, max_pull" % sys . argv [ 0 ] ) server_url = SERVER_URL username = USERNAME password = PASSWORD namespace = TEST_NAMESPACE classname = ...
def add_router_to_hosting_device ( self , context , hosting_device_id , router_id ) : """Add a ( non - hosted ) router to a hosting device ."""
e_context = context . elevated ( ) r_hd_binding_db = self . _get_router_binding_info ( e_context , router_id ) if r_hd_binding_db . hosting_device_id : if r_hd_binding_db . hosting_device_id == hosting_device_id : return raise routertypeawarescheduler . RouterHostedByHostingDevice ( router_id = router_i...
def _merge_fields ( a , b ) : """Merge two lists of fields . Fields in ` b ` override fields in ` a ` . Fields in ` a ` are output first ."""
a_names = set ( x [ 0 ] for x in a ) b_names = set ( x [ 0 ] for x in b ) a_keep = a_names - b_names fields = [ ] for name , field in a : if name in a_keep : fields . append ( ( name , field ) ) fields . extend ( b ) return fields
def main ( ) : '''Main entry point for the mongo _ backups CLI .'''
args = docopt ( __doc__ , version = __version__ ) if args . get ( 'backup' ) : backup_database ( args ) if args . get ( 'backup_all' ) : backup_all ( args ) if args . get ( 'decrypt' ) : decrypt_file ( args . get ( '<path>' ) ) if args . get ( 'configure' ) : configure ( service = 'all' ) if args . get ...
def __send_command ( self , command , command_string = b'' , response_size = 8 ) : """send command to the terminal"""
if command not in [ const . CMD_CONNECT , const . CMD_AUTH ] and not self . is_connect : raise ZKErrorConnection ( "instance are not connected." ) buf = self . __create_header ( command , command_string , self . __session_id , self . __reply_id ) try : if self . tcp : top = self . __create_tcp_top ( buf...
def _dB_dR ( self , R ) : """Return numpy array of dB / dR from B1 up to and including Bn ."""
return - self . _HNn / R ** 3 / self . _sin_alpha ** 2 * ( 0.8 * self . _HNn + R * self . _sin_alpha )
def iter_relation ( self ) : """Iterate through all ( point , element ) pairs in the relation ."""
for point in iter_points ( self . inputs ) : yield ( point , self . restrict ( point ) )
def extract_pattern ( pattern : str , ifiles : List [ str ] ) -> Dict [ str , any ] : '''This function match pattern to a list of input files , extract and return pieces of filenames as a list of variables with keys defined by pattern .'''
res = glob_wildcards ( pattern , [ ] ) for ifile in ifiles : matched = glob_wildcards ( pattern , [ ifile ] ) for key in matched . keys ( ) : if not matched [ key ] : # env . logger . warning ( ' Filename { } does not match pattern { } . None returned . ' . format ( ifile , pattern ) ) res [...
def createFolder ( self , name ) : """Creates a folder in which items can be placed . Folders are only visible to a user and solely used for organizing content within that user ' s content space ."""
url = "%s/createFolder" % self . root params = { "f" : "json" , "title" : name } self . _folders = None return self . _post ( url = url , param_dict = params , securityHandler = self . _securityHandler , proxy_port = self . _proxy_port , proxy_url = self . _proxy_url )
def prt_tsv ( self , prt = sys . stdout ) : """Print an ASCII text format ."""
prtfmt = self . objprt . get_prtfmt_str ( self . flds_cur ) prt . write ( "{FLDS}\n" . format ( FLDS = " " . join ( self . flds_cur ) ) ) WrSectionsTxt . prt_sections ( prt , self . desc2nts [ 'sections' ] , prtfmt , secspc = True )
def __gen_pointing_file ( self , top_level_layer ) : """Creates etree representations of PAULA XML files modeling pointing relations . Pointing relations are ahierarchical edges between any two nodes ( ` ` tok ` ` , ` ` mark ` ` or ` ` struct ` ` ) . They are used to signal pointing relations between tokens (...
paula_id = '{0}.{1}.{2}_{3}_pointing' . format ( top_level_layer , self . corpus_name , self . name , top_level_layer ) self . paulamap [ 'pointing' ] [ top_level_layer ] = paula_id E , tree = gen_paula_etree ( paula_id ) pointing_edges = select_edges_by ( self . dg , layer = top_level_layer , edge_type = EdgeTypes . p...
def add_instruction ( self , reil_instruction ) : """Add an instruction for analysis ."""
for expr in self . _translator . translate ( reil_instruction ) : self . _solver . add ( expr )
def render_nocache ( self ) : """Render the ` nocache ` blocks of the content and return the whole html"""
tmpl = template . Template ( '' . join ( [ # start by loading the cache library template . BLOCK_TAG_START , 'load %s' % self . get_templatetag_module ( ) , template . BLOCK_TAG_END , # and surround the cached template by " raw " tags self . RAW_TOKEN_START , self . content , self . RAW_TOKEN_END , ] ) ) return tmpl . ...
def _load_img ( handle , target_dtype = np . float32 , size = None , ** kwargs ) : """Load image file as numpy array ."""
image_pil = PIL . Image . open ( handle , ** kwargs ) # resize the image to the requested size , if one was specified if size is not None : if len ( size ) > 2 : size = size [ : 2 ] log . warning ( "`_load_img()` received size: {}, trimming to first two dims!" . format ( size ) ) image_pil = ima...
def accounting_sample_replace ( total , data , accounting_column , prob_column = None , max_iterations = 50 ) : """Sample rows with accounting with replacement . Parameters total : int The control total the sampled rows will attempt to match . data : pandas . DataFrame Table to sample from . accounting ...
# check for probabilities p = get_probs ( data , prob_column ) # determine avg number of accounting items per sample ( e . g . persons per household ) per_sample = data [ accounting_column ] . sum ( ) / ( 1.0 * len ( data . index . values ) ) curr_total = 0 remaining = total sample_rows = pd . DataFrame ( ) closest = N...
def is_macro_name ( func_name , dialect ) : """is _ macro _ name ( func _ name : str , dialect : str ) - > bool > > > is _ macro _ name ( ' yacc : define - parser ' ) True Tests if a word is a macro using the language ' s / dialect ' s convention , e . g macros in Lisp usually start with ' def ' and ' with ...
if not func_name : return False if dialect == 'lisp' : return re . search ( '^(macro|def|do|with-)' , func_name , re . I ) if dialect == 'scheme' : return re . search ( '^(call-|def|with-)' , func_name ) if dialect == 'clojure' : return re . search ( '^(def|with)' , func_name ) if dialect == 'newlisp' :...
def update ( self , account_sid = values . unset , api_version = values . unset , friendly_name = values . unset , sms_application_sid = values . unset , sms_fallback_method = values . unset , sms_fallback_url = values . unset , sms_method = values . unset , sms_url = values . unset , status_callback = values . unset ,...
return self . _proxy . update ( account_sid = account_sid , api_version = api_version , friendly_name = friendly_name , sms_application_sid = sms_application_sid , sms_fallback_method = sms_fallback_method , sms_fallback_url = sms_fallback_url , sms_method = sms_method , sms_url = sms_url , status_callback = status_cal...
def _tag ( val , tag ) : """Surround val with < tag > < / tag >"""
if isinstance ( val , str ) : val = bytes ( val , 'utf-8' ) return ( bytes ( '<' + tag + '>' , 'utf-8' ) + val + bytes ( '</' + tag + '>' , 'utf-8' ) )
def _receive_signal ( self , progress_subscript ) : """this function takes care of signals emitted by the subscripts Args : progress _ subscript : progress of subscript"""
self . progress = self . _estimate_progress ( ) self . updateProgress . emit ( int ( self . progress ) )
def replace_option_by_id ( cls , option_id , option , ** kwargs ) : """Replace Option Replace all attributes of Option This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . replace _ option _ by _ id ( option _ id , opt...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _replace_option_by_id_with_http_info ( option_id , option , ** kwargs ) else : ( data ) = cls . _replace_option_by_id_with_http_info ( option_id , option , ** kwargs ) return data
def find_DQ_extension ( self ) : """Return the suffix for the data quality extension and the name of the file which that DQ extension should be read from ."""
dqfile = None # Look for additional file with DQ array , primarily for WFPC2 data indx = self . _filename . find ( '.fits' ) if indx > 3 : suffix = self . _filename [ indx - 4 : indx ] dqfile = self . _filename . replace ( suffix [ : 3 ] , '_c1' ) elif indx < 0 and len ( self . _filename ) > 3 and self . _filen...
def _make_validate ( self , teststep_dict , entry_json ) : """parse HAR entry response and make teststep validate . Args : entry _ json ( dict ) : " request " : { } , " response " : { " status " : 200, " headers " : [ " name " : " Content - Type " , " value " : " application / json ; charset = utf -...
teststep_dict [ "validate" ] . append ( { "eq" : [ "status_code" , entry_json [ "response" ] . get ( "status" ) ] } ) resp_content_dict = entry_json [ "response" ] . get ( "content" ) headers_mapping = utils . convert_list_to_dict ( entry_json [ "response" ] . get ( "headers" , [ ] ) ) if "Content-Type" in headers_mapp...
def sync ( self ) : """Retrieve areas from ElkM1"""
self . elk . send ( ka_encode ( ) ) self . get_descriptions ( TextDescriptions . KEYPAD . value )
def _banner_default ( self ) : """Reimplement banner creation to let the user decide if he wants a banner or not"""
# Don ' t change banner for external kernels if self . external_kernel : return '' show_banner_o = self . additional_options [ 'show_banner' ] if show_banner_o : return self . long_banner ( ) else : return self . short_banner ( )
def get_objective_bank ( self ) : """Gets the ObjectiveBank associated with this session . return : ( osid . learning . ObjectiveBank ) - the ObjectiveBank associated with this session raise : OperationFailed - unable to complete request raise : PermissionDenied - authorization failure compliance : mandat...
# This should probably be accomplished via a handcar call instead of OSID url_path = construct_url ( 'objective_banks' , bank_id = self . _catalog_idstr ) return objects . ObjectiveBank ( self . _get_request ( url_path ) )
def cells ( ) : '''# Slow'''
import time def query_db ( ) : time . sleep ( 5 ) return [ 1 , 2 , 3 , 4 , 5 ] def clean ( data ) : time . sleep ( 2 ) return [ x for x in data if x % 2 == 0 ] def myfilter ( data ) : time . sleep ( 2 ) return [ x for x in data if x >= 3 ] rows = query_db ( ) data = clean ( rows ) data , len ( d...
def read_sas ( filepath_or_buffer , format = None , index = None , encoding = None , chunksize = None , iterator = False ) : """Read SAS files stored as either XPORT or SAS7BDAT format files . Parameters filepath _ or _ buffer : string or file - like object Path to the SAS file . format : string { ' xport '...
if format is None : buffer_error_msg = ( "If this is a buffer object rather " "than a string name, you must specify " "a format string" ) filepath_or_buffer = _stringify_path ( filepath_or_buffer ) if not isinstance ( filepath_or_buffer , str ) : raise ValueError ( buffer_error_msg ) fname = fil...
def text ( self ) : """Return the String assosicated with the current text"""
if self . m_name == - 1 or self . m_event != const . TEXT : return u'' return self . sb [ self . m_name ]
def type_assert_dict ( d , kcls = None , vcls = None , allow_none = False , cast_from = None , cast_to = None , dynamic = None , objcls = None , ctor = None , ) : """Checks that every key / value in @ d is an instance of @ kcls : @ vcls Will also unmarshal JSON objects to Python objects if the value is an insta...
_check_dstruct ( d , objcls ) if ( d is None and dynamic is not None ) : d = dynamic t = type ( d ) return t ( ( _check ( k , kcls ) if kcls else k , _check ( v , vcls , allow_none , cast_from , cast_to , ctor = ctor , ) if vcls else v , ) for k , v in d . items ( ) )
def _send_file_external_with_retry ( self , http_verb , host , url , http_headers , chunk ) : """Send chunk to host , url using http _ verb . If http _ verb is PUT and a connection error occurs retry a few times . Pauses between retries . Raises if unsuccessful ."""
count = 0 retry_times = 1 if http_verb == 'PUT' : retry_times = SEND_EXTERNAL_PUT_RETRY_TIMES while True : try : return self . data_service . send_external ( http_verb , host , url , http_headers , chunk ) except requests . exceptions . ConnectionError : count += 1 if count < retry_t...
def _create_model_matrices ( self ) : """Creates model matrices / vectors Returns None ( changes model attributes )"""
self . model_Y = self . data self . model_scores = np . zeros ( ( self . X . shape [ 1 ] , self . model_Y . shape [ 0 ] + 1 ) )
def from_tri_2_sym ( tri , dim ) : """convert a upper triangular matrix in 1D format to 2D symmetric matrix Parameters tri : 1D array Contains elements of upper triangular matrix dim : int The dimension of target matrix . Returns symm : 2D array Symmetric matrix in shape = [ dim , dim ]"""
symm = np . zeros ( ( dim , dim ) ) symm [ np . triu_indices ( dim ) ] = tri return symm
def resource_type ( self , rt ) : """Set the CoRE Link Format rt attribute of the resource . : param rt : the CoRE Link Format rt attribute"""
if not isinstance ( rt , str ) : rt = str ( rt ) self . _attributes [ "rt" ] = rt