signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def emit ( self , ctx , modules , fd ) : """Main control function . Set up the top - level parts of the sample document , then process recursively all nodes in all data trees , and finally emit the sample XML document ."""
if ctx . opts . sample_path is not None : path = ctx . opts . sample_path . split ( '/' ) if path [ 0 ] == '' : path = path [ 1 : ] else : path = [ ] for ( epos , etag , eargs ) in ctx . errors : if error . is_error ( error . err_level ( etag ) ) : raise error . EmitError ( "sample-xml-s...
def snli_dataset ( directory = 'data/' , train = False , dev = False , test = False , train_filename = 'snli_1.0_train.jsonl' , dev_filename = 'snli_1.0_dev.jsonl' , test_filename = 'snli_1.0_test.jsonl' , extracted_name = 'snli_1.0' , check_files = [ 'snli_1.0/snli_1.0_train.jsonl' ] , url = 'http://nlp.stanford.edu/p...
download_file_maybe_extract ( url = url , directory = directory , check_files = check_files ) get_transitions = lambda parse : [ 'reduce' if t == ')' else 'shift' for t in parse if t != '(' ] ret = [ ] splits = [ ( train , train_filename ) , ( dev , dev_filename ) , ( test , test_filename ) ] splits = [ f for ( request...
def create_continuous_query ( self , name , select , database = None , resample_opts = None ) : r"""Create a continuous query for a database . : param name : the name of continuous query to create : type name : str : param select : select statement for the continuous query : type select : str : param data...
query_string = ( "CREATE CONTINUOUS QUERY {0} ON {1}{2} BEGIN {3} END" ) . format ( quote_ident ( name ) , quote_ident ( database or self . _database ) , ' RESAMPLE ' + resample_opts if resample_opts else '' , select ) self . query ( query_string )
def warn ( self , collection ) : """Checks this code element for documentation related problems ."""
if not self . has_docstring ( ) : collection . append ( "WARNING: no docstring on code element {}" . format ( self . name ) )
def validate_file_ownership ( config ) : """Verify that configuration files are owned by the correct user / group ."""
files = config . get ( 'files' , { } ) for file_name , options in files . items ( ) : for key in options . keys ( ) : if key not in [ "owner" , "group" , "mode" ] : raise RuntimeError ( "Invalid ownership configuration: {}" . format ( key ) ) owner = options . get ( 'owner' , config . get ( ...
def addTrack ( self , track ) : """Add a : class : ` MediaStreamTrack ` to the set of media tracks which will be transmitted to the remote peer ."""
# check state is valid self . __assertNotClosed ( ) if track . kind not in [ 'audio' , 'video' ] : raise InternalError ( 'Invalid track kind "%s"' % track . kind ) # don ' t add track twice self . __assertTrackHasNoSender ( track ) for transceiver in self . __transceivers : if transceiver . kind == track . kind...
def get ( self , bucket = None , key = None , version_id = None , upload_id = None , uploads = None , download = None ) : """Get object or list parts of a multpart upload . : param bucket : The bucket ( instance or id ) to get the object from . ( Default : ` ` None ` ` ) : param key : The file key . ( Default...
if upload_id : return self . multipart_listparts ( bucket , key , upload_id ) else : obj = self . get_object ( bucket , key , version_id ) # If ' download ' is missing from query string it will have # the value None . return self . send_object ( bucket , obj , as_attachment = download is not None )
def _flat_crossproduct_scatter ( process , # type : WorkflowJobStep joborder , # type : MutableMapping [ Text , Any ] scatter_keys , # type : MutableSequence [ Text ] callback , # type : ReceiveScatterOutput startindex , # type : int runtimeContext # type : RuntimeContext ) : # type : ( . . . ) - > Tuple [ List [ Gener...
scatter_key = scatter_keys [ 0 ] jobl = len ( joborder [ scatter_key ] ) steps = [ ] put = startindex for index in range ( 0 , jobl ) : sjob = copy . copy ( joborder ) sjob [ scatter_key ] = joborder [ scatter_key ] [ index ] if len ( scatter_keys ) == 1 : if runtimeContext . postScatterEval is not ...
def good_surts_from_default ( default_surt ) : '''Takes a standard surt without scheme and without trailing comma , and returns a list of " good " surts that together match the same set of urls . For example : good _ surts _ from _ default ( ' com , example ) / path ' ) returns [ ' http : / / ( com , exam...
if default_surt == '' : return [ '' ] parts = default_surt . split ( ')' , 1 ) if len ( parts ) == 2 : orig_host_part , path_part = parts good_surts = [ 'http://(%s,)%s' % ( orig_host_part , path_part ) , 'https://(%s,)%s' % ( orig_host_part , path_part ) , 'http://(%s,www,)%s' % ( orig_host_part , path_par...
def cyclone ( adata , marker_pairs , gene_names , sample_names , iterations = 1000 , min_iter = 100 , min_pairs = 50 ) : """Assigns scores and predicted class to observations [ Scialdone15 ] _ [ Fechtner18 ] _ . Calculates scores for each observation and each phase and assigns prediction based on marker pairs i...
try : from pypairs import __version__ as pypairsversion from distutils . version import LooseVersion if LooseVersion ( pypairsversion ) < LooseVersion ( "v3.0.9" ) : raise ImportError ( 'Please only use `pypairs` >= v3.0.9 ' ) except ImportError : raise ImportError ( 'You need to install the pac...
def calledOnce ( cls , spy ) : # pylint : disable = invalid - name """Checking the inspector is called once Args : SinonSpy"""
cls . __is_spy ( spy ) if not ( spy . calledOnce ) : raise cls . failException ( cls . message )
def reference ( self ) : """A : class : ` ~ google . cloud . bigquery . model . ModelReference ` pointing to this model . Read - only . Returns : google . cloud . bigquery . model . ModelReference : pointer to this model ."""
ref = ModelReference ( ) ref . _proto = self . _proto . model_reference return ref
async def copy_context_with ( ctx : commands . Context , * , author = None , channel = None , ** kwargs ) : """Makes a new : class : ` Context ` with changed message properties ."""
# copy the message and update the attributes alt_message : discord . Message = copy . copy ( ctx . message ) alt_message . _update ( channel or alt_message . channel , kwargs ) # pylint : disable = protected - access if author is not None : alt_message . author = author # obtain and return a context of the same typ...
def collect ( self , step , content ) : '''given a name of a configuration key and the provided content , collect the required metadata from the user . Parameters step : the key in the configuration . Can be one of : user _ message _ < name > runtime _ arg _ < name > record _ asciinema record _ enviro...
# Option 1 : The step is just a message to print to the user if step . startswith ( 'user_message' ) : print ( content ) # Option 2 : The step is to collect a user prompt ( if not at runtime ) elif step . startswith ( 'user_prompt' ) : self . collect_argument ( step , content ) # Option 3 : The step is to recor...
def to_underscore_case ( camelcase_str ) : r"""References : http : / / stackoverflow . com / questions / 1175208 / convert - camelcase Example : > > > # ENABLE _ DOCTEST > > > from utool . util _ str import * # NOQA > > > camelcase _ str = ' UnderscoreFuncname ' > > > camel _ case _ str = to _ underscor...
s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , camelcase_str ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
def assemble ( self ) : """Assemble an array from a distributed array of object IDs ."""
first_block = ray . get ( self . objectids [ ( 0 , ) * self . ndim ] ) dtype = first_block . dtype result = np . zeros ( self . shape , dtype = dtype ) for index in np . ndindex ( * self . num_blocks ) : lower = DistArray . compute_block_lower ( index , self . shape ) upper = DistArray . compute_block_upper ( i...
def accel_next ( self , * args ) : """Callback to go to the next tab . Called by the accel key ."""
if self . get_notebook ( ) . get_current_page ( ) + 1 == self . get_notebook ( ) . get_n_pages ( ) : self . get_notebook ( ) . set_current_page ( 0 ) else : self . get_notebook ( ) . next_page ( ) return True
def resolve ( self , key ) : """Resolves the requested key to an object instance , raising a KeyError if the key is missing"""
registration = self . _registrations . get ( key ) if registration is None : raise KeyError ( "Unknown key: '{0}'" . format ( key ) ) return registration . resolve ( self , key )
def _cast_to_pod ( val ) : """Try cast to int , float , bool , str , in that order ."""
bools = { "True" : True , "False" : False } if val in bools : return bools [ val ] try : return int ( val ) except ValueError : try : return float ( val ) except ValueError : return tf . compat . as_text ( val )
def get_all_credit_notes ( self , params = None ) : """Get all credit notes This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing : param params : search params : return : list"""
if not params : params = { } return self . _iterate_through_pages ( self . get_credit_notes_per_page , resource = CREDIT_NOTES , ** { 'params' : params } )
def get_merge_direction ( cell1 , cell2 ) : """Determine the side of cell1 that can be merged with cell2. This is based on the location of the two cells in the table as well as the compatability of their height and width . For example these cells can merge : : cell1 cell2 merge " RIGHT " | foo | | dog | |...
cell1_left = cell1 . column cell1_right = cell1 . column + cell1 . column_count cell1_top = cell1 . row cell1_bottom = cell1 . row + cell1 . row_count cell2_left = cell2 . column cell2_right = cell2 . column + cell2 . column_count cell2_top = cell2 . row cell2_bottom = cell2 . row + cell2 . row_count if ( cell1_right =...
def sendInstanceChange ( self , view_no : int , suspicion = Suspicions . PRIMARY_DEGRADED ) : """Broadcast an instance change request to all the remaining nodes : param view _ no : the view number when the instance change is requested"""
# If not found any sent instance change messages in last # ` ViewChangeWindowSize ` seconds or the last sent instance change # message was sent long enough ago then instance change message can be # sent otherwise no . canSendInsChange , cooldown = self . insChngThrottler . acquire ( ) if canSendInsChange : logger ....
def handle_tags ( repo , ** kwargs ) : """: return : repo . tags ( )"""
log . info ( 'tags: %s %s' % ( repo , kwargs ) ) return [ str ( t ) for t in repo . tags ( ** kwargs ) ]
def set_result ( self , values , visible_columns = { } ) : """Set the result of this run . Use this method instead of manually setting the run attributes and calling after _ execution ( ) , this method handles all this by itself . @ param values : a dictionary with result values as returned by RunExecutor . e...
exitcode = values . pop ( 'exitcode' , None ) if exitcode is not None : self . values [ '@exitcode' ] = exitcode exitcode = util . ProcessExitCode . from_raw ( exitcode ) if exitcode . signal : self . values [ '@exitsignal' ] = exitcode . signal else : self . values [ '@returnvalue' ] = ...
def focus_prev ( self ) : """focus previous message in depth first order"""
mid = self . get_selected_mid ( ) localroot = self . _sanitize_position ( ( mid , ) ) if localroot == self . get_focus ( ) [ 1 ] : newpos = self . _tree . prev_position ( mid ) if newpos is not None : newpos = self . _sanitize_position ( ( newpos , ) ) else : newpos = localroot if newpos is not None...
def write ( self , * messages ) : """Push a message list to this context ' s input queue . : param mixed value : message"""
for message in messages : if not isinstance ( message , Token ) : message = ensure_tuple ( message , cls = self . _input_type , length = self . _input_length ) if self . _input_length is None : self . _input_length = len ( message ) self . input . put ( message )
def addDrizKeywords ( self , hdr , versions ) : """Add drizzle parameter keywords to header ."""
# Extract some global information for the keywords _geom = 'User parameters' _imgnum = 0 for pl in self . parlist : # Start by building up the keyword prefix based # on the image number for the chip # _ keyprefix = ' D % 03d ' % _ imgnum _imgnum += 1 drizdict = DRIZ_KEYWORDS . copy ( ) # Update drizdict wit...
def flush ( self ) : """flush ( ) - > List of decoded messages . Decodes the packets in the internal buffer . This enables the continuation of the processing of received packets after a : exc : ` ProtocolError ` has been handled . : return : A ( possibly empty ) list of decoded messages from the buffered ...
messages = [ ] while self . _packets : p = self . _packets . popleft ( ) try : msg = decode ( p ) except ProtocolError : # Add any already decoded messages to the exception self . _messages = messages raise messages . append ( msg ) return messages
def _create_L_ind ( self , L ) : """Convert T label matrices with labels in 0 . . . K _ t to a one - hot format Here we can view e . g . the $ ( i , j ) $ entries of the $ T $ label matrices as a _ label vector _ emitted by LF j for data point i . Args : L : a T - length list of [ n , m ] scipy . sparse lab...
# TODO : Update LabelModel to keep L , L _ ind , L _ aug as sparse matrices # throughout and remove this line . if issparse ( L [ 0 ] ) : L = [ L_t . todense ( ) for L_t in L ] # Make sure converted to numpy here L = self . _to_numpy ( L ) L_ind = np . ones ( ( self . n , self . m * self . k ) ) for yi , y in enume...
def _add_raster_layer ( self , raster_layer , layer_name , save_style = False ) : """Add a raster layer to the folder . : param raster _ layer : The layer to add . : type raster _ layer : QgsRasterLayer : param layer _ name : The name of the layer in the datastore . : type layer _ name : str : param save ...
source = gdal . Open ( raster_layer . source ( ) ) array = source . GetRasterBand ( 1 ) . ReadAsArray ( ) x_size = source . RasterXSize y_size = source . RasterYSize output = self . raster_driver . Create ( self . uri . absoluteFilePath ( ) , x_size , y_size , 1 , gdal . GDT_Byte , [ 'APPEND_SUBDATASET=YES' , 'RASTER_T...
def from_ids ( cls , path : PathOrStr , vocab : Vocab , train_ids : Collection [ Collection [ int ] ] , valid_ids : Collection [ Collection [ int ] ] , test_ids : Collection [ Collection [ int ] ] = None , train_lbls : Collection [ Union [ int , float ] ] = None , valid_lbls : Collection [ Union [ int , float ] ] = Non...
src = ItemLists ( path , TextList ( train_ids , vocab , path = path , processor = [ ] ) , TextList ( valid_ids , vocab , path = path , processor = [ ] ) ) src = src . label_for_lm ( ) if cls == TextLMDataBunch else src . label_from_lists ( train_lbls , valid_lbls , classes = classes , processor = [ ] ) if not is1d ( tr...
def fmt_cell ( self , value , width , cell_formating , ** text_formating ) : """Format sigle table cell ."""
strptrn = " {:" + '{:s}{:d}' . format ( cell_formating . get ( 'align' , '<' ) , width ) + "s} " strptrn = self . fmt_text ( strptrn , ** text_formating ) return strptrn . format ( value )
def fixtags ( self , text ) : """Clean up special characters , only run once , next - to - last before doBlockLevels"""
# french spaces , last one Guillemet - left # only if there is something before the space text = _guillemetLeftPat . sub ( ur'\1&nbsp;\2' , text ) # french spaces , Guillemet - right text = _guillemetRightPat . sub ( ur'\1&nbsp;' , text ) return text
def get_cosmosdb_account_keys ( access_token , subscription_id , rgname , account_name ) : '''Get the access keys for the specified Cosmos DB account . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . rgname ( str ) : Azure resource gro...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourcegroups/' , rgname , '/providers/Microsoft.DocumentDB/databaseAccounts/' , account_name , '/listKeys' , '?api-version=' , COSMOSDB_API ] ) return do_post ( endpoint , '' , access_token )
def match_patterns ( codedata ) : """Match patterns by shaman . PatternMatcher Get average ratio of pattern and language"""
ret = { } for index1 , pattern in enumerate ( shaman . PatternMatcher . PATTERNS ) : print ( 'Matching pattern %d "%s"' % ( index1 + 1 , pattern ) ) matcher = shaman . PatternMatcher ( pattern ) tmp = { } for index2 , ( language , code ) in enumerate ( codedata ) : if language not in shaman . SU...
def ptime ( timestr = None , tzone = None , fail = 0 , fmt = "%Y-%m-%d %H:%M:%S" ) : """Translate % Y - % m - % d % H : % M : % S into timestamp . : param timestr : string like 2018-03-15 01:27:56 , or time . time ( ) if not set . : param tzone : time compensation , int ( - time . timezone / 3600 ) by default ,...
tzone = Config . TIMEZONE if tzone is None else tzone fix_tz = - ( tzone * 3600 + time . timezone ) # : str ( timestr ) for datetime . datetime object timestr = str ( timestr or ttime ( ) ) try : return int ( time . mktime ( time . strptime ( timestr , fmt ) ) + fix_tz ) except : return fail
def get_logout_url ( self , redirect_url = None ) : """Generates CAS logout URL"""
url = urllib_parse . urljoin ( self . server_url , 'logout' ) if redirect_url : params = { self . logout_redirect_param_name : redirect_url } url += '?' + urllib_parse . urlencode ( params ) return url
def get_all_keys ( tweet , parent_key = '' ) : """Takes a tweet object and recursively returns a list of all keys contained in this level and all nexstted levels of the tweet . Args : tweet ( Tweet ) : the tweet dict parent _ key ( str ) : key from which this process will start , e . g . , you can get key...
items = [ ] for k , v in tweet . items ( ) : new_key = parent_key + " " + k if isinstance ( v , dict ) : items . extend ( get_all_keys ( v , parent_key = new_key ) ) else : items . append ( new_key . strip ( " " ) ) return items
def send ( self , to , subject , body , reply_to = None , ** kwargs ) : """Send email via AWS SES . : returns string : message id Composes an email message based on input data , and then immediately queues the message for sending . : type to : list of strings or string : param to : The To : field ( s ) of...
if not self . sender : raise AttributeError ( "Sender email 'sender' or 'source' is not provided" ) kwargs [ "to_addresses" ] = to kwargs [ "subject" ] = subject kwargs [ "body" ] = body kwargs [ "source" ] = self . _get_sender ( self . sender ) [ 0 ] kwargs [ "reply_addresses" ] = self . _get_sender ( reply_to or ...
def get_feed ( self , username ) : """Gets a user ' s feed . : param str username : User to fetch feed from ."""
r = self . _query_ ( '/users/%s/feed' % username , 'GET' ) results = [ Story ( item ) for item in r . json ( ) ] return results
def create_derivative ( self , word ) : '''Creates derivative of ( base ) word by adding any affixes that apply'''
result = None if self . char_to_strip != '' : if self . opt == "PFX" : result = word [ len ( self . char_to_strip ) : len ( word ) ] result = self . affix + result else : # SFX result = word [ 0 : len ( word ) - len ( self . char_to_strip ) ] result = result + self . affix else :...
def dispatch_write ( self , buf ) : """There is new stuff to write when possible"""
if self . state != STATE_DEAD and self . enabled : super ( ) . dispatch_write ( buf ) return True return False
def create_repo ( self , name ) : """todo : Docstring for create _ repo : param name : arg description : type name : type description : return : : rtype :"""
name = os . path . abspath ( name ) logger . debug ( "create_repo %s" , name ) self . safe_mkdir ( name ) udir = os . path . join ( name , '_upkg' ) self . safe_mkdir ( udir ) ctx = { 'pkg_name' : os . path . basename ( name ) , } for t in TMPLS : self . mk_tmpl ( os . path . join ( udir , t [ 'name' ] ) , t [ 'tmp...
def check_config_mode ( self , check_string = "config" , pattern = "" ) : """Checks if the device is in configuration mode or not ."""
if not pattern : pattern = re . escape ( self . base_prompt ) return super ( CiscoWlcSSH , self ) . check_config_mode ( check_string , pattern )
def iter_parents ( self , paths = '' , ** kwargs ) : """Iterate _ all _ parents of this commit . : param paths : Optional path or list of paths limiting the Commits to those that contain at least one of the paths : param kwargs : All arguments allowed by git - rev - list : return : Iterator yielding Commi...
# skip ourselves skip = kwargs . get ( "skip" , 1 ) if skip == 0 : # skip ourselves skip = 1 kwargs [ 'skip' ] = skip return self . iter_items ( self . repo , self , paths , ** kwargs )
def outformat_is_text ( ) : """Only safe to call within a click context ."""
ctx = click . get_current_context ( ) state = ctx . ensure_object ( CommandState ) return state . outformat_is_text ( )
def _parse_example_proto ( example_serialized ) : """Parses an Example proto containing a training example of an image . The output of the build _ image _ data . py image preprocessing script is a dataset containing serialized Example protocol buffers . Each Example proto contains the following fields ( value...
# Dense features in Example proto . feature_map = { 'image/encoded' : tf . FixedLenFeature ( [ ] , dtype = tf . string , default_value = '' ) , 'image/class/label' : tf . FixedLenFeature ( [ ] , dtype = tf . int64 , default_value = - 1 ) , 'image/class/text' : tf . FixedLenFeature ( [ ] , dtype = tf . string , default_...
def _maybe_mask_result ( self , result , mask , other , op_name ) : """Parameters result : array - like mask : array - like bool other : scalar or array - like op _ name : str"""
# may need to fill infs # and mask wraparound if is_float_dtype ( result ) : mask |= ( result == np . inf ) | ( result == - np . inf ) # if we have a float operand we are by - definition # a float result # or our op is a divide if ( ( is_float_dtype ( other ) or is_float ( other ) ) or ( op_name in [ 'rtruediv' , '...
def create_agency ( self ) : """Create an agency text file of definitions ."""
agency = self . agency links = self . find_table_links ( ) definition_dict = self . find_definition_urls ( links ) with open ( agency + '.txt' , 'w' ) as f : f . write ( str ( definition_dict ) )
def make_hash ( obj ) : '''Make a hash from an arbitrary nested dictionary , list , tuple or set , used to generate ID ' s for operations based on their name & arguments .'''
if isinstance ( obj , ( set , tuple , list ) ) : hash_string = '' . join ( [ make_hash ( e ) for e in obj ] ) elif isinstance ( obj , dict ) : hash_string = '' . join ( '' . join ( ( key , make_hash ( value ) ) ) for key , value in six . iteritems ( obj ) ) else : hash_string = ( # Constants - the values ca...
def preprocess_belscript ( lines ) : """Convert any multi - line SET statements into single line SET statements"""
set_flag = False for line in lines : if set_flag is False and re . match ( "SET" , line ) : set_flag = True set_line = [ line . rstrip ( ) ] # SET following SET elif set_flag and re . match ( "SET" , line ) : yield f"{' '.join(set_line)}\n" set_line = [ line . rstrip ( ) ] ...
def get_absolute_path ( some_path ) : """This function will return an appropriate absolute path for the path it is given . If the input is absolute , it will return unmodified ; if the input is relative , it will be rendered as relative to the current working directory ."""
if os . path . isabs ( some_path ) : return some_path else : return evaluate_relative_path ( os . getcwd ( ) , some_path )
def push ( self , field ) : '''Add a field to the container , if the field is a Container itself , it should be poped ( ) when done pushing into it : param field : BaseField to push'''
kassert . is_of_types ( field , BaseField ) container = self . _container ( ) field . enclosing = self if isinstance ( field , Container ) : self . _containers . append ( field ) if container : container . push ( field ) else : name = field . get_name ( ) if name in self . _fields_dict : raise K...
def git_clone ( prettyname : str , url : str , directory : str , branch : str = None , commit : str = None , clone_options : List [ str ] = None , run_func : Callable [ [ List [ str ] ] , Any ] = None ) -> bool : """Fetches a Git repository , unless we have it already . Args : prettyname : name to display to us...
run_func = run_func or subprocess . check_call clone_options = clone_options or [ ] # type : List [ str ] if os . path . isdir ( directory ) : log . info ( "Not re-cloning {} Git repository: using existing source " "in {}" . format ( prettyname , directory ) ) return False log . info ( "Fetching {} source from ...
def _node_is_match ( qualified_name , package_names , fqn ) : """Determine if a qualfied name matches an fqn , given the set of package names in the graph . : param List [ str ] qualified _ name : The components of the selector or node name , split on ' . ' . : param Set [ str ] package _ names : The set of...
if len ( qualified_name ) == 1 and fqn [ - 1 ] == qualified_name [ 0 ] : return True if qualified_name [ 0 ] in package_names : if is_selected_node ( fqn , qualified_name ) : return True for package_name in package_names : local_qualified_node_name = [ package_name ] + qualified_name if is_selec...
def get_room_config ( self , mucjid ) : """Query and return the room configuration form for the given MUC . : param mucjid : JID of the room to query : type mucjid : bare : class : ` ~ . JID ` : return : data form template for the room configuration : rtype : : class : ` aioxmpp . forms . Data ` . . seeal...
if mucjid is None or not mucjid . is_bare : raise ValueError ( "mucjid must be bare JID" ) iq = aioxmpp . stanza . IQ ( type_ = aioxmpp . structs . IQType . GET , to = mucjid , payload = muc_xso . OwnerQuery ( ) , ) return ( yield from self . client . send ( iq ) ) . form
def record ( self ) : # type : ( ) - > bytes '''A method to generate the string representing this UDF Entity ID . Parameters : None . Returns : A string representing this UDF Entity ID .'''
if not self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'UDF Entity ID not initialized' ) return struct . pack ( self . FMT , self . flags , self . identifier , self . suffix )
def split_curve ( obj , param , ** kwargs ) : """Splits the curve at the input parametric coordinate . This method splits the curve into two pieces at the given parametric coordinate , generates two different curve objects and returns them . It does not modify the input curve . Keyword Arguments : * ` ` fin...
# Validate input if not isinstance ( obj , abstract . Curve ) : raise GeomdlException ( "Input shape must be an instance of abstract.Curve class" ) if param == obj . knotvector [ 0 ] or param == obj . knotvector [ - 1 ] : raise GeomdlException ( "Cannot split on the corner points" ) # Keyword arguments span_fun...
def hide_node ( self , node ) : """Hides a node from the graph . The incoming and outgoing edges of the node will also be hidden . The node may be unhidden at some later time ."""
try : all_edges = self . all_edges ( node ) self . hidden_nodes [ node ] = ( self . nodes [ node ] , all_edges ) for edge in all_edges : self . hide_edge ( edge ) del self . nodes [ node ] except KeyError : raise GraphError ( 'Invalid node %s' % node )
def iterative_select ( obj , dimensions , selects , depth = None ) : """Takes the output of group _ select selecting subgroups iteratively , avoiding duplicating select operations ."""
ndims = len ( dimensions ) depth = depth if depth is not None else ndims items = [ ] if isinstance ( selects , dict ) : for k , v in selects . items ( ) : items += iterative_select ( obj . select ( ** { dimensions [ ndims - depth ] : k } ) , dimensions , v , depth - 1 ) else : for s in selects : ...
def write ( self , byte ) : """Writes a byte buffer to the underlying output file . Raise exception when file is already closed ."""
if self . is_closed_flag : raise Exception ( "Unable to write - already closed!" ) self . written += len ( byte ) self . file . write ( byte )
def replace_discount_promotion_by_id ( cls , discount_promotion_id , discount_promotion , ** kwargs ) : """Replace DiscountPromotion Replace all attributes of DiscountPromotion This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thr...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _replace_discount_promotion_by_id_with_http_info ( discount_promotion_id , discount_promotion , ** kwargs ) else : ( data ) = cls . _replace_discount_promotion_by_id_with_http_info ( discount_promotion_id , discount_promotion ...
def weld_agg ( array , weld_type , aggregations ) : """Multiple aggregations , optimized . Parameters array : numpy . ndarray or WeldObject Input array . weld _ type : WeldType Type of each element in the input array . aggregations : list of str Which aggregations to compute . Returns WeldObject ...
from functools import reduce obj_id , weld_obj = create_weld_object ( array ) # find which aggregation computations are actually needed to_compute = reduce ( lambda x , y : x | y , ( { agg } | _agg_dependencies [ agg ] for agg in aggregations ) ) # get priorities and sort in the proper order of computation to_compute =...
def make_response ( self , data : Any = None , ** kwargs : Any ) -> Any : r"""Validate response data and wrap it inside response factory . : param data : Response data . Could be ommited . : param \ * \ * kwargs : Keyword arguments to be passed to response factory ."""
if not self . _valid_request : logger . error ( 'Request not validated, cannot make response' ) raise self . make_error ( 'Request not validated before, cannot make ' 'response' ) if data is None and self . response_factory is None : logger . error ( 'Response data omit, but no response factory is used' ) ...
def get_dir_indices ( msg , dirs ) : '''Return path ( s ) indices of directory list from user input Args msg : str String with message to display before pass selection input dir _ list : array - like list of paths to be displayed and selected from Return input _ dir _ indices : array - like list of ...
import os # Get user input for paths to process usage = ( '\nEnter numbers preceeding paths seperated by commas (e.g. ' '`0,2,3`).\nTo select all paths type `all`.\nSingle directories ' 'can also be entered (e.g. `0`)\n\n' ) # Generate paths text to display dirs_str = [ '{:2} {:60}\n' . format ( i , p ) for i , p in e...
def create_ethereum_client ( uri , timeout = 60 , * , loop = None ) : """Create client to ethereum node based on schema . : param uri : Host on ethereum node : type uri : str : param timeout : An optional total time of timeout call : type timeout : int : param loop : An optional * event loop * instance ...
if loop is None : loop = asyncio . get_event_loop ( ) presult = urlparse ( uri ) if presult . scheme in ( 'ipc' , 'unix' ) : reader , writer = yield from asyncio . open_unix_connection ( presult . path , loop = loop ) return AsyncIOIPCClient ( reader , writer , uri , timeout , loop = loop ) elif presult . s...
def _namematcher ( regex ) : """Checks if a target name matches with an input regular expression ."""
matcher = re_compile ( regex ) def match ( target ) : target_name = getattr ( target , '__name__' , '' ) result = matcher . match ( target_name ) return result return match
def init_default ( self ) : """Initializes object with its default values Tries to load self . default _ filename from default data directory . For safety , filename is reset to None so that it doesn ' t point to the original file ."""
import f311 if self . default_filename is None : raise RuntimeError ( "Class '{}' has no default filename" . format ( self . __class__ . __name__ ) ) fullpath = f311 . get_default_data_path ( self . default_filename , class_ = self . __class__ ) self . load ( fullpath ) self . filename = None
def limit ( s , length = 72 ) : """If the length of the string exceeds the given limit , it will be cut off and three dots will be appended . @ param s : the string to limit @ type s : string @ param length : maximum length @ type length : non - negative integer @ return : limited string , at most lengt...
assert length >= 0 , "length limit must be a non-negative integer" if not s or len ( s ) <= length : return s if length == 0 : return "" return "%s..." % s [ : length ]
def unmount ( self , cid ) : """Unmounts and cleans - up after a previous mount ( ) ."""
driver = self . client . info ( ) [ 'Driver' ] driver_unmount_fn = getattr ( self , "_unmount_" + driver , self . _unsupported_backend ) driver_unmount_fn ( cid )
def report ( ) : """Show analysis report of the specified image ( s ) . The analysis report includes information on : Image Id - The image id ( as a hash ) Type - The type of image ( - - imagetype option used when anchore analyze was run ) CurrentTags - The current set of repo tags on the image AllTags - ...
ecode = 0 try : nav = init_nav_contexts ( ) result = nav . generate_reports ( ) # result = generate _ reports ( imagelist , showall = all , showdetails = details ) if result : anchore_utils . print_result ( config , result ) except : anchore_print_err ( "operation failed" ) ecode = 1 con...
def create_aws_clients ( region , profile , * clients ) : """Create boto3 clients for one or more AWS services . These are the services used within the libs : cloudformation , cloudfront , ec2 , iam , lambda , route53 , waf Args : region : the region in which to create clients that are region - specific ( all...
if not profile : profile = None client_key = ( region , profile ) aws_clients = client_cache . get ( client_key , { } ) requested_clients = set ( clients ) new_clients = requested_clients . difference ( aws_clients ) if not new_clients : return aws_clients session = aws_clients . get ( "SESSION" ) try : if ...
def setupRenderModels ( self ) : "Purpose : Create / destroy GL Render Models"
self . m_rTrackedDeviceToRenderModel = [ None ] * openvr . k_unMaxTrackedDeviceCount if self . m_pHMD is None : return for unTrackedDevice in range ( openvr . k_unTrackedDeviceIndex_Hmd + 1 , openvr . k_unMaxTrackedDeviceCount ) : if not self . m_pHMD . isTrackedDeviceConnected ( unTrackedDevice ) : con...
def template_shebang ( template , renderers , default , blacklist , whitelist , input_data ) : '''Check the template shebang line and return the list of renderers specified in the pipe . Example shebang lines : : # ! yaml _ jinja # ! yaml _ mako # ! mako | yaml # ! jinja | yaml # ! jinja | mako | yaml...
line = '' # Open up the first line of the sls template if template == ':string:' : line = input_data . split ( ) [ 0 ] else : with salt . utils . files . fopen ( template , 'r' ) as ifile : line = salt . utils . stringutils . to_unicode ( ifile . readline ( ) ) # Check if it starts with a shebang and no...
def create_node_tables ( self ) : """Create node and link tables if they don ' t exist ."""
self . cursor . execute ( 'PRAGMA foreign_keys=1' ) self . cursor . execute ( ''' CREATE TABLE IF NOT EXISTS datasets ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, key TEXT NOT NULL ) ''' ) self . cursor . execute ( ''' CREATE TABLE IF NOT E...
def udp_recv ( udpsock , peername , peerlen ) : """Receive zframe from UDP socket , and set address of peer that sent it The peername must be a char [ INET _ ADDRSTRLEN ] array if IPv6 is disabled or NI _ MAXHOST if it ' s enabled . Returns NULL when failing to get peer address . * * * This is for CZMQ intern...
return Zframe ( lib . zsys_udp_recv ( udpsock , peername , peerlen ) , False )
def format_plugin ( plugin ) : """Serialise ` plugin ` Attributes : name : Name of Python class id : Unique identifier version : Plug - in version category : Optional category requires : Plug - in requirements order : Plug - in order optional : Is the plug - in optional ? doc : The plug - in docum...
type = "Other" for order , _type in { pyblish . plugin . CollectorOrder : "Collector" , pyblish . plugin . ValidatorOrder : "Validator" , pyblish . plugin . ExtractorOrder : "Extractor" , pyblish . plugin . IntegratorOrder : "Integrator" } . items ( ) : if pyblish . lib . inrange ( plugin . order , base = order ) :...
def update ( self , date , data = None , inow = None ) : """Update security with a given date and optionally , some data . This will update price , value , weight , etc ."""
# filter for internal calls when position has not changed - nothing to # do . Internal calls ( stale root calls ) have None data . Also want to # make sure date has not changed , because then we do indeed want to # update . if date == self . now and self . _last_pos == self . _position : return if inow is None : ...
def params ( self ) : """Return a * copy * ( we hope ) of the parameters . DANGER : Altering properties directly doesn ' t call model . _ cache"""
params = odict ( [ ] ) for key , model in self . models . items ( ) : params . update ( model . params ) return params
def GetMemSharedSavedMB ( self ) : '''Retrieves the estimated amount of physical memory on the host saved from copy - on - write ( COW ) shared guest physical memory .'''
counter = c_uint ( ) ret = vmGuestLib . VMGuestLib_GetMemSharedSavedMB ( self . handle . value , byref ( counter ) ) if ret != VMGUESTLIB_ERROR_SUCCESS : raise VMGuestLibException ( ret ) return counter . value
def cancel_job ( self , job_id = None , job_name = None ) : """Cancel a running job . Args : job _ id ( str , optional ) : Identifier of job to be canceled . job _ name ( str , optional ) : Name of job to be canceled . Returns : dict : JSON response for the job cancel operation ."""
payload = { } if job_name is not None : payload [ 'job_name' ] = job_name if job_id is not None : payload [ 'job_id' ] = job_id jobs_url = self . _get_url ( 'jobs_path' ) res = self . rest_client . session . delete ( jobs_url , params = payload ) _handle_http_errors ( res ) return res . json ( )
def bs ( self ) : """: example ' integrate extensible convergence '"""
result = [ ] for word_list in self . bsWords : result . append ( self . random_element ( word_list ) ) return " " . join ( result )
def get_port_profile_for_intf_input_request_type_get_request_interface_type ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_port_profile_for_intf = ET . Element ( "get_port_profile_for_intf" ) config = get_port_profile_for_intf input = ET . SubElement ( get_port_profile_for_intf , "input" ) request_type = ET . SubElement ( input , "request-type" ) get_request = ET . SubElement ( request_type , "get-req...
def output_text ( account , all_data , show_hourly = False ) : """Format data to get a readable output ."""
print ( """ ################################# # Hydro Quebec data for account # # {} #################################""" . format ( account ) ) for contract , data in all_data . items ( ) : data [ 'contract' ] = contract if data [ 'period_total_bill' ] is None : data [ 'period_total_bill' ] = 0.0 i...
def do_resolve ( self , definitions ) : """Resolve named references to other WSDL objects . Ports without SOAP bindings are discarded . @ param definitions : A definitions object . @ type definitions : L { Definitions }"""
filtered = [ ] for p in self . ports : ref = qualify ( p . binding , self . root , definitions . tns ) binding = definitions . bindings . get ( ref ) if binding is None : raise Exception ( "binding '%s', not-found" % ( p . binding , ) ) if binding . soap is None : log . debug ( "binding ...
def post_periodic_filtered ( values , repeat_after , block ) : """After every * repeat _ after * items , blocks the next * block * items from * values * . Note that unlike : func : ` pre _ periodic _ filtered ` , * repeat _ after * can ' t be 0 . For example , to block every tenth item read from an ADC : : fr...
values = _normalize ( values ) if repeat_after < 1 : raise ValueError ( "repeat_after must be 1 or larger" ) if block < 1 : raise ValueError ( "block must be 1 or larger" ) it = iter ( values ) try : while True : for _ in range ( repeat_after ) : yield next ( it ) for _ in range ...
def setDropdown ( self , label , default = None , options = [ ] , description = 'Set Dropdown' , format = 'text' ) : """Set float in a notebook pipeline ( via interaction or with nbconvert )"""
obj = self . load ( label ) if obj == None : obj = default self . save ( obj , label ) # initialize with default dropdownw = Dropdown ( value = obj , options = options , description = description ) hndl = interact ( self . save , obj = dropdownw , label = fixed ( label ) , format = fixed ( format ) )
def heightmap_add_voronoi ( hm : np . ndarray , nbPoints : Any , nbCoef : int , coef : Sequence [ float ] , rnd : Optional [ tcod . random . Random ] = None , ) -> None : """Add values from a Voronoi diagram to the heightmap . Args : hm ( numpy . ndarray ) : A numpy . ndarray formatted for heightmap functions ....
nbPoints = len ( coef ) ccoef = ffi . new ( "float[]" , coef ) lib . TCOD_heightmap_add_voronoi ( _heightmap_cdata ( hm ) , nbPoints , nbCoef , ccoef , rnd . random_c if rnd else ffi . NULL , )
def stem ( self , s ) : """This should make the Stemmer picklable and unpicklable by not using bound methods"""
if self . _stemmer is None : return passthrough ( s ) try : # try the local attribute ` stemmer ` , a StemmerI instance first # if you use the self . stem method from an unpickled object it may not work return getattr ( getattr ( self , '_stemmer' , None ) , 'stem' , None ) ( s ) except ( AttributeError , TypeE...
def setup_logging ( verbosity , no_color , user_log_file ) : """Configures and sets up all of the logging Returns the requested logging level , as its integer value ."""
# Determine the level to be logging at . if verbosity >= 1 : level = "DEBUG" elif verbosity == - 1 : level = "WARNING" elif verbosity == - 2 : level = "ERROR" elif verbosity <= - 3 : level = "CRITICAL" else : level = "INFO" level_number = getattr ( logging , level ) # The " root " logger should matc...
def plot_magnification ( self , labels = None , which_indices = None , resolution = 60 , marker = '<>^vsd' , legend = True , plot_limits = None , updates = False , mean = True , covariance = True , kern = None , num_samples = 1000 , scatter_kwargs = None , plot_scatter = True , ** imshow_kwargs ) : """Plot the magn...
input_1 , input_2 = which_indices = self . get_most_significant_input_dimensions ( which_indices ) [ : 2 ] X = get_x_y_var ( self ) [ 0 ] _ , _ , Xgrid , _ , _ , xmin , xmax , resolution = helper_for_plot_data ( self , X , plot_limits , which_indices , None , resolution ) canvas , imshow_kwargs = pl ( ) . new_canvas ( ...
def time_range ( self , flag = None ) : '''time range of the current dataset : keyword flag : use a flag array to know the time range of an indexed slice of the object'''
if self . count == 0 : return [ [ None , None ] , [ None , None ] ] if flag is None : return cnes_convert ( [ self . date . min ( ) , self . date . max ( ) ] ) else : return cnes_convert ( [ self . date . compress ( flag ) . min ( ) , self . date . compress ( flag ) . max ( ) ] )
def _find_keep_files ( root , keep ) : '''Compile a list of valid keep files ( and directories ) . Used by _ clean _ dir ( )'''
real_keep = set ( ) real_keep . add ( root ) if isinstance ( keep , list ) : for fn_ in keep : if not os . path . isabs ( fn_ ) : continue fn_ = os . path . normcase ( os . path . abspath ( fn_ ) ) real_keep . add ( fn_ ) while True : fn_ = os . path . abspath...
def call_repeatedly ( func , interval , * args , ** kwargs ) : """Call a function at interval Returns both the thread object and the loop stopper Event ."""
main_thead = threading . current_thread ( ) stopped = threading . Event ( ) def loop ( ) : while not stopped . wait ( interval ) and main_thead . is_alive ( ) : # the first call is in ` interval ` secs func ( * args , ** kwargs ) return timer_thread = threading . Thread ( target = loop , daemon = True )...
def _sample_in_stratum ( self , stratum_idx , replace = True ) : """Sample an item uniformly from a stratum Parameters stratum _ idx : int stratum index to sample from replace : bool , optional , default True whether to sample with replacement Returns int location of the randomly selected item in th...
if replace : stratum_loc = np . random . choice ( self . sizes_ [ stratum_idx ] ) else : # Extract only the unsampled items stratum_locs = np . where ( ~ self . _sampled [ stratum_idx ] ) [ 0 ] stratum_loc = np . random . choice ( stratum_locs ) # Record that item has been sampled self . _sampled [ stratum_...
def _delete_map_from_user_by_id ( self , user , map_id ) : """Delete a mapfile entry from database ."""
map = self . _get_map_from_user_by_id ( user , map_id ) if map is None : return None Session . delete ( map ) Session . commit ( ) return map
def items ( self ) : """D . items ( ) - > a set - like object providing a view on D ' s items"""
keycol = self . _keycol for row in self . __iter__ ( ) : yield ( row [ keycol ] , dict ( row ) )
def getMe ( self ) : '''returns User Object'''
response_str = self . _command ( 'getMe' ) if ( not response_str ) : return False response = json . loads ( response_str ) return response
def recognize_file ( self , file_path ) : """This causes OpenALPR to attempt to recognize an image by opening a file on disk . : param file _ path : The path to the image that will be analyzed : return : An OpenALPR analysis in the form of a response dictionary"""
file_path = _convert_to_charp ( file_path ) ptr = self . _recognize_file_func ( self . alpr_pointer , file_path ) json_data = ctypes . cast ( ptr , ctypes . c_char_p ) . value json_data = _convert_from_charp ( json_data ) response_obj = json . loads ( json_data ) self . _free_json_mem_func ( ctypes . c_void_p ( ptr ) )...
def _rtg_add_summary_file ( eval_files , base_dir , data ) : """Parse output TP FP and FN files to generate metrics for plotting ."""
out_file = os . path . join ( base_dir , "validate-summary.csv" ) if not utils . file_uptodate ( out_file , eval_files . get ( "tp" , eval_files . get ( "fp" , eval_files [ "fn" ] ) ) ) : with file_transaction ( data , out_file ) as tx_out_file : with open ( tx_out_file , "w" ) as out_handle : w...