signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def forward ( self , x : torch . Tensor , mask : torch . Tensor ) -> torch . Tensor : """Follow Figure 1 ( left ) for connections ."""
x = self . sublayer [ 0 ] ( x , lambda x : self . self_attn ( x , x , x , mask ) ) return self . sublayer [ 1 ] ( x , self . feed_forward )
def get_adjusted_value ( self , asset , field , dt , perspective_dt , data_frequency , spot_value = None ) : """Returns a scalar value representing the value of the desired asset ' s field at the given dt with adjustments applied . Parameters asset : Asset The asset whose data is desired . field : { ' ope...
if spot_value is None : # if this a fetcher field , we want to use perspective _ dt ( not dt ) # because we want the new value as of midnight ( fetcher only works # on a daily basis , all timestamps are on midnight ) if self . _is_extra_source ( asset , field , self . _augmented_sources_map ) : spot_value =...
def update ( self ) : """Update the current GPS location ."""
self . _controller . update ( self . _id , wake_if_asleep = False ) data = self . _controller . get_drive_params ( self . _id ) if data : self . __longitude = data [ 'longitude' ] self . __latitude = data [ 'latitude' ] self . __heading = data [ 'heading' ] if self . __longitude and self . __latitude and se...
def restart ( name , timeout = 90 , with_deps = False , with_parents = False ) : '''Restart the named service . This issues a stop command followed by a start . Args : name : The name of the service to restart . . . note : : If the name passed is ` ` salt - minion ` ` a scheduled task is created and execu...
if 'salt-minion' in name : create_win_salt_restart_task ( ) return execute_salt_restart_task ( ) ret = set ( ) ret . add ( stop ( name = name , timeout = timeout , with_deps = with_deps , with_parents = with_parents ) ) ret . add ( start ( name = name , timeout = timeout , with_deps = with_deps , with_parents =...
def cast_value ( self , value , constraints = True ) : """https : / / github . com / frictionlessdata / tableschema - py # field"""
# Null value if value in self . __missing_values : value = None # Cast value cast_value = value if value is not None : cast_value = self . __cast_function ( value ) if cast_value == config . ERROR : raise exceptions . CastError ( ( 'Field "{field.name}" can\'t cast value "{value}" ' 'for type "{fiel...
def reset_password ( self , user , password ) : """Service method to reset a user ' s password . The same as : meth : ` change _ password ` except we this method sends a different notification email . Sends signal ` password _ reset ` . : param user : : param password : : return :"""
user . password = password self . user_manager . save ( user ) if app . config . SECURITY_SEND_PASSWORD_RESET_NOTICE_EMAIL : self . send_mail ( _ ( 'flask_unchained.bundles.security:email_subject.password_reset_notice' ) , to = user . email , template = 'security/email/password_reset_notice.html' , user = user ) pa...
def _preprocess_successor ( self , state , add_guard = True ) : # pylint : disable = unused - argument """Preprocesses the successor state . : param state : the successor state"""
# Next , simplify what needs to be simplified if o . SIMPLIFY_EXIT_STATE in state . options : state . solver . simplify ( ) if o . SIMPLIFY_EXIT_GUARD in state . options : state . scratch . guard = state . solver . simplify ( state . scratch . guard ) if o . SIMPLIFY_EXIT_TARGET in state . options : state ....
def funcSmthSpt ( aryFuncChnk , varSdSmthSpt ) : """Apply spatial smoothing to the input data . Parameters aryFuncChnk : np . array TODO varSdSmthSpt : float ( ? ) Extent of smoothing . Returns aryFuncChnk : np . array Smoothed data ."""
varNdim = aryFuncChnk . ndim # Number of time points in this chunk : varNumVol = aryFuncChnk . shape [ - 1 ] # Loop through volumes : if varNdim == 4 : for idxVol in range ( 0 , varNumVol ) : aryFuncChnk [ : , : , : , idxVol ] = gaussian_filter ( aryFuncChnk [ : , : , : , idxVol ] , varSdSmthSpt , order = 0...
def RemoveSession ( self , session_path ) : '''OBEX method to remove an existing transfer session . This takes the path of the transfer Session object and removes it .'''
manager = mockobject . objects [ '/' ] # Remove all the session ' s transfers . transfer_id = 0 while session_path + '/transfer' + str ( transfer_id ) in mockobject . objects : transfer_path = session_path + '/transfer' + str ( transfer_id ) transfer_id += 1 self . RemoveObject ( transfer_path ) manager...
def create_host_template ( self , name ) : """Creates a host template . @ param name : Name of the host template to create . @ return : An ApiHostTemplate object ."""
return host_templates . create_host_template ( self . _get_resource_root ( ) , name , self . name )
def _to_iplot ( self , colors = None , colorscale = None , kind = 'scatter' , mode = 'lines' , interpolation = 'linear' , symbol = 'dot' , size = '12' , fill = False , width = 3 , dash = 'solid' , sortbars = False , keys = False , bestfit = False , bestfit_colors = None , opacity = 0.6 , mean = False , mean_colors = No...
df = self . copy ( ) if asTimestamp : x = [ _ for _ in df . index ] elif df . index . __class__ . __name__ in ( 'PeriodIndex' , 'DatetimeIndex' ) : if asDates : df . index = df . index . date x = df . index . format ( ) elif isinstance ( df . index , pd . MultiIndex ) : x = [ '({0})' . format ( ...
def radec2sky ( ra , dec ) : """Convert [ ra ] , [ dec ] to [ ( ra [ 0 ] , dec [ 0 ] ) , . . . . ] and also ra , dec to [ ( ra , dec ) ] if ra / dec are not iterable Parameters ra , dec : float or iterable Sky coordinates Returns sky : numpy . array array of ( ra , dec ) coordinates ."""
try : sky = np . array ( list ( zip ( ra , dec ) ) ) except TypeError : sky = np . array ( [ ( ra , dec ) ] ) return sky
def get_real_field ( model , field_name ) : '''Get the real field from a model given its name . Handle nested models recursively ( aka . ` ` _ _ ` ` lookups )'''
parts = field_name . split ( '__' ) field = model . _meta . get_field ( parts [ 0 ] ) if len ( parts ) == 1 : return model . _meta . get_field ( field_name ) elif isinstance ( field , models . ForeignKey ) : return get_real_field ( field . rel . to , '__' . join ( parts [ 1 : ] ) ) else : raise Exception ( ...
def update_infos ( self , forced = False , test = False ) : """Update satellite info each self . polling _ interval seconds so we smooth arbiter actions for just useful actions . Raise a satellite update status Brok If forced is True , then ignore the ping period . This is used when the configuration has no...
logger . debug ( "Update informations, forced: %s" , forced ) # First look if it ' s not too early to ping now = time . time ( ) if not forced and self . last_check and self . last_check + self . polling_interval > now : logger . debug ( "Too early to ping %s, ping period is %ds!, last check: %d, now: %d" , self . ...
def module ( self ) : """The module specified by the ` ` library ` ` attribute ."""
if self . _module is None : if self . library is None : raise ValueError ( "Backend '%s' doesn't specify a library attribute" % self . __class__ ) try : if '.' in self . library : mod_path , cls_name = self . library . rsplit ( '.' , 1 ) mod = import_module ( mod_path ) ...
def sanitize_args ( args ) : """args may need a bunch of logic to set proper defaults that argparse is not well suited for ."""
if args . release is None : args . release = 'nautilus' args . default_release = True # XXX This whole dance is because - - stable is getting deprecated if args . stable is not None : LOG . warning ( 'the --stable flag is deprecated, use --release instead' ) args . release = args . stable # XXX Tango en...
def set_id_in_fkeys ( cls , payload ) : """Looks for any keys in the payload that end with either _ id or _ ids , signaling a foreign key field . For each foreign key field , checks whether the value is using the name of the record or the actual primary ID of the record ( which may include the model abbreviatio...
for key in payload : val = payload [ key ] if not val : continue if key . endswith ( "_id" ) : model = getattr ( THIS_MODULE , cls . FKEY_MAP [ key ] ) rec_id = model . replace_name_with_id ( name = val ) payload [ key ] = rec_id elif key . endswith ( "_ids" ) : m...
def compare_password ( expected , actual ) : """Compare two 64byte encoded passwords ."""
if expected == actual : return True , "OK" msg = [ ] ver_exp = expected [ - 8 : ] . rstrip ( ) ver_act = actual [ - 8 : ] . rstrip ( ) if expected [ : - 8 ] != actual [ : - 8 ] : msg . append ( "Password mismatch" ) if ver_exp != ver_act : msg . append ( "asterisk_mbox version mismatch. Client: '" + ver_ac...
def rprojs ( self ) : """Return the projected ( in xy / uv plane ) radius of each element ( either vertices or centers depending on the setting in the mesh ) with respect to the center of the star . NOTE : unscaled ( ComputedColumn )"""
# TODO : should this be moved to Mesh ? Even though its surely possible # to compute without being placed in orbit , projecting in x , y doesn ' t # make much sense without LOS orientation . rprojs = np . linalg . norm ( self . coords_for_computations [ : , : 2 ] , axis = 1 ) return ComputedColumn ( self , rprojs )
def get_unit_process_ids ( self , unit_processes , expect_success = True , pgrep_full = False ) : """Construct a dict containing unit sentries , process names , and process IDs . : param unit _ processes : A dictionary of Amulet sentry instance to list of process names . : param expect _ success : if False ...
pid_dict = { } for sentry_unit , process_list in six . iteritems ( unit_processes ) : pid_dict [ sentry_unit ] = { } for process in process_list : pids = self . get_process_id_list ( sentry_unit , process , expect_success = expect_success , pgrep_full = pgrep_full ) pid_dict [ sentry_unit ] . up...
def _ord_to_str ( ordinal , weights ) : """Reverse function of _ str _ to _ ord ."""
chars = [ ] for weight in weights : if ordinal == 0 : return "" . join ( chars ) ordinal -= 1 index , ordinal = divmod ( ordinal , weight ) chars . append ( _ALPHABET [ index ] ) return "" . join ( chars )
def add_ui ( self , klass , * args , ** kwargs ) : '''Add an UI element for the current scene . The approach is the same as renderers . . . warning : : The UI api is not yet finalized'''
ui = klass ( self . widget , * args , ** kwargs ) self . widget . uis . append ( ui ) return ui
def _position_phonemes ( self , phonemes ) : '''Mark syllable boundaries , and , in future , other positional / suprasegmental features ?'''
for i in range ( len ( phonemes ) ) : phonemes [ i ] = PositionedPhoneme ( phonemes [ i ] ) phonemes [ i ] . syllable_initial = self . is_syllable_initial ( phonemes , i ) phonemes [ i ] . syllable_final = self . is_syllable_final ( phonemes , i ) return phonemes
def get_ea_indexed ( self ) : """Calculate the address for all indexed addressing modes"""
addr , postbyte = self . read_pc_byte ( ) # log . debug ( " \ tget _ ea _ indexed ( ) : postbyte : $ % 02x ( % s ) from $ % 04x " , # postbyte , byte2bit _ string ( postbyte ) , addr rr = ( postbyte >> 5 ) & 3 try : register_str = self . INDEX_POSTBYTE2STR [ rr ] except KeyError : raise RuntimeError ( "Register...
def parse_directive_locations ( lexer : Lexer ) -> List [ NameNode ] : """DirectiveLocations"""
# optional leading pipe expect_optional_token ( lexer , TokenKind . PIPE ) locations : List [ NameNode ] = [ ] append = locations . append while True : append ( parse_directive_location ( lexer ) ) if not expect_optional_token ( lexer , TokenKind . PIPE ) : break return locations
def download ( source , sink = None ) : """Download a file . Parameters source : str Where the file comes from . Some URL . sink : str or None ( default : same filename in current directory ) Where the file gets stored . Some filepath in the local file system ."""
try : from urllib . request import urlretrieve # Python 3 except ImportError : from urllib import urlretrieve # Python 2 if sink is None : sink = os . path . abspath ( os . path . split ( source ) [ 1 ] ) urlretrieve ( source , sink ) return sink
def cameraUrls ( self , camera = None , home = None , cid = None ) : """Return the vpn _ url and the local _ url ( if available ) of a given camera in order to access to its live feed Can ' t use the is _ local property which is mostly false in case of operator dynamic IP change after presence start sequence"...
local_url = None vpn_url = None if cid : camera_data = self . cameraById ( cid ) else : camera_data = self . cameraByName ( camera = camera , home = home ) if camera_data : vpn_url = camera_data [ 'vpn_url' ] resp = postRequest ( vpn_url + '/command/ping' ) temp_local_url = resp [ 'local_url' ] ...
def is_correctness_available ( self , question_id ) : """is a measure of correctness available for the question"""
response = self . get_response ( question_id ) if response . is_answered ( ) : item = self . _get_item ( response . get_item_id ( ) ) return item . is_correctness_available_for_response ( response ) return False
def asyncImap ( asyncCallable , * iterables ) : """itertools . imap for deferred callables"""
deferreds = imap ( asyncCallable , * iterables ) return gatherResults ( deferreds , consumeErrors = True )
def set_api_server_info ( host = None , port = None , protocol = None ) : ''': param host : API server hostname : type host : string : param port : API server port . If not specified , * port * is guessed based on * protocol * . : type port : string : param protocol : Either " http " or " https " : type p...
global APISERVER_PROTOCOL , APISERVER_HOST , APISERVER_PORT , APISERVER if host is not None : APISERVER_HOST = host if port is not None : APISERVER_PORT = port if protocol is not None : APISERVER_PROTOCOL = protocol if port is None or port == '' : APISERVER = APISERVER_PROTOCOL + "://" + APISERVER_HOST ...
def full ( self ) : """Return True if there are maxsize items in the queue . Note : if the Queue was initialized with maxsize = 0 ( the default ) , then full ( ) is never True ."""
if self . _parent . _maxsize <= 0 : return False else : return self . qsize ( ) >= self . _parent . _maxsize
def add_leaves ( self , values_array , do_hash = False ) : """Add leaves to the tree . Similar to chainpoint merkle tree library , this accepts hash values as an array of Buffers or hex strings . : param values _ array : array of values to add : param do _ hash : whether to hash the values before inserting"""
self . tree [ 'is_ready' ] = False [ self . _add_leaf ( value , do_hash ) for value in values_array ]
def getCompoundIdForFeatureId ( self , featureId ) : """Returns server - style compound ID for an internal featureId . : param long featureId : id of feature in database : return : string representing ID for the specified GA4GH protocol Feature object in this FeatureSet ."""
if featureId is not None and featureId != "" : compoundId = datamodel . FeatureCompoundId ( self . getCompoundId ( ) , str ( featureId ) ) else : compoundId = "" return str ( compoundId )
def format_grammar_string ( grammar_dictionary : Dict [ str , List [ str ] ] ) -> str : """Formats a dictionary of production rules into the string format expected by the Parsimonious Grammar class ."""
grammar_string = '\n' . join ( [ f"{nonterminal} = {' / '.join(right_hand_side)}" for nonterminal , right_hand_side in grammar_dictionary . items ( ) ] ) return grammar_string . replace ( "\\" , "\\\\" )
def getSegmentInfo ( self , collectActiveData = False ) : """Returns information about the distribution of segments , synapses and permanence values in the current TP . If requested , also returns information regarding the number of currently active segments and synapses . The method returns the following tup...
nSegments , nSynapses = 0 , 0 nActiveSegs , nActiveSynapses = 0 , 0 distSegSizes , distNSegsPerCell = { } , { } distPermValues = { } # Num synapses with given permanence values numAgeBuckets = 20 distAges = [ ] ageBucketSize = int ( ( self . lrnIterationIdx + 20 ) / 20 ) for i in range ( numAgeBuckets ) : distAges ...
def get_anomalies ( smoothed_errors , y_true , z , window , all_anomalies , error_buffer ) : """Helper method to get anomalies ."""
mu = np . mean ( smoothed_errors ) sigma = np . std ( smoothed_errors ) epsilon = mu + ( z * sigma ) # compare to epsilon errors_seq , anomaly_indices , max_error_below_e = group_consecutive_anomalies ( smoothed_errors , epsilon , y_true , error_buffer , window , all_anomalies ) if len ( errors_seq ) > 0 : anomaly_...
def computeScaledProbabilities ( listOfScales = [ 1.0 , 1.5 , 2.0 , 2.5 , 3.0 , 3.5 , 4.0 ] , listofkValues = [ 64 , 128 , 256 ] , kw = 32 , n = 1000 , numWorkers = 10 , nTrials = 1000 , ) : """Compute the impact of S on match probabilities for a fixed value of n ."""
# Create arguments for the possibilities we want to test args = [ ] theta , _ = getTheta ( kw ) for ki , k in enumerate ( listofkValues ) : for si , s in enumerate ( listOfScales ) : args . append ( { "k" : k , "kw" : kw , "n" : n , "theta" : theta , "nTrials" : nTrials , "inputScaling" : s , "errorIndex" :...
def parallel_newton ( func , x0 , fprime = None , par_args = ( ) , simple_args = ( ) , tol = 1.48e-8 , maxiter = 50 , parallel = True , ** kwargs ) : """A parallelized version of : func : ` scipy . optimize . newton ` . Arguments : func The function to search for zeros , called as ` ` f ( x , [ * par _ args ....
from scipy . optimize import newton from . parallel import make_parallel_helper phelp = make_parallel_helper ( parallel ) if not isinstance ( par_args , tuple ) : raise ValueError ( 'par_args must be a tuple' ) if not isinstance ( simple_args , tuple ) : raise ValueError ( 'simple_args must be a tuple' ) bc_raw...
def get_page_by_id ( self , page_id , expand = None ) : """Get page by ID : param page _ id : Content ID : param expand : OPTIONAL : expand e . g . history : return :"""
url = 'rest/api/content/{page_id}?expand={expand}' . format ( page_id = page_id , expand = expand ) return self . get ( url )
def create ( self ) : """Override method for creating FormBaseNew form"""
self . add_handlers ( { '^T' : self . quit , '^Q' : self . quit } ) self . services_tft = self . add ( npyscreen . TitleFixedText , name = 'No services running.' , value = '' ) services = Services ( self . core , external = self . external ) if services : self . services_tft . hidden = True for service in servi...
def get_result ( self , commit , default = MemoteResult ( ) ) : """Return an individual result from the history if it exists ."""
assert self . _results is not None , "Please call the method `load_history` first." return self . _results . get ( commit , default )
def get_value_from_view ( context , field ) : """Responsible for deriving the displayed value for the passed in ' field ' . This first checks for a particular method on the ListView , then looks for a method on the object , then finally treats it as an attribute ."""
view = context [ 'view' ] obj = None if 'object' in context : obj = context [ 'object' ] value = view . lookup_field_value ( context , obj , field ) # it ' s a date if type ( value ) == datetime : return format_datetime ( value ) return value
def download ( self , ** kwargs ) : """If table contains Gravity Spy triggers ` EventTable ` Parameters nproc : ` int ` , optional , default : 1 number of CPUs to use for parallel file reading download _ path : ` str ` optional , default : ' download ' Specify where the images end up . download _ durs :...
from six . moves . urllib . request import urlopen import os # back to pandas try : images_db = self . to_pandas ( ) except ImportError as exc : exc . args = ( 'pandas is required to download triggers' , ) raise # Remove any broken links images_db = images_db . loc [ images_db . url1 != '' ] training_set = ...
def from_request ( cls , http_method , http_url , headers = None , parameters = None , query_string = None ) : """Combines multiple parameter sources ."""
if parameters is None : parameters = { } # Headers if headers : auth_header = None for k , v in headers . items ( ) : if k . lower ( ) == 'authorization' or k . upper ( ) == 'HTTP_AUTHORIZATION' : auth_header = v # Check that the authorization header is OAuth . if auth_header and...
def _tls_auth_encrypt ( self , s ) : """Return the TLSCiphertext . encrypted _ record for AEAD ciphers ."""
wcs = self . tls_session . wcs write_seq_num = struct . pack ( "!Q" , wcs . seq_num ) wcs . seq_num += 1 return wcs . cipher . auth_encrypt ( s , b"" , write_seq_num )
def reset_subscription_since ( self , account_id , datetime_str ) : """Handler for ` - - reset - subscription - since ` command . Args : account _ id ( int ) : id of the account to reset . datetime _ str ( str ) : string representing the datetime used in the next poll to retrieve data since . Returns : ...
data = { 'account_id' : account_id , 'datetime' : datetime_str , } return self . _perform_post_request ( self . reset_subscription_since_endpoint , data , self . token_header )
def train ( hparams , output_dir , env_problem_name , report_fn = None ) : """Train ."""
env_fn = initialize_env_specs ( hparams , env_problem_name ) tf . logging . vlog ( 1 , "HParams in trainer_model_free.train : %s" , misc_utils . pprint_hparams ( hparams ) ) tf . logging . vlog ( 1 , "Using hparams.base_algo: %s" , hparams . base_algo ) learner = rl_utils . LEARNERS [ hparams . base_algo ] ( hparams . ...
def process ( self , job_id ) : """Process a job by the queue"""
self . _logger . info ( '{:.2f}: Process job {}' . format ( self . _env . now , job_id ) ) # log time of commencement of service self . _observer . notify_service ( time = self . _env . now , job_id = job_id ) # draw a new service time try : service_time = next ( self . _service_time_generator ) except StopIteratio...
def _converged ( self ) : """Check convergence based on maximum absolute difference Returns converged : boolean Whether the parameter estimation converged . max _ diff : float Maximum absolute difference between prior and posterior ."""
diff = self . local_prior - self . local_posterior_ max_diff = np . max ( np . fabs ( diff ) ) if self . verbose : _ , mse = self . _mse_converged ( ) diff_ratio = np . sum ( diff ** 2 ) / np . sum ( self . local_posterior_ ** 2 ) logger . info ( 'tfa prior posterior max diff %f mse %f diff_ratio %f' % ( ( ...
def getmatch ( self , regex , group = 0 , flags = 0 ) : """The same as # Scanner . match ( ) , but returns the captured group rather than the regex match object , or None if the pattern didn ' t match ."""
match = self . match ( regex , flags ) if match : return match . group ( group ) return None
def GetOobResult ( self , param , user_ip , gitkit_token = None ) : """Gets out - of - band code for ResetPassword / ChangeEmail request . Args : param : dict of HTTP POST params user _ ip : string , end user ' s IP address gitkit _ token : string , the gitkit token if user logged in Returns : A dict of...
if 'action' in param : try : if param [ 'action' ] == GitkitClient . RESET_PASSWORD_ACTION : request = self . _PasswordResetRequest ( param , user_ip ) oob_code , oob_link = self . _BuildOobLink ( request , param [ 'action' ] ) return { 'action' : GitkitClient . RESET_PAS...
def from_items ( cls , items , columns = None , orient = 'columns' ) : """Construct a DataFrame from a list of tuples . . . deprecated : : 0.23.0 ` from _ items ` is deprecated and will be removed in a future version . Use : meth : ` DataFrame . from _ dict ( dict ( items ) ) < DataFrame . from _ dict > ` i...
warnings . warn ( "from_items is deprecated. Please use " "DataFrame.from_dict(dict(items), ...) instead. " "DataFrame.from_dict(OrderedDict(items)) may be used to " "preserve the key order." , FutureWarning , stacklevel = 2 ) keys , values = lzip ( * items ) if orient == 'columns' : if columns is not None : ...
def list_tasks ( collector ) : """List the available _ tasks"""
print ( "Usage: dashmat <task>" ) print ( "" ) print ( "Available tasks to choose from are:" ) print ( "-----------------------------------" ) print ( "" ) keygetter = lambda item : item [ 1 ] . label tasks = sorted ( available_actions . items ( ) , key = keygetter ) sorted_tasks = sorted ( list ( tasks ) , key = lambd...
def tilequeue_enqueue_full_pyramid_from_toi ( cfg , peripherals , args ) : """enqueue a full pyramid from the z10 toi"""
logger = make_logger ( cfg , 'enqueue_tiles_of_interest' ) logger . info ( 'Enqueueing tiles of interest' ) logger . info ( 'Fetching tiles of interest ...' ) tiles_of_interest = peripherals . toi . fetch_tiles_of_interest ( ) n_toi = len ( tiles_of_interest ) logger . info ( 'Fetching tiles of interest ... done' ) raw...
def _wrap_coro_function_with_sem ( self , coro_func ) : """Decorator set the coro _ function has sem / interval control ."""
sem = self . frequency . sem interval = self . frequency . interval @ wraps ( coro_func ) async def new_coro_func ( * args , ** kwargs ) : if sem : async with sem : result = await coro_func ( * args , ** kwargs ) if interval : await asyncio . sleep ( interval ) ...
def default ( self , user_input ) : '''if no other command was invoked'''
try : for i in self . _cs . disasm ( unhexlify ( self . cleanup ( user_input ) ) , self . base_address ) : print ( "0x%08x:\t%s\t%s" % ( i . address , i . mnemonic , i . op_str ) ) except CsError as e : print ( "Error: %s" % e )
def biselect ( table , * args , ** kwargs ) : """Return two tables , the first containing selected rows , the second containing remaining rows . E . g . : : > > > import petl as etl > > > table1 = [ [ ' foo ' , ' bar ' , ' baz ' ] , . . . [ ' a ' , 4 , 9.3 ] , . . . [ ' a ' , 2 , 88.2 ] , . . . [ ' b ' ...
# override complement kwarg kwargs [ 'complement' ] = False t1 = select ( table , * args , ** kwargs ) kwargs [ 'complement' ] = True t2 = select ( table , * args , ** kwargs ) return t1 , t2
def nanmedian ( values , axis = None , skipna = True , mask = None ) : """Parameters values : ndarray axis : int , optional skipna : bool , default True mask : ndarray [ bool ] , optional nan - mask if known Returns result : float Unless input is a float array , in which case use the same precisio...
def get_median ( x ) : mask = notna ( x ) if not skipna and not mask . all ( ) : return np . nan return np . nanmedian ( x [ mask ] ) values , mask , dtype , dtype_max , _ = _get_values ( values , skipna , mask = mask ) if not is_float_dtype ( values ) : values = values . astype ( 'f8' ) val...
def attach_disk ( name = None , kwargs = None , call = None ) : '''Attach an existing disk to an existing instance . CLI Example : . . code - block : : bash salt - cloud - a attach _ disk myinstance disk _ name = mydisk mode = READ _ WRITE'''
if call != 'action' : raise SaltCloudSystemExit ( 'The attach_disk action must be called with -a or --action.' ) if not name : log . error ( 'Must specify an instance name.' ) return False if not kwargs or 'disk_name' not in kwargs : log . error ( 'Must specify a disk_name to attach.' ) return False...
def add_tokens_for_single ( self , ignore = False ) : """Add the tokens for the single signature"""
args = self . single . args name = self . single . python_name # Reset indentation to proper amount and add signature self . reset_indentation ( self . indent_type * self . single . indent ) self . result . extend ( self . tokens . make_single ( name , args ) ) # Add skip if necessary if ignore : self . single . sk...
def user_loggedin ( sender , ** kwargs ) : """collect metrics about user logins"""
values = { 'value' : 1 , 'path' : kwargs [ 'request' ] . path , 'user_id' : str ( kwargs [ 'user' ] . pk ) , 'username' : kwargs [ 'user' ] . username , } write ( 'user_logins' , values = values )
def read_message ( self ) : """Return the next text or binary message from the socket . This is an internal method as calling this will not cleanup correctly if an exception is called . Use ` receive ` instead ."""
opcode = None message = None while True : header , payload = self . read_frame ( ) f_opcode = header . opcode if f_opcode in ( self . OPCODE_TEXT , self . OPCODE_BINARY ) : # a new frame if opcode : raise WebSocketError ( "The opcode in non-fin frame is expected to be zero, got {0!r}" . ...
def subscribe ( self , plan , charge_immediately = True , application_fee_percent = None , coupon = None , quantity = None , metadata = None , tax_percent = None , billing_cycle_anchor = None , trial_end = None , trial_from_plan = None , trial_period_days = None , ) : """Subscribes this customer to a plan . : par...
from . billing import Subscription # Convert Plan to id if isinstance ( plan , StripeModel ) : plan = plan . id stripe_subscription = Subscription . _api_create ( plan = plan , customer = self . id , application_fee_percent = application_fee_percent , coupon = coupon , quantity = quantity , metadata = metadata , bi...
def add_picture ( self , p ) : """needs to look like this ( under draw : page ) < draw : frame draw : style - name = " gr2 " draw : text - style - name = " P2 " draw : layer = " layout " svg : width = " 19.589cm " svg : height = " 13.402cm " svg : x = " 3.906cm " svg : y = " 4.378cm " > < draw : image xlink : h...
# pictures should be added the the draw : frame element self . pic_frame = PictureFrame ( self , p ) self . pic_frame . add_node ( "draw:image" , attrib = { "xlink:href" : "Pictures/" + p . internal_name , "xlink:type" : "simple" , "xlink:show" : "embed" , "xlink:actuate" : "onLoad" , } , ) self . _preso . _pictures . ...
def get_name ( ) : '''Get desktop environment or OS . Get the OS name or desktop environment . * * List of Possible Values * * | Windows | windows | | Mac OS X | mac | | GNOME 3 + | gnome | | GNOME 2 | gnome2 | | XFCE | xfce4 | | KDE | kde | | Unity | unity | | LXDE | lxde | | i3wm | i3 | | ...
if sys . platform in [ 'win32' , 'cygwin' ] : return 'windows' elif sys . platform == 'darwin' : return 'mac' else : desktop_session = os . environ . get ( 'XDG_CURRENT_DESKTOP' ) or os . environ . get ( 'DESKTOP_SESSION' ) if desktop_session is not None : desktop_session = desktop_session . low...
def load_scoring_function ( scoring_func ) : """converts mymodule . myfunc in the myfunc object itself so tpot receives a scoring function"""
if scoring_func and ( "." in scoring_func ) : try : module_name , func_name = scoring_func . rsplit ( '.' , 1 ) module_path = os . getcwd ( ) sys . path . insert ( 0 , module_path ) scoring_func = getattr ( import_module ( module_name ) , func_name ) sys . path . pop ( 0 ) ...
def prepend_items ( self , items , ** kwargs ) : """Method to prepend data to multiple : class : ` ~ . Item ` objects . . . seealso : : : meth : ` append _ items `"""
rv = self . prepend_multi ( items , ** kwargs ) for k , v in items . dict . items ( ) : if k . success : k . value = v [ 'fragment' ] + k . value return rv
def get_connection_state ( self , connection : str ) -> Dict [ str , Any ] : """For an already established connection return its state ."""
if connection not in self . connections : raise ConnectionNotOpen ( connection ) return self . connections [ connection ] . state
def get_optional_attrs ( optional_attrs ) : """Prepare to store data from user - desired optional fields . Not loading these optional fields by default saves in space and speed . But allow the possibility for saving these fields , if the user desires , Including : comment consider def is _ class _ level is ...
attrs_opt = set ( [ 'def' , 'defn' , 'synonym' , 'relationship' , 'xref' , 'subset' , 'comment' ] ) # Required attributes are always loaded . All others are optionally loaded . # Allow user to specify either : ' def ' or ' defn ' # ' def ' is an obo field name , but ' defn ' is legal Python attribute name getnm = lambd...
def calculate_relevance_table ( X , y , ml_task = 'auto' , n_jobs = defaults . N_PROCESSES , chunksize = defaults . CHUNKSIZE , test_for_binary_target_binary_feature = defaults . TEST_FOR_BINARY_TARGET_BINARY_FEATURE , test_for_binary_target_real_feature = defaults . TEST_FOR_BINARY_TARGET_REAL_FEATURE , test_for_real_...
if ml_task not in [ 'auto' , 'classification' , 'regression' ] : raise ValueError ( 'ml_task must be one of: \'auto\', \'classification\', \'regression\'' ) elif ml_task == 'auto' : ml_task = infer_ml_task ( y ) if n_jobs == 0 : map_function = map else : pool = Pool ( n_jobs ) map_function = partial...
def call_with_retry ( func : Callable , exceptions , max_retries : int , logger : Logger , * args , ** kwargs ) : """Call a function and retry it on failure ."""
attempt = 0 while True : try : return func ( * args , ** kwargs ) except exceptions as e : attempt += 1 if attempt >= max_retries : raise delay = exponential_backoff ( attempt , cap = 60 ) logger . warning ( '%s: retrying in %s' , e , delay ) time . sl...
def is_decorated_with_property_setter ( node ) : """Check if the function is decorated as a property setter . : param node : The node to check . : type node : astroid . nodes . FunctionDef : returns : True if the function is a property setter , False otherwise . : rtype : bool"""
if not node . decorators : return False for decorator in node . decorators . nodes : if ( isinstance ( decorator , astroid . nodes . Attribute ) and decorator . attrname == "setter" ) : return True return False
def read_line_stderr ( self , time_limit = None ) : """Read a line from the process . On Windows , this the time _ limit has no effect , it always blocks ."""
if self . proc is not None : return self . proc . stderr . readline ( ) . decode ( ) else : return None
def read ( self , address , length_bytes , x , y , p = 0 ) : """Read a bytestring from an address in memory . Parameters address : int The address at which to start reading the data . length _ bytes : int The number of bytes to read from memory . Large reads are transparently broken into multiple SCP re...
# Call the SCPConnection to perform the read on our behalf connection = self . _get_connection ( x , y ) return connection . read ( self . scp_data_length , self . scp_window_size , x , y , p , address , length_bytes )
def poll_values ( ) : """Shows how to poll values from the subscription ."""
subscription = processor . create_parameter_subscription ( [ '/YSS/SIMULATOR/BatteryVoltage1' ] ) sleep ( 5 ) print ( 'Latest value:' ) print ( subscription . get_value ( '/YSS/SIMULATOR/BatteryVoltage1' ) ) sleep ( 5 ) print ( 'Latest value:' ) print ( subscription . get_value ( '/YSS/SIMULATOR/BatteryVoltage1' ) )
def _on_new_location ( self , form ) : """Set a new desired location entered in the pop - up form ."""
self . _desired_longitude = float ( form . data [ "long" ] ) self . _desired_latitude = float ( form . data [ "lat" ] ) self . _desired_zoom = 13 self . _screen . force_update ( )
def repertoire ( self , direction , mechanism , purview ) : """Return the cause or effect repertoire based on a direction . Args : direction ( Direction ) : | CAUSE | or | EFFECT | . mechanism ( tuple [ int ] ) : The mechanism for which to calculate the repertoire . purview ( tuple [ int ] ) : The purview...
if direction == Direction . CAUSE : return self . cause_repertoire ( mechanism , purview ) elif direction == Direction . EFFECT : return self . effect_repertoire ( mechanism , purview ) return validate . direction ( direction )
def encode_multipart_formdata ( fields , files ) : """fields is a sequence of ( name , value ) elements for regular form fields . files is a sequence of ( name , filename , value ) elements for data to be uploaded as files Return ( content _ type , body ) ready for httplib . HTTP instance"""
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [ ] for ( key , value ) in fields : L . append ( '--' + BOUNDARY ) L . append ( 'Content-Disposition: form-data; name="%s"' % key ) L . append ( '' ) L . append ( value ) for ( key , filename , value ) in files : L . append ( '--' + BOU...
def slugify ( value , allow_unicode = False ) : """Convert to ASCII if ' allow _ unicode ' is False . Convert spaces to hyphens . Remove characters that aren ' t alphanumerics , underscores , or hyphens . Convert to lowercase . Also strip leading and trailing whitespace ."""
value if allow_unicode : value = unicodedata . normalize ( 'NFKC' , value ) else : value = unicodedata . normalize ( 'NFKD' , value ) . encode ( 'ascii' , 'ignore' ) . decode ( 'ascii' ) value = re . sub ( r'[^\w\s-]' , '' , value ) . strip ( ) . lower ( ) return re . sub ( r'[-\s]+' , '-' , value )
def main ( source , reference , downsample , steps , plot ) : """Given a source image and a reference image , Find the rio color formula which results in an output with similar histogram to the reference image . Uses simulated annealing to determine optimal settings . Increase the - - downsample option to s...
global fig , txt , imgs click . echo ( "Reading source data..." , err = True ) with rasterio . open ( source ) as src : if downsample is None : ratio = calc_downsample ( src . width , src . height ) else : ratio = downsample w = int ( src . width // ratio ) h = int ( src . height // rati...
def get_unique_counter ( self , redis_conn = None , host = 'localhost' , port = 6379 , key = 'unique_counter' , cycle_time = 5 , start_time = None , window = SECONDS_1_HOUR , roll = True , keep_max = 12 ) : '''Generate a new UniqueCounter . Useful for exactly counting unique objects @ param redis _ conn : A pre...
counter = UniqueCounter ( key = key , cycle_time = cycle_time , start_time = start_time , window = window , roll = roll , keep_max = keep_max ) counter . setup ( redis_conn = redis_conn , host = host , port = port ) return counter
def register_view ( self , view ) : """Called when the View was registered"""
super ( GraphicalEditorController , self ) . register_view ( view ) self . view . connect ( 'meta_data_changed' , self . _meta_data_changed ) self . focus_changed_handler_id = self . view . editor . connect ( 'focus-changed' , self . _move_focused_item_into_viewport ) self . view . editor . connect ( "drag-data-receive...
def filter ( self , func ) : """Returns a packet list filtered by a truth function . This truth function has to take a packet as the only argument and return a boolean value ."""
# noqa : E501 return self . __class__ ( [ x for x in self . res if func ( x ) ] , name = "filtered %s" % self . listname )
def user ( self , match ) : """Return User object for a given Slack ID or name"""
if len ( match ) == 9 and match [ 0 ] == 'U' : return self . _lookup ( User , 'id' , match ) return self . _lookup ( User , 'name' , match )
def _handle_long_response ( self , res ) : """Splits messages that are too long into multiple events : param res : a slack response string or dict"""
is_rtm_message = isinstance ( res , basestring ) is_api_message = isinstance ( res , dict ) if is_rtm_message : text = res elif is_api_message : text = res [ 'text' ] message_length = len ( text ) if message_length <= SLACK_MESSAGE_LIMIT : return [ res ] remaining_str = text responses = [ ] while remaining_...
def load_config ( self , ** kwargs ) : """Load the configuration for the user or seed it with defaults . : return : Boolean if successful"""
virgin_config = False if not os . path . exists ( CONFIG_PATH ) : virgin_config = True os . makedirs ( CONFIG_PATH ) if not os . path . exists ( CONFIG_FILE ) : virgin_config = True if not virgin_config : self . config = json . load ( open ( CONFIG_FILE ) ) else : self . logger . info ( '[!] Process...
def prepareInsert ( self , oself , store ) : """Prepare for insertion into the database by making the dbunderlying attribute of the item a relative pathname with respect to the store rather than an absolute pathname ."""
if self . relative : fspath = self . __get__ ( oself ) oself . __dirty__ [ self . attrname ] = self , self . infilter ( fspath , oself , store )
def t_OCTAL ( t ) : r'[0-7 ] + [ oO ]'
t . value = t . value [ : - 1 ] t . type = 'NUMBER' t . value = int ( t . value , 8 ) return t
def discretize_path ( entities , vertices , path , scale = 1.0 ) : """Turn a list of entity indices into a path of connected points . Parameters entities : ( j , ) entity objects Objects like ' Line ' , ' Arc ' , etc . vertices : ( n , dimension ) float Vertex points in space . path : ( m , ) int Inde...
# make sure vertices are numpy array vertices = np . asanyarray ( vertices ) path_len = len ( path ) if path_len == 0 : raise ValueError ( 'Cannot discretize empty path!' ) if path_len == 1 : # case where we only have one entity discrete = np . asanyarray ( entities [ path [ 0 ] ] . discrete ( vertices , scale ...
def _actionsFreqsAngles ( self , * args , ** kwargs ) : """NAME : actionsFreqsAngles ( _ actionsFreqsAngles ) PURPOSE : evaluate the actions , frequencies , and angles ( jr , lz , jz , Omegar , Omegaphi , Omegaz , angler , anglephi , anglez ) INPUT : Either : a ) R , vR , vT , z , vz [ , phi ] : 1 ) f...
if len ( args ) == 5 : # R , vR . vT , z , vz pragma : no cover raise IOError ( "You need to provide phi when calculating angles" ) elif len ( args ) == 6 : # R , vR . vT , z , vz , phi R , vR , vT , z , vz , phi = args else : self . _parse_eval_args ( * args ) R = self . _eval_R vR = self . _eval_v...
def matches ( self , properties ) : """Tests if the given properties matches this LDAP filter and its children : param properties : A dictionary of properties : return : True if the properties matches this filter , else False"""
# Use a generator , and declare it outside of the method call # = > seems to be quite a speed up trick generator = ( criterion . matches ( properties ) for criterion in self . subfilters ) # Extract " if " from loops and use built - in methods if self . operator == OR : result = any ( generator ) else : result ...
def get_default_account_data ( self ) -> AccountData : """This interface is used to get the default account in WalletManager . : return : an AccountData object that contain all the information of a default account ."""
for acct in self . wallet_in_mem . accounts : if not isinstance ( acct , AccountData ) : raise SDKException ( ErrorCode . other_error ( 'Invalid account data in memory.' ) ) if acct . is_default : return acct raise SDKException ( ErrorCode . get_default_account_err )
def getLoggerWithNullHandler ( logger_name ) : """Gets the logger initialized with the ` logger _ name ` and a NullHandler ."""
logger = logging . getLogger ( logger_name ) if not logger . handlers : logger . addHandler ( NullHandler ( ) ) return logger
def get_client_nowait ( self ) : """Gets a Client object ( not necessary connected ) . If max _ size is reached , this method will return None ( and won ' t block ) . Returns : A Client instance ( not necessary connected ) as result ( or None ) ."""
if self . __sem is not None : if self . __sem . _value == 0 : return None self . __sem . acquire ( ) _ , client = self . _get_client_from_pool_or_make_it ( ) return client
def com_google_fonts_check_whitespace_glyphnames ( ttFont ) : """Font has * * proper * * whitespace glyph names ?"""
from fontbakery . utils import get_glyph_name def getGlyphEncodings ( font , names ) : result = set ( ) for subtable in font [ 'cmap' ] . tables : if subtable . isUnicode ( ) : for codepoint , name in subtable . cmap . items ( ) : if name in names : result...
def get_stars_of_children_of ( self , component ) : """same as get _ children _ of except if any of the children are orbits , this will recursively follow the tree to return a list of all children ( grandchildren , etc ) stars under that orbit"""
stars = self . get_stars ( ) orbits = self . get_orbits ( ) stars_children = [ ] for child in self . get_children_of ( component ) : if child in stars : stars_children . append ( child ) elif child in orbits : stars_children += self . get_stars_of_children_of ( child ) else : # maybe an enve...
def _retry_deliveries ( self ) : """Handle [ MQTT - 4.4.0-1 ] by resending PUBLISH and PUBREL messages for pending out messages : return :"""
self . logger . debug ( "Begin messages delivery retries" ) tasks = [ ] for message in itertools . chain ( self . session . inflight_in . values ( ) , self . session . inflight_out . values ( ) ) : tasks . append ( asyncio . wait_for ( self . _handle_message_flow ( message ) , 10 , loop = self . _loop ) ) if tasks ...
def parse_network_data ( data_packet = None , include_filter_key = None , filter_keys = [ ] , record_tcp = True , record_udp = True , record_arp = True , record_icmp = True ) : """build _ node : param data _ packet : raw recvfrom data : param filter _ keys : list of strings to filter and remove baby - birding...
node = { "id" : build_key ( ) , "data_type" : UNKNOWN , "eth_protocol" : None , "eth_src_mac" : None , "eth_dst_mac" : None , "eth_length" : SIZE_ETH_HEADER , "ip_version_ih1" : None , "ip_version" : None , "ip_ih1" : None , "ip_hdr_len" : None , "ip_tos" : None , "ip_tlen" : None , "ip_id" : None , "ip_frag_off" : Non...
def _title_uptodate ( self , fullfile , pid , _title ) : """Check fb photo title against provided title , returns true if they match"""
i = self . fb . get_object ( pid ) if i . has_key ( 'name' ) : if _title == i [ 'name' ] : return True return False
def launched ( ) : """Test whether the current python environment is the correct lore env . : return : : any : ` True ` if the environment is launched : rtype : bool"""
if not PREFIX : return False return os . path . realpath ( sys . prefix ) == os . path . realpath ( PREFIX )