signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get ( self , index : int ) -> TOption [ T ] : """: param index : Usage : > > > TList ( [ 1 , 2 , 3 , 4 , 5 ] ) . get ( 3) Option - - > 4 > > > TList ( [ 1 , 2 , 3 , 4 , 5 ] ) . get ( 5) Option - - > None"""
return TOption ( self [ index ] ) if len ( self ) > index else TOption ( None )
def contributors ( self ) : """Property to retrieve or access the list of contributors ."""
if not self . _contributors : self . _contributors = self . get_contributors ( ) return self . _contributors
def transform ( self , data ) : """: param data : DataFrame with column to encode : return : encoded Series"""
with timer ( 'transform %s' % self . name , logging . DEBUG ) : transformed = super ( Token , self ) . transform ( self . tokenize ( data ) ) return transformed . reshape ( ( len ( data ) , self . sequence_length ) )
def start ( self ) : """: meth : ` WStoppableTask . start ` implementation that creates new thread"""
start_event = self . start_event ( ) stop_event = self . stop_event ( ) ready_event = self . ready_event ( ) def thread_target ( ) : try : start_event . set ( ) self . thread_started ( ) if ready_event is not None : ready_event . set ( ) except Exception as e : self ....
def _draw_arrow ( self , x1 , y1 , x2 , y2 , Dx , Dy , label = "" , width = 1.0 , arrow_curvature = 1.0 , color = "grey" , patchA = None , patchB = None , shrinkA = 0 , shrinkB = 0 , arrow_label_size = None ) : """Draws a slightly curved arrow from ( x1 , y1 ) to ( x2 , y2 ) . Will allow the given patches at star...
# set arrow properties dist = _sqrt ( ( ( x2 - x1 ) / float ( Dx ) ) ** 2 + ( ( y2 - y1 ) / float ( Dy ) ) ** 2 ) arrow_curvature *= 0.075 # standard scale rad = arrow_curvature / ( dist ) tail_width = width head_width = max ( 0.5 , 2 * width ) head_length = head_width self . ax . annotate ( "" , xy = ( x2 , y2 ) , xyc...
def _parse_response ( self , result_page ) : """Takes a result page of sending the sms , returns an extracted tuple : ( ' numeric _ err _ code ' , ' < sent _ queued _ message _ id > ' , ' < smsglobalmsgid > ' ) Returns None if unable to extract info from result _ page , it should be safe to assume that it was...
# Sample result _ page , single line - > " OK : 0 ; Sent queued message ID : 2063619577732703 SMSGlobalMsgID : 6171799108850954" resultline = result_page . splitlines ( ) [ 0 ] # get result line if resultline . startswith ( 'ERROR:' ) : raise Exception ( resultline . replace ( 'ERROR: ' , '' ) ) patt = re . compile...
def split_number_and_unit ( s ) : """Parse a string that consists of a integer number and an optional unit . @ param s a non - empty string that starts with an int and is followed by some letters @ return a triple of the number ( as int ) and the unit"""
if not s : raise ValueError ( 'empty value' ) s = s . strip ( ) pos = len ( s ) while pos and not s [ pos - 1 ] . isdigit ( ) : pos -= 1 number = int ( s [ : pos ] ) unit = s [ pos : ] . strip ( ) return ( number , unit )
def error ( msg , delay = 0.5 , chevrons = True , verbose = True ) : """Log a message to stdout ."""
if verbose : if chevrons : click . secho ( "\n❯❯ " + msg , err = True , fg = "red" ) else : click . secho ( msg , err = True , fg = "red" ) time . sleep ( delay )
async def get_token ( cls , host , ** params ) : """POST / oauth / v2 / token Get a new token : param host : host of the service : param params : will contain : params = { " grant _ type " : " password " , " client _ id " : " a string " , " client _ secret " : " a string " , " username " : " a login "...
params [ 'grant_type' ] = "password" path = "/oauth/v2/token" async with aiohttp . ClientSession ( ) as sess : async with sess . post ( host + path , data = params ) as resp : data = await cls . handle_json_response ( resp ) return data . get ( "access_token" )
def is_on_filesystem ( value , ** kwargs ) : """Indicate whether ` ` value ` ` is a file or directory that exists on the local filesystem . : param value : The value to evaluate . : returns : ` ` True ` ` if ` ` value ` ` is valid , ` ` False ` ` if it is not . : rtype : : class : ` bool < python : bool > `...
try : value = validators . path_exists ( value , ** kwargs ) except SyntaxError as error : raise error except Exception : return False return True
def geometric_center ( coords , periodic ) : '''Geometric center taking into account periodic boundaries'''
max_vals = periodic theta = 2 * np . pi * ( coords / max_vals ) eps = np . cos ( theta ) * max_vals / ( 2 * np . pi ) zeta = np . sin ( theta ) * max_vals / ( 2 * np . pi ) eps_avg = eps . sum ( axis = 0 ) zeta_avg = zeta . sum ( axis = 0 ) theta_avg = np . arctan2 ( - zeta_avg , - eps_avg ) + np . pi return theta_avg ...
def receive ( self , protocolTreeNode ) : """: type protocolTreeNode : ProtocolTreeNode"""
if not self . processIqRegistry ( protocolTreeNode ) : if protocolTreeNode . tag == "message" : self . onMessage ( protocolTreeNode ) elif not protocolTreeNode . tag == "receipt" : # receipts will be handled by send layer self . toUpper ( protocolTreeNode )
def _check_operators ( self , operators ) : """Check Inputs This method cheks that the input operators and weights are correctly formatted Parameters operators : list , tuple or np . ndarray List of linear operator class instances Returns np . array operators Raises TypeError For invalid input t...
if not isinstance ( operators , ( list , tuple , np . ndarray ) ) : raise TypeError ( 'Invalid input type, operators must be a list, ' 'tuple or numpy array.' ) operators = np . array ( operators ) if not operators . size : raise ValueError ( 'Operator list is empty.' ) for operator in operators : if not ha...
def update ( self , * args , ** kw ) : '''Update the dictionary with items and names : : ( items , names , * * kw ) ( dict , names , * * kw ) ( MIDict , names , * * kw ) Optional positional argument ` ` names ` ` is only allowed when ` ` self . indices ` ` is empty ( no indices are set yet ) .'''
if len ( args ) > 1 and self . indices : raise ValueError ( 'Only one positional argument is allowed when the' 'index names are already set.' ) if not self . indices : # empty ; init again _MI_init ( self , * args , ** kw ) return d = MIMapping ( * args , ** kw ) if not d . indices : return names = forc...
def get ( self , subscription_id = None , stream = None , historics_id = None , page = None , per_page = None , order_by = None , order_dir = None , include_finished = None ) : """Show details of the Subscriptions belonging to this user . Uses API documented at http : / / dev . datasift . com / docs / api / rest ...
params = { } if subscription_id : params [ 'id' ] = subscription_id if stream : params [ 'hash' ] = stream if historics_id : params [ 'historics_id' ] = historics_id if page : params [ 'page' ] = page if per_page : params [ 'per_page' ] = per_page if order_by : params [ 'order_by' ] = order_by i...
def dusk_utc ( self , date , latitude , longitude , depression = 0 , observer_elevation = 0 ) : """Calculate dusk time in the UTC timezone . : param date : Date to calculate for . : type date : : class : ` datetime . date ` : param latitude : Latitude - Northern latitudes should be positive : type latitude ...
if depression == 0 : depression = self . _depression depression += 90 try : return self . _calc_time ( depression , SUN_SETTING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches %d deg...
def getReadAlignmentId ( self , gaAlignment ) : """Returns a string ID suitable for use in the specified GA ReadAlignment object in this ReadGroupSet ."""
compoundId = datamodel . ReadAlignmentCompoundId ( self . getCompoundId ( ) , gaAlignment . fragment_name ) return str ( compoundId )
def _call ( self , x ) : """Return ` ` self ( x ) ` ` ."""
with self . mutex : result = pyshearlab . SLsheardec2D ( x , self . shearlet_system ) return np . moveaxis ( result , - 1 , 0 )
def forward ( self , observations ) : """Calculate model outputs"""
input_data = self . input_block ( observations ) policy_base_output = self . policy_backbone ( input_data ) value_base_output = self . value_backbone ( input_data ) action_output = self . action_head ( policy_base_output ) value_output = self . value_head ( value_base_output ) return action_output , value_output
def add_by_steps ( self , entries_by_step , table = None , columns = None ) : """Add entries to the main table . The * entries * variable should be an iterable yielding iterables ."""
for entries in entries_by_step : self . add ( entries , table = table , columns = columns )
def format_request_email_title ( increq , ** ctx ) : """Format the email message title for inclusion request notification . : param increq : Inclusion request object for which the request is made . : type increq : ` invenio _ communities . models . InclusionRequest ` : param ctx : Optional extra context param...
template = current_app . config [ "COMMUNITIES_REQUEST_EMAIL_TITLE_TEMPLATE" ] , return format_request_email_templ ( increq , template , ** ctx )
def connections ( self ) : """Returns all of the loaded connections names as a list"""
conn = lambda x : str ( x ) . replace ( 'connection:' , '' ) return [ conn ( name ) for name in self . sections ( ) ]
def nearest ( self , idx ) : """Return datetime of record whose datetime is nearest idx ."""
hi = self . after ( idx ) lo = self . before ( idx ) if hi is None : return lo if lo is None : return hi if abs ( hi - idx ) < abs ( lo - idx ) : return hi return lo
def to_docstring ( kwargs , lpad = '' ) : """Reconstruct a docstring from keyword argument info . Basically reverses : func : ` extract _ kwargs ` . Parameters kwargs : list Output from the extract _ kwargs function lpad : str , optional Padding string ( from the left ) . Returns str The docstring...
buf = io . StringIO ( ) for name , type_ , description in kwargs : buf . write ( '%s%s: %s\n' % ( lpad , name , type_ ) ) for line in description : buf . write ( '%s %s\n' % ( lpad , line ) ) return buf . getvalue ( )
def tryCComment ( self , block ) : """C comment checking . If the previous line begins with a " / * " or a " * " , then return its leading white spaces + ' * ' + the white spaces after the * return : filler string or null , if not in a C comment"""
indentation = None prevNonEmptyBlock = self . _prevNonEmptyBlock ( block ) if not prevNonEmptyBlock . isValid ( ) : return None prevNonEmptyBlockText = prevNonEmptyBlock . text ( ) if prevNonEmptyBlockText . endswith ( '*/' ) : try : foundBlock , notUsedColumn = self . findTextBackward ( prevNonEmptyBlo...
def inception_v3 ( inputs , num_classes = 1000 , is_training = True , dropout_keep_prob = 0.8 , min_depth = 16 , depth_multiplier = 1.0 , prediction_fn = slim . softmax , spatial_squeeze = True , reuse = None , scope = 'InceptionV3' ) : """Inception model from http : / / arxiv . org / abs / 1512.00567. " Rethinki...
if depth_multiplier <= 0 : raise ValueError ( 'depth_multiplier is not greater than zero.' ) def depth ( d ) : return max ( int ( d * depth_multiplier ) , min_depth ) with tf . variable_scope ( scope , 'InceptionV3' , [ inputs , num_classes ] , reuse = reuse ) as scope : with slim . arg_scope ( [ slim . bat...
def delete ( zone ) : '''Delete the specified configuration from memory and stable storage . zone : string name of zone CLI Example : . . code - block : : bash salt ' * ' zonecfg . delete epyon'''
ret = { 'status' : True } # delete zone res = __salt__ [ 'cmd.run_all' ] ( 'zonecfg -z {zone} delete -F' . format ( zone = zone , ) ) ret [ 'status' ] = res [ 'retcode' ] == 0 ret [ 'message' ] = res [ 'stdout' ] if ret [ 'status' ] else res [ 'stderr' ] if ret [ 'message' ] == '' : del ret [ 'message' ] else : ...
def download ( ) : """Download all files from an FTP share"""
ftp = ftplib . FTP ( SITE ) ftp . set_debuglevel ( DEBUG ) ftp . login ( USER , PASSWD ) ftp . cwd ( DIR ) filelist = ftp . nlst ( ) filecounter = MANAGER . counter ( total = len ( filelist ) , desc = 'Downloading' , unit = 'files' ) for filename in filelist : with Writer ( filename , ftp . size ( filename ) , DEST...
def color_is_disabled ( ** envars ) : '''Look for clues in environment , e . g . : - https : / / bixense . com / clicolors / - http : / / no - color . org / Arguments : envars : Additional environment variables to check for equality , i . e . ` ` MYAPP _ COLOR _ DISABLED = ' 1 ' ` ` Returns : None , B...
result = None if 'NO_COLOR' in env : result = True elif env . CLICOLOR == '0' : result = True log . debug ( '%r (NO_COLOR=%s, CLICOLOR=%s)' , result , env . NO_COLOR or '' , env . CLICOLOR or '' ) for name , value in envars . items ( ) : envar = getattr ( env , name ) if envar . value == value : ...
def explain_lifecycle ( self , index = None , params = None ) : """` < https : / / www . elastic . co / guide / en / elasticsearch / reference / current / ilm - explain - lifecycle . html > ` _ : arg index : The name of the index to explain"""
return self . transport . perform_request ( "GET" , _make_path ( index , "_ilm" , "explain" ) , params = params )
def is_imagej ( self ) : """Return ImageJ description if exists , else None ."""
for description in ( self . description , self . description1 ) : if not description : return None if description [ : 7 ] == 'ImageJ=' : return description return None
def match_time_series ( self , timeseries1 , timeseries2 ) : """Return two lists of the two input time series with matching dates : param TimeSeries timeseries1 : The first timeseries : param TimeSeries timeseries2 : The second timeseries : return : Two two dimensional lists containing the matched values , ...
time1 = map ( lambda item : item [ 0 ] , timeseries1 . to_twodim_list ( ) ) time2 = map ( lambda item : item [ 0 ] , timeseries2 . to_twodim_list ( ) ) matches = filter ( lambda x : ( x in time1 ) , time2 ) listX = filter ( lambda x : ( x [ 0 ] in matches ) , timeseries1 . to_twodim_list ( ) ) listY = filter ( lambda x...
def get_next_types ( self , n = None ) : """Gets the next set of ` ` Types ` ` in this list . The specified amount must be less than or equal to the return from ` ` available ( ) ` ` . arg : n ( cardinal ) : the number of ` ` Type ` ` elements requested which must be less than or equal to ` ` available ( ) ...
import sys from . . osid . osid_errors import IllegalState , OperationFailed if n > self . available ( ) : # ! ! ! This is not quite as specified ( see method docs ) ! ! ! raise IllegalState ( 'not enough elements available in this list' ) else : next_list = [ ] x = 0 while x < n : try : ...
def stats ( self ) : """shotcut to pull out useful info for interactive use"""
printDebug ( "Classes.....: %d" % len ( self . all_classes ) ) printDebug ( "Properties..: %d" % len ( self . all_properties ) )
def z_at_value ( func , fval , unit , zmax = 1000. , ** kwargs ) : r"""Wrapper around astropy . cosmology . z _ at _ value to handle numpy arrays . Getting a z for a cosmological quantity involves numerically inverting ` ` func ` ` . The ` ` zmax ` ` argument sets how large of a z to guess ( see : py : func :...
fval , input_is_array = ensurearray ( fval ) # make sure fval is atleast 1D if fval . size == 1 and fval . ndim == 0 : fval = fval . reshape ( 1 ) zs = numpy . zeros ( fval . shape , dtype = float ) # the output array for ( ii , val ) in enumerate ( fval ) : try : zs [ ii ] = astropy . cosmology . z_at_...
def hkdf_expand ( pseudo_random_key , info = b"" , length = 32 , hash = hashlib . sha512 ) : '''Expand ` pseudo _ random _ key ` and ` info ` into a key of length ` bytes ` using HKDF ' s expand function based on HMAC with the provided hash ( default SHA - 512 ) . See the HKDF draft RFC and paper for usage note...
hash_len = hash ( ) . digest_size length = int ( length ) if length > 255 * hash_len : raise Exception ( "Cannot expand to more than 255 * %d = %d bytes using the specified hash function" % ( hash_len , 255 * hash_len ) ) blocks_needed = length // hash_len + ( 0 if length % hash_len == 0 else 1 ) # ceil okm = b"" o...
def _clone ( self , cid ) : """Create a temporary image snapshot from a given cid . Temporary image snapshots are marked with a sentinel label so that they can be cleaned on unmount ."""
try : iid = self . client . commit ( container = cid , conf = { 'Labels' : { 'io.projectatomic.Temporary' : 'true' } } ) [ 'Id' ] except docker . errors . APIError as ex : raise MountError ( str ( ex ) ) self . tmp_image = iid return self . _create_temp_container ( iid )
def _select_query_method ( cls , url ) : """Select the correct query method based on the URL Works for ` DataQualityFlag ` and ` DataQualityDict `"""
if urlparse ( url ) . netloc . startswith ( 'geosegdb.' ) : # only DB2 server return cls . query_segdb return cls . query_dqsegdb
def query ( self , filter_text , max_servers = 10 , timeout = 30 , ** kw ) : r"""Query game servers https : / / developer . valvesoftware . com / wiki / Master _ Server _ Query _ Protocol . . note : : When specifying ` ` filter _ text ` ` use * raw strings * otherwise python won ' t treat backslashes as lit...
if 'geo_location_ip' in kw : kw [ 'geo_location_ip' ] = ip_to_int ( kw [ 'geo_location_ip' ] ) kw [ 'filter_text' ] = filter_text kw [ 'max_servers' ] = max_servers resp = self . _s . send_job_and_wait ( MsgProto ( EMsg . ClientGMSServerQuery ) , kw , timeout = timeout , ) if resp is None : return None resp = p...
def adjust_image ( f , max_size = ( 800 , 800 ) , new_format = None , jpeg_quality = 90 , fill = False , stretch = False , return_new_image = False , force_jpeg_save = True ) : """Підганяє зображення під параметри . max _ size - максимальний розмір картинки . один з розмірів може бути None ( авто ) new _ forma...
assert isinstance ( max_size , ( list , tuple ) ) and len ( max_size ) == 2 assert 0 < jpeg_quality <= 100 if new_format : new_format = new_format . lower ( ) if new_format not in ( 'jpeg' , 'png' , 'gif' ) : raise RuntimeError ( 'Invalid new_format value.' ) f . seek ( 0 ) img = Image . open ( f ) if (...
def addSource ( self , itemSource ) : """Add the given L { IBatchProcessor } as a source of input for this indexer ."""
_IndexerInputSource ( store = self . store , indexer = self , source = itemSource ) itemSource . addReliableListener ( self , style = iaxiom . REMOTE )
def __find_variant ( self , value ) : """Find the messages . Variant type that describes this value . Args : value : The value whose variant type is being determined . Returns : The messages . Variant value that best describes value ' s type , or None if it ' s a type we don ' t know how to handle ."""
if isinstance ( value , bool ) : return messages . Variant . BOOL elif isinstance ( value , six . integer_types ) : return messages . Variant . INT64 elif isinstance ( value , float ) : return messages . Variant . DOUBLE elif isinstance ( value , six . string_types ) : return messages . Variant . STRING...
def get_expr_id ( self , search_group , search , lars_id , instruments , gps_start_time , gps_end_time , comments = None ) : """Return the expr _ def _ id for the row in the table whose values match the givens . If a matching row is not found , returns None . @ search _ group : string representing the search ...
# create string from instrument set instruments = ifos_from_instrument_set ( instruments ) # look for the ID for row in self : if ( row . search_group , row . search , row . lars_id , row . instruments , row . gps_start_time , row . gps_end_time , row . comments ) == ( search_group , search , lars_id , instruments ...
def dump_to_stream ( self , cnf , stream , ** opts ) : """: param cnf : Configuration data to dump : param stream : Config file or file like object write to : param opts : optional keyword parameters"""
tree = container_to_etree ( cnf , ** opts ) etree_write ( tree , stream )
def _parseAtImports ( self , src ) : """[ import [ S | CDO | CDC ] * ] *"""
result = [ ] while isAtRuleIdent ( src , 'import' ) : ctxsrc = src src = stripAtRuleIdent ( src ) import_ , src = self . _getStringOrURI ( src ) if import_ is None : raise self . ParseError ( 'Import expecting string or url' , src , ctxsrc ) mediums = [ ] medium , src = self . _getIdent ...
def add_nio ( self , nio , port_number ) : """Adds a NIO as new port on Frame Relay switch . : param nio : NIO instance to add : param port _ number : port to allocate for the NIO"""
if port_number in self . _nios : raise DynamipsError ( "Port {} isn't free" . format ( port_number ) ) log . info ( 'Frame Relay switch "{name}" [{id}]: NIO {nio} bound to port {port}' . format ( name = self . _name , id = self . _id , nio = nio , port = port_number ) ) self . _nios [ port_number ] = nio yield from...
def load_markov ( argv , stdin ) : """Load and return markov algorithm ."""
if len ( argv ) > 3 : with open ( argv [ 3 ] ) as input_file : return Algorithm ( input_file . readlines ( ) ) else : return Algorithm ( stdin . readlines ( ) )
def _run_cnvkit_shared_orig ( inputs , backgrounds ) : """Original CNVkit implementation with full normalization and segmentation ."""
work_dir = _sv_workdir ( inputs [ 0 ] ) raw_work_dir = utils . safe_makedir ( os . path . join ( work_dir , "raw" ) ) background_name = dd . get_sample_name ( backgrounds [ 0 ] ) if backgrounds else "flat" background_cnn = os . path . join ( raw_work_dir , "%s_background.cnn" % ( background_name ) ) ckouts = [ ] for cu...
def char2range ( d , is_bytes = False , invert = True ) : """Convert the characters in the dict to a range in string form ."""
fmt = bytesformat if is_bytes else uniformat maxrange = MAXASCII if is_bytes else MAXUNICODE for k1 in sorted ( d . keys ( ) ) : v1 = d [ k1 ] if not isinstance ( v1 , list ) : char2range ( v1 , is_bytes = is_bytes , invert = invert ) else : inverted = k1 . startswith ( '^' ) v1 . so...
def system_requirements ( ) : """Check if all necessary packages are installed on system : return : None or raise exception if some tooling is missing"""
command_exists ( "systemd-nspawn" , [ "systemd-nspawn" , "--version" ] , "Command systemd-nspawn does not seems to be present on your system" "Do you have system with systemd" ) command_exists ( "machinectl" , [ "machinectl" , "--no-pager" , "--help" ] , "Command machinectl does not seems to be present on your system" ...
def get_tag_values ( self , tags , columns ) : """function to get the tag values from tags and columns"""
tag_values = [ ] i = 0 while i < len ( columns ) : tag_key = columns [ i ] if tag_key in tags : tag_values . append ( tags . get ( tag_key ) ) else : tag_values . append ( None ) i += 1 return tag_values
def basic_auth ( f ) : """Injects auth , into requests call over route : return : route"""
def wrapper ( * args , ** kwargs ) : self = args [ 0 ] if 'auth' in kwargs : raise AttributeError ( "don't set auth token explicitly" ) assert self . is_connected , "not connected, call router.connect(email, password) first" if self . _jwt_auth : kwargs [ 'auth' ] = self . _jwt_auth ...
def is_name_in_grace_period ( self , name , block_number ) : """Given a name and block number , determine if it is in the renewal grace period at that block . * names in revealed but not ready namespaces are never expired , unless the namespace itself is expired ; * names in ready namespaces enter the grace per...
cur = self . db . cursor ( ) name_rec = namedb_get_name ( cur , name , block_number , include_expired = False ) if name_rec is None : # expired already or doesn ' t exist return False namespace_id = get_namespace_from_name ( name ) namespace_rec = namedb_get_namespace ( cur , namespace_id , block_number , include_h...
def sum_string ( amount , gender , items = None ) : """Get sum in words @ param amount : amount of objects @ type amount : C { integer types } @ param gender : gender of object ( MALE , FEMALE or NEUTER ) @ type gender : C { int } @ param items : variants of object in three forms : for one object , for ...
if isinstance ( items , six . text_type ) : items = split_values ( items ) if items is None : items = ( u"" , u"" , u"" ) try : one_item , two_items , five_items = items except ValueError : raise ValueError ( "Items must be 3-element sequence" ) check_positive ( amount ) if amount == 0 : if five_ite...
def btc_tx_is_segwit ( tx_serialized ) : """Is this serialized ( hex - encoded ) transaction a segwit transaction ?"""
marker_offset = 4 # 5th byte is the marker byte flag_offset = 5 # 6th byte is the flag byte marker_byte_string = tx_serialized [ 2 * marker_offset : 2 * ( marker_offset + 1 ) ] flag_byte_string = tx_serialized [ 2 * flag_offset : 2 * ( flag_offset + 1 ) ] if marker_byte_string == '00' and flag_byte_string != '00' : # s...
def _Rforce ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ Rforce PURPOSE : evaluate the radial force for this potential INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : the radial force HISTORY : 2010-07-10 - Written - Bovy ( NYU )"""
return - R / ( R ** 2. + z ** 2. ) ** ( self . alpha / 2. )
def plot_inducing ( self , visible_dims = None , projection = '2d' , label = 'inducing' , legend = True , ** plot_kwargs ) : """Plot the inducing inputs of a sparse gp model : param array - like visible _ dims : an array specifying the input dimensions to plot ( maximum two ) : param kwargs plot _ kwargs : keyw...
canvas , kwargs = pl ( ) . new_canvas ( projection = projection , ** plot_kwargs ) plots = _plot_inducing ( self , canvas , visible_dims , projection , label , ** kwargs ) return pl ( ) . add_to_canvas ( canvas , plots , legend = legend )
def generate_bond_subgraphs_from_break ( bond_graph , atom1 , atom2 ) : """Splits the bond graph between two atoms to producing subgraphs . Notes This will not work if there are cycles in the bond graph . Parameters bond _ graph : networkx . Graph Graph of covalent bond network atom1 : isambard . ampal ...
bond_graph . remove_edge ( atom1 , atom2 ) try : subgraphs = list ( networkx . connected_component_subgraphs ( bond_graph , copy = False ) ) finally : # Add edge bond_graph . add_edge ( atom1 , atom2 ) return subgraphs
def calculate_metric ( Js , logJs , loglogJs , logloglogJs , loglogloglogJs , mapping ) : """This function will take the various integrals calculated by get _ moments and convert this into a metric for the appropriate parameter space . Parameters Js : Dictionary The list of ( log ^ 0 x ) * x * * ( - i / 3 )...
# How many dimensions in the parameter space ? maxLen = len ( mapping . keys ( ) ) metric = numpy . matrix ( numpy . zeros ( shape = ( maxLen , maxLen ) , dtype = float ) ) unmax_metric = numpy . matrix ( numpy . zeros ( shape = ( maxLen + 1 , maxLen + 1 ) , dtype = float ) ) for i in range ( 16 ) : for j in range ...
def dump ( self , backend , node ) : '''High - level function to call a ` backend ' on a ` node ' to generate code for module ` module _ name ' .'''
assert issubclass ( backend , Backend ) b = backend ( ) b . attach ( self ) return b . run ( node )
def run_check ( self , data ) : """Check for uncommon words and difficult words in file ."""
if not data : sys . exit ( 1 ) data , sentences , chars , num_words = self . pre_check ( data ) w_dict = Counter ( data ) uniq_len , uncommon , uncom_len = self . gsl ( w_dict ) non_dchall_set = Counter ( { word : count for word , count in w_dict . items ( ) if word and word not in self . dale_chall_words } ) diff_...
def filter ( args ) : """% prog filter paired . fastq Filter to get high qv reads . Use interleaved format ( one file ) or paired format ( two files ) to filter on paired reads ."""
p = OptionParser ( filter . __doc__ ) p . add_option ( "-q" , dest = "qv" , default = 20 , type = "int" , help = "Minimum quality score to keep [default: %default]" ) p . add_option ( "-p" , dest = "pct" , default = 95 , type = "int" , help = "Minimum percent of bases that have [-q] quality " "[default: %default]" ) op...
def add_entry ( self , date , entry ) : """Add the given entry to the textual representation ."""
in_date = False insert_at = 0 for ( lineno , line ) in enumerate ( self . lines ) : # Search for the date of the entry if isinstance ( line , DateLine ) and line . date == date : in_date = True # Insert here if there is no existing Entry for this date insert_at = lineno continue ...
def preprocess_cell ( self , cell , resources , cell_index ) : """Also extracts attachments"""
from nbformat . notebooknode import NotebookNode attach_names = [ ] # Just move the attachment into an output for k , attach in cell . get ( 'attachments' , { } ) . items ( ) : for mime_type in self . extract_output_types : if mime_type in attach : if not 'outputs' in cell : cell...
def get_resource_attribute ( collection , key , attribute ) : """Return the appropriate * Response * for retrieving an attribute of a single resource . : param string collection : a : class : ` sandman . model . Model ` endpoint : param string key : the primary key for the : class : ` sandman . model . Model ...
resource = retrieve_resource ( collection , key ) _validate ( endpoint_class ( collection ) , request . method , resource ) value = getattr ( resource , attribute ) if isinstance ( value , Model ) : return resource_response ( value ) else : return attribute_response ( resource , attribute , value )
def set_default_host ( cls , value ) : """Default : " http : / / 127.0.0.1:80" A string that will be automatically included at the beginning of the url generated for doing each http request ."""
if value is None : cls . DEFAULT_HOST = "http://127.0.0.1:80" else : scheme , host , port = get_hostname_parameters_from_url ( value ) cls . DEFAULT_HOST = "%s://%s:%s" % ( scheme , host , port )
def fast_hash ( self ) : """Get a CRC32 or xxhash . xxh64 reflecting the DataStore . Returns hashed : int , checksum of data"""
fast = sum ( i . fast_hash ( ) for i in self . data . values ( ) ) return fast
def _updateJobWhenDone ( self ) : """Asynchronously update the status of the job on the disk , first waiting until the writing threads have finished and the input blockFn has stopped blocking ."""
def asyncUpdate ( ) : try : # Wait till all file writes have completed for i in range ( len ( self . workers ) ) : self . queue . put ( None ) for thread in self . workers : thread . join ( ) # Wait till input block - fn returns - in the event of an exception ...
def _infer_xy_labels ( darray , x , y , imshow = False , rgb = None ) : """Determine x and y labels . For use in _ plot2d darray must be a 2 dimensional data array , or 3d for imshow only ."""
assert x is None or x != y if imshow and darray . ndim == 3 : return _infer_xy_labels_3d ( darray , x , y , rgb ) if x is None and y is None : if darray . ndim != 2 : raise ValueError ( 'DataArray must be 2d' ) y , x = darray . dims elif x is None : if y not in darray . dims and y not in darray ...
def _generate_provenance ( self ) : """Function to generate provenance at the end of the IF ."""
# noinspection PyTypeChecker hazard = definition ( self . _provenance [ 'hazard_keywords' ] [ 'hazard' ] ) exposures = [ definition ( layer . keywords [ 'exposure' ] ) for layer in self . exposures ] # InaSAFE set_provenance ( self . _provenance , provenance_impact_function_name , self . name ) set_provenance ( self . ...
def remove ( self , order , cells ) : """Remove cells at a given order from the MOC ."""
self . _normalized = False order = self . _validate_order ( order ) for cell in cells : cell = self . _validate_cell ( order , cell ) self . _compare_operation ( order , cell , True , 'remove' )
def _get_port_profile_id ( self , request ) : """Get the port profile ID from the request path ."""
# Note ( alexcoman ) : The port profile ID can be found as suffix # in request path . port_profile_id = request . path . split ( "/" ) [ - 1 ] . strip ( ) if uuidutils . is_uuid_like ( port_profile_id ) : LOG . debug ( "The instance id was found in request path." ) return port_profile_id LOG . debug ( "Failed t...
def replace_su ( network , su_to_replace ) : """Replace the storage unit su _ to _ replace with a bus for the energy carrier , two links for the conversion of the energy carrier to and from electricity , a store to keep track of the depletion of the energy carrier and its CO2 emissions , and a variable genera...
su = network . storage_units . loc [ su_to_replace ] bus_name = "{} {}" . format ( su [ "bus" ] , su [ "carrier" ] ) link_1_name = "{} converter {} to AC" . format ( su_to_replace , su [ "carrier" ] ) link_2_name = "{} converter AC to {}" . format ( su_to_replace , su [ "carrier" ] ) store_name = "{} store {}" . format...
def apply_transformer_types ( network ) : """Calculate transformer electrical parameters x , r , b , g from standard types ."""
trafos_with_types_b = network . transformers . type != "" if trafos_with_types_b . zsum ( ) == 0 : return missing_types = ( pd . Index ( network . transformers . loc [ trafos_with_types_b , 'type' ] . unique ( ) ) . difference ( network . transformer_types . index ) ) assert missing_types . empty , ( "The type(s) {...
def get_align ( text ) : "Return ( halign , valign , angle ) of the < text > ."
( x1 , x2 , h , v , a ) = unaligned_get_dimension ( text ) return ( h , v , a )
def DeriveReportKey ( cls , root_key , report_id , sent_timestamp ) : """Derive a standard one time use report signing key . The standard method is HMAC - SHA256 ( root _ key , MAGIC _ NUMBER | | report _ id | | sent _ timestamp ) where MAGIC _ NUMBER is 0x000002 and all integers are in little endian ."""
signed_data = struct . pack ( "<LLL" , AuthProvider . ReportKeyMagic , report_id , sent_timestamp ) hmac_calc = hmac . new ( root_key , signed_data , hashlib . sha256 ) return bytearray ( hmac_calc . digest ( ) )
def url_to_filename ( url ) : """Safely translate url to relative filename Args : url ( str ) : A target url string Returns : str"""
# remove leading / trailing slash if url . startswith ( '/' ) : url = url [ 1 : ] if url . endswith ( '/' ) : url = url [ : - 1 ] # remove pardir symbols to prevent unwilling filesystem access url = remove_pardir_symbols ( url ) # replace dots to underscore in filename part url = replace_dots_to_underscores_at_...
def getHelpAsString ( docstring = False , show_ver = True ) : """Return useful help from a file in the script directory called ` ` _ _ taskname _ _ . help ` `"""
install_dir = os . path . dirname ( __file__ ) taskname = util . base_taskname ( __taskname__ , __package__ ) htmlfile = os . path . join ( install_dir , 'htmlhelp' , taskname + '.html' ) helpfile = os . path . join ( install_dir , taskname + '.help' ) if docstring or ( not docstring and not os . path . exists ( htmlfi...
def geom_iter ( self , g_nums ) : """Iterator over a subset of geometries . The indices of the geometries to be returned are indicated by an iterable of | int | \\ s passed as ` g _ nums ` . As with : meth : ` geom _ single ` , each geometry is returned as a length - 3N | npfloat _ | with each atom ' s x / ...
# Using the custom coded pack _ tups to not have to care whether the # input is iterable from . utils import pack_tups vals = pack_tups ( g_nums ) for val in vals : yield self . geom_single ( val [ 0 ] )
def render_to_template ( self ) : """Render the current menu instance to a template and return a string"""
context_data = self . get_context_data ( ) template = self . get_template ( ) context_data [ 'current_template' ] = template . template . name return template . render ( context_data )
def generate_cont ( self , max_length , state_size , reply_to , backward , dataset ) : """Generate texts from start / end . Parameters max _ length : ` int ` or ` None ` Maximum sentence length . state _ size : ` int ` State size . reply _ to : ` str ` or ` None ` Input string . backward : ` bool ` ...
state = self . get_cont_state ( reply_to , backward ) while True : parts = self . generate ( state_size , state , dataset , backward ) if reply_to is not None : if backward : parts = chain ( reversed ( list ( parts ) ) , ( reply_to , ) ) else : parts = chain ( ( reply_to ...
def pid ( name ) : '''Returns the PID of a container name Container name CLI Example : . . code - block : : bash salt myminion nspawn . pid arch1'''
try : return int ( info ( name ) . get ( 'PID' ) ) except ( TypeError , ValueError ) as exc : raise CommandExecutionError ( 'Unable to get PID for container \'{0}\': {1}' . format ( name , exc ) )
def get_queryset ( self , * args , ** kwargs ) : """Ensures that this manager always returns nodes in tree order ."""
qs = super ( TreeManager , self ) . get_queryset ( * args , ** kwargs ) # Restrict operations to pages on the current site if needed if settings . PAGES_HIDE_SITES and settings . PAGES_USE_SITE_ID : return qs . order_by ( self . tree_id_attr , self . left_attr ) . filter ( sites = settings . SITE_ID ) else : re...
def _copy ( self ) : """Copies this instance . Its IonEvent ( if any ) is not preserved . Keeping this protected until / unless we decide there ' s use for it publicly ."""
args , kwargs = self . _to_constructor_args ( self ) value = self . __class__ ( * args , ** kwargs ) value . ion_event = None value . ion_type = self . ion_type value . ion_annotations = self . ion_annotations return value
def xml_path_completion ( xml_path ) : """Takes in a local xml path and returns a full path . if @ xml _ path is absolute , do nothing if @ xml _ path is not absolute , load xml that is shipped by the package"""
if xml_path . startswith ( "/" ) : full_path = xml_path else : full_path = os . path . join ( robosuite . models . assets_root , xml_path ) return full_path
def from_xdr_object ( cls , op_xdr_object ) : """Creates a : class : ` ChangeTrust ` object from an XDR Operation object ."""
if not op_xdr_object . sourceAccount : source = None else : source = encode_check ( 'account' , op_xdr_object . sourceAccount [ 0 ] . ed25519 ) . decode ( ) line = Asset . from_xdr_object ( op_xdr_object . body . changeTrustOp . line ) limit = Operation . from_xdr_amount ( op_xdr_object . body . changeTrustOp ....
def get_name ( self , language ) : """Return the name of this course"""
return self . gettext ( language , self . _name ) if self . _name else ""
def idxmin ( self , axis = 0 , skipna = True ) : """Return index of first occurrence of minimum over requested axis . NA / null values are excluded . Parameters axis : { 0 or ' index ' , 1 or ' columns ' } , default 0 0 or ' index ' for row - wise , 1 or ' columns ' for column - wise skipna : boolean , de...
axis = self . _get_axis_number ( axis ) indices = nanops . nanargmin ( self . values , axis = axis , skipna = skipna ) index = self . _get_axis ( axis ) result = [ index [ i ] if i >= 0 else np . nan for i in indices ] return Series ( result , index = self . _get_agg_axis ( axis ) )
def list_apps ( self , cmd = None , embed_tasks = False , embed_counts = False , embed_deployments = False , embed_readiness = False , embed_last_task_failure = False , embed_failures = False , embed_task_stats = False , app_id = None , label = None , ** kwargs ) : """List all apps . : param str cmd : if passed ,...
params = { } if cmd : params [ 'cmd' ] = cmd if app_id : params [ 'id' ] = app_id if label : params [ 'label' ] = label embed_params = { 'app.tasks' : embed_tasks , 'app.counts' : embed_counts , 'app.deployments' : embed_deployments , 'app.readiness' : embed_readiness , 'app.lastTaskFailure' : embed_last_ta...
def __remove_trailing_zeros ( self , collection ) : """Removes trailing zeroes from indexable collection of numbers"""
index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]
def endpoint_is_activated ( endpoint_id , until , absolute_time ) : """Executor for ` globus endpoint is - activated `"""
client = get_client ( ) res = client . endpoint_get_activation_requirements ( endpoint_id ) def fail ( deadline = None ) : exp_string = "" if deadline is not None : exp_string = " or will expire within {} seconds" . format ( deadline ) message = "The endpoint is not activated{}.\n\n" . format ( exp_...
def initialize_state ( self ) : """Call this to initialize the state of the UI after everything has been connected ."""
if self . __scan_hardware_source : self . __profile_changed_event_listener = self . __scan_hardware_source . profile_changed_event . listen ( self . __update_profile_index ) self . __frame_parameters_changed_event_listener = self . __scan_hardware_source . frame_parameters_changed_event . listen ( self . __upda...
def p_command ( p ) : """command : IDENTIFIER arguments ' ; ' | IDENTIFIER arguments block"""
# print ( " COMMAND : " , p [ 1 ] , p [ 2 ] , p [ 3 ] ) tests = p [ 2 ] . get ( 'tests' ) block = None if p [ 3 ] != ';' : block = p [ 3 ] handler = sifter . handler . get ( 'command' , p [ 1 ] ) if handler is None : print ( "No handler registered for command '%s' on line %d" % ( p [ 1 ] , p . lineno ( 1 ) ) ) ...
def to_native_units ( self , motor ) : """Return the native speed measurement required to achieve desired rotations - per - minute"""
assert abs ( self . rotations_per_minute ) <= motor . max_rpm , "invalid rotations-per-minute: {} max RPM is {}, {} was requested" . format ( motor , motor . max_rpm , self . rotations_per_minute ) return self . rotations_per_minute / motor . max_rpm * motor . max_speed
def AddCampaign ( self , client_customer_id , campaign_name , ad_channel_type , budget ) : """Add a Campaign to the client account . Args : client _ customer _ id : str Client Customer Id to use when creating Campaign . campaign _ name : str Name of the campaign to be added . ad _ channel _ type : str Prima...
self . client . SetClientCustomerId ( client_customer_id ) campaign_service = self . client . GetService ( 'CampaignService' ) budget_id = self . AddBudget ( client_customer_id , budget ) operations = [ { 'operator' : 'ADD' , 'operand' : { 'name' : campaign_name , 'status' : 'PAUSED' , 'biddingStrategyConfiguration' : ...
def identify_and_tag_DOI ( line ) : """takes a single citation line and attempts to locate any DOI references . DOI references are recognised in both http ( url ) format and also the standard DOI notation ( DOI : . . . ) @ param line : ( string ) the reference line in which to search for DOI ' s . @ return ...
# Used to hold the DOI strings in the citation line doi_strings = [ ] # Run the DOI pattern on the line , returning the re . match objects matched_doi = re_doi . finditer ( line ) # For each match found in the line for match in reversed ( list ( matched_doi ) ) : # Store the start and end position start = match . s...
def undeploy_api_gateway ( self , lambda_name , domain_name = None , base_path = None ) : """Delete a deployed REST API Gateway ."""
print ( "Deleting API Gateway.." ) api_id = self . get_api_id ( lambda_name ) if domain_name : # XXX - Remove Route53 smartly here ? # XXX - This doesn ' t raise , but doesn ' t work either . try : self . apigateway_client . delete_base_path_mapping ( domainName = domain_name , basePath = '(none)' if base_p...
def push_theme_to_ckan ( catalog , portal_url , apikey , identifier = None , label = None ) : """Escribe la metadata de un theme en el portal pasado por parámetro . Args : catalog ( DataJson ) : El catálogo de origen que contiene el theme . portal _ url ( str ) : La URL del portal CKAN de destino . apik...
ckan_portal = RemoteCKAN ( portal_url , apikey = apikey ) theme = catalog . get_theme ( identifier = identifier , label = label ) group = map_theme_to_group ( theme ) pushed_group = ckan_portal . call_action ( 'group_create' , data_dict = group ) return pushed_group [ 'name' ]
def get_file ( self , user , handle ) : """Retrieve a file for a user . : returns : a : class : ` pathlib . Path ` instance to this file , or None if no file can be found for this handle ."""
user_dir = self . user_dir ( user ) if not user_dir . exists ( ) : return None if not is_valid_handle ( handle ) : return None file_path = user_dir / handle if not file_path . exists ( ) and not file_path . is_file ( ) : return None return file_path
def next ( self ) : """Next point in iteration"""
while True : x , y = next ( self . scan ) self . index += 1 if ( self . index < self . start ) : continue if ( self . index > self . stop ) : raise StopIteration ( "skip stopping" ) if ( ( self . index - self . start ) % self . step != 0 ) : continue return x , y