INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Renames a given instance based on parent_node and name.
def _set_details_tree_node(self, parent_node, name, instance): """Renames a given `instance` based on `parent_node` and `name`. Adds meta information like depth as well. """ depth = parent_node._depth + 1 if parent_node.v_is_root: branch = name # We add below root ...
Returns an iterator over nodes hanging below a given start node.
def _iter_nodes(self, node, recursive=False, max_depth=float('inf'), with_links=True, in_search=False, predicate=None): """Returns an iterator over nodes hanging below a given start node. :param node: Start node :param recursive: Whether recursivel...
Returns a dictionary with pairings of ( full ) names as keys and instances as values.
def _to_dict(self, node, fast_access=True, short_names=False, nested=False, copy=True, with_links=True): """ Returns a dictionary with pairings of (full) names as keys and instances as values. :param fast_access: If true parameter or result values are returned instead of t...
Returns an iterator over a node s children.
def _make_child_iterator(node, with_links, current_depth=0): """Returns an iterator over a node's children. In case of using a trajectory as a run (setting 'v_crun') some sub branches that do not belong to the run are blinded out. """ cdp1 = current_depth + 1 if with_li...
Iterator function traversing the tree below node in breadth first search manner.
def _recursive_traversal_bfs(node, linked_by=None, max_depth=float('inf'), with_links=True, in_search=False, predicate=None): """Iterator function traversing the tree below `node` in breadth first search manner. If `run_name` is given on...
Fast search for a node in the tree.
def _very_fast_search(self, node, key, max_depth, with_links, crun): """Fast search for a node in the tree. The tree is not traversed but the reference dictionaries are searched. :param node: Parent node to start from :param key: Name of node to find ...
Searches for an item in the tree below node
def _search(self, node, key, max_depth=float('inf'), with_links=True, crun=None): """ Searches for an item in the tree below `node` :param node: The parent node below which the search is performed :param key: Name to search for. Can be the short name, the full name or...
Performs a backwards search from the terminal node back to the start node
def _backwards_search(self, start_node, split_name, max_depth=float('inf'), shortcuts=True): """ Performs a backwards search from the terminal node back to the start node :param start_node: The node from where search starts, or here better way where backwards search should end....
Searches for all occurrences of name under node.
def _get_all(self, node, name, max_depth, shortcuts): """ Searches for all occurrences of `name` under `node`. :param node: Start node :param name: Name what to look for can be longer and separated by colons, i.e. `mygroupA.mygroupB.myparam`. :par...
Searches for an item ( parameter/ result/ group node ) with the given name.
def _get(self, node, name, fast_access, shortcuts, max_depth, auto_load, with_links): """Searches for an item (parameter/result/group node) with the given `name`. :param node: The node below which the search is performed :param name: Name of the item (full name or parts of the ful...
Searches for an item ( parameter/ result/ group node ) with the given name.
def _perform_get(self, node, split_name, fast_access, shortcuts, max_depth, auto_load, with_links, try_auto_load_directly): """Searches for an item (parameter/result/group node) with the given `name`. :param node: The node below which the search is performed ...
Alternative naming you can use node. kids. name instead of node. name for easier tab completion.
def kids(self): """Alternative naming, you can use `node.kids.name` instead of `node.name` for easier tab completion.""" if self._kids is None: self._kids = NNTreeNodeKids(self) return self._kids
Can be called from storage service to create a new group to bypass name checking
def _add_group_from_storage(self, args, kwargs): """Can be called from storage service to create a new group to bypass name checking""" return self._nn_interface._add_generic(self, type_name=GROUP, group_type...
Can be called from storage service to create a new leaf to bypass name checking
def _add_leaf_from_storage(self, args, kwargs): """Can be called from storage service to create a new leaf to bypass name checking""" return self._nn_interface._add_generic(self, type_name=LEAF, group_type_na...
Returns a list of all children names
def f_dir_data(self): """Returns a list of all children names""" if (self._nn_interface is not None and self._nn_interface._root_instance is not None and self.v_root.v_auto_load): try: if self.v_is_root: self.f_l...
Creates a dummy object containing the whole tree to make unfolding easier.
def _debug(self): """Creates a dummy object containing the whole tree to make unfolding easier. This method is only useful for debugging purposes. If you use an IDE and want to unfold the trajectory tree, you always need to open the private attribute `_children`. Use to this function to...
Returns the parent of the node.
def f_get_parent(self): """Returns the parent of the node. Raises a TypeError if current node is root. """ if self.v_is_root: raise TypeError('Root does not have a parent') elif self.v_location == '': return self.v_root else: return s...
Adds an empty generic group under the current node.
def f_add_group(self, *args, **kwargs): """Adds an empty generic group under the current node. You can add to a generic group anywhere you want. So you are free to build your parameter tree with any structure. You do not necessarily have to follow the four subtrees `config`, `parameters...
Adds a link to an existing node.
def f_add_link(self, name_or_item, full_name_or_item=None): """Adds a link to an existing node. Can be called as ``node.f_add_link(other_node)`` this will add a link the `other_node` with the link name as the name of the node. Or can be called as ``node.f_add_link(name, other_node)`` t...
Removes a link from from the current group node with a given name.
def f_remove_link(self, name): """ Removes a link from from the current group node with a given name. Does not delete the link from the hard drive. If you want to do this, checkout :func:`~pypet.trajectory.Trajectory.f_delete_links` """ if name not in self._links: r...
Adds an empty generic leaf under the current node.
def f_add_leaf(self, *args, **kwargs): """Adds an empty generic leaf under the current node. You can add to a generic leaves anywhere you want. So you are free to build your trajectory tree with any structure. You do not necessarily have to follow the four subtrees `config`, `parameters...
Recursively removes the group and all it s children.
def f_remove(self, recursive=True, predicate=None): """Recursively removes the group and all it's children. :param recursive: If removal should be applied recursively. If not, node can only be removed if it has no children. :param predicate: In case of rec...
Removes a child of the group.
def f_remove_child(self, name, recursive=False, predicate=None): """Removes a child of the group. Note that groups and leaves are only removed from the current trajectory in RAM. If the trajectory is stored to disk, this data is not affected. Thus, removing children can be only be used ...
Checks if the node contains a specific parameter or result.
def f_contains(self, item, with_links=True, shortcuts=False, max_depth=None): """Checks if the node contains a specific parameter or result. It is checked if the item can be found via the :func:`~pypet.naturalnaming.NNGroupNode.f_get` method. :param item: Parameter/Result name or insta...
Iterates recursively ( default ) over nodes hanging below this group.
def f_iter_nodes(self, recursive=True, with_links=True, max_depth=None, predicate=None): """Iterates recursively (default) over nodes hanging below this group. :param recursive: Whether to iterate the whole sub tree or only immediate children. :param with_links: If links should be considered ...
Iterates ( recursively ) over all leaves hanging below the current group.
def f_iter_leaves(self, with_links=True): """Iterates (recursively) over all leaves hanging below the current group. :param with_links: If links should be ignored, leaves hanging below linked nodes are not listed. :returns: Iterator over all leaf nodes """ ...
Searches for all occurrences of name under node.
def f_get_all(self, name, max_depth=None, shortcuts=True): """ Searches for all occurrences of `name` under `node`. Links are NOT considered since nodes are searched bottom up in the tree. :param node: Start node :param name: Name of what to look for, can be ...
Similar to f_get but returns the default value if name is not found in the trajectory.
def f_get_default(self, name, default=None, fast_access=True, with_links=True, shortcuts=True, max_depth=None, auto_load=False): """ Similar to `f_get`, but returns the default value if `name` is not found in the trajectory. This function uses the `f_get` method and will return th...
Searches and returns an item ( parameter/ result/ group node ) with the given name.
def f_get(self, name, fast_access=False, with_links=True, shortcuts=True, max_depth=None, auto_load=False): """Searches and returns an item (parameter/result/group node) with the given `name`. :param name: Name of the item (full name or parts of the full name) :param fast_access:...
Returns a children dictionary.
def f_get_children(self, copy=True): """Returns a children dictionary. :param copy: Whether the group's original dictionary or a shallow copy is returned. If you want the real dictionary please do not modify it at all! :returns: Dictionary of nodes """ ...
Returns a dictionary of groups hanging immediately below this group.
def f_get_groups(self, copy=True): """Returns a dictionary of groups hanging immediately below this group. :param copy: Whether the group's original dictionary or a shallow copy is returned. If you want the real dictionary please do not modify it at all! :returns: Dict...
Returns a dictionary of all leaves hanging immediately below this group.
def f_get_leaves(self, copy=True): """Returns a dictionary of all leaves hanging immediately below this group. :param copy: Whether the group's original dictionary or a shallow copy is returned. If you want the real dictionary please do not modify it at all! :returns: ...
Returns a link dictionary.
def f_get_links(self, copy=True): """Returns a link dictionary. :param copy: Whether the group's original dictionary or a shallow copy is returned. If you want the real dictionary please do not modify it at all! :returns: Dictionary of nodes """ if cop...
Stores a child or recursively a subtree to disk.
def f_store_child(self, name, recursive=False, store_data=pypetconstants.STORE_DATA, max_depth=None): """Stores a child or recursively a subtree to disk. :param name: Name of child to store. If grouped ('groupA.groupB.childC') the path along the way to las...
Stores a group node to disk
def f_store(self, recursive=True, store_data=pypetconstants.STORE_DATA, max_depth=None): """Stores a group node to disk :param recursive: Whether recursively all children should be stored too. Default is ``True``. :param store_data: For how to choose '...
Loads a child or recursively a subtree from disk.
def f_load_child(self, name, recursive=False, load_data=pypetconstants.LOAD_DATA, max_depth=None): """Loads a child or recursively a subtree from disk. :param name: Name of child to load. If grouped ('groupA.groupB.childC') the path along the way to last no...
Loads a group from disk.
def f_load(self, recursive=True, load_data=pypetconstants.LOAD_DATA, max_depth=None): """Loads a group from disk. :param recursive: Default is ``True``. Whether recursively all nodes below the current node should be loaded, too. Note that links are ne...
Adds an empty parameter group under the current node.
def f_add_parameter_group(self, *args, **kwargs): """Adds an empty parameter group under the current node. Can be called with ``f_add_parameter_group('MyName', 'this is an informative comment')`` or ``f_add_parameter_group(name='MyName', comment='This is an informative comment')`` or wi...
Adds a parameter under the current node.
def f_add_parameter(self, *args, **kwargs): """ Adds a parameter under the current node. There are two ways to add a new parameter either by adding a parameter instance: >>> new_parameter = Parameter('group1.group2.myparam', data=42, comment='Example!') >>> traj.f_add_parameter(new_par...
Adds an empty result group under the current node.
def f_add_result_group(self, *args, **kwargs): """Adds an empty result group under the current node. Adds the full name of the current node as prefix to the name of the group. If current node is a single run (root) adds the prefix `'results.runs.run_08%d%'` to the full name where `'08%d...
Adds a result under the current node.
def f_add_result(self, *args, **kwargs): """Adds a result under the current node. There are two ways to add a new result either by adding a result instance: >>> new_result = Result('group1.group2.myresult', 1666, x=3, y=4, comment='Example!') >>> traj.f_add_result(new_result) ...
Adds an empty derived parameter group under the current node.
def f_add_derived_parameter_group(self, *args, **kwargs): """Adds an empty derived parameter group under the current node. Adds the full name of the current node as prefix to the name of the group. If current node is a single run (root) adds the prefix `'derived_parameters.runs.run_08%d%'` ...
Adds a derived parameter under the current group.
def f_add_derived_parameter(self, *args, **kwargs): """Adds a derived parameter under the current group. Similar to :func:`~pypet.naturalnaming.ParameterGroup.f_add_parameter` Naming prefixes are added as in :func:`~pypet.naturalnaming.DerivedParameterGroup.f_add_derived_parame...
Adds an empty config group under the current node.
def f_add_config_group(self, *args, **kwargs): """Adds an empty config group under the current node. Adds the full name of the current node as prefix to the name of the group. If current node is the trajectory (root), the prefix `'config'` is added to the full name. The `name` can also...
Adds a config parameter under the current group.
def f_add_config(self, *args, **kwargs): """Adds a config parameter under the current group. Similar to :func:`~pypet.naturalnaming.ParameterGroup.f_add_parameter`. If current group is the trajectory the prefix `'config'` is added to the name. """ return self._nn_inter...
The fitness function
def eval_one_max(traj, individual): """The fitness function""" traj.f_add_result('$set.$.individual', list(individual)) fitness = sum(individual) traj.f_add_result('$set.$.fitness', fitness) traj.f_store() return (fitness,)
Takes a unit string like 1. * volt and returns the BRIAN2 unit.
def unit_from_expression(expr): """Takes a unit string like ``'1. * volt'`` and returns the BRIAN2 unit.""" if expr == '1': return get_unit_fast(1) elif isinstance(expr, str): mod = ast.parse(expr, mode='eval') expr = mod.body return unit_from_expression(expr) elif expr._...
Simply checks if data is supported
def f_supports(self, data): """ Simply checks if data is supported """ if isinstance(data, Quantity): return True elif super(Brian2Parameter, self).f_supports(data): return True return False
Simply checks if data is supported
def _supports(self, data): """ Simply checks if data is supported """ if isinstance(data, Quantity): return True elif super(Brian2Result, self)._supports(data): return True return False
To add a monitor use f_set_single ( monitor brian_monitor ).
def f_set_single(self, name, item): """ To add a monitor use `f_set_single('monitor', brian_monitor)`. Otherwise `f_set_single` works similar to :func:`~pypet.parameter.Result.f_set_single`. """ if type(item) in [SpikeMonitor, StateMonitor, PopulationRateMonitor]: if self.v_...
Adds commit information to the trajectory.
def add_commit_variables(traj, commit): """Adds commit information to the trajectory.""" git_time_value = time.strftime('%Y_%m_%d_%Hh%Mm%Ss', time.localtime(commit.committed_date)) git_short_name = str(commit.hexsha[0:7]) git_commit_name = 'commit_%s_' % git_short_name git_commit_name = 'git.' + g...
Makes a commit and returns if a new commit was triggered and the SHA_1 code of the commit.
def make_git_commit(environment, git_repository, user_message, git_fail): """ Makes a commit and returns if a new commit was triggered and the SHA_1 code of the commit. If `git_fail` is `True` program fails instead of triggering a new commit given not committed changes. Then a `GitDiffError` is raised. ...
Flattens a nested dictionary.
def flatten_dictionary(nested_dict, separator): """Flattens a nested dictionary. New keys are concatenations of nested keys with the `separator` in between. """ flat_dict = {} for key, val in nested_dict.items(): if isinstance(val, dict): new_flat_dict = flatten_dictionary(val,...
Nests a given flat dictionary.
def nest_dictionary(flat_dict, separator): """ Nests a given flat dictionary. Nested keys are created by splitting given keys around the `separator`. """ nested_dict = {} for key, val in flat_dict.items(): split_key = key.split(separator) act_dict = nested_dict final_key = ...
Plots a progress bar to the given logger for large for loops.
def progressbar(index, total, percentage_step=10, logger='print', log_level=logging.INFO, reprint=True, time=True, length=20, fmt_string=None, reset=False): """Plots a progress bar to the given `logger` for large for loops. To be used inside a for-loop at the end of the loop: .. code-bloc...
Helper function to support both Python versions
def _get_argspec(func): """Helper function to support both Python versions""" if inspect.isclass(func): func = func.__init__ if not inspect.isfunction(func): # Init function not existing return [], False parameters = inspect.signature(func).parameters args = [] uses_stars...
Takes a function and keyword arguments and returns the ones that can be passed.
def get_matching_kwargs(func, kwargs): """Takes a function and keyword arguments and returns the ones that can be passed.""" args, uses_startstar = _get_argspec(func) if uses_startstar: return kwargs.copy() else: matching_kwargs = dict((k, kwargs[k]) for k in args if k in kwargs) ...
Sorts a list of results in O ( n ) in place ( since every run is unique )
def result_sort(result_list, start_index=0): """Sorts a list of results in O(n) in place (since every run is unique) :param result_list: List of tuples [(run_idx, res), ...] :param start_index: Index with which to start, every entry before `start_index` is ignored """ if len(result_list) < 2: ...
Formats timestamp to human readable format
def format_time(timestamp): """Formats timestamp to human readable format""" format_string = '%Y_%m_%d_%Hh%Mm%Ss' formatted_time = datetime.datetime.fromtimestamp(timestamp).strftime(format_string) return formatted_time
Returns local tcp address for a given port automatic port if None
def port_to_tcp(port=None): """Returns local tcp address for a given `port`, automatic port if `None`""" #address = 'tcp://' + socket.gethostbyname(socket.getfqdn()) domain_name = socket.getfqdn() try: addr_list = socket.getaddrinfo(domain_name, None) except Exception: addr_list = so...
Like os. makedirs but takes care about race conditions
def racedirs(path): """Like os.makedirs but takes care about race conditions""" if os.path.isfile(path): raise IOError('Path `%s` is already a file not a directory') while True: try: if os.path.isdir(path): # only break if full path has been created or exists ...
Resets to the progressbar to start a new one
def _reset(self, index, total, percentage_step, length): """Resets to the progressbar to start a new one""" self._start_time = datetime.datetime.now() self._start_index = index self._current_index = index self._percentage_step = percentage_step self._total = float(total) ...
Calculates remaining time as a string
def _get_remaining(self, index): """Calculates remaining time as a string""" try: current_time = datetime.datetime.now() time_delta = current_time - self._start_time try: total_seconds = time_delta.total_seconds() except AttributeError: ...
Returns annotations as dictionary.
def f_to_dict(self, copy=True): """Returns annotations as dictionary. :param copy: Whether to return a shallow copy or the real thing (aka _dict). """ if copy: return self._dict.copy() else: return self._dict
Returns annotations
def f_get(self, *args): """Returns annotations If len(args)>1, then returns a list of annotations. `f_get(X)` with *X* integer will return the annotation with name `annotation_X`. If the annotation contains only a single entry you can call `f_get()` without arguments. If you c...
Sets annotations
def f_set(self, *args, **kwargs): """Sets annotations Items in args are added as `annotation` and `annotation_X` where 'X' is the position in args for following arguments. """ for idx, arg in enumerate(args): valstr = self._translate_key(idx) self.f_set_...
Removes key from annotations
def f_remove(self, key): """Removes `key` from annotations""" key = self._translate_key(key) try: del self._dict[key] except KeyError: raise AttributeError('Your annotations do not contain %s' % key)
Returns all annotations lexicographically sorted as a concatenated string.
def f_ann_to_str(self): """Returns all annotations lexicographically sorted as a concatenated string.""" resstr = '' for key in sorted(self._dict.keys()): resstr += '%s=%s; ' % (key, str(self._dict[key])) return resstr[:-2]
Turns a given shared data item into a an ordinary one.
def make_ordinary_result(result, key, trajectory=None, reload=True): """Turns a given shared data item into a an ordinary one. :param result: Result container with shared data :param key: The name of the shared data :param trajectory: The trajectory, only needed if shared data has no a...
Turns an ordinary data item into a shared one.
def make_shared_result(result, key, trajectory, new_class=None): """Turns an ordinary data item into a shared one. Removes the old result from the trajectory and replaces it. Empties the given result. :param result: The result containing ordinary data :param key: Name of ordinary data item :pa...
Creates shared data on disk with a StorageService on disk.
def create_shared_data(self, **kwargs): """Creates shared data on disk with a StorageService on disk. Needs to be called before shared data can be used later on. Actual arguments of ``kwargs`` depend on the type of data to be created. For instance, creating an array one can use the key...
Interface with the underlying storage.
def _request_data(self, request, args=None, kwargs=None): """Interface with the underlying storage. Passes request to the StorageService that performs the appropriate action. For example, given a shared table ``t``. ``t.remove_row(4)`` is parsed into ``request='remove_row', args=(4,)`` ...
Returns the actula node of the underlying data.
def get_data_node(self): """Returns the actula node of the underlying data. In case one uses HDF5 this will be the HDF5 leaf node. """ if not self._storage_service.is_open: warnings.warn('You requesting the data item but your store is not open, ' '...
Checks if outer data structure is supported.
def _supports(self, item): """Checks if outer data structure is supported.""" result = super(SharedResult, self)._supports(item) result = result or type(item) in SharedResult.SUPPORTED_DATA return result
Calls the corresponding function of the shared data item
def create_shared_data(self, name=None, **kwargs): """Calls the corresponding function of the shared data item""" if name is None: item = self.f_get() else: item = self.f_get(name) return item.create_shared_data(**kwargs)
Target function that manipulates the trajectory.
def manipulate_multiproc_safe(traj): """ Target function that manipulates the trajectory. Stores the current name of the process into the trajectory and **overwrites** previous settings. :param traj: Trajectory container with multiprocessing safe storage service """ # Manipulate the...
Example of a sophisticated simulation that involves multiplying two values.
def multiply(traj, result_list): """Example of a sophisticated simulation that involves multiplying two values. This time we will store tha value in a shared list and only in the end add the result. :param traj: Trajectory containing the parameters in a particular combination, it ...
Hanldes locking of locks
def _lock(self, name, client_id, request_id): """Hanldes locking of locks If a lock is already locked sends a WAIT command, else LOCKs it and sends GO. Complains if a given client re-locks a lock without releasing it before. """ if name in self._locks: othe...
Handles unlocking
def _unlock(self, name, client_id, request_id): """Handles unlocking Complains if a non-existent lock should be released or if a lock should be released that was acquired by another client before. """ if name in self._locks: other_client_id, other_request_id...
Runs server
def run(self): """Runs server""" try: self._start() running = True while running: msg = '' name = '' client_id = '' request_id = '' request = self._socket.recv_string() s...
Handles locking
def _lock(self, name, client_id, request_id): """Handles locking Locking time is stored to determine time out. If a lock is timed out it can be acquired by a different client. """ if name in self._locks: other_client_id, other_request_id, lock_time = self._locks[nam...
Handles unlocking
def _unlock(self, name, client_id, request_id): """Handles unlocking""" if name in self._locks: other_client_id, other_request_id, lock_time = self._locks[name] if other_client_id != client_id: response = (self.RELEASE_ERROR + self.DELIMITER + ...
Notifies the Server to shutdown
def send_done(self): """Notifies the Server to shutdown""" self.start(test_connection=False) self._logger.debug('Sending shutdown signal') self._req_rep(ZMQServer.DONE)
Closes socket and terminates context
def finalize(self): """Closes socket and terminates context NO-OP if already closed. """ if self._context is not None: if self._socket is not None: self._close_socket(confused=False) self._context.term() self._context = None ...
Starts connection to server if not existent.
def start(self, test_connection=True): """Starts connection to server if not existent. NO-OP if connection is already established. Makes ping-pong test as well if desired. """ if self._context is None: self._logger.debug('Starting Client') self._context ...
Returns response and number of retries
def _req_rep_retry(self, request): """Returns response and number of retries""" retries_left = self.RETRIES while retries_left: self._logger.log(1, 'Sending REQ `%s`', request) self._send_request(request) socks = dict(self._poll.poll(self.TIMEOUT)) ...
Acquires lock and returns True
def acquire(self): """Acquires lock and returns `True` Blocks until lock is available. """ self.start(test_connection=False) while True: str_response, retries = self._req_rep_retry(LockerServer.LOCK) response = str_response.split(LockerServer.DELIMITER) ...
Releases lock
def release(self): """Releases lock""" # self.start(test_connection=False) str_response, retries = self._req_rep_retry(LockerServer.UNLOCK) response = str_response.split(LockerServer.DELIMITER) if response[0] == LockerServer.RELEASED: pass # Everything is fine ...
Handles listening requests from the client.
def listen(self): """ Handles listening requests from the client. There are 4 types of requests: 1- Check space in the queue 2- Tests the socket 3- If there is a space, it sends data 4- after data is sent, puts it to queue for storing """ count = 0 ...
If there is space it sends data to server
def put(self, data, block=True): """ If there is space it sends data to server If no space in the queue It returns the request in every 10 millisecond until there will be space in the queue. """ self.start(test_connection=False) while True: respon...
Detects if lock client was forked.
def _detect_fork(self): """Detects if lock client was forked. Forking is detected by comparing the PID of the current process with the stored PID. """ if self._pid is None: self._pid = os.getpid() if self._context is not None: current_pid = os.ge...
Checks for forking and starts/ restarts if desired
def start(self, test_connection=True): """Checks for forking and starts/restarts if desired""" self._detect_fork() super(ForkAwareLockerClient, self).start(test_connection)
Puts data on queue
def _put_on_queue(self, to_put): """Puts data on queue""" old = self.pickle_queue self.pickle_queue = False try: self.queue.put(to_put, block=True) finally: self.pickle_queue = old
Puts data on queue
def _put_on_pipe(self, to_put): """Puts data on queue""" self.acquire_lock() self._send_chunks(to_put) self.release_lock()
Handles data and returns True or False if everything is done.
def _handle_data(self, msg, args, kwargs): """Handles data and returns `True` or `False` if everything is done.""" stop = False try: if msg == 'DONE': stop = True elif msg == 'STORE': if 'msg' in kwargs: store_msg = kwar...
Starts listening to the queue.
def run(self): """Starts listening to the queue.""" try: while True: msg, args, kwargs = self._receive_data() stop = self._handle_data(msg, args, kwargs) if stop: break finally: if self._storage_service.i...
Gets data from queue
def _receive_data(self): """Gets data from queue""" result = self.queue.get(block=True) if hasattr(self.queue, 'task_done'): self.queue.task_done() return result
Gets data from pipe
def _receive_data(self): """Gets data from pipe""" while True: while len(self._buffer) < self.max_size and self.conn.poll(): data = self._read_chunks() if data is not None: self._buffer.append(data) if len(self._buffer) > 0: ...
Acquires a lock before storage and releases it afterwards.
def store(self, *args, **kwargs): """Acquires a lock before storage and releases it afterwards.""" try: self.acquire_lock() return self._storage_service.store(*args, **kwargs) finally: if self.lock is not None: try: self.rel...
Simply keeps a reference to the stored data
def store(self, msg, stuff_to_store, *args, **kwargs): """Simply keeps a reference to the stored data """ trajectory_name = kwargs['trajectory_name'] if trajectory_name not in self.references: self.references[trajectory_name] = [] self.references[trajectory_name].append((msg,...