signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def serialize ( pagination , ** kwargs ) : """Return resumption token serializer ."""
if not pagination . has_next : return token_builder = URLSafeTimedSerializer ( current_app . config [ 'SECRET_KEY' ] , salt = kwargs [ 'verb' ] , ) schema = _schema_from_verb ( kwargs [ 'verb' ] , partial = False ) data = dict ( seed = random . random ( ) , page = pagination . next_num , kwargs = schema . dump ( kw...
def _from_pb ( cls , pb , set_key = True , ent = None , key = None ) : """Internal helper to create an entity from an EntityProto protobuf ."""
if not isinstance ( pb , entity_pb . EntityProto ) : raise TypeError ( 'pb must be a EntityProto; received %r' % pb ) if ent is None : ent = cls ( ) # A key passed in overrides a key in the pb . if key is None and pb . key ( ) . path ( ) . element_size ( ) : key = Key ( reference = pb . key ( ) ) # If set _...
def setAccessRules ( self , pid , public = False ) : """Set access rules for a resource . Current only allows for setting the public or private setting . : param pid : The HydroShare ID of the resource : param public : True if the resource should be made public ."""
url = "{url_base}/resource/accessRules/{pid}/" . format ( url_base = self . url_base , pid = pid ) params = { 'public' : public } r = self . _request ( 'PUT' , url , data = params ) if r . status_code != 200 : if r . status_code == 403 : raise HydroShareNotAuthorized ( ( 'PUT' , url ) ) elif r . status_...
def _parse_raw ( self , raw ) : """Parse a raw dictionary to create a resource . : type raw : Dict [ str , Any ]"""
self . raw = raw if not raw : raise NotImplementedError ( "We cannot instantiate empty resources: %s" % raw ) dict2resource ( raw , self , self . _options , self . _session )
def to_string ( mnemonic ) : """Return the string representation of the given mnemonic ."""
strings = { # Arithmetic Instructions ReilMnemonic . ADD : "add" , ReilMnemonic . SUB : "sub" , ReilMnemonic . MUL : "mul" , ReilMnemonic . DIV : "div" , ReilMnemonic . MOD : "mod" , ReilMnemonic . BSH : "bsh" , # Bitwise Instructions ReilMnemonic . AND : "and" , ReilMnemonic . OR : "or" , ReilMnemonic . XOR : "xor" , ...
def _deserialize_datetime ( self , data ) : """Take any values coming in as a datetime and deserialize them"""
for key in data : if isinstance ( data [ key ] , dict ) : if data [ key ] . get ( 'type' ) == 'datetime' : data [ key ] = datetime . datetime . fromtimestamp ( data [ key ] [ 'value' ] ) return data
def _ipc_send ( self , sock , message_type , payload ) : '''Send and receive a message from the ipc . NOTE : this is not thread safe'''
sock . sendall ( self . _pack ( message_type , payload ) ) data , msg_type = self . _ipc_recv ( sock ) return data
def derivatives ( self , x , y , Rs , theta_Rs , e1 , e2 , center_x = 0 , center_y = 0 ) : """returns df / dx and df / dy of the function ( integral of NFW )"""
phi_G , q = param_util . ellipticity2phi_q ( e1 , e2 ) x_shift = x - center_x y_shift = y - center_y cos_phi = np . cos ( phi_G ) sin_phi = np . sin ( phi_G ) e = min ( abs ( 1. - q ) , 0.99 ) xt1 = ( cos_phi * x_shift + sin_phi * y_shift ) * np . sqrt ( 1 - e ) xt2 = ( - sin_phi * x_shift + cos_phi * y_shift ) * np . ...
def compile ( ** kwargs ) : r"""There are three modes of parameters : func : ` compile ( ) ` can take : ` ` string ` ` , ` ` filename ` ` , and ` ` dirname ` ` . The ` ` string ` ` parameter is the most basic way to compile Sass . It simply takes a string of Sass code , and then returns a compiled CSS strin...
modes = set ( ) for mode_name in MODES : if mode_name in kwargs : modes . add ( mode_name ) if not modes : raise TypeError ( 'choose one at least in ' + and_join ( MODES ) ) elif len ( modes ) > 1 : raise TypeError ( and_join ( modes ) + ' are exclusive each other; ' 'cannot be used at a time' , ) p...
def score_meaning ( text ) : """Returns a score in [ 0,1 ] range if the text makes any sense in English ."""
# all _ characters = re . findall ( ' [ - ~ ] ' , text ) # match 32-126 in ASCII table all_characters = re . findall ( '[a-zA-Z ]' , text ) # match 32-126 in ASCII table if len ( all_characters ) == 0 : return 0 repetition_count = Counter ( all_characters ) score = ( len ( all_characters ) ) ** 2 / ( len ( repetiti...
def r2_score ( pred : Tensor , targ : Tensor ) -> Rank0Tensor : "R2 score ( coefficient of determination ) between ` pred ` and ` targ ` ."
pred , targ = flatten_check ( pred , targ ) u = torch . sum ( ( targ - pred ) ** 2 ) d = torch . sum ( ( targ - targ . mean ( ) ) ** 2 ) return 1 - u / d
def check ( self , data ) : """For backwards compatibility , this method handles checkboxes and radio buttons in a single call . It will not uncheck any checkboxes unless explicitly specified by ` ` data ` ` , in contrast with the default behavior of : func : ` ~ Form . set _ checkbox ` ."""
for ( name , value ) in data . items ( ) : try : self . set_checkbox ( { name : value } , uncheck_other_boxes = False ) continue except InvalidFormMethod : pass try : self . set_radio ( { name : value } ) continue except InvalidFormMethod : pass raise ...
def __sort_analyses ( sentence ) : '''Sorts analysis of all the words in the sentence . This is required for consistency , because by default , analyses are listed in arbitrary order ;'''
for word in sentence : if ANALYSIS not in word : raise Exception ( '(!) Error: no analysis found from word: ' + str ( word ) ) else : word [ ANALYSIS ] = sorted ( word [ ANALYSIS ] , key = lambda x : "_" . join ( [ x [ ROOT ] , x [ POSTAG ] , x [ FORM ] , x [ CLITIC ] ] ) ) return sentence
def _sticker_templates_vocabularies ( self ) : """Returns the vocabulary to be used in AdmittedStickerTemplates . small _ default If the object has saved not AdmittedStickerTemplates . admitted stickers , this method will return an empty DisplayList . Otherwise it returns the stickers selected in admitted ....
admitted = self . getAdmittedStickers ( ) if not admitted : return DisplayList ( ) voc = DisplayList ( ) stickers = getStickerTemplates ( ) for sticker in stickers : if sticker . get ( 'id' ) in admitted : voc . add ( sticker . get ( 'id' ) , sticker . get ( 'title' ) ) return voc
def setup_jukebox_logger ( ) : """Setup the jukebox top - level logger with handlers The logger has the name ` ` jukebox ` ` and is the top - level logger for all other loggers of jukebox . It does not propagate to the root logger , because it also has a StreamHandler and that might cause double output . The ...
log = logging . getLogger ( "jb" ) log . propagate = False handler = logging . StreamHandler ( sys . stdout ) fmt = "%(levelname)-8s:%(name)s: %(message)s" formatter = logging . Formatter ( fmt ) handler . setFormatter ( formatter ) log . addHandler ( handler ) level = DEFAULT_LOGGING_LEVEL log . setLevel ( level )
def stem ( u , v , dfs_data ) : """The stem of Bu ( v ) is the edge uv in Bu ( v ) ."""
# return dfs _ data [ ' graph ' ] . get _ first _ edge _ id _ by _ node _ ids ( u , v ) uv_edges = dfs_data [ 'graph' ] . get_edge_ids_by_node_ids ( u , v ) buv_edges = B ( u , v , dfs_data ) for edge_id in uv_edges : if edge_id in buv_edges : return edge_id return None
def removeItem ( self , index ) : """Alias for removeComponent"""
self . _stim . removeComponent ( index . row ( ) , index . column ( ) )
def _init_ubuntu_user ( self ) : """Initialize the ubuntu user . : return : bool : If the initialization was successful : raises : : class : ` paramiko . ssh _ exception . AuthenticationException ` if the authentication fails"""
# TODO : Test this on an image without the ubuntu user setup . auth_user = self . user ssh = None try : # Run w / o allocating a pty , so we fail if sudo prompts for a passwd ssh = self . _get_ssh_client ( self . host , "ubuntu" , self . private_key_path , ) stdout , stderr = self . _run_command ( ssh , "sudo -...
def _matches ( self , entities = None , extensions = None , domains = None , regex_search = False ) : """Checks whether the file matches all of the passed entities and extensions . Args : entities ( dict ) : A dictionary of entity names - > regex patterns . extensions ( str , list ) : One or more file exten...
if extensions is not None : if isinstance ( extensions , six . string_types ) : extensions = [ extensions ] extensions = '(' + '|' . join ( extensions ) + ')$' if re . search ( extensions , self . filename ) is None : return False if domains is not None : domains = listify ( domains ) ...
def calibrate_threshold ( self , pairs_valid , y_valid , strategy = 'accuracy' , min_rate = None , beta = 1. ) : """Decision threshold calibration for pairwise binary classification Method that calibrates the decision threshold ( cutoff point ) of the metric learner . This threshold will then be used when calli...
self . _validate_calibration_params ( strategy , min_rate , beta ) pairs_valid , y_valid = self . _prepare_inputs ( pairs_valid , y_valid , type_of_inputs = 'tuples' ) n_samples = pairs_valid . shape [ 0 ] if strategy == 'accuracy' : scores = self . decision_function ( pairs_valid ) scores_sorted_idces = np . a...
def exciter ( self , Xexc , Pexc , Vexc ) : """Exciter model . Based on Exciter . m from MatDyn by Stijn Cole , developed at Katholieke Universiteit Leuven . See U { http : / / www . esat . kuleuven . be / electa / teaching / matdyn / } for more information ."""
exciters = self . exciters F = zeros ( Xexc . shape ) typ1 = [ e . generator . _i for e in exciters if e . model == CONST_EXCITATION ] typ2 = [ e . generator . _i for e in exciters if e . model == IEEE_DC1A ] # Exciter type 1 : constant excitation F [ typ1 , : ] = 0.0 # Exciter type 2 : IEEE DC1A Efd = Xexc [ typ2 , 0 ...
def has_u_umlaut ( word : str ) -> bool : """Does the word have an u - umlaut ? > > > has _ u _ umlaut ( " höfn " ) True > > > has _ u _ umlaut ( " börnum " ) True > > > has _ u _ umlaut ( " barn " ) False : param word : Old Norse word : return : has an u - umlaut occurred ?"""
word_syl = s . syllabify_ssp ( word ) s_word_syl = [ Syllable ( syl , VOWELS , CONSONANTS ) for syl in word_syl ] if len ( s_word_syl ) == 1 and s_word_syl [ - 1 ] . nucleus [ 0 ] in [ "ö" , "ǫ" ] : return True elif len ( s_word_syl ) >= 2 and s_word_syl [ - 1 ] . nucleus [ 0 ] == "u" : return s_word_syl [ - 2 ...
def process ( self , metric ) : """Process a metric by sending it to TSDB"""
entry = { 'timestamp' : metric . timestamp , 'value' : metric . value , "tags" : { } } entry [ "tags" ] [ "hostname" ] = metric . host if self . cleanMetrics : metric = MetricWrapper ( metric , self . log ) if self . skipAggregates and metric . isAggregate ( ) : return for tagKey in metric . getTags...
def _get_tgt_length ( self , var ) : """Get the total length of the whole reference sequence"""
if var . type == "g" or var . type == "m" : return float ( "inf" ) else : # Get genomic sequence access number for this transcript identity_info = self . hdp . get_tx_identity_info ( var . ac ) if not identity_info : raise HGVSDataNotAvailableError ( "No identity info available for {ac}" . format ( ...
def retrieveVals ( self ) : """Retrieve values for graphs ."""
for iface in self . _ifaceList : stats = self . _ifaceStats . get ( iface ) graph_name = 'netiface_traffic_%s' % iface if self . hasGraph ( graph_name ) : self . setGraphVal ( graph_name , 'rx' , stats . get ( 'rxbytes' ) * 8 ) self . setGraphVal ( graph_name , 'tx' , stats . get ( 'txbytes'...
def reshape ( self , * shape ) : """Reshape the Series object Cannot change the last dimension . Parameters shape : one or more ints New shape"""
if prod ( self . shape ) != prod ( shape ) : raise ValueError ( "Reshaping must leave the number of elements unchanged" ) if self . shape [ - 1 ] != shape [ - 1 ] : raise ValueError ( "Reshaping cannot change the size of the constituent series (last dimension)" ) if self . labels is not None : newlabels = s...
def bestscan ( self , seq ) : """m . bestscan ( seq ) - - Return the score of the best match to the motif in the supplied sequence"""
matches , endpoints , scores = self . scan ( seq , - 100 ) if not scores : return - 100 scores . sort ( ) best = scores [ - 1 ] return best
def npy_to_numpy ( npy_array ) : # type : ( object ) - > np . array """Convert an NPY array into numpy . Args : npy _ array ( npy array ) : to be converted to numpy array Returns : ( np . array ) : converted numpy array ."""
stream = BytesIO ( npy_array ) return np . load ( stream , allow_pickle = True )
def auto_inline_code ( self , node ) : """Try to automatically generate nodes for inline literals . Parameters node : nodes . literal Original codeblock node Returns tocnode : docutils node The converted toc tree node , None if conversion is not possible ."""
assert isinstance ( node , nodes . literal ) if len ( node . children ) != 1 : return None content = node . children [ 0 ] if not isinstance ( content , nodes . Text ) : return None content = content . astext ( ) . strip ( ) if content . startswith ( '$' ) and content . endswith ( '$' ) : if not self . conf...
def inverse_kinematics ( self , target_position_right , target_orientation_right , target_position_left , target_orientation_left , rest_poses , ) : """Helper function to do inverse kinematics for a given target position and orientation in the PyBullet world frame . Args : target _ position _ { right , left }...
ndof = 48 ik_solution = list ( p . calculateInverseKinematics ( self . ik_robot , self . effector_right , target_position_right , targetOrientation = target_orientation_right , restPoses = rest_poses [ : 7 ] , lowerLimits = self . lower , upperLimits = self . upper , jointRanges = self . ranges , jointDamping = [ 0.7 ]...
def check_name_not_on_dapi ( cls , dap ) : '''Check that the package _ name is not registered on Dapi . Return list of problems .'''
problems = list ( ) if dap . meta [ 'package_name' ] : from . import dapicli d = dapicli . metadap ( dap . meta [ 'package_name' ] ) if d : problems . append ( DapProblem ( 'This dap name is already registered on Dapi' , level = logging . WARNING ) ) return problems
def detect_tag ( filename ) : """Return type and position of ID3v2 tag in filename . Returns ( tag _ class , offset , length ) , where tag _ class is either Tag22 , Tag23 , or Tag24 , and ( offset , length ) is the position of the tag in the file ."""
with fileutil . opened ( filename , "rb" ) as file : file . seek ( 0 ) header = file . read ( 10 ) file . seek ( 0 ) if len ( header ) < 10 : raise NoTagError ( "File too short" ) if header [ 0 : 3 ] != b"ID3" : raise NoTagError ( "ID3v2 tag not found" ) if header [ 3 ] not in _t...
def call ( self , additional_fields , restriction , shape , depth , max_items , offset ) : """Find subfolders of a folder . : param additional _ fields : the extra fields that should be returned with the folder , as FieldPath objects : param shape : The set of attributes to return : param depth : How deep in ...
from . folders import Folder roots = { f . root for f in self . folders } if len ( roots ) != 1 : raise ValueError ( 'FindFolder must be called with folders in the same root hierarchy (%r)' % roots ) root = roots . pop ( ) for elem in self . _paged_call ( payload_func = self . get_payload , max_items = max_items , ...
def glob ( patterns , * , flags = 0 ) : """Glob ."""
return list ( iglob ( util . to_tuple ( patterns ) , flags = flags ) )
def close ( self ) : """turn off stream and close socket"""
if self . streamSock : self . watch ( enable = False ) self . streamSock . close ( ) self . streamSock = None
def run ( scenario , magicc_version = 6 , ** kwargs ) : """Run a MAGICC scenario and return output data and ( optionally ) config parameters . As a reminder , putting ` ` out _ parameters = 1 ` ` will cause MAGICC to write out its parameters into ` ` out / PARAMETERS . OUT ` ` and they will then be read into ...
if magicc_version == 6 : magicc_cls = MAGICC6 elif magicc_version == 7 : magicc_cls = MAGICC7 else : raise ValueError ( "MAGICC version {} is not available" . format ( magicc_version ) ) with magicc_cls ( ) as magicc : results = magicc . run ( scenario = scenario , ** kwargs ) return results
def insert_rows ( fc , features , fields , includeOIDField = False , oidField = None ) : """inserts rows based on a list features object"""
if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) icur = None if includeOIDField : arcpy . AddField_management ( fc , "FSL_OID" , "LONG" ) fields . append ( "FSL_OID" ) if len ( features ) > 0 : fields . append ( "SHAPE@" ) workspace = os . path . dirname ( fc ) ...
def arrays_to_hdf5 ( filename = "cache.hdf5" ) : """Returns registry for serialising arrays to a HDF5 reference ."""
return Registry ( types = { numpy . ndarray : SerNumpyArrayToHDF5 ( filename , "cache.lock" ) } , hooks = { '<ufunc>' : SerUFunc ( ) } , hook_fn = _numpy_hook )
def confirmation_view ( template , doc = "Display a confirmation view." ) : """Confirmation view generator for the " comment was posted / flagged / deleted / approved " views ."""
def confirmed ( request ) : comment = None if 'c' in request . GET : try : comment = comments . get_model ( ) . objects . get ( pk = request . GET [ 'c' ] ) except ( ObjectDoesNotExist , ValueError ) : pass return render ( request , template , { 'comment' : comment } ...
def _do_if_else_condition ( self , condition ) : """Common logic for evaluating the conditions on # if , # ifdef and # ifndef lines ."""
self . save ( ) d = self . dispatch_table if condition : self . start_handling_includes ( ) d [ 'elif' ] = self . stop_handling_includes d [ 'else' ] = self . stop_handling_includes else : self . stop_handling_includes ( ) d [ 'elif' ] = self . do_elif d [ 'else' ] = self . start_handling_includ...
def PushItem ( self , item , block = True ) : """Push an item on to the queue . If no ZeroMQ socket has been created , one will be created the first time this method is called . Args : item ( object ) : item to push on the queue . block ( Optional [ bool ] ) : whether the push should be performed in block...
if not self . _zmq_socket : self . _CreateZMQSocket ( ) if not self . _terminate_event : raise RuntimeError ( 'Missing terminate event.' ) logger . debug ( 'Push on {0:s} queue, port {1:d}' . format ( self . name , self . port ) ) last_retry_timestamp = time . time ( ) + self . timeout_seconds while not self . ...
def _strip_placeholder_braces ( p_matchobj ) : """Returns string with conditional braces around placeholder stripped and percent sign glued into placeholder character . Returned string is composed from ' start ' , ' before ' , ' placeholder ' , ' after ' , ' whitespace ' , and ' end ' match - groups of p _ ma...
before = p_matchobj . group ( 'before' ) or '' placeholder = p_matchobj . group ( 'placeholder' ) after = p_matchobj . group ( 'after' ) or '' whitespace = p_matchobj . group ( 'whitespace' ) or '' return before + '%' + placeholder + after + whitespace
def disambiguate ( self , symclasses ) : """Use the connection to the atoms around a given vertex as a multiplication function to disambiguate a vertex"""
offsets = self . offsets result = symclasses [ : ] for index in self . range : try : val = 1 for offset , bondtype in offsets [ index ] : val *= symclasses [ offset ] * bondtype except OverflowError : # Hmm , how often does this occur ? val = 1L for offset , bondtype ...
def visit_Name ( self , node ) : """Return dependencies for given variable . It have to be register first ."""
if node . id in self . naming : return self . naming [ node . id ] elif node . id in self . global_declarations : return [ frozenset ( [ self . global_declarations [ node . id ] ] ) ] elif isinstance ( node . ctx , ast . Param ) : deps = [ frozenset ( ) ] self . naming [ node . id ] = deps return de...
def try_again_later ( self , seconds ) : """Put this cluster in retry - wait ( or consider it dead )"""
if not self . failed : self . fails += 1 self . retry_at = ( dt . datetime . now ( ) + timedelta ( seconds = seconds ) )
def main ( ) : """Main method ."""
run_config = _parse_args ( sys . argv [ 1 : ] ) gitlab_config = GitLabConfig ( run_config . url , run_config . token ) manager = ProjectVariablesManager ( gitlab_config , run_config . project ) output = json . dumps ( manager . get ( ) , sort_keys = True , indent = 4 , separators = ( "," , ": " ) ) print ( output )
def records ( account_id ) : """Fetch locks data"""
s = boto3 . Session ( ) table = s . resource ( 'dynamodb' ) . Table ( 'Sphere11.Dev.ResourceLocks' ) results = table . scan ( ) for r in results [ 'Items' ] : if 'LockDate' in r : r [ 'LockDate' ] = datetime . fromtimestamp ( r [ 'LockDate' ] ) if 'RevisionDate' in r : r [ 'RevisionDate' ] = dat...
def modis_filename2modisdate ( modis_fname ) : """# MODIS _ FILENAME2DATE : Convert MODIS file name to MODIS date # @ author : Renaud DUSSURGET ( LER PAC / IFREMER ) # @ history : Created by RD on 29/10/2012"""
if not isinstance ( modis_fname , list ) : modis_fname = [ modis_fname ] return [ os . path . splitext ( os . path . basename ( m ) ) [ 0 ] [ 1 : 12 ] for m in modis_fname ]
def _phir ( self , rho , T , x ) : """Residual contribution to the free Helmholtz energy Parameters rho : float Density , [ kg / m3] T : float Temperature , [ K ] x : float Mole fraction of ammonia in mixture , [ mol / mol ] Returns prop : dict dictionary with residual adimensional helmholtz ene...
# Temperature reducing value , Eq 4 Tc12 = 0.9648407 / 2 * ( IAPWS95 . Tc + NH3 . Tc ) Tn = ( 1 - x ) ** 2 * IAPWS95 . Tc + x ** 2 * NH3 . Tc + 2 * x * ( 1 - x ** 1.125455 ) * Tc12 dTnx = - 2 * IAPWS95 . Tc * ( 1 - x ) + 2 * x * NH3 . Tc + 2 * Tc12 * ( 1 - x ** 1.125455 ) - 2 * Tc12 * 1.12455 * x ** 1.12455 # Density r...
def locale_export ( ) : """Exports for dealing with Click - based programs and ASCII / Unicode errors . RuntimeError : Click will abort further execution because Python 3 was configured to use ASCII as encoding for the environment . Consult https : / / click . palletsprojects . com / en / 7 . x / python3 / fo...
locale_to_use = "C.UTF-8" try : locales = subprocess . check_output ( [ "locale" , "-a" ] ) . decode ( errors = "ignore" ) . split ( "\n" ) except subprocess . CalledProcessError : locales = [ ] for locale in locales : if locale . lower ( ) . endswith ( ( "utf-8" , "utf8" ) ) : locale_to_use = local...
def landing_target_send ( self , time_usec , target_num , frame , angle_x , angle_y , distance , size_x , size_y , force_mavlink1 = False ) : '''The location of a landing area captured from a downward facing camera time _ usec : Timestamp ( micros since boot or Unix epoch ) ( uint64 _ t ) target _ num : The ID ...
return self . send ( self . landing_target_encode ( time_usec , target_num , frame , angle_x , angle_y , distance , size_x , size_y ) , force_mavlink1 = force_mavlink1 )
def get_locales ( self ) : """Get a list of supported locales . Computes the list using ` ` I18N _ LANGUAGES ` ` configuration variable ."""
if self . _locales_cache is None : langs = [ self . babel . default_locale ] for l , dummy_title in current_app . config . get ( 'I18N_LANGUAGES' , [ ] ) : langs . append ( self . babel . load_locale ( l ) ) self . _locales_cache = langs return self . _locales_cache
def transition ( value , maximum , start , end ) : """Transition between two values . : param value : Current iteration . : param maximum : Maximum number of iterations . : param start : Start value . : param end : End value . : returns : Transitional value ."""
return round ( start + ( end - start ) * value / maximum , 2 )
def rr_absent ( name , HostedZoneId = None , DomainName = None , PrivateZone = False , Name = None , Type = None , SetIdentifier = None , region = None , key = None , keyid = None , profile = None ) : '''Ensure the Route53 record is deleted . name The name of the state definition . This will be used for Name if...
Name = Name if Name else name if Type is None : raise SaltInvocationError ( "'Type' is a required parameter when deleting resource records." ) ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } args = { 'Id' : HostedZoneId , 'Name' : DomainName , 'PrivateZone' : PrivateZone , 'region' : re...
def pad ( x , p = 3 ) : """Pad tensor in H , W Remarks : TensorFlow uses " ceil ( input _ spatial _ shape [ i ] / strides [ i ] ) " rather than explicit padding like Caffe , pyTorch does . Hence , we need to pad here beforehand . Args : x ( tf . tensor ) : incoming tensor p ( int , optional ) : padding ...
return tf . pad ( x , [ [ 0 , 0 ] , [ 0 , 0 ] , [ p , p ] , [ p , p ] ] )
def _include_environment_variables ( self , program , executor_vars ) : """Define environment variables ."""
env_vars = { 'RESOLWE_HOST_URL' : self . settings_actual . get ( 'RESOLWE_HOST_URL' , 'localhost' ) , } set_env = self . settings_actual . get ( 'FLOW_EXECUTOR' , { } ) . get ( 'SET_ENV' , { } ) env_vars . update ( executor_vars ) env_vars . update ( set_env ) export_commands = [ 'export {}={}' . format ( key , shlex ....
def wait_for_path_blocking ( path : pathlib . Path , timeout : int = 30 ) -> None : """Waits up to ` ` timeout ` ` seconds for the path to appear at path ` ` path ` ` otherwise raises : exc : ` TimeoutError ` ."""
start_at = time . monotonic ( ) while time . monotonic ( ) - start_at < timeout : if path . exists ( ) : return else : time . sleep ( 0.05 ) raise TimeoutError ( f"IPC socket file {path} has not appeared in {timeout} seconds" )
def mux ( index , * mux_ins , ** kwargs ) : """Multiplexer returning the value of the wire in . : param WireVector index : used as the select input to the multiplexer : param WireVector mux _ ins : additional WireVector arguments selected when select > 1 : param WireVector kwargs : additional WireVectors , ke...
if kwargs : # only " default " is allowed as kwarg . if len ( kwargs ) != 1 or 'default' not in kwargs : try : result = select ( index , ** kwargs ) import warnings warnings . warn ( "Predicates are being deprecated in Mux. " "Use the select operator instead." , stackleve...
def hash_sha256 ( buf ) : """AuthenticationHelper . hash"""
a = hashlib . sha256 ( buf ) . hexdigest ( ) return ( 64 - len ( a ) ) * '0' + a
def convert_numeric_id_to_id36 ( numeric_id ) : """Convert an integer into its base36 string representation . This method has been cleaned up slightly to improve readability . For more info see : https : / / github . com / reddit / reddit / blob / master / r2 / r2 / lib / utils / _ utils . pyx https : / / w...
# base36 allows negative numbers , but reddit does not if not isinstance ( numeric_id , six . integer_types ) or numeric_id < 0 : raise ValueError ( "must supply a positive int/long" ) # Alphabet used for base 36 conversion alphabet = '0123456789abcdefghijklmnopqrstuvwxyz' alphabet_len = len ( alphabet ) # Temp ass...
def encode_intervals ( self , duration , intervals , values , dtype = np . bool , multi = True , fill = None ) : '''Encode labeled intervals as a time - series matrix . Parameters duration : number The duration ( in frames ) of the track intervals : np . ndarray , shape = ( n , 2) The list of intervals ...
if fill is None : fill = fill_value ( dtype ) frames = time_to_frames ( intervals , sr = self . sr , hop_length = self . hop_length ) n_total = int ( time_to_frames ( duration , sr = self . sr , hop_length = self . hop_length ) ) values = values . astype ( dtype ) n_alloc = n_total if np . any ( frames ) : n_al...
def parse_args ( ) : """Parse the command line arguments"""
global default_device parser = argparse . ArgumentParser ( description = 'Initialize OATH token for use with yhsm-validation-server' , add_help = True , formatter_class = argparse . ArgumentDefaultsHelpFormatter , ) parser . add_argument ( '-D' , '--device' , dest = 'device' , default = default_device , required = Fals...
def _strip_nones ( d : Dict [ str , Any ] ) -> Dict [ str , Any ] : """An attribute with type None is equivalent to an absent attribute . : param d : Object with attributes : return : Object dictionary w / Nones and underscores removed"""
return OrderedDict ( { k : None if isinstance ( v , JSGNull ) else v for k , v in d . items ( ) if not k . startswith ( "_" ) and v is not None and v is not Empty and ( issubclass ( type ( v ) , JSGObject ) or ( not issubclass ( type ( v ) , JSGString ) or v . val is not None ) and ( not issubclass ( type ( v ) , AnyTy...
def geodetic2ecef ( lat : float , lon : float , alt : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : """point transformation from Geodetic of specified ellipsoid ( default WGS - 84 ) to ECEF Parameters lat : float or numpy . ndarray of float target geodetic latitude ...
if ell is None : ell = Ellipsoid ( ) if deg : lat = radians ( lat ) lon = radians ( lon ) with np . errstate ( invalid = 'ignore' ) : # need np . any ( ) to handle scalar and array cases if np . any ( ( lat < - pi / 2 ) | ( lat > pi / 2 ) ) : raise ValueError ( '-90 <= lat <= 90' ) # radius of c...
def listener_create_event ( self , listener_info ) : """Process listener create event . This is lbaas v2 vif will be plugged into ovs when first listener is created and unpluged from ovs when last listener is deleted"""
listener_data = listener_info . get ( 'listener' ) lb_list = listener_data . get ( 'loadbalancers' ) for lb in lb_list : lb_id = lb . get ( 'id' ) req = dict ( instance_id = ( lb_id . replace ( '-' , '' ) ) ) instances = self . get_vms_for_this_req ( ** req ) if not instances : lb_info = self . ...
def simple_moving_matrix ( x , n = 10 ) : """Create simple moving matrix . Parameters x : ndarray A numpy array n : integer The number of sample points used to make average Returns ndarray A n x n numpy array which will be useful for calculating confidentail interval of simple moving average"""
if x . ndim > 1 and len ( x [ 0 ] ) > 1 : x = np . average ( x , axis = 1 ) h = n / 2 o = 0 if h * 2 == n else 1 xx = [ ] for i in range ( h , len ( x ) - h ) : xx . append ( x [ i - h : i + h + o ] ) return np . array ( xx )
def _add_lines ( specification , module ) : """Return autodoc commands for a basemodels docstring . Note that ` collection classes ` ( e . g . ` Model ` , ` ControlParameters ` , ` InputSequences ` are placed on top of the respective section and the ` contained classes ` ( e . g . model methods , ` ControlPar...
caption = _all_spec2capt . get ( specification , 'dummy' ) if caption . split ( ) [ - 1 ] in ( 'parameters' , 'sequences' , 'Masks' ) : exists_collectionclass = True name_collectionclass = caption . title ( ) . replace ( ' ' , '' ) else : exists_collectionclass = False lines = [ ] if specification == 'model...
def _parse_networks ( networks ) : '''Common logic for parsing the networks'''
networks = salt . utils . args . split_input ( networks or [ ] ) if not networks : networks = { } else : # We don ' t want to recurse the repack , as the values of the kwargs # being passed when connecting to the network will not be dictlists . networks = salt . utils . data . repack_dictlist ( networks ) i...
def save ( self , * args , ** kwargs ) : """Customized to generate an image from the pdf file ."""
# open image from pdf img = Image ( filename = self . file . path + '[0]' ) # make new filename filename = os . path . basename ( self . file . path ) . split ( '.' ) [ : - 1 ] if type ( filename ) == list : filename = '' . join ( filename ) # TODO : Would be better to compute this path from the upload _ to # setti...
def _send ( self ) : """Send data to graphite . Data that can not be sent will be queued ."""
# Check to see if we have a valid socket . If not , try to connect . try : try : if self . socket is None : self . log . debug ( "GraphiteHandler: Socket is not connected. " "Reconnecting." ) self . _connect ( ) if self . socket is None : self . log . debug ( "Gra...
def logged_in ( f ) : """Decorator for Page methods that require the user to be authenticated ."""
@ wraps ( f ) def wrapped_method ( self , * args , ** kwargs ) : if not self . reddit . is_oauth_session ( ) : self . term . show_notification ( 'Not logged in' ) return None return f ( self , * args , ** kwargs ) return wrapped_method
def filter ( self , read ) : """Check if a read passes the filter . @ param read : A C { Read } instance . @ return : C { read } if C { read } passes the filter , C { False } if not ."""
self . readIndex += 1 if self . alwaysFalse : return False if self . wantedSequenceNumberGeneratorExhausted : return False if self . nextWantedSequenceNumber is not None : if self . readIndex + 1 == self . nextWantedSequenceNumber : # We want this sequence . try : self . nextWantedSequen...
def print_err ( * args , ** kwargs ) : """print _ err ( * args , flush = False ) Same as * print * , but outputs to stderr . If * flush * is * True * , stderr is flushed after printing ."""
sys . stderr . write ( " " . join ( str ( arg ) for arg in args ) + "\n" ) if kwargs . get ( "flush" , False ) : sys . stderr . flush ( )
def is_ipv6_filter ( ip , options = None ) : '''Returns a bool telling if the value passed to it was a valid IPv6 address . ip The IP address . net : False Consider IP addresses followed by netmask . options CSV of options regarding the nature of the IP address . E . g . : loopback , multicast , private...
_is_ipv6 = _is_ipv ( ip , 6 , options = options ) return isinstance ( _is_ipv6 , six . string_types )
def _get_answer ( self , part ) : """Note : Answers are only revealed after a correct submission . If you ' ve have not already solved the puzzle , AocdError will be raised ."""
answer_fname = getattr ( self , "answer_{}_fname" . format ( part ) ) if os . path . isfile ( answer_fname ) : with open ( answer_fname ) as f : return f . read ( ) . strip ( ) # scrape puzzle page for any previously solved answers response = requests . get ( self . url , cookies = self . _cookies , headers...
def lemmatise ( self , word ) : '''Tries to find the base form ( lemma ) of the given word , using the data provided by the Projekt deutscher Wortschatz . This method returns a list of potential lemmas . > > > gn . lemmatise ( u ' Männer ' ) [ u ' Mann ' ] > > > gn . lemmatise ( u ' XYZ123 ' ) [ u ' XY...
lemmas = list ( self . _mongo_db . lemmatiser . find ( { 'word' : word } ) ) if lemmas : return [ lemma [ 'lemma' ] for lemma in lemmas ] else : return [ word ]
def _pad_added ( self , element , pad ) : """The callback for GstElement ' s " pad - added " signal ."""
# Decoded data is ready . Connect up the decoder , finally . name = pad . query_caps ( None ) . to_string ( ) if name . startswith ( 'audio/x-raw' ) : nextpad = self . conv . get_static_pad ( 'sink' ) if not nextpad . is_linked ( ) : self . _got_a_pad = True pad . link ( nextpad )
def get_projection_on_elements ( self ) : """Method returning a dictionary of projections on elements . Returns : a dictionary in the { Spin . up : [ ] [ { Element : values } ] , Spin . down : [ ] [ { Element : values } ] } format if there is no projections in the band structure returns an empty dict"""
result = { } structure = self . structure for spin , v in self . projections . items ( ) : result [ spin ] = [ [ collections . defaultdict ( float ) for i in range ( len ( self . kpoints ) ) ] for j in range ( self . nb_bands ) ] for i , j , k in itertools . product ( range ( self . nb_bands ) , range ( len ( s...
def coupling_constant ( self , specie ) : """Computes the couplling constant C _ q as defined in : Wasylishen R E , Ashbrook S E , Wimperis S . NMR of quadrupolar nuclei in solid materials [ M ] . John Wiley & Sons , 2012 . ( Chapter 3.2) C _ q for a specific atom type for this electric field tensor : C _ q...
planks_constant = FloatWithUnit ( 6.62607004E-34 , "m^2 kg s^-1" ) Vzz = FloatWithUnit ( self . V_zz , "V ang^-2" ) e = FloatWithUnit ( - 1.60217662E-19 , "C" ) # Convert from string to Specie object if isinstance ( specie , str ) : # isotope was provided in string format if len ( specie . split ( "-" ) ) > 1 : ...
def compute_search_efficiency_in_bins ( found , total , ndbins , sim_to_bins_function = lambda sim : ( sim . distance , ) ) : """Calculate search efficiency in the given ndbins . The first dimension of ndbins must be bins over injected distance . sim _ to _ bins _ function must map an object to a tuple indexing...
bins = bin_utils . BinnedRatios ( ndbins ) # increment the numerator and denominator with found / found + missed injs [ bins . incnumerator ( sim_to_bins_function ( sim ) ) for sim in found ] [ bins . incdenominator ( sim_to_bins_function ( sim ) ) for sim in total ] # regularize by setting denoms to 1 to avoid nans bi...
def terminate ( self ) : """Terminate Qutepart instance . This method MUST be called before application stop to avoid crashes and some other interesting effects Call it on close to free memory and stop background highlighting"""
self . text = '' self . _completer . terminate ( ) if self . _highlighter is not None : self . _highlighter . terminate ( ) if self . _vim is not None : self . _vim . terminate ( )
def validate ( self ) : """Validate workflow object . This method currently validates the workflow object with the use of cwltool . It writes the workflow to a tmp CWL file , reads it , validates it and removes the tmp file again . By default , the workflow is written to file using absolute paths to the ste...
# define tmpfile ( fd , tmpfile ) = tempfile . mkstemp ( ) os . close ( fd ) try : # save workflow object to tmpfile , # do not recursively call validate function self . save ( tmpfile , mode = 'abs' , validate = False ) # load workflow from tmpfile document_loader , processobj , metadata , uri = load_cwl (...
def userstream_user ( self , delegate , stall_warnings = None , with_ = 'followings' , replies = None ) : """Streams messages for a single user . https : / / dev . twitter . com / docs / api / 1.1 / get / user The ` ` stringify _ friend _ ids ` ` parameter is always set to ` ` ' true ' ` ` for consistency wit...
params = { 'stringify_friend_ids' : 'true' } set_bool_param ( params , 'stall_warnings' , stall_warnings ) set_str_param ( params , 'with' , with_ ) set_str_param ( params , 'replies' , replies ) svc = TwitterStreamService ( lambda : self . _get_userstream ( 'user.json' , params ) , delegate ) return svc
def setHoverable ( self , state ) : """Sets whether or not this is a hoverable button . When in a hoverable state , the icon will only be visible when the button is hovered on . : param state | < bool >"""
self . _hoverable = state self . _hoverIcon = self . icon ( )
def copy ( string ) : """Copy given string into system clipboard ."""
win32clipboard . OpenClipboard ( ) win32clipboard . EmptyClipboard ( ) win32clipboard . SetClipboardText ( string ) win32clipboard . CloseClipboard ( )
def compute_merkle_tree ( items : Iterable [ bytes ] ) -> MerkleTree : """Calculates the merkle root for a given list of items"""
if not all ( isinstance ( l , bytes ) and len ( l ) == 32 for l in items ) : raise ValueError ( 'Not all items are hashes' ) leaves = sorted ( items ) if len ( leaves ) == 0 : return MerkleTree ( layers = [ [ EMPTY_MERKLE_ROOT ] ] ) if not len ( leaves ) == len ( set ( leaves ) ) : raise ValueError ( 'The l...
def posthoc_nemenyi_friedman ( a , y_col = None , block_col = None , group_col = None , melted = False , sort = False ) : '''Calculate pairwise comparisons using Nemenyi post hoc test for unreplicated blocked data . This test is usually conducted post hoc if significant results of the Friedman ' s test are obta...
if melted and not all ( [ block_col , group_col , y_col ] ) : raise ValueError ( 'block_col, group_col, y_col should be explicitly specified if using melted data' ) def compare_stats ( i , j ) : dif = np . abs ( R [ groups [ i ] ] - R [ groups [ j ] ] ) qval = dif / np . sqrt ( k * ( k + 1. ) / ( 6. * n ) )...
def rotation_matrix ( axis , theta ) : """The Euler – Rodrigues formula . Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians . Parameters axis : vector to rotate around theta : rotation angle , in rad"""
axis = np . asarray ( axis ) axis = axis / np . linalg . norm ( axis ) a = np . cos ( theta / 2 ) b , c , d = - axis * np . sin ( theta / 2 ) aa , bb , cc , dd = a * a , b * b , c * c , d * d bc , ad , ac , ab , bd , cd = b * c , a * d , a * c , a * b , b * d , c * d return np . array ( [ [ aa + bb - cc - dd , 2 * ( bc...
def _on_message ( self , delivery_frame , properties , body , consumer ) : """Callback when a message is received from the server . This method wraps a user - registered callback for message delivery . It decodes the message body , determines the message schema to validate the message with , and validates the...
_legacy_twisted_log . msg ( "Message arrived with delivery tag {tag} for {consumer}" , tag = delivery_frame . delivery_tag , consumer = consumer , logLevel = logging . DEBUG , ) try : message = get_message ( delivery_frame . routing_key , properties , body ) message . queue = consumer . queue except ValidationE...
def temperature ( temp : Number , unit : str = 'C' ) -> str : """Formats a temperature element into a string with both C and F values Used for both Temp and Dew Ex : 34 ° C ( 93 ° F )"""
unit = unit . upper ( ) if not ( temp and unit in ( 'C' , 'F' ) ) : return '' if unit == 'C' : converted = temp . value * 1.8 + 32 converted = str ( int ( round ( converted ) ) ) + '°F' # type : ignore elif unit == 'F' : converted = ( temp . value - 32 ) / 1.8 converted = str ( int ( round ( con...
def close ( self ) : """Close all active poll instances and remove all callbacks ."""
if self . _mpoll is None : return for mpoll in self . _mpoll . values ( ) : mpoll . close ( ) self . _mpoll . clear ( ) self . _mpoll = None
def get_class_paths ( _class , saltclass_path ) : '''Converts the dotted notation of a saltclass class to its possible file counterparts . : param str _ class : Dotted notation of the class : param str saltclass _ path : Root to saltclass storage : return : 3 - tuple of possible file counterparts : rtype : ...
straight = os . path . join ( saltclass_path , 'classes' , '{0}.yml' . format ( _class ) ) sub_straight = os . path . join ( saltclass_path , 'classes' , '{0}.yml' . format ( _class . replace ( '.' , os . sep ) ) ) sub_init = os . path . join ( saltclass_path , 'classes' , _class . replace ( '.' , os . sep ) , 'init.ym...
def resolve_url_ext ( to , params_ = None , anchor_ = None , args = None , kwargs = None ) : """Advanced resolve _ url which can includes GET - parameters and anchor ."""
url = resolve_url ( to , * ( args or ( ) ) , ** ( kwargs or { } ) ) if params_ : url += '?' + urllib . urlencode ( encode_url_query_params ( params_ ) ) if anchor_ : url += '#' + anchor_ return url
def add_proxy_for ( self , name , widget ) : """Create a proxy for a widget and add it to this group : param name : The name or key of the proxy , which will be emitted with the changed signal : param widget : The widget to create a proxy for"""
proxy = proxy_for ( widget ) self . add_proxy ( name , proxy )
def _remove_double_brackets ( text ) : """Remove double brackets ( internal links ) but leave the viewable text . Args : text : a unicode string Returns : a unicode string"""
def replacement_fn ( s ) : if u":" in s : # this is probably a category or something like that . return "" # keep the part after the bar . bar_pos = s . find ( u"|" ) if bar_pos == - 1 : return s return s [ bar_pos + 1 : ] return _find_and_replace ( text , u"[[" , u"]]" , replacement...
def replace_nones ( dict_or_list ) : """Update a dict or list in place to replace ' none ' string values with Python None ."""
def replace_none_in_value ( value ) : if isinstance ( value , basestring ) and value . lower ( ) == "none" : return None return value items = dict_or_list . iteritems ( ) if isinstance ( dict_or_list , dict ) else enumerate ( dict_or_list ) for accessor , value in items : if isinstance ( value , ( d...
def replace_namespaced_replication_controller_dummy_scale ( self , name , namespace , body , ** kwargs ) : """replace scale of the specified ReplicationControllerDummy This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread =...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . replace_namespaced_replication_controller_dummy_scale_with_http_info ( name , namespace , body , ** kwargs ) else : ( data ) = self . replace_namespaced_replication_controller_dummy_scale_with_http_info ( name , namespace...
def _export ( self , args , ** extra_args ) : """Export is the entry point for exporting docker images ."""
if not isinstance ( args , argparse . Namespace ) : raise TypeError ( logger . error ( "args should of an instance of argparse.Namespace" ) ) # Warn the consumer about unsafe Docker Practices if args . no_validation : logger . warning ( "#######################################################\n" "Validation has...
def remove_logger ( self , cb_id ) : '''Remove a logger . @ param cb _ id The ID of the logger to remove . @ raises NoLoggerError'''
if cb_id not in self . _loggers : raise exceptions . NoLoggerError ( cb_id , self . name ) conf = self . object . get_configuration ( ) res = conf . remove_service_profile ( cb_id . get_bytes ( ) ) del self . _loggers [ cb_id ]
def log_param ( name , value ) : '''Log a parameter value to the console . Parameters name : str Name of the parameter being logged . value : any Value of the parameter being logged .'''
log ( 'setting {} = {}' , click . style ( str ( name ) ) , click . style ( str ( value ) , fg = 'yellow' ) )