INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Make a handler for authorized and disconnect callbacks.
def make_handler(f, remote, with_response=True): """Make a handler for authorized and disconnect callbacks. :param f: Callable or an import path to a callable """ if isinstance(f, six.string_types): f = import_string(f) @wraps(f) def inner(*args, **kwargs): if with_response: ...
The decorator for ensuring thread - safe when current cache instance is concurrent status.
def _enable_lock(func): """ The decorator for ensuring thread-safe when current cache instance is concurrent status. """ @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.is_concurrent: only_read = kwargs.get('only_read') if only_rea...
Execute cleanup operation when the decorated function completed.
def _enable_cleanup(func): """ Execute cleanup operation when the decorated function completed. """ @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] result = func(*args, **kwargs) self.cleanup(self) return result return wrapper
Use thread pool for executing a task if self. enable_thread_pool is True.
def _enable_thread_pool(func): """ Use thread pool for executing a task if self.enable_thread_pool is True. Return an instance of future when flag is_async is True otherwise will to block waiting for the result until timeout then returns the result. """ @functools.wraps(func) def wrapper(*...
>>> cache = Cache ( log_level = logging. WARNING ) >>> cache. put ( a 0 ) >>> cache. put ( b 1 ) >>> cache. size () 2 >>> cache. clear () >>> cache. size () 0
def clear(self, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> cache.put('a', 0) >>> cache.put('b', 1) >>> cache.size() 2 >>> cache.clear() >>> cache.size() 0 """ self.cache_items.clear() self.total_a...
>>> cache = Cache ( log_level = logging. WARNING ) >>> def evict ( dict evict_number = 10 ): pass >>> cache. replace_evict_func ( evict ) True >>> def evict_b ( dict ): pass >>> cache. replace_evict_func ( evict_b ) False >>> def evict_c ( dict a b ): pass >>> cache. replace_evict_func ( evict_c ) False
def replace_evict_func(self, func, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> def evict(dict, evict_number=10): pass >>> cache.replace_evict_func(evict) True >>> def evict_b(dict): pass >>> cache.replace_evict_func(evict_b) Fals...
>>> cache = Cache ( log_level = logging. WARNING ) >>> def cleanup ( self ): pass >>> cache. replace_cleanup_func ( cleanup ) True >>> def cleanup_b ( self other ): pass >>> cache. replace_cleanup_func ( cleanup_b ) False
def replace_cleanup_func(self, func, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> def cleanup(self): pass >>> cache.replace_cleanup_func(cleanup) True >>> def cleanup_b(self, other): pass >>> cache.replace_cleanup_func(cleanup_b) ...
>>> cache = Cache ( log_level = logging. WARNING ) >>> def cache_loader ( key ): pass >>> cache. with_cache_loader ( cache_loader ) True >>> def cache_loader_b ( key value ): pass >>> cache. with_cache_loader ( cache_loader_b ) False
def with_cache_loader(self, func, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> def cache_loader(key): pass >>> cache.with_cache_loader(cache_loader) True >>> def cache_loader_b(key, value): pass >>> cache.with_cache_loader(cache_loader_b)...
>>> cache = Cache ( log_level = logging. WARNING ) >>> def cache_writer ( key ): pass >>> cache. with_cache_writer ( cache_writer ) False >>> def cache_writer ( key value ): pass >>> cache. with_cache_writer ( cache_writer ) True
def with_cache_writer(self, func, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> def cache_writer(key): pass >>> cache.with_cache_writer(cache_writer) False >>> def cache_writer(key, value): pass >>> cache.with_cache_writer(cache_writer) ...
>>> cache = Cache ( log_level = logging. WARNING ) >>> cache. stop_regularly_cleanup () True >>> cache. stop_regularly_cleanup () False
def stop_regularly_cleanup(self, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> cache.stop_regularly_cleanup() True >>> cache.stop_regularly_cleanup() False """ if hasattr(self, 'cleanup_supervisor') and self.cleanup_supervisor is n...
>>> cache = Cache ( regularly_cleanup = False log_level = logging. ERROR ) >>> cache. start_regularly_cleanup () True >>> cache. start_regularly_cleanup () False
def start_regularly_cleanup(self, regularly_cleanup_interval=None, only_read=False): """ >>> cache = Cache(regularly_cleanup=False, log_level=logging.ERROR) >>> cache.start_regularly_cleanup() True >>> cache.start_regularly_cleanup() False """ if not hasat...
>>> cache = Cache ( enable_thread_pool = False log_level = logging. ERROR ) >>> cache. with_thread_pool () True >>> cache. with_thread_pool () False
def with_thread_pool(self, init_func=None, only_read=False): """ >>> cache = Cache(enable_thread_pool=False, log_level=logging.ERROR) >>> cache.with_thread_pool() True >>> cache.with_thread_pool() False """ if not hasattr(self, 'thread_pool') or self.threa...
>>> cache = Cache ( log_level = logging. WARNING ) >>> cache. unable_thread_pool () True >>> cache. unable_thread_pool () False
def unable_thread_pool(self, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> cache.unable_thread_pool() True >>> cache.unable_thread_pool() False """ if self.enable_thread_pool and hasattr(self, 'thread_pool') and self.thread_pool is...
>>> cache = Cache ( log_level = logging. WARNING ) >>> cache. shutdown_thread_pool () True >>> cache. unable_thread_pool () True >>> cache. shutdown_thread_pool () False
def shutdown_thread_pool(self, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> cache.shutdown_thread_pool() True >>> cache.unable_thread_pool() True >>> cache.shutdown_thread_pool() False """ if self.enable_thread_poo...
>>> cache = Cache ( log_level = logging. WARNING ) >>> cache. set_capacity ( 100 ) >>> cache. capacity 100 >>> cache. set_capacity ( haha ) >>> cache. capacity 100
def set_capacity(self, new_capacity, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> cache.set_capacity(100) >>> cache.capacity 100 >>> cache.set_capacity('haha') >>> cache.capacity 100 """ if not isinstance(new_capac...
>>> cache = Cache ( log_level = logging. WARNING ) >>> cache. set_expire ( 40 ) >>> cache. expire 40 >>> cache. set_expire ( haha ) >>> cache. expire 40
def set_expire(self, new_expire, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> cache.set_expire(40) >>> cache.expire 40 >>> cache.set_expire('haha') >>> cache.expire 40 """ if not isinstance(new_expire, int) or new_...
>>> cache = Cache ( log_level = logging. WARNING ) >>> cache. set_evict_number ( 10 ) >>> cache. evict_number 10 >>> cache. set_evict_number ( haha ) >>> cache. evict_number 10
def set_evict_number(self, new_evict_number, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> cache.set_evict_number(10) >>> cache.evict_number 10 >>> cache.set_evict_number('haha') >>> cache.evict_number 10 """ if not...
>>> cache = Cache ( log_level = logging. WARNING ) >>> cache. read_after_refresh_expire True >>> cache. with_read_after_refresh_expire ( False ) >>> cache. read_after_refresh_expire False >>> cache. with_read_after_refresh_expire ( haha ) >>> cache. read_after_refresh_expire False
def with_read_after_refresh_expire(self, flag, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> cache.read_after_refresh_expire True >>> cache.with_read_after_refresh_expire(False) >>> cache.read_after_refresh_expire False >>> cache.w...
Returns a list that each element is a dictionary of the statistic info of the cache item.
def statistic_record(self, desc=True, timeout=3, is_async=False, only_read=True, *keys): """ Returns a list that each element is a dictionary of the statistic info of the cache item. """ if len(keys) == 0: records = self._generate_statistic_records() else: ...
The decorator for simplifying of use cache it supports auto - update cache ( if parameter auto_update is True ) load cache from other level cache system or data source and writes back the update result to the other level cache system or data source if cache miss.
def access_cache(self, key=None, key_location_on_param=0, expire=None, auto_update=True, cache_loader=None, cache_writer=None, timeout=1): """ The decorator for simplifying of use cache, it supports auto-update cache(if parameter auto_update is True), load cache from other l...
Test:
def get(self, key, timeout=1, is_async=False, only_read=True): """ Test: >>> import time >>> cache = Cache(expire=2) >>> cache.put(key='a', value=0) >>> cache.put(key='b', value=1) >>> cache.put(key='c',value= 2) >>> cache.get('a') 0 >>> c...
Test:
def put(self, key, value, expire=None, timeout=1, is_async=True, only_read=False): """ Test: >>> cache = Cache(expire=2) >>> cache.put('a', 0) >>> cache.get('a') 0 >>> cache.put('a', 1) >>> cache.get('a') 1 """ if key in self.cache...
Test:
def pop(self, key, timeout=1, is_async=False, only_read=False): """ Test: >>> cache = Cache(log_level=logging.WARNING) >>> cache.put('a', 0) >>> cache.pop('a') 0 >>> cache.pop('b') == None True """ if key not in self.cache_items: ...
Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only.
def signature_unsafe(m, sk, pk, hash_func=H): """ Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. """ h = hash_func(sk) a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2)) r = Hint(bytearray([h[j] for j in...
Not safe to use when any argument is secret. See module docstring. This function should be used only for verifying public signatures of public messages.
def checkvalid(s, m, pk): """ Not safe to use when any argument is secret. See module docstring. This function should be used only for verifying public signatures of public messages. """ if len(s) != b // 4: raise ValueError("signature length is wrong") if len(pk) != b // 8: ...
Upgrade database.
def upgrade(): """Upgrade database.""" op.create_table( 'oauthclient_remoteaccount', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column( 'e...
Upgrade database.
def upgrade(): """Upgrade database.""" current_date = datetime.utcnow() # Add 'created' and 'updated' columns to RemoteAccount _add_created_updated_columns('oauthclient_remoteaccount', current_date) # Add 'created' and 'updated' columns to RemoteToken _add_created_updated_columns('oauthclient_...
Downgrade database.
def downgrade(): """Downgrade database.""" # Remove 'created' and 'updated' columns op.drop_column('oauthclient_remoteaccount', 'created') op.drop_column('oauthclient_remoteaccount', 'updated') op.drop_column('oauthclient_remotetoken', 'created') op.drop_column('oauthclient_remotetoken', 'updat...
Compatibility with NLTK. Returns the cmudict lexicon as a dictionary whose keys are lowercase words and whose values are lists of pronunciations.
def dict(): """ Compatibility with NLTK. Returns the cmudict lexicon as a dictionary, whose keys are lowercase words and whose values are lists of pronunciations. """ default = defaultdict(list) for key, value in entries(): default[key].append(value) return default
Return a list of symbols.
def symbols(): """Return a list of symbols.""" symbols = [] for line in symbols_stream(): symbols.append(line.decode('utf-8').strip()) return symbols
( internal ) Determines the type of a given object. Discriminates between Piper Worker FunctionType and Iterable instances. It returns a tuple of boolean variables i. e: ( is_piper is_worker is_function is_iterable_of_pipers is_iterable_of_workers is_iterable_of_functions ).
def _inspect(instance): """ (internal) Determines the type of a given ``object``. Discriminates between ``Piper``, ``Worker``, ``FunctionType`` and ``Iterable`` instances. It returns a ``tuple`` of boolean variables i.e: (is_piper, is_worker, is_function, is_iterable_of_pipers, is_iterable_of...
( internal ) Composes a sequence of functions in the global variable TASK. The resulting composition is given the input inbox and arguments args kwargs.
def _comp_task(inbox, args, kwargs): """ (internal) Composes a sequence of functions in the global variable TASK. The resulting composition is given the input "inbox" and arguments "args", "kwargs". """ # Note. this function uses a global variable which must be defined on the # remote...
Custom compare function. Returns 1 if the first Piper instance is upstream of the second Piper instance - 1 if the first Piper is downstream of the second Piper and 0 if the two Pipers are independent. Arguments: - piper1 ( Piper ) Piper instance. - piper2 ( Piper ) Piper instance.
def children_after_parents(self, piper1, piper2): """ Custom compare function. Returns ``1`` if the first ``Piper`` instance is upstream of the second ``Piper`` instance, ``-1`` if the first ``Piper`` is downstream of the second ``Piper`` and ``0`` if the two ``Pipers`` are in...
Given a Piper instance or the id of the Piper. Returns the Piper instance if it can be resolved else raises a DaggerError or returns False depending on the forgive argument. Arguments: - piper ( Piper or id ( Piper )) a Piper instance or its id to be found in the Dagger. - forgive ( bool ) [ default: False ] If forgive...
def resolve(self, piper, forgive=False): """ Given a ``Piper`` instance or the ``id`` of the ``Piper``. Returns the ``Piper`` instance if it can be resolved else raises a ``DaggerError`` or returns ``False`` depending on the "forgive" argument. Arguments: ...
Connects Pipers in the order input - > output. See Piper. connect. According to the pipes ( topology ). If datas is given will connect the input Pipers to the input data see: Dagger. connect_inputs. Argumensts: - datas ( sequence ) [ default: None ] valid sequence of input data. see: Dagger. connect_inputs.
def connect(self, datas=None): """ Connects ``Pipers`` in the order input -> output. See ``Piper.connect``. According to the pipes (topology). If "datas" is given will connect the input ``Pipers`` to the input data see: ``Dagger.connect_inputs``. Argumensts: ...
Connects input Pipers to datas input data in the correct order determined by the Piper. ornament attribute and the Dagger. _cmp function.
def connect_inputs(self, datas): """ Connects input ``Pipers`` to "datas" input data in the correct order determined, by the ``Piper.ornament`` attribute and the ``Dagger._cmp`` function. It is assumed that the input data is in the form of an iterator and that all inp...
Given the pipeline topology disconnects Pipers in the order output - > input. This also disconnects inputs. See Dagger. connect Piper. connect and Piper. disconnect. If forced is True NuMap instances will be emptied. Arguments: - forced ( bool ) [ default: False ] If set True all tasks from all NuMaps instances used in...
def disconnect(self, forced=False): """ Given the pipeline topology disconnects ``Pipers`` in the order output -> input. This also disconnects inputs. See ``Dagger.connect``, ``Piper.connect`` and ``Piper.disconnect``. If "forced" is ``True`` ``NuMap`` instances will be emptied....
Given the pipeline topology starts Pipers in the order input - > output. See Piper. start. Pipers instances are started in two stages which allows them to share NuMaps.
def start(self): """ Given the pipeline topology starts ``Pipers`` in the order input -> output. See ``Piper.start``. ``Pipers`` instances are started in two stages, which allows them to share ``NuMaps``. """ # top - > bottom of pipeline pipers = self.p...
Stops the Pipers according to pipeline topology.
def stop(self): """ Stops the ``Pipers`` according to pipeline topology. """ self.log.debug('%s begins stopping routine' % repr(self)) self.log.debug('%s triggers stopping in input pipers' % repr(self)) inputs = self.get_inputs() for piper in inputs: ...
Returns Piper instances which are inputs to the pipeline i. e. have no incoming pipes ( outgoing dependency edges ).
def get_inputs(self): """ Returns ``Piper`` instances, which are inputs to the pipeline i.e. have no incoming pipes (outgoing dependency edges). """ start_p = [p for p in self.postorder() if not self.outgoing_edges(p)] self.log.debug('%s got input pipers %s' % ...
Returns Piper instances which are outputs to the pipeline i. e. have no outgoing pipes ( incoming dependency edges ).
def get_outputs(self): """ Returns ``Piper`` instances, which are outputs to the pipeline i.e. have no outgoing pipes (incoming dependency edges). """ end_p = [p for p in self.postorder() if not self.incoming_edges(p)] self.log.debug('%s got output pipers %s' % ...
Adds a Piper instance to this Dagger but only if the Piper is not already there. Optionally creates a new Piper if the piper argument is valid for the Piper constructor. Returns a tuple ( new_piper_created piper_instance ) indicating whether a new Piper has been created and the instance of the added Piper. Optionally t...
def add_piper(self, piper, xtra=None, create=True, branch=None): """ Adds a ``Piper`` instance to this ``Dagger``, but only if the ``Piper`` is not already there. Optionally creates a new ``Piper`` if the "piper" argument is valid for the ``Piper`` constructor. Returns a ``tuple`` ...
Removes a Piper from the Dagger instance.
def del_piper(self, piper, forced=False): """ Removes a ``Piper`` from the ``Dagger`` instance. Arguments: - piper(``Piper`` or id(``Piper``)) ``Piper`` instance or ``Piper`` instance id. - forced(bool) [default: ``False``] If "forced" is ``True``, wil...
Adds a pipe ( A... N ) which is an N - tuple tuple of Pipers instances. Adding a pipe means to add all the Pipers and connect them in the specified left to right order. The direction of the edges in the DictGraph is reversed compared to the left to right data - flow in a pipe.
def add_pipe(self, pipe, branch=None): """ Adds a pipe (A, ..., N) which is an N-``tuple`` tuple of ``Pipers`` instances. Adding a pipe means to add all the ``Pipers`` and connect them in the specified left to right order. The direction of the edges in the ``DictGraph`...
Deletes a pipe ( A... N ) which is an N - tuple of Piper instances. Deleting a pipe means to delete all the connections between Pipers and to delete all the Pipers. If forced is False only Pipers which are not used anymore ( i. e. have not downstream Pipers ) are deleted.
def del_pipe(self, pipe, forced=False): """ Deletes a pipe (A, ..., N) which is an N-``tuple`` of ``Piper`` instances. Deleting a pipe means to delete all the connections between ``Pipers`` and to delete all the ``Pipers``. If "forced" is ``False`` only ``Pipers`` which are no...
Adds a sequence of Pipers instances to the Dagger in the specified order. Takes optional arguments for Dagger. add_piper. Arguments: - pipers ( sequence of valid add_piper arguments ) Sequence of Pipers or valid Dagger. add_piper arguments to be added to the Dagger in the left to right order.
def add_pipers(self, pipers, *args, **kwargs): """ Adds a sequence of ``Pipers`` instances to the ``Dagger`` in the specified order. Takes optional arguments for ``Dagger.add_piper``. Arguments: - pipers(sequence of valid ``add_piper`` arguments) Sequence of ...
Deletes a sequence of Pipers instances from the Dagger in the reverse of the specified order. Takes optional arguments for Dagger. del_piper. Arguments: - pipers ( sequence of valid del_piper arguments ) Sequence of Pipers or valid Dagger. del_piper arguments to be removed from the Dagger in the right to left order.
def del_pipers(self, pipers, *args, **kwargs): """ Deletes a sequence of ``Pipers`` instances from the ``Dagger`` in the reverse of the specified order. Takes optional arguments for ``Dagger.del_piper``. Arguments: - pipers (sequence of valid ``del_pi...
Adds a sequence of pipes to the Dagger in the specified order. Takes optional arguments for Dagger. add_pipe. Arguments: - pipes ( sequence of valid add_pipe arguments ) Sequence of pipes or other valid Dagger. add_pipe arguments to be added to the Dagger in the left to right order.
def add_pipes(self, pipes, *args, **kwargs): """ Adds a sequence of pipes to the ``Dagger`` in the specified order. Takes optional arguments for ``Dagger.add_pipe``. Arguments: - pipes(sequence of valid ``add_pipe`` arguments) Sequence of pipes o...
Deletes a sequence of pipes from the Dagger in the specified order. Takes optional arguments for Dagger. del_pipe. Arguments: - pipes ( sequence of valid del_pipe arguments ) Sequence of pipes or other valid Dagger. del_pipe arguments to be removed from the Dagger in the left to right order.
def del_pipes(self, pipes, *args, **kwargs): """ Deletes a sequence of pipes from the ``Dagger`` in the specified order. Takes optional arguments for ``Dagger.del_pipe``. Arguments: - pipes(sequence of valid ``del_pipe`` arguments) Sequence of pipes or ...
( internal ) executes when last output piper raises StopIteration.
def _finish(self, ispausing): """ (internal) executes when last output piper raises ``StopIteration``. """ if ispausing: self.log.debug('%s paused' % repr(self)) else: self._finished.set() self.log.debug('%s finished' % repr(self))
( internal ) calls the next method of weaved tasks until they are finished or The Plumber instance is stopped see: Dagger. chinkup.
def _plunge(tasks, pausing, finish): """ (internal) calls the next method of weaved tasks until they are finished or The ``Plumber`` instance is stopped see: ``Dagger.chinkup``. """ # If no result received either not started or start & stop # could have been called before...
( internal ) generates imports code and runtime calls to save a pipeline.
def _code(self): """ (internal) generates imports, code and runtime calls to save a pipeline. """ icode, tcode = '', '' # imports, task code icall, pcall = '', '' # imap calls, piper calls tdone, idone = [], [] # task done, imap done for piper in self: ...
Saves pipeline as a Python source code file. Arguments: - filename ( path ) Path to save the pipeline source code.
def save(self, filename): """ Saves pipeline as a Python source code file. Arguments: - filename(``path``) Path to save the pipeline source code. """ handle = open(filename, 'wb') handle.write(P_LAY % self._code()) handle.clo...
Instanciates ( loads ) pipeline from a source code file. Arguments: - filename ( path ) location of the pipeline source code.
def load(self, filename): """ Instanciates (loads) pipeline from a source code file. Arguments: - filename(``path``) location of the pipeline source code. """ dir_name = os.path.dirname(filename) mod_name = os.path.basename(filename)...
Starts the pipeline by connecting the input Pipers of the pipeline to the input data connecting the pipeline and starting the NuMap instances. The order of items in the datas argument sequence should correspond to the order of the input Pipers defined by Dagger. _cmp and Piper. ornament.
def start(self, datas): """ Starts the pipeline by connecting the input ``Pipers`` of the pipeline to the input data, connecting the pipeline and starting the ``NuMap`` instances. The order of items in the "datas" argument sequence should correspond to the orde...
Executes a started pipeline by pulling results from it s output Pipers. Processing nodes i. e. Pipers with the track attribute set True will have their returned results stored within the Dagger. stats [ pipers_tracked ] dictionary. A running pipeline can be paused.
def run(self): """ Executes a started pipeline by pulling results from it's output ``Pipers``. Processing nodes i.e. ``Pipers`` with the ``track`` attribute set ``True`` will have their returned results stored within the ``Dagger.stats['pipers_tracked']`` dictionary. A running...
Waits ( blocks ) until a running pipeline finishes. Arguments: - timeout ( int ) [ default: None ] Specifies the timeout RuntimeError will be raised. The default is to wait indefinetely for the pipeline to finish.
def wait(self, timeout=None): """ Waits (blocks) until a running pipeline finishes. Arguments: - timeout(``int``) [default: ``None``] Specifies the timeout, ``RuntimeError`` will be raised. The default is to wait indefinetely for the pipeline ...
Pauses a running pipeline. This will stop retrieving results from the pipeline. Parallel parts of the pipeline will stop after the NuMap buffer is has been filled. A paused pipeline can be run or stopped.
def pause(self): """ Pauses a running pipeline. This will stop retrieving results from the pipeline. Parallel parts of the pipeline will stop after the ``NuMap`` buffer is has been filled. A paused pipeline can be run or stopped. """ # 1. stop the plumbing thr...
Stops a paused pipeline. This will a trigger a StopIteration in the inputs of the pipeline. And retrieve the buffered results. This will stop all Pipers and NuMaps. Python will not terminate cleanly if a pipeline is running or paused.
def stop(self): """ Stops a paused pipeline. This will a trigger a ``StopIteration`` in the inputs of the pipeline. And retrieve the buffered results. This will stop all ``Pipers`` and ``NuMaps``. Python will not terminate cleanly if a pipeline is running or paused. ...
Makes the Piper ready to return results. This involves starting the the provided NuMap instance. If multiple Pipers share a NuMap instance the order in which these Pipers are started is important. The valid order is upstream before downstream. The NuMap instance can only be started once but the process can be done in 2...
def start(self, stages=None): """ Makes the ``Piper`` ready to return results. This involves starting the the provided ``NuMap`` instance. If multiple ``Pipers`` share a ``NuMap`` instance the order in which these ``Pipers`` are started is important. The valid order is upstrea...
Connects the Piper instance to its upstream Pipers that should be given as a sequence. This connects this Piper. inbox with the upstream Piper. outbox respecting any consume spawn and produce arguments. Arguments: - inbox ( sequence ) sequence of Piper instances.
def connect(self, inbox): """ Connects the ``Piper`` instance to its upstream ``Pipers`` that should be given as a sequence. This connects this ``Piper.inbox`` with the upstream ``Piper.outbox`` respecting any "consume", "spawn" and "produce" arguments. Argumen...
Attempts to cleanly stop the Piper instance. A Piper is started if its NuMap instance is started. Non - parallel Pipers do not have to be started or stopped. An NuMap instance can be stopped by triggering its stopping procedure and retrieving results from the NuMaps end tasks. Because neither the Piper nor the NuMap kn...
def stop(self, forced=False, **kwargs): """ Attempts to cleanly stop the ``Piper`` instance. A ``Piper`` is "started" if its ``NuMap`` instance is "started". Non-parallel ``Pipers`` do not have to be started or stopped. An ``NuMap`` instance can be stopped by triggering its st...
Disconnects the Piper instance from its upstream Pipers or input data if the Piper is the input node of a pipeline. Arguments: - forced ( bool ) [ default: False ] If True the Piper will try to forcefully remove all tasks ( including the spawned ones ) from the NuMap instance.
def disconnect(self, forced=False): """ Disconnects the ``Piper`` instance from its upstream ``Pipers`` or input data if the ``Piper`` is the input node of a pipeline. Arguments: - forced(``bool``) [default: ``False``] If ``True`` the ``Piper`` will ...
Returns the next result. If no result is availble within the specified ( during construction ) timeout then a PiperError which wraps a TimeoutError is ** returned **.
def next(self): """ Returns the next result. If no result is availble within the specified (during construction) "timeout" then a ``PiperError`` which wraps a ``TimeoutError`` is **returned**. If the result is a ``WorkerError`` it is also wrapped in a ``PiperError`` ...
( internal ) inject/ replace all functions into a rpyc connection object.
def _inject(self, conn): """ (internal) inject/replace all functions into a rpyc connection object. """ # provide PAPY_DEFAULTS remotely # provide PAPY_RUNTIME remotely if not 'PAPY_INJECTED' in conn.namespace: _inject_func(get_defaults, conn) ...
Returns the next sequence of results given stride and n.
def next(self): """ Returns the next sequence of results, given stride and n. """ try: results = self._stride_buffer.pop() except (IndexError, AttributeError): self._rebuffer() results = self._stride_buffer.pop() if not results...
Returns the next result from the chained iterables given stride.
def next(self): """ Returns the next result from the chained iterables given ``"stride"``. """ if self.s: self.s -= 1 else: self.s = self.stride - 1 self.i = (self.i + 1) % self.l # new iterable return self.iterables[self.i].ne...
( very internal ) refill the repeat buffer
def _rebuffer(self): """ (very internal) refill the repeat buffer """ results = [] exceptions = [] for i in xrange(self.stride): try: results.append(self.iterable.next()) exceptions.append(False) except Exception, ex...
( very internal ) returns the next result given stride and n.
def next(self): """ (very internal) returns the next result, given ``"stride"`` and ``"n"``. """ try: res, excp = self._stride_buffer.next() except (StopIteration, AttributeError): try: self._stride_buffer = izip(*self._repeat_buff...
( internal ) refill the repeat buffer
def _rebuffer(self): """ (internal) refill the repeat buffer """ # collect a stride worth of results(result lists) or exceptions results = [] exceptions = [] for i in xrange(self.stride): try: results.append(self.iterable.next(...
( internal ) returns the next result from the iterator if the piper is started.
def next(self): """ (internal) returns the next result from the iterator if the piper is started. """ if self.piper.imap is imap and \ self.piper.started is False: raise StopIteration else: return self.iterator.next()
( internal ) returns the next result from the itertools. tee object for the wrapped Piper instance or re - raises an Exception.
def next(self): """ (internal) returns the next result from the ``itertools.tee`` object for the wrapped ``Piper`` instance or re-raises an ``Exception``. """ # do not acquire lock if NuMap is not finished. if self.finished: raise StopIteration ...
Get a list of results as CSV.
def list_csv(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin """Get a list of results as CSV. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) S...
Get updates of a running result via long - polling. If no updates are available CDRouter waits up to 10 seconds before sending an empty response.
def updates(self, id, update_id=None): # pylint: disable=invalid-name,redefined-builtin """Get updates of a running result via long-polling. If no updates are available, CDRouter waits up to 10 seconds before sending an empty response. :param id: Result ID as an int. :param update_id: (optiona...
Pause a running result.
def pause(self, id, when=None): # pylint: disable=invalid-name,redefined-builtin """Pause a running result. :param id: Result ID as an int. :param when: Must be string `end-of-test` or `end-of-loop`. """ return self.service.post(self.base+str(id)+'/pause/', params={'when': when}...
Unpause a running result.
def unpause(self, id): # pylint: disable=invalid-name,redefined-builtin """Unpause a running result. :param id: Result ID as an int. """ return self.service.post(self.base+str(id)+'/unpause/')
Export a result.
def export(self, id, exclude_captures=False): # pylint: disable=invalid-name,redefined-builtin """Export a result. :param id: Result ID as an int. :param exclude_captures: If bool `True`, don't export capture files :rtype: tuple `(io.BytesIO, 'filename')` """ return self...
Bulk export a set of results.
def bulk_export(self, ids, exclude_captures=False): """Bulk export a set of results. :param ids: Int list of result IDs. :rtype: tuple `(io.BytesIO, 'filename')` """ return self.service.bulk_export(self.base, ids, params={'exclude_captures': exclude_captures})
Bulk copy a set of results.
def bulk_copy(self, ids): """Bulk copy a set of results. :param ids: Int list of result IDs. :return: :class:`results.Result <results.Result>` list """ schema = ResultSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
Compute stats for all results.
def all_stats(self): """Compute stats for all results. :return: :class:`results.AllStats <results.AllStats>` object :rtype: results.AllStats """ schema = AllStatsSchema() resp = self.service.post(self.base, params={'stats': 'all'}) return self.service.decode(sche...
Compute stats for a set of results.
def set_stats(self, ids): """Compute stats for a set of results. :param id: Result IDs as int list. :return: :class:`results.SetStats <results.SetStats>` object :rtype: results.SetStats """ schema = SetStatsSchema() resp = self.service.post(self.base, params={'st...
Compute diff stats for a set of results.
def diff_stats(self, ids): """Compute diff stats for a set of results. :param id: Result IDs as int list. :return: :class:`results.DiffStats <results.DiffStats>` object :rtype: results.DiffStats """ schema = DiffStatsSchema() resp = self.service.post(self.base, p...
Compute stats for a result.
def single_stats(self, id): # pylint: disable=invalid-name,redefined-builtin """Compute stats for a result. :param id: Result ID as an int. :return: :class:`results.SingleStats <results.SingleStats>` object :rtype: results.SingleStats """ schema = SingleStatsSchema() ...
Compute progress stats for a result.
def progress_stats(self, id): # pylint: disable=invalid-name,redefined-builtin """Compute progress stats for a result. :param id: Result ID as an int. :return: :class:`results.Progress <results.Progress>` object :rtype: results.Progress """ schema = ProgressSchema() ...
Compute summary stats for a result.
def summary_stats(self, id): # pylint: disable=invalid-name,redefined-builtin """Compute summary stats for a result. :param id: Result ID as an int. :return: :class:`results.SummaryStats <results.SummaryStats>` object :rtype: results.SummaryStats """ schema = SummaryStat...
Get a list of logdir files.
def list_logdir(self, id, filter=None, sort=None): # pylint: disable=invalid-name,redefined-builtin """Get a list of logdir files. :param id: Result ID as an int. :param filter: Filter to apply as string. :param sort: Sort field to apply as string. :return: :class:`results.LogDi...
Download a logdir file.
def get_logdir_file(self, id, filename): # pylint: disable=invalid-name,redefined-builtin """Download a logdir file. :param id: Result ID as an int. :param filename: Logdir filename as string. :rtype: tuple `(io.BytesIO, 'filename')` """ resp = self.service.get(self.base...
Download logdir archive in tgz or zip format.
def download_logdir_archive(self, id, format='zip', exclude_captures=False): # pylint: disable=invalid-name,redefined-builtin """Download logdir archive in tgz or zip format. :param id: Result ID as an int. :param format: (optional) Format to download, must be string `zip` or `tgz`. :pa...
CERN logout view.
def logout(): """CERN logout view.""" logout_url = REMOTE_APP['logout_url'] apps = current_app.config.get('OAUTHCLIENT_REMOTE_APPS') if apps: cern_app = apps.get('cern', REMOTE_APP) logout_url = cern_app['logout_url'] return redirect(logout_url, code=302)
Return a remote application based with given client ID.
def find_remote_by_client_id(client_id): """Return a remote application based with given client ID.""" for remote in current_oauthclient.oauth.remote_apps.values(): if remote.name == 'cern' and remote.consumer_key == client_id: return remote
Prepare list of allowed group names.
def fetch_groups(groups): """Prepare list of allowed group names. :param groups: The complete list of groups. :returns: A filtered list of groups. """ hidden_groups = current_app.config.get( 'OAUTHCLIENT_CERN_HIDDEN_GROUPS', OAUTHCLIENT_CERN_HIDDEN_GROUPS) hidden_groups_re = current_app...
Return a dict with extra data retrieved from cern oauth.
def fetch_extra_data(resource): """Return a dict with extra data retrieved from cern oauth.""" person_id = resource.get('PersonID', [None])[0] identity_class = resource.get('IdentityClass', [None])[0] department = resource.get('Department', [None])[0] return dict( person_id=person_id, ...
Fetch account groups and extra data from resource if necessary.
def account_groups_and_extra_data(account, resource, refresh_timedelta=None): """Fetch account groups and extra data from resource if necessary.""" updated = datetime.utcnow() modified_since = updated if refresh_timedelta is not None: modified_since += refresh_t...
Extend identity with roles based on CERN groups.
def extend_identity(identity, groups): """Extend identity with roles based on CERN groups.""" provides = set([UserNeed(current_user.email)] + [ RoleNeed('{0}@cern.ch'.format(name)) for name in groups ]) identity.provides |= provides session[OAUTHCLIENT_CERN_SESSION_KEY] = provides
Prepare new mapping with Value s groupped by Type.
def get_dict_from_response(response): """Prepare new mapping with 'Value's groupped by 'Type'.""" result = {} if getattr(response, '_resp') and response._resp.code > 400: return result for i in response.data: # strip the schema from the key k = i['Type'].replace(REMOTE_APP_RESOU...
Query CERN Resources to get user info and groups.
def get_resource(remote): """Query CERN Resources to get user info and groups.""" cached_resource = session.pop('cern_resource', None) if cached_resource: return cached_resource response = remote.get(REMOTE_APP_RESOURCE_API_URL) dict_response = get_dict_from_response(response) session['...
Retrieve remote account information used to find local user.
def account_info(remote, resp): """Retrieve remote account information used to find local user.""" resource = get_resource(remote) valid_identities = current_app.config.get( 'OAUTHCLIENT_CERN_ALLOWED_IDENTITY_CLASSES', OAUTHCLIENT_CERN_ALLOWED_IDENTITY_CLASSES ) identity_class = res...
Handle unlinking of remote account.
def disconnect_handler(remote, *args, **kwargs): """Handle unlinking of remote account.""" if not current_user.is_authenticated: return current_app.login_manager.unauthorized() account = RemoteAccount.get(user_id=current_user.get_id(), client_id=remote.consumer_key) ...
Perform additional setup after user have been logged in.
def account_setup(remote, token, resp): """Perform additional setup after user have been logged in.""" resource = get_resource(remote) with db.session.begin_nested(): person_id = resource.get('PersonID', [None]) external_id = resource.get('uidNumber', person_id)[0] # Set CERN perso...
Store groups in session whenever identity changes.
def on_identity_changed(sender, identity): """Store groups in session whenever identity changes. :param identity: The user identity where information are stored. """ if isinstance(identity, AnonymousIdentity): return client_id = current_app.config['CERN_APP_CREDENTIALS']['consumer_key'] ...