signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def indices ( self , names , axis = None ) : """get the row and col indices of names . If axis is None , two ndarrays are returned , corresponding the indices of names for each axis Parameters names : iterable column and / or row names axis : ( int ) ( optional ) the axis to search . Returns numpy ....
return Matrix . find_rowcol_indices ( names , self . row_names , self . col_names , axis = axis )
def deltas ( predicted_values , rewards , mask , gamma = 0.99 ) : r"""Computes TD - residuals from V ( s ) and rewards . Where a ` delta ` , i . e . a td - residual is defined as : delta _ { b , t } = r _ { b , t } + \ gamma * v _ { b , t + 1 } - v _ { b , t } . Args : predicted _ values : ndarray of shape ...
# ` d ` s are basically one - step TD residuals . d = [ ] _ , T = rewards . shape # pylint : disable = invalid - name for t in range ( T ) : d . append ( rewards [ : , t ] + ( gamma * predicted_values [ : , t + 1 ] ) - predicted_values [ : , t ] ) return np . array ( d ) . T * mask
def close ( self ) : """Stops accepting new connections , cancels all currently running requests . Request handlers are able to handle ` CancelledError ` and exit properly ."""
if self . _server is None : raise RuntimeError ( 'Server is not started' ) self . _server . close ( ) for handler in self . _handlers : handler . close ( )
def _process_block ( self , node , ** kwargs ) : """Processes a block e . g . ` { % block my _ block % } { % endblock % } `"""
# check if this node already has a ' super _ block ' attribute if not hasattr ( node , 'super_block' ) : # since it doesn ' t it must be the last block in the inheritance chain node . super_block = None # see if there has been a child block defined - if there is this # will be the first block in the inherit...
def Tan ( input_vertex : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex : """Takes the tangent of a vertex . Tan ( vertex ) . : param input _ vertex : the vertex"""
return Double ( context . jvm_view ( ) . TanVertex , label , cast_to_double_vertex ( input_vertex ) )
def translate_query_params ( cls , ** kwargs ) : """Translate an arbirtary keyword argument to the expected query . TODO : refactor this into something less insane . XXX : Clean this up . It ' s * too * flexible . In the v2 API , many endpoints expect a particular query argument to be in the form of ` query...
values = [ ] output = kwargs . copy ( ) query = kwargs . pop ( 'query' , None ) # remove any of the TRANSLATE _ QUERY _ PARAMs in output for param in ( cls . TRANSLATE_QUERY_PARAM or [ ] ) : popped = output . pop ( param , None ) if popped is not None : values . append ( popped ) # if query is provided ...
def do_march ( self ) : """March about and trace the outline of our object Returns perimeter : list The pixels on the perimeter of the region [ [ x1 , y1 ] , . . . ]"""
x , y = self . find_start_point ( ) perimeter = self . walk_perimeter ( x , y ) return perimeter
def auto_setup ( self ) : """Automatic setup based on Firmata ' s " Capability Query " """
self . add_cmd_handler ( CAPABILITY_RESPONSE , self . _handle_report_capability_response ) self . send_sysex ( CAPABILITY_QUERY , [ ] ) self . pass_time ( 0.1 ) # Serial SYNC while self . bytes_available ( ) : self . iterate ( ) # handle _ report _ capability _ response will write self . _ layout if self . _layout ...
def key_to_kind ( cls , key ) : """Return the kind specified by a given _ _ property _ _ key . Args : key : key whose kind name is requested . Returns : The kind specified by key ."""
if key . kind ( ) == Kind . KIND_NAME : return key . id ( ) else : return key . parent ( ) . id ( )
def refine_cand ( candsfile , candnum , threshold ) : """Run refinement search for candnum in list _ cands with abs ( snr ) > threshold"""
reproduce . refine_cand ( candsfile , candnum = candnum , threshold = threshold )
def get_output_values ( self ) : """Return an escaped string of comma separated value _ name : value pairs"""
# Handle primitive values here and implicitly convert them to a dict because # it allows the API to be simpler . # Also influxDB mandates that each value also has a name so the default name # for any non - dict value is " value " if not isinstance ( self . values , dict ) : metric_values = { 'value' : self . values...
def run_inference_on_image ( image ) : """Runs inference on an image . Args : image : Image file name . Returns : Nothing"""
if not tf . gfile . Exists ( image ) : tf . logging . fatal ( 'File does not exist %s' , image ) image_data = tf . gfile . FastGFile ( image , 'rb' ) . read ( ) # Creates graph from saved GraphDef . create_graph ( ) with tf . Session ( ) as sess : # Some useful tensors : # ' softmax : 0 ' : A tensor containing the ...
def gen_nf_quick_check ( output , ascii_props = False , append = False , prefix = "" ) : """Generate quick check properties ."""
categories = [ ] nf = { } all_chars = ALL_ASCII if ascii_props else ALL_CHARS file_name = os . path . join ( HOME , 'unicodedata' , UNIVERSION , 'DerivedNormalizationProps.txt' ) with codecs . open ( file_name , 'r' , 'utf-8' ) as uf : for line in uf : if not line . startswith ( '#' ) : data = l...
def recursively_get_files_from_directory ( directory ) : """Return all filenames under recursively found in a directory"""
return [ os . path . join ( root , filename ) for root , directories , filenames in os . walk ( directory ) for filename in filenames ]
def QA_indicator_MIKE ( DataFrame , N = 12 ) : """MIKE指标 指标说明 MIKE是另外一种形式的路径指标 。 买卖原则 1 WEAK - S , MEDIUM - S , STRONG - S三条线代表初级 、 中级 、 强力支撑 。 2 WEAK - R , MEDIUM - R , STRONG - R三条线代表初级 、 中级 、 强力压力 。"""
HIGH = DataFrame . high LOW = DataFrame . low CLOSE = DataFrame . close TYP = ( HIGH + LOW + CLOSE ) / 3 LL = LLV ( LOW , N ) HH = HHV ( HIGH , N ) WR = TYP + ( TYP - LL ) MR = TYP + ( HH - LL ) SR = 2 * HH - LL WS = TYP - ( HH - TYP ) MS = TYP - ( HH - LL ) SS = 2 * LL - HH return pd . DataFrame ( { 'WR' : WR , 'MR' :...
def dispatch ( self , request ) : """Takes a request and dispatches its data to a jsonrpc method . : param request : a werkzeug request with json data : type request : werkzeug . wrappers . Request : return : json output of the corresponding method : rtype : str . . versionadded : : 0.1.0"""
def _wrapped ( ) : messages = self . _get_request_messages ( request ) results = [ self . _dispatch_and_handle_errors ( message ) for message in messages ] non_notification_results = [ x for x in results if x is not None ] if len ( non_notification_results ) == 0 : return None elif len ( mes...
def activate ( self ) : """Activate a Vera scene . This will call the Vera api to activate a scene ."""
payload = { 'id' : 'lu_action' , 'action' : 'RunScene' , 'serviceId' : self . scene_service } result = self . vera_request ( ** payload ) logger . debug ( "activate: " "result of vera_request with payload %s: %s" , payload , result . text ) self . _active = True
def init_app ( self , app , ** kwargs ) : """Initialize application object ."""
self . init_db ( app , ** kwargs ) app . config . setdefault ( 'ALEMBIC' , { 'script_location' : pkg_resources . resource_filename ( 'invenio_db' , 'alembic' ) , 'version_locations' : [ ( base_entry . name , pkg_resources . resource_filename ( base_entry . module_name , os . path . join ( * base_entry . attrs ) ) ) for...
def calculate2d ( self , force = True ) : """recalculate 2d coordinates . currently rings can be calculated badly . : param force : ignore existing coordinates of atoms"""
for ml in ( self . __reagents , self . __reactants , self . __products ) : for m in ml : m . calculate2d ( force ) self . fix_positions ( )
def decline_weak_feminine_noun ( ns : str , gs : str , np : str ) : """Gives the full declension of weak feminine nouns . > > > decline _ weak _ feminine _ noun ( " saga " , " sögu " , " sögur " ) saga sögu sögu sögu sögur sögur sögum sagna > > > decline _ weak _ feminine _ noun ( " kona...
if ns [ - 1 ] == "i" and gs [ - 1 ] == "i" and not np : print ( ns ) print ( ns ) print ( ns ) print ( ns ) else : # nominative singular print ( ns ) # accusative singular print ( gs ) # dative singular print ( gs ) # genitive singular print ( gs ) # nominative plural ...
def load ( fp , base_uri = "" , loader = None , jsonschema = False , load_on_repr = True , ** kwargs ) : """Drop in replacement for : func : ` json . load ` , where JSON references are proxied to their referent data . : param fp : File - like object containing JSON document : param kwargs : This function take...
if loader is None : loader = functools . partial ( jsonloader , ** kwargs ) return JsonRef . replace_refs ( json . load ( fp , ** kwargs ) , base_uri = base_uri , loader = loader , jsonschema = jsonschema , load_on_repr = load_on_repr , )
def remove_user_from_group ( self , username , group_name ) : """Remove given user from a group : param username : str : param group _ name : str : return :"""
log . warning ( 'Removing user from a group...' ) url = 'rest/api/2/group/user' params = { 'groupname' : group_name , 'username' : username } return self . delete ( url , params = params )
def set_seed ( self , rho_seed , mu_seed ) : """set seeds manually ( should add dimensionality check )"""
self . rho = rho_seed self . mu = mu_seed
def send_messages ( self , data , timeout = 30 , endpoint = '/collab/start/' ) : """Send messages to server , along with user authentication ."""
address = 'https://{}{}' . format ( self . COLLAB_SERVER , endpoint ) params = { 'client_name' : 'ok-client' , 'client_version' : client . __version__ , } log . info ( 'Sending messages to %s' , address ) try : r = requests . post ( address , params = params , json = data , timeout = timeout ) r . raise_for_sta...
def finite_datetimes ( self , finite_start , finite_stop ) : """Simply returns the points in time that correspond to turn of month ."""
start_date = self . _align ( finite_start ) aligned_stop = self . _align ( finite_stop ) dates = [ ] for m in itertools . count ( ) : t = start_date + relativedelta ( months = m ) if t >= aligned_stop : return dates if t >= finite_start : dates . append ( t )
def get_new_session ( self ) : """Returns a new session using the object ' s proxies and headers"""
session = Session ( ) session . headers = self . headers session . proxies = self . _get_request_proxies ( ) return session
def vsan_configured ( name , enabled , add_disks_to_vsan = False ) : '''Configures a host ' s VSAN properties such as enabling or disabling VSAN , or adding VSAN - eligible disks to the VSAN system for the host . name Name of the state . enabled Ensures whether or not VSAN should be enabled on a host as a...
ret = { 'name' : name , 'result' : False , 'changes' : { } , 'comment' : '' } esxi_cmd = 'esxi.cmd' host = __pillar__ [ 'proxy' ] [ 'host' ] current_vsan_enabled = __salt__ [ esxi_cmd ] ( 'get_vsan_enabled' ) . get ( host ) error = current_vsan_enabled . get ( 'Error' ) if error : ret [ 'comment' ] = 'Error: {0}' ....
def create ( self , parameters = { } , ** kwargs ) : """Create an instance of the US Weather Forecast Service with typical starting settings ."""
# Add parameter during create for UAA issuer uri = self . uaa . service . settings . data [ 'uri' ] + '/oauth/token' parameters [ "trustedIssuerIds" ] = [ uri ] super ( PredixService , self ) . create ( parameters = parameters , ** kwargs )
def get_tracks ( self , offset = 0 , limit = 50 ) : """Get user ' s tracks ."""
response = self . client . get ( self . client . USER_TRACKS % ( self . name , offset , limit ) ) return self . _parse_response ( response , strack )
def reload ( self , client = None ) : """API call : reload the config via a ` ` GET ` ` request . This method will reload the newest data for the config . See https : / / cloud . google . com / deployment - manager / runtime - configurator / reference / rest / v1beta1 / projects . configs / get : type clien...
client = self . _require_client ( client ) # We assume the config exists . If it doesn ' t it will raise a NotFound # exception . resp = client . _connection . api_request ( method = "GET" , path = self . path ) self . _set_properties ( api_response = resp )
def constraints ( self ) : """Returns full : class : ` list ` of : class : ` Constraint < cqparts . constraint . Constraint > ` instances , after a successful : meth : ` build ` : return : list of named : class : ` Constraint < cqparts . constraint . Constraint > ` instances : rtype : : class : ` list ` For...
if self . _constraints is None : self . build ( recursive = False ) return self . _constraints
def extend ( self , source , new_image_name , s2i_args = None ) : """extend this s2i - enabled image using provided source , raises ConuException if ` s2i build ` fails : param source : str , source used to extend the image , can be path or url : param new _ image _ name : str , name of the new , extended ima...
s2i_args = s2i_args or [ ] c = self . _s2i_command ( [ "build" ] + s2i_args + [ source , self . get_full_name ( ) ] ) if new_image_name : c . append ( new_image_name ) try : run_cmd ( c ) except subprocess . CalledProcessError as ex : raise ConuException ( "s2i build failed: %s" % ex ) return S2IDockerImage...
def inline_compress_chunk ( chunk , level = 1 ) : """Compress a string using gzip . : type chunk : str : param chunk : The string to be compressed . : rtype : str : returns : ` chunk ` compressed ."""
b = cStringIO . StringIO ( ) g = gzip . GzipFile ( fileobj = b , mode = 'wb' , compresslevel = level ) g . write ( chunk ) g . close ( ) cc = b . getvalue ( ) b . close ( ) return cc
def unsubscribe ( SubscriptionArn , region = None , key = None , keyid = None , profile = None ) : '''Unsubscribe a specific SubscriptionArn of a topic . CLI Example : . . code - block : : bash salt myminion boto3 _ sns . unsubscribe my _ subscription _ arn region = us - east - 1'''
if not SubscriptionArn . startswith ( 'arn:aws:sns:' ) : # Grrr , AWS sent us an ARN that ' s NOT and ARN . . . . # This can happen if , for instance , a subscription is left in PendingAcceptance or similar # Note that anything left in PendingConfirmation will be auto - deleted by AWS after 30 days # anyway , so this i...
def mtf_bitransformer_tiny ( ) : """Small encoder - decoder model for testing ."""
hparams = mtf_bitransformer_base ( ) hparams . batch_size = 2 hparams . mesh_shape = "" hparams . d_model = 128 hparams . encoder_layers = [ "self_att" , "drd" ] * 2 hparams . decoder_layers = [ "self_att" , "enc_att" , "drd" ] * 2 hparams . num_heads = 4 hparams . d_ff = 512 return hparams
def unit_ball_L2 ( shape ) : """A tensorflow variable tranfomed to be constrained in a L2 unit ball . EXPERIMENTAL : Do not use for adverserial examples if you need to be confident they are strong attacks . We are not yet confident in this code ."""
x = tf . Variable ( tf . zeros ( shape ) ) return constrain_L2 ( x )
def init_app ( self , app ) : """For Flask using the app config"""
self . __init__ ( aws_access_key_id = app . config . get ( "SES_AWS_ACCESS_KEY" ) , aws_secret_access_key = app . config . get ( "SES_AWS_SECRET_KEY" ) , region = app . config . get ( "SES_REGION" , "us-east-1" ) , sender = app . config . get ( "SES_SENDER" , None ) , reply_to = app . config . get ( "SES_REPLY_TO" , No...
def canonical_peer ( self , peer ) : """Get the canonical peer name"""
their_host , their_port = url_to_host_port ( peer ) if their_host in [ '127.0.0.1' , '::1' ] : their_host = 'localhost' return "%s:%s" % ( their_host , their_port )
def verifier ( self , url ) : """Will ask user to click link to accept app and write code"""
webbrowser . open ( url ) print ( 'A browser should have opened up with a link to allow us to access' ) print ( 'your account, follow the instructions on the link and paste the verifier' ) print ( 'Code into here to give us access, if the browser didn\'t open, the link is:' ) print ( url ) print ( ) return input ( 'Ver...
def set ( self , locs , values ) : """Modify Block in - place with new item value Returns None"""
values = conversion . ensure_datetime64ns ( values , copy = False ) self . values [ locs ] = values
def json_encode ( data_type , obj , caller_permissions = None , alias_validators = None , old_style = False , should_redact = False ) : """Encodes an object into JSON based on its type . Args : data _ type ( Validator ) : Validator for obj . obj ( object ) : Object to be serialized . caller _ permissions ( ...
for_msgpack = False serializer = StoneToJsonSerializer ( caller_permissions , alias_validators , for_msgpack , old_style , should_redact ) return serializer . encode ( data_type , obj )
async def volume ( self , ctx , volume : int ) : """Changes the player ' s volume"""
if ctx . voice_client is None : return await ctx . send ( "Not connected to a voice channel." ) ctx . voice_client . source . volume = volume / 100 await ctx . send ( "Changed volume to {}%" . format ( volume ) )
def diffmap ( adata , n_comps = 15 , copy = False ) : """Diffusion Maps [ Coifman05 ] _ [ Haghverdi15 ] _ [ Wolf18 ] _ . Diffusion maps [ Coifman05 ] _ has been proposed for visualizing single - cell data by [ Haghverdi15 ] _ . The tool uses the adapted Gaussian kernel suggested by [ Haghverdi16 ] _ in the im...
if 'neighbors' not in adata . uns : raise ValueError ( 'You need to run `pp.neighbors` first to compute a neighborhood graph.' ) if n_comps <= 2 : raise ValueError ( 'Provide any value greater than 2 for `n_comps`. ' ) adata = adata . copy ( ) if copy else adata _diffmap ( adata , n_comps = n_comps ) return ada...
def _wmi_to_ts ( self , wmi_ts ) : '''Convert a wmi formatted timestamp into an epoch .'''
year , month , day , hour , minute , second , microsecond , tz = to_time ( wmi_ts ) tz_delta = timedelta ( minutes = int ( tz ) ) if '+' in wmi_ts : tz_delta = - tz_delta dt = ( datetime ( year = year , month = month , day = day , hour = hour , minute = minute , second = second , microsecond = microsecond ) + tz_de...
def easter ( year , method = EASTER_WESTERN ) : """This method was ported from the work done by GM Arts , on top of the algorithm by Claus Tondering , which was based in part on the algorithm of Ouding ( 1940 ) , as quoted in " Explanatory Supplement to the Astronomical Almanac " , P . Kenneth Seidelmann , ...
if not ( 1 <= method <= 3 ) : raise ValueError ( "invalid method" ) # g - Golden year - 1 # c - Century # h - ( 23 - Epact ) mod 30 # i - Number of days from March 21 to Paschal Full Moon # j - Weekday for PFM ( 0 = Sunday , etc ) # p - Number of days from March 21 to Sunday on or before PFM # ( - 6 to 28 methods 1...
def shear_from_matrix ( matrix ) : """Return shear angle , direction and plane from shear matrix . > > > angle = np . pi / 2.0 > > > direct = [ 0.0 , 1.0 , 0.0] > > > point = [ 0.0 , 0.0 , 0.0] > > > normal = np . cross ( direct , np . roll ( direct , 1 ) ) > > > S0 = shear _ matrix ( angle , direct , poi...
M = np . array ( matrix , dtype = np . float64 , copy = False ) M33 = M [ : 3 , : 3 ] # normal : cross independent eigenvectors corresponding to the eigenvalue 1 w , V = np . linalg . eig ( M33 ) i = np . where ( abs ( np . real ( w ) - 1.0 ) < 1e-4 ) [ 0 ] if len ( i ) < 2 : raise ValueError ( "no two linear indep...
def forward_kinematics ( self , joints , full_kinematics = False ) : """Returns the transformation matrix of the forward kinematics Parameters joints : list The list of the positions of each joint . Note : Inactive joints must be in the list . full _ kinematics : bool Return the transformation matrices of...
frame_matrix = np . eye ( 4 ) if full_kinematics : frame_matrixes = [ ] if len ( self . links ) != len ( joints ) : raise ValueError ( "Your joints vector length is {} but you have {} links" . format ( len ( joints ) , len ( self . links ) ) ) for index , ( link , joint_angle ) in enumerate ( zip ( self . links...
def _dict_lookup_bitwise_add ( cls , item , ** kwargs ) : '''kwarg value _ lookup bool to determine if item _ list should be compared to keys or values kwarg test _ zero is used to determine if 0 should be tested when value _ lookup is false lookup should be a dict with integers for keys if value _ lookup i...
value_lookup = kwargs . get ( 'value_lookup' , False ) test_zero = kwargs . get ( 'test_zero' , False ) ret_val = None if str ( item ) . lower ( ) == 'not defined' : return None if value_lookup : if not isinstance ( item , list ) : return 'Invalid Value' ret_val = 0 else : if not isinstance ( it...
def path ( i ) : """Input : { } Output : { return - return code = 0 , if successful > 0 , if error ( error ) - error text if return > 0 Output from from ' detect _ cid _ in _ current _ path ' function"""
o = i . get ( 'out' , '' ) r = detect_cid_in_current_path ( i ) if r [ 'return' ] > 0 : return r rx = convert_entry_to_cid ( r ) if rx [ 'return' ] > 0 : return rx cuoa = rx [ 'cuoa' ] cid = rx [ 'cid' ] xcuoa = rx [ 'xcuoa' ] xcid = rx [ 'xcid' ] # If console , print CIDs if o == 'con' : out ( cuoa ) o...
def apply ( self , func , ids = None , applyto = 'measurement' , noneval = nan , setdata = False , output_format = 'dict' , ID = None , ** kwargs ) : '''Apply func to each of the specified measurements . Parameters func : callable Accepts a Measurement object or a DataFrame . ids : hashable | iterable of ha...
if ids is None : ids = self . keys ( ) else : ids = to_list ( ids ) result = dict ( ( i , self [ i ] . apply ( func , applyto , noneval , setdata ) ) for i in ids ) if output_format == 'collection' : can_keep_as_collection = all ( [ isinstance ( r , self . _measurement_class ) for r in result . values ( ) ]...
def csv ( self , jql , limit = 1000 ) : """Get issues from jql search result with all related fields : param jql : JQL query : param limit : max results in the output file : return : CSV file"""
url = 'sr/jira.issueviews:searchrequest-csv-all-fields/temp/SearchRequest.csv?tempMax={limit}&jqlQuery={jql}' . format ( limit = limit , jql = jql ) return self . get ( url , not_json_response = True , headers = { 'Accept' : 'application/csv' } )
def run ( self , f , * args , ** kwargs ) : """Run the given function with this L { Action } as its execution context ."""
parent = _ACTION_CONTEXT . set ( self ) try : return f ( * args , ** kwargs ) finally : _ACTION_CONTEXT . reset ( parent )
def _convert_name ( self , name ) : """Convert ` ` name ` ` to int if it looks like an int . Otherwise , return it as is ."""
if re . search ( '^\d+$' , name ) : if len ( name ) > 1 and name [ 0 ] == '0' : # Don ' t treat strings beginning with " 0 " as ints return name return int ( name ) return name
def get_datastreams ( self ) : """To get list of Datastream"""
datastreams = [ ] response = self . http . get ( '/Datastream' ) for datastream in response : datastreams . append ( Schemas . Datastream ( datastream = datastream ) ) return datastreams
def write ( self ) : """Write the configuration to : attr : ` path `"""
with open ( self . path , 'w' ) as f : self . config . write ( f )
def _commit_hostname_handler ( self , cmd ) : """Special handler for hostname change on commit operation ."""
current_prompt = self . device . find_prompt ( ) . strip ( ) terminating_char = current_prompt [ - 1 ] pattern = r"[>#{}]\s*$" . format ( terminating_char ) # Look exclusively for trailing pattern that includes ' # ' and ' > ' output = self . device . send_command_expect ( cmd , expect_string = pattern ) # Reset base p...
def alpha2 ( self , code ) : """Return the two letter country code when passed any type of ISO 3166-1 country code . If no match is found , returns an empty string ."""
code = force_text ( code ) . upper ( ) if code . isdigit ( ) : lookup_code = int ( code ) def find ( alt_codes ) : return alt_codes [ 1 ] == lookup_code elif len ( code ) == 3 : lookup_code = code def find ( alt_codes ) : return alt_codes [ 0 ] == lookup_code else : find = None if fi...
def _load_data ( ) : """Load the word and character mapping data into a dictionary . In the data files , each line is formatted like this : HANZI PINYIN _ READING / PINYIN _ READING So , lines need to be split by ' \t ' and then the Pinyin readings need to be split by ' / ' ."""
data = { } for name , file_name in ( ( 'words' , 'hanzi_pinyin_words.tsv' ) , ( 'characters' , 'hanzi_pinyin_characters.tsv' ) ) : # Split the lines by tabs : [ [ hanzi , pinyin ] . . . ] . lines = [ line . split ( '\t' ) for line in dragonmapper . data . load_data_file ( file_name ) ] # Make a dictionary : { h...
def __indent ( self , lines , indent , initial = 2 ) : """This will indent the given set of lines by normal HTML layout . An initial indent of ` 2 * indent ` will be used to account for the ` < html > < head > ` or ` < html > < body > ` levels ."""
tagempty = re . compile ( r"""<\w+(\s+[^>]*?)*/>""" ) tagopen = re . compile ( r"""<\w+(\s+[^>]*?)*>""" ) tagclose = re . compile ( r"""</\w+\s*>""" ) prefix = indent * initial for i in range ( len ( lines ) ) : line = lines [ i ] . strip ( ) if tagempty . match ( line ) : line = prefix + line elif ...
def get_year ( self ) : """Return the year from the database in the format expected by the URL ."""
year = super ( BuildableDayArchiveView , self ) . get_year ( ) fmt = self . get_year_format ( ) dt = date ( int ( year ) , 1 , 1 ) return dt . strftime ( fmt )
def size ( self , size = None ) : """Returns or sets ( if a value is provided ) the diameter of the series ' data points . : param Number size : If given , the series ' size will be set to this . : rtype : ` ` Number ` `"""
if size is None : return self . _size else : if not is_numeric ( size ) : raise TypeError ( "size must be number, not '%s'" % str ( size ) ) self . _size = size
def matmul ( a , b , output_shape = None , reduced_dims = None , name = None ) : """Alias for einsum ( [ a , b ] ) ."""
return einsum ( [ a , b ] , output_shape = output_shape , reduced_dims = reduced_dims , name = name )
def findspans ( self , type , set = None ) : """Find span annotation of the specified type that include this word"""
if issubclass ( type , AbstractAnnotationLayer ) : layerclass = type else : layerclass = ANNOTATIONTYPE2LAYERCLASS [ type . ANNOTATIONTYPE ] e = self while True : if not e . parent : break e = e . parent for layer in e . select ( layerclass , set , False ) : for e2 in layer : ...
def get_line ( self , line = 1 ) : """Return a specific line ."""
verse_size = len ( self . get_verse ( ) ) + 1 if line > 1 : verse = math . floor ( ( line - 1 ) / verse_size ) line_in_verse = ( line - 1 ) % verse_size try : return self . verses [ verse ] [ line_in_verse ] except IndexError : return '' else : return self . verses [ 0 ] [ 0 ]
def _add_sj_index_commands ( fq1 , ref_file , gtf_file ) : """newer versions of STAR can generate splice junction databases on thephfly this is preferable since we can tailor it to the read lengths"""
if _has_sj_index ( ref_file ) : return "" else : rlength = fastq . estimate_maximum_read_length ( fq1 ) cmd = " --sjdbGTFfile %s " % gtf_file cmd += " --sjdbOverhang %s " % str ( rlength - 1 ) return cmd
def _eager_expr_from_flat_schema ( flat_schema ) : """: type flat _ schema : dict"""
result = [ ] for path , join_method in flat_schema . items ( ) : if join_method == JOINED : result . append ( joinedload ( path ) ) elif join_method == SUBQUERY : result . append ( subqueryload ( path ) ) else : raise ValueError ( 'Bad join method `{}` in `{}`' . format ( join_method...
def OnDoubleClick ( self , event ) : """Double click on a given square in the map"""
node = HotMapNavigator . findNodeAtPosition ( self . hot_map , event . GetPosition ( ) ) if node : wx . PostEvent ( self , SquareActivationEvent ( node = node , point = event . GetPosition ( ) , map = self ) )
def colorize ( text , messageType = None ) : """Function that colorizes a message . Args : text : The string to be colorized . messageType : Possible options include " ERROR " , " WARNING " , " SUCCESS " , " INFO " or " BOLD " . Returns : string : Colorized if the option is correct , including a tag at ...
formattedText = str ( text ) # Set colors if "ERROR" in messageType : formattedText = colorama . Fore . RED + formattedText elif "WARNING" in messageType : formattedText = colorama . Fore . YELLOW + formattedText elif "SUCCESS" in messageType : formattedText = colorama . Fore . GREEN + formattedText elif "I...
def finalize ( self , process_row = None ) : """Restore the LigolwSegmentList objects to the XML tables in preparation for output . All segments from all segment lists are inserted into the tables in time order , but this is NOT behaviour external applications should rely on . This is done simply in the bel...
if process_row is not None : process_id = process_row . process_id elif self . process is not None : process_id = self . process . process_id else : raise ValueError ( "must supply a process row to .__init__()" ) # ensure ID generators are synchronized with table contents self . segment_def_table . sync_nex...
def _format_links_fields ( self , links ) : """Format the fields containing links into 4 - tuples printable by _ print _ fields ( ) ."""
fields = list ( ) for link in links : linked_model = link [ 'mdl' ] ( super_context ) null = self . _marker_true if link [ 'null' ] is True else self . _marker_false # In LinkProxy , if reverse _ name is empty then only reverse has the name # of the field on the link _ source side field_name = link ...
def getLeastUsedCell ( self , c ) : """For the least used cell in a column"""
segmentsPerCell = numpy . zeros ( self . cellsPerColumn , dtype = 'uint32' ) for i in range ( self . cellsPerColumn ) : segmentsPerCell [ i ] = self . getNumSegmentsInCell ( c , i ) cellMinUsage = numpy . where ( segmentsPerCell == segmentsPerCell . min ( ) ) [ 0 ] # return cellMinUsage [ 0 ] # return the first cel...
def knapsack_greedy ( items , maxweight ) : r"""non - optimal greedy version of knapsack algorithm does not sort input . Sort the input by largest value first if desired . Args : ` items ` ( tuple ) : is a sequence of tuples ` ( value , weight , id _ ) ` , where ` value ` is a scalar and ` weight ` is a n...
items_subset = [ ] total_weight = 0 total_value = 0 for item in items : value , weight = item [ 0 : 2 ] if total_weight + weight > maxweight : continue else : items_subset . append ( item ) total_weight += weight total_value += value return total_value , items_subset
def addVariantAnnotationSet ( self , variantAnnotationSet ) : """Adds the specified variantAnnotationSet to this dataset ."""
id_ = variantAnnotationSet . getId ( ) self . _variantAnnotationSetIdMap [ id_ ] = variantAnnotationSet self . _variantAnnotationSetIds . append ( id_ )
def is_orthogonal ( matrix : np . ndarray , * , rtol : float = 1e-5 , atol : float = 1e-8 ) -> bool : """Determines if a matrix is approximately orthogonal . A matrix is orthogonal if it ' s square and real and its transpose is its inverse . Args : matrix : The matrix to check . rtol : The per - matrix - ...
return ( matrix . shape [ 0 ] == matrix . shape [ 1 ] and np . all ( np . imag ( matrix ) == 0 ) and np . allclose ( matrix . dot ( matrix . T ) , np . eye ( matrix . shape [ 0 ] ) , rtol = rtol , atol = atol ) )
def plot_fit ( self , intervals = True , ** kwargs ) : """Plots the fit of the model Parameters intervals : Boolean Whether to plot 95 % confidence interval of states Returns None ( plots data and the fit )"""
import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) series_type = kwargs . get ( 'series_type' , 'Smoothed' ) if self . latent_variables . estimated is False : raise Exception ( "No latent variables estimated!" ) else : date_index = copy . deepcopy ( self . ...
def _flush ( self , finish = False ) : """Internal API to flush . Buffer is flushed to GCS only when the total amount of buffered data is at least self . _ blocksize , or to flush the final ( incomplete ) block of the file with finish = True ."""
while ( ( finish and self . _buffered >= 0 ) or ( not finish and self . _buffered >= self . _blocksize ) ) : tmp_buffer = [ ] tmp_buffer_len = 0 excess = 0 while self . _buffer : buf = self . _buffer . popleft ( ) size = len ( buf ) self . _buffered -= size tmp_buffer . a...
def _set_min_level ( self , handler_class , level ) : """Generic method to setLevel for handlers ."""
if self . _exist_handler ( handler_class ) : if not level : self . _delete_handler ( handler_class ) else : self . _update_handler ( handler_class , level = level ) elif level : self . _create_handler ( handler_class , level )
def exists ( name , region = None , key = None , keyid = None , profile = None ) : '''Check to see if an SNS topic exists . CLI example : : salt myminion boto _ sns . exists mytopic region = us - east - 1'''
topics = get_all_topics ( region = region , key = key , keyid = keyid , profile = profile ) if name . startswith ( 'arn:aws:sns:' ) : return name in list ( topics . values ( ) ) else : return name in list ( topics . keys ( ) )
def get_attrs ( cls ) : """Get all class attributes ordered by definition"""
ignore = dir ( type ( 'dummy' , ( object , ) , { } ) ) + [ '__metaclass__' ] attrs = [ item for item in inspect . getmembers ( cls ) if item [ 0 ] not in ignore and not isinstance ( item [ 1 ] , ( types . FunctionType , types . MethodType , classmethod , staticmethod , property ) ) ] # sort by idx and use attribute nam...
def is_image ( filename ) : """Determine if given filename is an image ."""
# note : isfile ( ) also accepts symlinks return os . path . isfile ( filename ) and filename . lower ( ) . endswith ( ImageExts )
def sweep_to_proto_dict ( sweep : Sweep , repetitions : int = 1 ) -> Dict : """Converts sweep into an equivalent protobuf representation ."""
msg = { } # type : Dict if not sweep == UnitSweep : sweep = _to_zip_product ( sweep ) msg [ 'sweep' ] = { 'factors' : [ _sweep_zip_to_proto_dict ( cast ( Zip , factor ) ) for factor in sweep . factors ] } msg [ 'repetitions' ] = repetitions return msg
def get_vnetwork_hosts_output_vnetwork_hosts_interface_type ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_vnetwork_hosts = ET . Element ( "get_vnetwork_hosts" ) config = get_vnetwork_hosts output = ET . SubElement ( get_vnetwork_hosts , "output" ) vnetwork_hosts = ET . SubElement ( output , "vnetwork-hosts" ) interface_type = ET . SubElement ( vnetwork_hosts , "interface-type" ) inter...
def ind_zero_freq ( self ) : """Index of the first point for which the freqencies are equal or greater than zero ."""
ind = np . searchsorted ( self . frequencies , 0 ) if ind >= len ( self . frequencies ) : raise ValueError ( "No positive frequencies found" ) return ind
def from_dict ( cls , entries , ** kwargs ) : """Create Catalog from the given set of entries Parameters entries : dict - like A mapping of name : entry which supports dict - like functionality , e . g . , is derived from ` ` collections . abc . Mapping ` ` . kwargs : passed on the constructor Things li...
from dask . base import tokenize cat = cls ( ** kwargs ) cat . _entries = entries cat . _tok = tokenize ( kwargs , entries ) return cat
def _clean_salt_variables ( params , variable_prefix = "__" ) : '''Pops out variables from params which starts with ` variable _ prefix ` .'''
list ( list ( map ( params . pop , [ k for k in params if k . startswith ( variable_prefix ) ] ) ) ) return params
def image_create ( self , disk , label = None , description = None ) : """Creates a new Image from a disk you own . : param disk : The Disk to imagize . : type disk : Disk or int : param label : The label for the resulting Image ( defaults to the disk ' s label . : type label : str : param description :...
params = { "disk_id" : disk . id if issubclass ( type ( disk ) , Base ) else disk , } if label is not None : params [ "label" ] = label if description is not None : params [ "description" ] = description result = self . post ( '/images' , data = params ) if not 'id' in result : raise UnexpectedResponseError...
def make_usage_key_from_deprecated_string ( self , location_url ) : """Deprecated mechanism for creating a UsageKey given a CourseKey and a serialized Location . NOTE : this prejudicially takes the tag , org , and course from the url not self . Raises : InvalidKeyError : if the url does not parse"""
warnings . warn ( "make_usage_key_from_deprecated_string is deprecated! Please use make_usage_key" , DeprecationWarning , stacklevel = 2 ) return BlockUsageLocator . from_string ( location_url ) . replace ( run = self . run )
def scan_text ( text ) : """Scan text , and replace items that match shutit ' s pattern format , ie : { { shutit . THING } }"""
while True : match = re . match ( "(.*){{ shutit.(.*) }}(.*)$" , text ) if match : before = match . group ( 1 ) name = match . group ( 2 ) after = match . group ( 3 ) text = before + """''' + shutit.cfg[self.module_id][\"""" + name + """\"] + '''""" + after else : bre...
def decode_list ( self , ids ) : """Transform a sequence of int ids into a their string versions . This method supports transforming individual input / output ids to their string versions so that sequence to / from text conversions can be visualized in a human readable format . Args : ids : list of intege...
decoded_ids = [ ] for id_ in ids : if 0 <= id_ < self . _num_reserved_ids : decoded_ids . append ( RESERVED_TOKENS [ int ( id_ ) ] ) else : decoded_ids . append ( id_ - self . _num_reserved_ids ) return [ str ( d ) for d in decoded_ids ]
def add_dop ( self , dop , precision = 100 ) : """Add GPSDOP ( float ) ."""
self . _ef [ "GPS" ] [ piexif . GPSIFD . GPSDOP ] = ( int ( abs ( dop ) * precision ) , precision )
def authenticate ( credentials , sock_info ) : """Authenticate sock _ info ."""
mechanism = credentials . mechanism auth_func = _AUTH_MAP . get ( mechanism ) auth_func ( credentials , sock_info )
def hashes ( self ) : """Hashes of all possible permutations of the URL in canonical form"""
for url_variant in self . url_permutations ( self . canonical ) : url_hash = self . digest ( url_variant ) yield url_hash
def process_firmware_image ( compact_firmware_file , ilo_object ) : """Processes the firmware file . Processing the firmware file entails extracting the firmware file from its compact format . Along with the raw ( extracted ) firmware file , this method also sends out information of whether or not the extract...
fw_img_extractor = firmware_controller . get_fw_extractor ( compact_firmware_file ) LOG . debug ( 'Extracting firmware file: %s ...' , compact_firmware_file ) raw_fw_file_path , is_extracted = fw_img_extractor . extract ( ) # Note ( deray ) : Need to check if this processing is for RIS or RIBCL # based systems . For Ge...
def from_scale ( cls , gold_number , precision , recall , title ) : """deprecated , for backward compactbility try to use from _ score"""
tp_count = get_numerator ( recall , gold_number ) positive_count = get_denominator ( precision , tp_count ) fp_count = positive_count - tp_count fn_count = gold_number - tp_count scale_report = cls ( [ 'tp' ] * tp_count , [ 'fp' ] * fp_count , [ 'fn' ] * fn_count , title ) return scale_report
def validate ( ** vkargs ) : """Validates and manipulates keyword arguments by user defined callables . Handles ValueError and missing arguments by raising HTTPError ( 403 ) ."""
def decorator ( func ) : def wrapper ( ** kargs ) : for key , value in six . iteritems ( vkargs ) : if key not in kargs : abort ( 403 , 'Missing parameter: %s' % key ) try : kargs [ key ] = value ( kargs [ key ] ) except ValueError : ...
def __run_blast ( blast_command , input_file , * args , ** kwargs ) : '''Run a blast variant on the given input file .'''
# XXX : Eventually , translate results on the fly as requested ? Or # just always use our parsed object ? if 'outfmt' in kwargs : raise Exception ( 'Use of the -outfmt option is not supported' ) num_processes = kwargs . get ( 'pb_num_processes' , os . sysconf ( 'SC_NPROCESSORS_ONLN' ) ) fields = kwargs . get ( 'pb_...
def merge ( a , b , path = None ) : """merges b into a > > > a = { 1 : { " a " : " A " } , 2 : { " b " : " B " } , 8 : [ ] } > > > b = { 2 : { " c " : " C " } , 3 : { " d " : " D " } } > > > c = merge ( a , b ) > > > c = = a = = { 8 : [ ] , 1 : { " a " : " A " } , 2 : { " c " : " C " , " b " : " B " } , 3 :...
if path is None : path = [ ] for key in b : if key in a : if isinstance ( a [ key ] , dict ) and isinstance ( b [ key ] , dict ) : merge ( a [ key ] , b [ key ] , path + [ str ( key ) ] ) elif a [ key ] == b [ key ] : pass # same leaf value else : ...
def siblings_before ( self ) : """: return : a list of this node ' s siblings that occur * before * this node in the DOM ."""
impl_nodelist = self . adapter . get_node_children ( self . parent . impl_node ) before_nodelist = [ ] for n in impl_nodelist : if n == self . impl_node : break before_nodelist . append ( n ) return self . _convert_nodelist ( before_nodelist )
def convert_to_raw ( number , value , length ) : """Get the value of an option as a ByteArray . : param number : the option number : param value : the option value : param length : the option length : return : the value of an option as a BitArray"""
opt_type = defines . OptionRegistry . LIST [ number ] . value_type if length == 0 and opt_type != defines . INTEGER : return bytes ( ) elif length == 0 and opt_type == defines . INTEGER : return 0 elif opt_type == defines . STRING : if isinstance ( value , bytes ) : return value . decode ( "utf-8" )...
async def load_tracks ( self , query ) -> LoadResult : """Executes a loadtracks request . Only works on Lavalink V3. Parameters query : str Returns LoadResult"""
self . __check_node_ready ( ) url = self . _uri + quote ( str ( query ) ) data = await self . _get ( url ) if isinstance ( data , dict ) : return LoadResult ( data ) elif isinstance ( data , list ) : modified_data = { "loadType" : LoadType . V2_COMPAT , "tracks" : data } return LoadResult ( modified_data )