signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def import_crtomo ( self , directory , frequency_file = 'frequencies.dat' , data_prefix = 'volt_' , ** kwargs ) : """CRTomo importer"""
# we get not electrode positions ( dummy1 ) and no topography data # ( dummy2) df , dummy1 , dumm2 = reda_crtomo_exporter . load_seit_data ( directory , frequency_file , data_prefix , ** kwargs ) self . _add_to_container ( df ) print ( 'Summary:' ) self . _describe_data ( df )
def to_header ( self ) : """Converts the object back into an HTTP header ."""
if self . date is not None : return http_date ( self . date ) if self . etag is not None : return quote_etag ( self . etag ) return ""
def _ ( path ) : """Normalize path to unicode : param path : path : return : normalize path > > > _ ( None ) > > > _ ( u ( " test1 " ) ) u ' test1' > > > _ ( " test2 " ) u ' test2'"""
if path is None : return u ( "" ) if not PY3 : if type ( path ) == unicode : return path try : return _decode_utf8 ( path ) except UnicodeDecodeError : pass return path
def luminosity_to_flux ( lumErg_S , dist_Mpc ) : """* Convert luminosity to a flux * * * Key Arguments : * * - ` ` lumErg _ S ` ` - - luminosity in ergs / sec - ` ` dist _ Mpc ` ` - - distance in Mpc * * Return : * * - ` ` fluxErg _ cm2 _ S ` ` - - flux in ergs / cm2 / s"""
# # # # # # > IMPORTS # # # # # # # STANDARD LIB # # # # THIRD PARTY # # import numpy as np import math # # LOCAL APPLICATION # # # # # # # # > VARIABLE SETTINGS # # # # # # # # # # # > ACTION ( S ) # # # # # # Convert the distance to cm distCm = dist_Mpc * MPC_2_CMS fluxErg_cm2_S = lumErg_S / ( 4 * np . pi * distCm **...
def from_string ( species_string : str ) : """Returns a Dummy from a string representation . Args : species _ string ( str ) : A string representation of a dummy species , e . g . , " X2 + " , " X3 + " . Returns : A DummySpecie object . Raises : ValueError if species _ string cannot be intepreted ."""
m = re . search ( r"([A-Z][a-z]*)([0-9.]*)([+\-]*)(.*)" , species_string ) if m : sym = m . group ( 1 ) if m . group ( 2 ) == "" and m . group ( 3 ) == "" : oxi = 0 else : oxi = 1 if m . group ( 2 ) == "" else float ( m . group ( 2 ) ) oxi = - oxi if m . group ( 3 ) == "-" else oxi ...
def _gen_trend_graph ( start , end , force_overwrite = False ) : """Total trend graph for machine category ."""
filename = graphs . get_trend_graph_filename ( start , end ) csv_filename = os . path . join ( GRAPH_ROOT , filename + '.csv' ) png_filename = os . path . join ( GRAPH_ROOT , filename + '.png' ) _check_directory_exists ( csv_filename ) _check_directory_exists ( png_filename ) if not settings . GRAPH_DEBUG or force_over...
def makeAnimation ( self ) : """Use pymovie to render ( visual + audio ) + text overlays ."""
aclip = mpy . AudioFileClip ( "sound.wav" ) self . iS = self . iS . set_audio ( aclip ) self . iS . write_videofile ( "mixedVideo.webm" , 15 , audio = True ) print ( "wrote " + "mixedVideo.webm" )
def Matsumoto_1977 ( mp , rhop , dp , rhog , D , Vterminal = 1 ) : r'''Calculates saltation velocity of the gas for pneumatic conveying , according to [ 1 ] _ and reproduced in [ 2 ] _ , [ 3 ] _ , and [ 4 ] _ . First equation is used if third equation yeilds d * higher than dp . Otherwise , use equation 2. ...
limit = 1.39 * D * ( rhop / rhog ) ** - 0.74 A = pi / 4 * D ** 2 if limit < dp : # Corase routine Frp = Vterminal / ( g * dp ) ** 0.5 Frs_sorta = 1. / ( g * D ) ** 0.5 expression1 = 0.373 * ( rhop / rhog ) ** 1.06 * ( Frp / 10. ) ** - 3.7 * ( Frs_sorta / 10. ) ** 3.61 expression2 = mp / rhog / A V =...
def set_bootdev ( self , bootdev , persist = False , uefiboot = None ) : """Set boot device to use on next reboot : param bootdev : * network - - Request network boot * hd - - Boot from hard drive * safe - - Boot from hard drive , requesting ' safe mode ' * optical - - boot from CD / DVD / BD drive * se...
reqbootdev = bootdev if ( bootdev not in boot_devices_write and bootdev not in boot_devices_read ) : raise exc . InvalidParameterValue ( 'Unsupported device ' + repr ( bootdev ) ) bootdev = boot_devices_write . get ( bootdev , bootdev ) if bootdev == 'None' : payload = { 'Boot' : { 'BootSourceOverrideEnabled' :...
def _serialize_lnk ( lnk ) : """Serialize a predication lnk to surface form into the SimpleMRS encoding ."""
s = "" if lnk is not None : s = '<' if lnk . type == Lnk . CHARSPAN : cfrom , cto = lnk . data s += '' . join ( [ str ( cfrom ) , ':' , str ( cto ) ] ) elif lnk . type == Lnk . CHARTSPAN : cfrom , cto = lnk . data s += '' . join ( [ str ( cfrom ) , '#' , str ( cto ) ] ) e...
def commentdoc ( text ) : """Returns a Doc representing a comment ` text ` . ` text ` is treated as words , and any whitespace may be used to break the comment to multiple lines ."""
if not text : raise ValueError ( 'Expected non-empty comment str, got {}' . format ( repr ( text ) ) ) commentlines = [ ] for line in text . splitlines ( ) : alternating_words_ws = list ( filter ( None , WHITESPACE_PATTERN_TEXT . split ( line ) ) ) starts_with_whitespace = bool ( WHITESPACE_PATTERN_TEXT . m...
def download_urls ( cls , urls , force_download = False ) : """Downloads all CTD URLs that don ' t exist : param iter [ str ] urls : iterable of URL of CTD : param bool force _ download : force method to download"""
for url in urls : file_path = cls . get_path_to_file_from_url ( url ) if os . path . exists ( file_path ) and not force_download : log . info ( 'already downloaded %s to %s' , url , file_path ) else : log . info ( 'downloading %s to %s' , url , file_path ) download_timer = time . tim...
def Get ( self , key ) : """Get alert by providing name , ID , or other unique key . If key is not unique and finds multiple matches only the first will be returned"""
for alert in self . alerts : if alert . id == key : return ( alert ) elif alert . name == key : return ( alert )
def get_starting_chunk ( filename , length = 1024 ) : """: param filename : File to open and get the first little chunk of . : param length : Number of bytes to read , default 1024. : returns : Starting chunk of bytes ."""
# Ensure we open the file in binary mode try : with open ( filename , 'rb' ) as f : chunk = f . read ( length ) return chunk except IOError as e : print ( e )
def redundancy_input_rbridge_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) redundancy = ET . Element ( "redundancy" ) config = redundancy input = ET . SubElement ( redundancy , "input" ) rbridge_id = ET . SubElement ( input , "rbridge-id" ) rbridge_id . text = kwargs . pop ( 'rbridge_id' ) callback = kwargs . pop ( 'callback' , self . _callback ) return call...
def _get_dummy_request ( base_url , user ) : """Create a dummy request . Use the ` ` base _ url ` ` , so code can use ` ` request . build _ absolute _ uri ( ) ` ` to create absolute URLs ."""
split_url = urlsplit ( base_url ) is_secure = split_url [ 0 ] == 'https' dummy_request = RequestFactory ( HTTP_HOST = split_url [ 1 ] ) . get ( '/' , secure = is_secure ) dummy_request . is_secure = lambda : is_secure dummy_request . user = user or AnonymousUser ( ) dummy_request . site = None # Workaround for wagtail ...
def _remove_wrappers ( self ) : """Uninstall the PluginLoader monkey patches ."""
ansible_mitogen . loaders . action_loader . get = action_loader__get ansible_mitogen . loaders . connection_loader . get = connection_loader__get ansible . executor . process . worker . WorkerProcess . run = worker__run
def set_uservar ( self , user , name , value ) : """Set a variable for a user . This is like the ` ` < set > ` ` tag in RiveScript code . : param str user : The user ID to set a variable for . : param str name : The name of the variable to set . : param str value : The value to set there ."""
self . _session . set ( user , { name : value } )
def native_obj ( self ) : """Native storage object ."""
if self . __native is None : self . __native = self . _get_object ( ) return self . __native
def _prepare_value_nd ( self , value , vshape ) : """Given value and vshape , create an ` NDArray ` from value with the same context and dtype as the current one and broadcast it to vshape ."""
if isinstance ( value , numeric_types ) : value_nd = full ( shape = vshape , val = value , ctx = self . context , dtype = self . dtype ) elif isinstance ( value , NDArray ) : value_nd = value . as_in_context ( self . context ) if value_nd . dtype != self . dtype : value_nd = value_nd . astype ( self...
def is_pp_seq_no_stable ( self , msg : Checkpoint ) : """: param ppSeqNo : : return : True if ppSeqNo is less than or equal to last stable checkpoint , false otherwise"""
pp_seq_no = msg . seqNoEnd ck = self . firstCheckPoint if ck : _ , ckState = ck return ckState . isStable and ckState . seqNo >= pp_seq_no else : return False
def is_all_field_none ( self ) : """: rtype : bool"""
if self . _id_ is not None : return False if self . _created is not None : return False if self . _updated is not None : return False if self . _invoice_date is not None : return False if self . _invoice_number is not None : return False if self . _status is not None : return False if self . _gr...
def tea_decipher ( v , key ) : """Tiny Decryption Algorithm decription ( TEA ) See https : / / en . wikipedia . org / wiki / Tiny _ Encryption _ Algorithm"""
DELTA = 0x9e3779b9 n = len ( v ) rounds = 6 + 52 // n sum = ( rounds * DELTA ) y = v [ 0 ] while sum != 0 : e = ( sum >> 2 ) & 3 for p in range ( n - 1 , - 1 , - 1 ) : z = v [ ( n + p - 1 ) % n ] v [ p ] = ( v [ p ] - MX ( z , y , sum , key , p , e ) ) & 0xffffffff y = v [ p ] sum -=...
def mid ( self , value ) : """Sets the MID of the message . : type value : Integer : param value : the MID : raise AttributeError : if value is not int or cannot be represented on 16 bits ."""
if not isinstance ( value , int ) or value > 65536 : raise AttributeError self . _mid = value
def get_list ( self , name , default = None ) : """Retrieves an environment variable as a list . Note that while implicit access of environment variables containing tuples will return tuples , using this method will coerce tuples to lists . Args : name ( str ) : The case - insensitive , unprefixed variabl...
if name not in self : if default is not None : return default raise EnvironmentError . not_found ( self . _prefix , name ) return list ( self [ name ] )
def set_decode_area ( codec , image , start_x = 0 , start_y = 0 , end_x = 0 , end_y = 0 ) : """Wraps openjp2 library function opj _ set _ decode area . Sets the given area to be decoded . This function should be called right after read _ header and before any tile header reading . Parameters codec : CODEC _...
OPENJP2 . opj_set_decode_area . argtypes = [ CODEC_TYPE , ctypes . POINTER ( ImageType ) , ctypes . c_int32 , ctypes . c_int32 , ctypes . c_int32 , ctypes . c_int32 ] OPENJP2 . opj_set_decode_area . restype = check_error OPENJP2 . opj_set_decode_area ( codec , image , ctypes . c_int32 ( start_x ) , ctypes . c_int32 ( s...
def frequency ( self , literal ) : """Returns the frequency of a clamped variable Parameters literal : : class : ` caspo . core . literal . Literal ` The clamped variable Returns float The frequency of the given literal Raises ValueError If the variable is not present in any of the clampings"""
df = self . to_dataframe ( ) if literal . variable in df . columns : return len ( df [ df [ literal . variable ] == literal . signature ] ) / float ( len ( self ) ) else : raise ValueError ( "Variable not found: %s" % literal . variable )
def _compute_edges ( self ) : """Compute the edges of the current surface . Returns : Tuple [ ~ curve . Curve , ~ curve . Curve , ~ curve . Curve ] : The edges of the surface ."""
nodes1 , nodes2 , nodes3 = _surface_helpers . compute_edge_nodes ( self . _nodes , self . _degree ) edge1 = _curve_mod . Curve ( nodes1 , self . _degree , _copy = False ) edge2 = _curve_mod . Curve ( nodes2 , self . _degree , _copy = False ) edge3 = _curve_mod . Curve ( nodes3 , self . _degree , _copy = False ) return ...
def mousePressEvent ( self , event ) : """Overloads the mouse press event to handle special cases and bypass when the scene is in view mode . : param event < QMousePressEvent >"""
# ignore events when the scene is in view mode scene = self . scene ( ) if scene and scene . inViewMode ( ) : event . ignore ( ) return # block the selection signals if scene : scene . blockSelectionSignals ( True ) # clear the selection if ( not ( self . isSelected ( ) or event . modifiers ( ) == Q...
def compute_laplacian ( self , lap_type = 'combinatorial' ) : r"""Compute a graph Laplacian . For undirected graphs , the combinatorial Laplacian is defined as . . math : : L = D - W , where : math : ` W ` is the weighted adjacency matrix and : math : ` D ` the weighted degree matrix . The normalized Laplac...
if lap_type != self . lap_type : # Those attributes are invalidated when the Laplacian is changed . # Alternative : don ' t allow the user to change the Laplacian . self . _lmax = None self . _U = None self . _e = None self . _coherence = None self . _D = None self . lap_type = lap_type if not self ...
def _visit_body ( self , node ) : """Traverse the body of the node manually . If the first node is an expression which contains a string or bytes it marks that as a docstring ."""
if ( node . body and isinstance ( node . body [ 0 ] , ast . Expr ) and self . is_base_string ( node . body [ 0 ] . value ) ) : node . body [ 0 ] . value . is_docstring = True self . visit ( node . body [ 0 ] . value ) for sub_node in node . body : self . visit ( sub_node )
def P_isothermal_critical_flow ( P , fd , D , L ) : r'''Calculates critical flow pressure ` Pcf ` for a fluid flowing isothermally and suffering pressure drop caused by a pipe ' s friction factor . . . math : : P _ 2 = P _ { 1 } e ^ { \ frac { 1 } { 2 D } \ left ( D \ left ( \ operatorname { LambertW } { \ ...
# Correct branch of lambertw found by trial and error lambert_term = float ( lambertw ( - exp ( ( - D - L * fd ) / D ) , - 1 ) . real ) return P * exp ( ( D * ( lambert_term + 1.0 ) + L * fd ) / ( 2.0 * D ) )
def determine_position ( position , img , mark ) : """Options : TL : top - left TR : top - right BR : bottom - right BL : bottom - left C : centered R : random X % xY % : relative positioning on both the X and Y axes X % xY : relative positioning on the X axis and absolute positioning on the Y axi...
left = top = 0 max_left = max ( img . size [ 0 ] - mark . size [ 0 ] , 0 ) max_top = max ( img . size [ 1 ] - mark . size [ 1 ] , 0 ) # Added a 10px margin from corners to apply watermark . margin = 10 if not position : position = 'r' if isinstance ( position , tuple ) : left , top = position elif isinstance ( ...
def _trace ( frame , event , arg ) : """Trace function calls ."""
if event in ( 'call' , 'c_call' ) : _trace_line ( frame , event , arg ) elif event in ( 'return' , 'c_return' ) : _trace_line ( frame , event , arg ) print ( " return:" , arg ) # elif event in ( ' exception ' , ' c _ exception ' ) : # _ trace _ line ( frame , event , arg ) return _trace
def namedb_get_account_history ( cur , address , offset = None , count = None ) : """Get the history of an account ' s tokens"""
sql = 'SELECT * FROM accounts WHERE address = ? ORDER BY block_id DESC, vtxindex DESC' args = ( address , ) if count is not None : sql += ' LIMIT ?' args += ( count , ) if offset is not None : sql += ' OFFSET ?' args += ( offset , ) sql += ';' rows = namedb_query_execute ( cur , sql , args ) ret = [ ] f...
def _get_maps_from_user ( self , user ) : """Get mapfiles owned by a user from the database ."""
req = Session . query ( Map ) . select_from ( join ( Map , User ) ) return req . filter ( User . login == user ) . all ( )
def clean ( s , lowercase = True , replace_by_none = r'[^ \-\_A-Za-z0-9]+' , replace_by_whitespace = r'[\-\_]' , strip_accents = None , remove_brackets = True , encoding = 'utf-8' , decode_error = 'strict' ) : """Clean string variables . Clean strings in the Series by removing unwanted tokens , whitespace and b...
if s . shape [ 0 ] == 0 : return s # Lower s if lower is True if lowercase is True : s = s . str . lower ( ) # Accent stripping based on https : / / github . com / scikit - learn / # scikit - learn / blob / 412996f / sklearn / feature _ extraction / text . py # BSD license if not strip_accents : pass elif c...
def _init_cache ( self ) : """Initialise the depth cache calling REST endpoint : return :"""
self . _last_update_id = None self . _depth_message_buffer = [ ] res = self . _client . get_order_book ( symbol = self . _symbol , limit = self . _limit ) # process bid and asks from the order book for bid in res [ 'bids' ] : self . _depth_cache . add_bid ( bid ) for ask in res [ 'asks' ] : self . _depth_cache ...
def visibility ( self ) : """See the class documentation ."""
if self . _cached_vis is None : self . _cached_vis = _visibility ( self ) return self . _cached_vis
def _one_to_many_query ( cls , query_obj , search4 , model_attrib ) : """extends and returns a SQLAlchemy query object to allow one - to - many queries : param query _ obj : SQL Alchemy query object : param str search4 : search string : param model _ attrib : attribute in model"""
model = model_attrib . parent . class_ if isinstance ( search4 , str ) : query_obj = query_obj . join ( model ) . filter ( model_attrib . like ( search4 ) ) elif isinstance ( search4 , int ) : query_obj = query_obj . join ( model ) . filter ( model_attrib == search4 ) elif isinstance ( search4 , Iterable ) : ...
def _check_missing_slots ( ob ) : """Check that all slots have been initialized when a custom _ _ init _ _ method is provided . Parameters ob : immutable The instance that was just initialized . Raises TypeError Raised when the instance has not set values that are named in the _ _ slots _ _ ."""
missing_slots = tuple ( filter ( lambda s : not hasattr ( ob , s ) , ob . __slots__ ) , ) if missing_slots : raise TypeError ( 'not all slots initialized in __init__, missing: {0}' . format ( missing_slots , ) , )
def flush ( self ) : '''Write all the enqueued bytestring before this flush call to disk . Block until all the above bytestring are written .'''
with self . _lock : if self . _closed : raise IOError ( 'Writer is closed' ) self . _byte_queue . join ( ) self . _writer . flush ( )
def get_color_label ( self ) : """Text for colorbar label"""
if self . args . norm : return 'Normalized to {}' . format ( self . args . norm ) if len ( self . units ) == 1 and self . usetex : return r'ASD $\left({0}\right)$' . format ( self . units [ 0 ] . to_string ( 'latex' ) . strip ( '$' ) ) elif len ( self . units ) == 1 : return 'ASD ({0})' . format ( self . un...
def match ( self , route ) : """Match input route and return new Message instance with parsed content"""
_resource = trim_resource ( self . resource ) self . method = self . method . lower ( ) resource_match = route . resource_regex . search ( _resource ) if resource_match is None : return None # build params and querystring params = resource_match . groupdict ( ) querystring = params . pop ( "querystring" , "" ) seta...
def _create_page ( cls , page , lang , auto_title , cms_app = None , parent = None , namespace = None , site = None , set_home = False ) : """Create a single page or titles : param page : Page instance : param lang : language code : param auto _ title : title text for the newly created title : param cms _ a...
from cms . api import create_page , create_title from cms . utils . conf import get_templates default_template = get_templates ( ) [ 0 ] [ 0 ] if page is None : page = create_page ( auto_title , language = lang , parent = parent , site = site , template = default_template , in_navigation = True , published = True )...
def get_child_catalogs ( self , catalog_id ) : """Gets the child catalogs of the given ` ` id ` ` . arg : catalog _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Catalog ` ` to query return : ( osid . cataloging . CatalogList ) - the child catalogs of the ` ` id ` ` raise : NotFound - a ` ` Catalog ` ...
# Implemented from template for # osid . resource . BinHierarchySession . get _ child _ bins if self . _catalog_session is not None : return self . _catalog_session . get_child_catalogs ( catalog_id = catalog_id ) return CatalogLookupSession ( self . _proxy , self . _runtime ) . get_catalogs_by_ids ( list ( self . ...
def color_lerp ( c1 : Tuple [ int , int , int ] , c2 : Tuple [ int , int , int ] , a : float ) -> Color : """Return the linear interpolation between two colors . ` ` a ` ` is the interpolation value , with 0 returing ` ` c1 ` ` , 1 returning ` ` c2 ` ` , and 0.5 returing a color halfway between both . Args : ...
return Color . _new_from_cdata ( lib . TCOD_color_lerp ( c1 , c2 , a ) )
def _check_date_format ( date , api ) : '''Checks that the given date string conforms to the given API ' s date format specification'''
try : datetime . datetime . strptime ( date , api . DATE_FORMAT ) except ValueError : raise ValueError ( "Date '{}' does not conform to API format: {}" . format ( date , api . DATE_FORMAT ) )
def thread ( self ) : '''Run in a thread'''
thread = threading . Thread ( target = self . listen ) thread . start ( ) try : yield self finally : self . unlisten ( ) thread . join ( )
def load_data ( filename ) : """Loads data from a file . Parameters filename : : obj : ` str ` The file to load the collection from . Returns : obj : ` numpy . ndarray ` of float The data read from the file . Raises ValueError If the file extension is not . npy or . npz ."""
file_root , file_ext = os . path . splitext ( filename ) data = None if file_ext == '.npy' : data = np . load ( filename ) elif file_ext == '.npz' : data = np . load ( filename ) [ 'arr_0' ] else : raise ValueError ( 'Extension %s not supported for point reads' % ( file_ext ) ) return data
def scan ( TableName = None , IndexName = None , AttributesToGet = None , Limit = None , Select = None , ScanFilter = None , ConditionalOperator = None , ExclusiveStartKey = None , ReturnConsumedCapacity = None , TotalSegments = None , Segment = None , ProjectionExpression = None , FilterExpression = None , ExpressionA...
pass
def update ( self , client = None ) : """API call : update the project via a ` ` PUT ` ` request . See https : / / cloud . google . com / resource - manager / reference / rest / v1beta1 / projects / update : type client : : class : ` google . cloud . resource _ manager . client . Client ` or : data : ` None...
client = self . _require_client ( client ) data = { "name" : self . name , "labels" : self . labels , "parent" : self . parent } resp = client . _connection . api_request ( method = "PUT" , path = self . path , data = data ) self . set_properties_from_api_repr ( resp )
def read_file ( paths ) : """read config from path or list of paths : param str | list [ str ] paths : path or list of paths : return dict : loaded and merged config"""
if isinstance ( paths , str ) : paths = [ paths ] re = { } for path in paths : cfg = yaml . load ( open ( path ) ) merge ( re , cfg ) return re
def save_formset ( self , request , form , formset , change ) : """Given an inline formset save it to the database ."""
formset . save ( ) for form in formset . forms : if hasattr ( form , 'nested_formsets' ) and form not in formset . deleted_forms : for nested_formset in form . nested_formsets : self . save_formset ( request , form , nested_formset , change )
def ttl ( self , value ) : """Change self ttl with input value . : param float value : new ttl in seconds ."""
# get timer timer = getattr ( self , Annotation . __TIMER , None ) # if timer is running , stop the timer if timer is not None : timer . cancel ( ) # initialize timestamp timestamp = None # if value is None if value is None : # nonify timer timer = None else : # else , renew a timer # get timestamp timestam...
def setup_hds ( self ) : """setup modflow head save file observations for given kper ( zero - based stress period index ) and k ( zero - based layer index ) pairs using the kperk argument . Note this can setup a shit - ton of observations this is useful for dataworth analyses or for monitoring water lev...
if self . hds_kperk is None or len ( self . hds_kperk ) == 0 : return from . gw_utils import setup_hds_obs # if len ( self . hds _ kperk ) = = 2: # try : # if len ( self . hds _ kperk [ 0 ] = = 2 ) : # pass # except : # self . hds _ kperk = [ self . hds _ kperk ] oc = self . m . get_package ( "OC" ) if oc is None :...
def attach_rconfiguration ( context , id , name , topic_id , component_types , data ) : """attach _ rconfiguration ( context , name , topic _ id , component _ types , data ) : Attach an rconfiguration to a Remote CI > > > dcictl remoteci - attach - rconfiguration ID [ OPTIONS ] : param string id : id of the r...
result = remoteci . add_rconfiguration ( context , id , name , topic_id , component_types , data ) utils . format_output ( result , context . format )
def color_transaction ( self , transaction ) : """Computes the asset ID and asset quantity of every output in the transaction . : param CTransaction transaction : The transaction to color . : return : A list containing all the colored outputs of the transaction . : rtype : Future [ list [ TransactionOutput ] ...
# If the transaction is a coinbase transaction , the marker output is always invalid if not transaction . is_coinbase ( ) : for i , output in enumerate ( transaction . vout ) : # Parse the OP _ RETURN script marker_output_payload = MarkerOutput . parse_script ( output . scriptPubKey ) if marker_outp...
def format_ffmpeg_filter ( name , params ) : """Build a string to call a FFMpeg filter ."""
return "%s=%s" % ( name , ":" . join ( "%s=%s" % ( k , v ) for k , v in params . items ( ) ) )
def incoming_manipulators ( self ) : """* * DEPRECATED * * : All incoming SON manipulators . . . versionchanged : : 3.5 Deprecated . . . versionadded : : 2.0"""
warnings . warn ( "Database.incoming_manipulators() is deprecated" , DeprecationWarning , stacklevel = 2 ) return [ manipulator . __class__ . __name__ for manipulator in self . __incoming_manipulators ]
def description ( self ) : """A list of the metrics this query will ask for ."""
if 'metrics' in self . raw : metrics = self . raw [ 'metrics' ] head = metrics [ 0 : - 1 ] or metrics [ 0 : 1 ] text = ", " . join ( head ) if len ( metrics ) > 1 : tail = metrics [ - 1 ] text = text + " and " + tail else : text = 'n/a' return text
def clear_published ( self ) : """Removes the published status . : raise : ` ` NoAccess ` ` - - ` ` Metadata . isRequired ( ) ` ` is ` ` true ` ` or ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` ` * compliance : mandatory - - This method must be implemented . *"""
metadata = Metadata ( ** settings . METADATA [ 'published' ] ) if metadata . is_read_only ( ) or metadata . is_required ( ) : raise NoAccess ( ) self . _my_map [ 'published' ] = False
def _set_ospf_level12 ( self , v , load = False ) : """Setter method for ospf _ level12 , mapped from YANG variable / routing _ system / router / isis / router _ isis _ cmds _ holder / address _ family / ipv6 / af _ ipv6 _ unicast / af _ ipv6 _ attributes / af _ common _ attributes / redistribute / ospf / ospf _ le...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGBool , is_leaf = True , yang_name = "ospf-level12" , rest_name = "level-1-2" , parent = self , choice = ( u'ch-ospf-levels' , u'ca-ospf-level12' ) , path_helper = self . _path_helper , extmethods = self . _extmethods , re...
def get_game_high_scores ( self , user_id , chat_id = None , message_id = None , inline_message_id = None ) : """Use this method to get data for high score tables . Will return the score of the specified user and several of his neighbors in a game . On success , returns an Array of GameHighScore objects . This me...
assert_type_or_raise ( user_id , int , parameter_name = "user_id" ) assert_type_or_raise ( chat_id , None , int , parameter_name = "chat_id" ) assert_type_or_raise ( message_id , None , int , parameter_name = "message_id" ) assert_type_or_raise ( inline_message_id , None , unicode_type , parameter_name = "inline_messag...
def output_row ( self , name ) : "Output a scoring row ."
print ( "%10s %4d %0.3f %0.3f %0.3f" % ( name , self . gold , self . precision ( ) , self . recall ( ) , self . fscore ( ) ) )
def _filter_running ( runnings ) : '''Filter out the result : True + no changes data'''
ret = dict ( ( tag , value ) for tag , value in six . iteritems ( runnings ) if not value [ 'result' ] or value [ 'changes' ] ) return ret
def find_splice ( cigar ) : '''Takes a cigar string and finds the first splice position as an offset from the start . To find the 5 ' end ( read coords ) of the junction for a reverse read , pass in the reversed cigar tuple'''
offset = 0 # a soft clip at the end of the read is taken as splicing # where as a soft clip at the start is not . if cigar [ 0 ] [ 0 ] == 4 : offset = cigar [ 0 ] [ 1 ] cigar = cigar [ 1 : ] for op , bases in cigar : if op in ( 3 , 4 ) : # N or S : found the splice return offset elif op in ( 0 ,...
def imshow ( self , canvas , X , extent = None , label = None , vmin = None , vmax = None , ** kwargs ) : """Show the image stored in X on the canvas . The origin of the image show is ( 0,0 ) , such that X [ 0,0 ] gets plotted at [ 0,0 ] of the image ! the kwargs are plotting library specific kwargs !"""
raise NotImplementedError ( "Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library" )
def _del_repo_from_file ( repo , filepath ) : '''Remove a repo from filepath'''
with salt . utils . files . fopen ( filepath ) as fhandle : output = [ ] regex = re . compile ( REPO_REGEXP ) for line in fhandle : line = salt . utils . stringutils . to_unicode ( line ) if regex . search ( line ) : if line . startswith ( '#' ) : line = line [ 1 ...
def clonemedium ( medium , uuid_in = None , file_in = None , uuid_out = None , file_out = None , mformat = None , variant = None , existing = False , ** kwargs ) : '''Clone a new VM from an existing VM CLI Example : . . code - block : : bash salt ' hypervisor ' vboxmanage . clonemedium < name > < new _ name >...
params = '' valid_mediums = ( 'disk' , 'dvd' , 'floppy' ) if medium in valid_mediums : params += medium else : raise CommandExecutionError ( 'Medium must be one of: {0}.' . format ( ', ' . join ( valid_mediums ) ) ) if ( uuid_in and file_in ) or ( not uuid_in and not file_in ) : raise CommandExecutionError ...
def open_umanager ( self ) : """Used to open an uManager session ."""
if self . umanager_opened : return self . ser . write ( self . cmd_umanager_invocation ) # optimistic approach first : assume umanager is not invoked if self . read_loop ( lambda x : x . endswith ( self . umanager_prompt ) , self . timeout * self . umanager_waitcoeff ) : self . umanager_opened = True else : # i...
def map_http_status_to_exception ( http_code ) : """Bind a HTTP status to an HttpError . : param http _ code : The HTTP code : type http _ code : int : return The HttpError that fits to the http _ code or HttpError . : rtype Any subclass of HttpError or HttpError"""
http_exceptions = HttpError . __subclasses__ ( ) for http_exception in http_exceptions : http_statuses = http_exception . HTTP_STATUSES if isinstance ( http_statuses , int ) : http_statuses = [ http_exception . HTTP_STATUSES ] try : if http_code in http_statuses : return http_exc...
def get_description ( self , lang : str = None ) -> Literal : """Get the description of the object : param lang : Lang to retrieve : return : Description string representation : rtype : Literal"""
return self . metadata . get_single ( key = DC . description , lang = lang )
def _create_all_new_chains ( self , converter ) -> Tuple [ List [ Converter ] , List [ Converter ] , List [ Converter ] , List [ Converter ] ] : """Creates all specific and generic chains that may be built by adding this converter to the existing chains . : param converter : : return : generic _ chains , generi...
specific_chains , specific_nonstrict_chains , generic_chains , generic_nonstrict_chains = [ ] , [ ] , [ ] , [ ] if converter . is_generic ( ) : # the smaller chain : the singleton : ) generic_chains . append ( ConversionChain ( initial_converters = [ converter ] , strict_chaining = True ) ) else : specific_chai...
def message_interactions ( self ) : """Access the message _ interactions : returns : twilio . rest . proxy . v1 . service . session . participant . message _ interaction . MessageInteractionList : rtype : twilio . rest . proxy . v1 . service . session . participant . message _ interaction . MessageInteractionLi...
if self . _message_interactions is None : self . _message_interactions = MessageInteractionList ( self . _version , service_sid = self . _solution [ 'service_sid' ] , session_sid = self . _solution [ 'session_sid' ] , participant_sid = self . _solution [ 'sid' ] , ) return self . _message_interactions
def apply_transform ( self , transform ) : """Apply a homogenous transformation to the PointCloud object in - place . Parameters transform : ( 4 , 4 ) float Homogenous transformation to apply to PointCloud"""
self . vertices = transformations . transform_points ( self . vertices , matrix = transform )
def cnes2modis ( cnes_date , YYYYDDDHHMM = None , YYYYDDD = True ) : """# CNES2MODIS : Convert CNES julian days to MODIS data format ( YYYYDDD ) # @ author : Renaud DUSSURGET ( LEGOS / CTOH ) # @ history : Created by RD on 2/12/2011 # Adapted to Python on 29/10/2012 by RD ( now at LER PAC / IFREMER )"""
# Setup defaults if YYYYDDDHHMM is None : YYYYDDDHHMM = False if YYYYDDD : YYYYDDDHHMM = False if YYYYDDDHHMM : YYYYDDD = False str , obj = cnes_convert ( cnes_date ) dat = [ o . strftime ( "%Y%j%H%M" ) for o in obj ] return dat
def get_vert_connectivity ( mesh_v , mesh_f ) : """Returns a sparse matrix ( of size # verts x # verts ) where each nonzero element indicates a neighborhood relation . For example , if there is a nonzero element in position ( 15,12 ) , that means vertex 15 is connected by an edge to vertex 12."""
vpv = sp . csc_matrix ( ( len ( mesh_v ) , len ( mesh_v ) ) ) # for each column in the faces . . . for i in range ( 3 ) : IS = mesh_f [ : , i ] JS = mesh_f [ : , ( i + 1 ) % 3 ] data = np . ones ( len ( IS ) ) ij = np . vstack ( ( row ( IS . flatten ( ) ) , row ( JS . flatten ( ) ) ) ) mtx = sp . cs...
def linkify ( self , timeperiods = None , commands = None , contacts = None , # pylint : disable = R0913 realms = None , resultmodulations = None , businessimpactmodulations = None , escalations = None , hostgroups = None , checkmodulations = None , macromodulations = None ) : """Create link between objects : : *...
self . linkify_with_timeperiods ( timeperiods , 'notification_period' ) self . linkify_with_timeperiods ( timeperiods , 'check_period' ) self . linkify_with_timeperiods ( timeperiods , 'maintenance_period' ) self . linkify_with_timeperiods ( timeperiods , 'snapshot_period' ) self . linkify_h_by_h ( ) self . linkify_h_b...
def outputSaveCallback ( self , at_data , ** kwargs ) : """Test method for outputSaveCallback Simply writes a file in the output tree corresponding to the number of files in the input tree ."""
path = at_data [ 0 ] d_outputInfo = at_data [ 1 ] other . mkdir ( self . str_outputDir ) filesSaved = 0 other . mkdir ( path ) if not self . testType : str_outfile = '%s/file-ls.txt' % path else : str_outfile = '%s/file-count.txt' % path with open ( str_outfile , 'w' ) as f : self . dp . qprint ( "saving: %...
def distance ( self , loc ) : """Calculate the great circle distance between two points on the earth ( specified in decimal degrees )"""
assert type ( loc ) == type ( self ) # convert decimal degrees to radians lon1 , lat1 , lon2 , lat2 = map ( radians , [ self . lon , self . lat , loc . lon , loc . lat , ] ) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin ( dlat / 2 ) ** 2 + cos ( lat1 ) * cos ( lat2 ) * sin ( dlon / 2 ) ** 2 c = 2 * ...
async def rawmsg ( self , command , * args , ** kwargs ) : """Send raw message ."""
message = str ( self . _create_message ( command , * args , ** kwargs ) ) await self . _send ( message )
def get_unique_variable_names ( text , nb ) : '''returns a list of possible variables names that are not found in the original text .'''
base_name = '__VAR_' var_names = [ ] i = 0 j = 0 while j < nb : tentative_name = base_name + str ( i ) if text . count ( tentative_name ) == 0 and tentative_name not in ALL_NAMES : var_names . append ( tentative_name ) ALL_NAMES . append ( tentative_name ) j += 1 i += 1 return var_na...
def write_gif ( dataset , filename , fps = 10 ) : """Write a NumPy array to GIF 89a format . Or write a list of NumPy arrays to an animation ( GIF 89a format ) . - Positional arguments : : : param dataset : A NumPy arrayor list of arrays with shape rgb x rows x cols and integer values in [ 0 , 255 ] . : p...
try : check_dataset ( dataset ) except ValueError as e : dataset = try_fix_dataset ( dataset ) check_dataset ( dataset ) delay_time = 100 // int ( fps ) def encode ( d ) : four_d = isinstance ( dataset , numpy . ndarray ) and len ( dataset . shape ) == 4 if four_d or not isinstance ( dataset , numpy...
def format_cffi_externs ( cls ) : """Generate stubs for the cffi bindings from @ _ extern _ decl methods ."""
extern_decls = [ f . extern_signature . pretty_print ( ) for _ , f in cls . _extern_fields . items ( ) ] return ( 'extern "Python" {\n' + '\n' . join ( extern_decls ) + '\n}\n' )
def file_chunk ( filename , size = _BUFFERING ) : """returns a generator function which when called will emit x - sized chunks of filename ' s contents"""
def chunks ( ) : with open ( filename , "rb" , _BUFFERING ) as fd : buf = fd . read ( size ) while buf : yield buf buf = fd . read ( size ) return chunks
def get_next_parameters ( self , n = None ) : """Gets the next set of ` ` Parameters ` ` in this list which must be less than or equal to the return from ` ` available ( ) ` ` . arg : n ( cardinal ) : the number of ` ` Parameter ` ` elements requested which must be less than or equal to ` ` available ( ) ` ` ...
# Implemented from template for osid . resource . ResourceList . get _ next _ resources 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 : tr...
def get_extra_managed_storage_volume_paths ( self , start = 0 , count = - 1 , filter = '' , sort = '' ) : """Gets the list of extra managed storage volume paths . Args : start : The first item to return , using 0 - based indexing . If not specified , the default is 0 - start with the first available item . ...
uri = self . URI + '/repair?alertFixType=ExtraManagedStorageVolumePaths' return self . _client . get_all ( start , count , filter = filter , sort = sort , uri = uri )
def create_native_pay_url ( self , productid ) : """创建 native pay url 详情请参考 支付开发文档 : param productid : 本地商品ID : return : 返回URL"""
params , sign , = self . _pay_sign_dict ( productid = productid ) params [ 'sign' ] = sign return NATIVE_BASE_URL + urlencode ( params )
def mbar_ ( self , col , x = None , y = None , rsum = None , rmean = None ) : """Splits a column into multiple series based on the column ' s unique values . Then visualize theses series in a chart . Parameters : column to split , x axis column , y axis column Optional : rsum = " 1D " to resample and sum data...
return self . _multiseries ( col , x , y , "bar" , rsum , rmean )
def get_forecast_fromstr ( self , reply ) : """Gets the weather data from a darksky api response string and stores it in the respective dictionaries if available . This function should be used to fetch weather information ."""
self . forecast = json . loads ( reply ) for item in self . forecast . keys ( ) : setattr ( self , item , self . forecast [ item ] )
def version_add ( package , version , pkghash , force = False ) : """Add a new version for a given package hash . Version format needs to follow PEP 440. Versions are permanent - once created , they cannot be modified or deleted ."""
team , owner , pkg = parse_package ( package ) session = _get_session ( team ) try : Version ( version ) except ValueError : url = "https://www.python.org/dev/peps/pep-0440/#examples-of-compliant-version-schemes" raise CommandException ( "Invalid version format; see %s" % url ) if not force : answer = i...
def setting_address ( key ) : """Computes the radix address for the given setting key . Keys are broken into four parts , based on the dots in the string . For example , the key ` a . b . c ` address is computed based on ` a ` , ` b ` , ` c ` and the empty string . A longer key , for example ` a . b . c . d ....
# split the key into 4 parts , maximum key_parts = key . split ( '.' , maxsplit = _MAX_KEY_PARTS - 1 ) # compute the short hash of each part addr_parts = [ _short_hash ( x . encode ( ) ) for x in key_parts ] # pad the parts with the empty hash , if needed addr_parts . extend ( [ _EMPTY_PART ] * ( _MAX_KEY_PARTS - len (...
def get_metadata ( self , refresh = True ) : """return cached metadata by default : param refresh : bool , returns up to date metadata if set to True : return : dict"""
if refresh or not self . _metadata : ident = self . _id or self . name if not ident : raise ConuException ( "This container does not have a valid identifier." ) out = run_cmd ( [ "machinectl" , "--no-pager" , "show" , ident ] , return_output = True , ignore_status = True ) if "Could not get path...
def getRotatedSize ( corners , angle ) : """Determine the size of a rotated ( meta ) image ."""
if angle : _rotm = fileutil . buildRotMatrix ( angle ) # Rotate about the center _corners = np . dot ( corners , _rotm ) else : # If there is no rotation , simply return original values _corners = corners return computeRange ( _corners )
def get_pdf ( article , debug = False ) : """Download an article PDF from arXiv . : param article : The ADS article to retrieve . : type article : : class : ` ads . search . Article ` : returns : The binary content of the requested PDF ."""
print ( 'Retrieving {0}' . format ( article ) ) identifier = [ _ for _ in article . identifier if 'arXiv' in _ ] if identifier : url = 'http://arXiv.org/pdf/{0}.{1}' . format ( identifier [ 0 ] [ 9 : 13 ] , '' . join ( _ for _ in identifier [ 0 ] [ 14 : ] if _ . isdigit ( ) ) ) else : # No arXiv version . Ask ADS t...
def mousePressEvent ( self , event ) : """Override Qt method Add / remove breakpoints by single click ."""
line_number = self . editor . get_linenumber_from_mouse_event ( event ) shift = event . modifiers ( ) & Qt . ShiftModifier self . editor . debugger . toogle_breakpoint ( line_number , edit_condition = shift )
def read ( self , file_name , delim = ',' , sep = '\t' ) : """Read a directed hypergraph from a file , where nodes are represented as strings . Each column is separated by " sep " , and the individual tail nodes and head nodes are delimited by " delim " . The header line is currently ignored , but columns s...
in_file = open ( file_name , 'r' ) # Skip the header line in_file . readline ( ) line_number = 2 for line in in_file . readlines ( ) : line = line . strip ( ) # Skip empty lines if not line : continue words = line . split ( sep ) if not ( 2 <= len ( words ) <= 3 ) : raise IOError ( "...
def get_tags_from_full_ob ( ob , reqtags = None ) : """Parameters ob ( ObservationResult ) : Observation result reqtags ( dict ) : Keywords Returns A dictionary"""
# each instrument should have one # perhaps each mode . . . files = ob . frames cfiles = ob . children alltags = { } if reqtags is None : reqtags = [ ] # Init alltags . . . # Open first image if files : for fname in files [ : 1 ] : with fname . open ( ) as fd : header = fd [ 0 ] . header ...
def delete_file ( i ) : """Input : { ( repo _ uoa ) - repo UOA module _ uoa - module UOA data _ uoa - data UOA filename - filename to delete including relative path ( force ) - if ' yes ' , force deleting without questions Output : { return - return code = 0 , if successful > 0 , if error ( error ...
# Check if global writing is allowed r = check_writing ( { 'delete' : 'yes' } ) if r [ 'return' ] > 0 : return r o = i . get ( 'out' , '' ) ruoa = i . get ( 'repo_uoa' , '' ) muoa = i . get ( 'module_uoa' , '' ) duoa = i . get ( 'data_uoa' , '' ) # Check file fn = i . get ( 'filename' , '' ) if fn == '' : x = i...