_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q274000
diff_roessler
test
def diff_roessler(value_array, a, c): """The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler system evaluated at `value_...
python
{ "resource": "" }
q274001
compact_hdf5_file
test
def compact_hdf5_file(filename, name=None, index=None, keep_backup=True): """Can compress an HDF5 to reduce file size. The properties on how to compress the new file are taken from a given trajectory in the file. Simply calls ``ptrepack`` from the command line. (Se also https://pytables.github.io/u...
python
{ "resource": "" }
q274002
_explored_parameters_in_group
test
def _explored_parameters_in_group(traj, group_node): """Checks if one the parameters in `group_node` is explored. :param traj: Trajectory container :param group_node: Group node :return: `True` or `False` """ explored = False for param in traj.f_get_explored_parameters(): if pa...
python
{ "resource": "" }
q274003
CNNeuronGroup._build_model_eqs
test
def _build_model_eqs(traj): """Computes model equations for the excitatory and inhibitory population. Equation objects are created by fusing `model.eqs` and `model.synaptic.eqs` and replacing `PRE` by `i` (for inhibitory) or `e` (for excitatory) depending on the type of population. ...
python
{ "resource": "" }
q274004
CNNeuronGroup.pre_build
test
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the neuron groups. Pre-build is only performed if none of the relevant parameters is explored. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network construct...
python
{ "resource": "" }
q274005
CNNeuronGroup.build
test
def build(self, traj, brian_list, network_dict): """Builds the neuron groups. Build is only performed if neuron group was not pre-build before. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. A...
python
{ "resource": "" }
q274006
CNNeuronGroup._build_model
test
def _build_model(self, traj, brian_list, network_dict): """Builds the neuron groups from `traj`. Adds the neuron groups to `brian_list` and `network_dict`. """ model = traj.parameters.model # Create the equations for both models eqs_dict = self._build_model_eqs(traj) ...
python
{ "resource": "" }
q274007
CNConnections.pre_build
test
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List o...
python
{ "resource": "" }
q274008
CNConnections.build
test
def build(self, traj, brian_list, network_dict): """Builds the connections. Build is only performed if connections have not been pre-build. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds:...
python
{ "resource": "" }
q274009
CNNetworkRunner.add_parameters
test
def add_parameters(self, traj): """Adds all necessary parameters to `traj` container.""" par= traj.f_add_parameter(Brian2Parameter,'simulation.durations.initial_run', 500*ms, comment='Initialisation run for more realistic ' 'measur...
python
{ "resource": "" }
q274010
CNFanoFactorComputer._compute_fano_factor
test
def _compute_fano_factor(spike_res, neuron_id, time_window, start_time, end_time): """Computes Fano Factor for one neuron. :param spike_res: Result containing the spiketimes of all neurons :param neuron_id: Index of neuron for which FF is computed :param time...
python
{ "resource": "" }
q274011
CNFanoFactorComputer._compute_mean_fano_factor
test
def _compute_mean_fano_factor( neuron_ids, spike_res, time_window, start_time, end_time): """Computes average Fano Factor over many neurons. :param neuron_ids: List of neuron indices to average over :param spike_res: Result containing all the spikes :param ti...
python
{ "resource": "" }
q274012
CNFanoFactorComputer.analyse
test
def analyse(self, traj, network, current_subrun, subrun_list, network_dict): """Calculates average Fano Factor of a network. :param traj: Trajectory container Expects: `results.monitors.spikes_e`: Data from SpikeMonitor for excitatory neurons Adds: ...
python
{ "resource": "" }
q274013
CNMonitorAnalysis.add_to_network
test
def add_to_network(self, traj, network, current_subrun, subrun_list, network_dict): """Adds monitors to the network if the measurement run is carried out. :param traj: Trajectory container :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_l...
python
{ "resource": "" }
q274014
CNMonitorAnalysis._add_monitors
test
def _add_monitors(self, traj, network, network_dict): """Adds monitors to the network""" neurons_e = network_dict['neurons_e'] monitor_list = [] # Spiketimes self.spike_monitor = SpikeMonitor(neurons_e) monitor_list.append(self.spike_monitor) # Membrane Poten...
python
{ "resource": "" }
q274015
CNMonitorAnalysis._make_folder
test
def _make_folder(self, traj): """Makes a subfolder for plots. :return: Path name to print folder """ print_folder = os.path.join(traj.analysis.plot_folder, traj.v_name, traj.v_crun) print_folder = os.path.abspath(print_folder) if not ...
python
{ "resource": "" }
q274016
CNMonitorAnalysis._plot_result
test
def _plot_result(self, traj, result_name): """Plots a state variable graph for several neurons into one figure""" result = traj.f_get(result_name) varname = result.record_variables[0] values = result[varname] times = result.t record = result.record for idx, celi...
python
{ "resource": "" }
q274017
CNMonitorAnalysis._print_graphs
test
def _print_graphs(self, traj): """Makes some plots and stores them into subfolders""" print_folder = self._make_folder(traj) # If we use BRIAN's own raster_plot functionality we # need to sue the SpikeMonitor directly plt.figure() plt.scatter(self.spike_monitor.t, self.s...
python
{ "resource": "" }
q274018
CNMonitorAnalysis.analyse
test
def analyse(self, traj, network, current_subrun, subrun_list, network_dict): """Extracts monitor data and plots. Data extraction is done if all subruns have been completed, i.e. `len(subrun_list)==0` First, extracts results from the monitors and stores them into `traj`. Next, ...
python
{ "resource": "" }
q274019
get_batch
test
def get_batch(): """Function that parses the batch id from the command line arguments""" optlist, args = getopt.getopt(sys.argv[1:], '', longopts='batch=') batch = 0 for o, a in optlist: if o == '--batch': batch = int(a) print('Found batch %d' % batch) return batch
python
{ "resource": "" }
q274020
explore_batch
test
def explore_batch(traj, batch): """Chooses exploration according to `batch`""" explore_dict = {} explore_dict['sigma'] = np.arange(10.0 * batch, 10.0*(batch+1), 1.0).tolist() # for batch = 0 explores sigma in [0.0, 1.0, 2.0, ..., 9.0], # for batch = 1 explores sigma in [10.0, 11.0, 12.0, ..., 19.0] ...
python
{ "resource": "" }
q274021
NNTreeNode.vars
test
def vars(self): """Alternative naming, you can use `node.vars.name` instead of `node.v_name`""" if self._vars is None: self._vars = NNTreeNodeVars(self) return self._vars
python
{ "resource": "" }
q274022
NNTreeNode.func
test
def func(self): """Alternative naming, you can use `node.func.name` instead of `node.f_func`""" if self._func is None: self._func = NNTreeNodeFunc(self) return self._func
python
{ "resource": "" }
q274023
NNTreeNode._rename
test
def _rename(self, full_name): """Renames the tree node""" self._full_name = full_name if full_name: self._name = full_name.rsplit('.', 1)[-1]
python
{ "resource": "" }
q274024
NNTreeNode._set_details
test
def _set_details(self, depth, branch, run_branch): """Sets some details for internal handling.""" self._depth = depth self._branch = branch self._run_branch = run_branch
python
{ "resource": "" }
q274025
NaturalNamingInterface._node_to_msg
test
def _node_to_msg(store_load, node): """Maps a given node and a store_load constant to the message that is understood by the storage service. """ if node.v_is_leaf: if store_load == STORE: return pypetconstants.LEAF elif store_load == LOAD: ...
python
{ "resource": "" }
q274026
NaturalNamingInterface._remove_subtree
test
def _remove_subtree(self, start_node, name, predicate=None): """Removes a subtree from the trajectory tree. Does not delete stuff from disk only from RAM. :param start_node: The parent node from where to start :param name: Name of child which will be deleted and recursively all nodes b...
python
{ "resource": "" }
q274027
NaturalNamingInterface._delete_node
test
def _delete_node(self, node): """Deletes a single node from the tree. Removes all references to the node. Note that the 'parameters', 'results', 'derived_parameters', and 'config' groups hanging directly below root cannot be deleted. Also the root node itself cannot be deleted....
python
{ "resource": "" }
q274028
NaturalNamingInterface._remove_node_or_leaf
test
def _remove_node_or_leaf(self, instance, recursive=False): """Removes a single node from the tree. Only from RAM not from hdf5 file! :param instance: The node to be deleted :param recursive: If group nodes with children should be deleted """ full_name = instance.v_ful...
python
{ "resource": "" }
q274029
NaturalNamingInterface._remove_along_branch
test
def _remove_along_branch(self, actual_node, split_name, recursive=False): """Removes a given node from the tree. Starts from a given node and walks recursively down the tree to the location of the node we want to remove. We need to walk from a start node in case we want to check on the...
python
{ "resource": "" }
q274030
NaturalNamingInterface._translate_shortcut
test
def _translate_shortcut(self, name): """Maps a given shortcut to corresponding name * 'run_X' or 'r_X' to 'run_XXXXXXXXX' * 'crun' to the current run name in case of a single run instance if trajectory is used via `v_crun` * 'par' 'parameters' * 'dpar' to 'derived_p...
python
{ "resource": "" }
q274031
NaturalNamingInterface._add_prefix
test
def _add_prefix(self, split_names, start_node, group_type_name): """Adds the correct sub branch prefix to a given name. Usually the prefix is the full name of the parent node. In case items are added directly to the trajectory the prefixes are chosen according to the matching subbranch. ...
python
{ "resource": "" }
q274032
NaturalNamingInterface._determine_types
test
def _determine_types(start_node, first_name, add_leaf, add_link): """Determines types for generic additions""" if start_node.v_is_root: where = first_name else: where = start_node._branch if where in SUBTREE_MAPPING: type_tuple = SUBTREE_MAPPING[where...
python
{ "resource": "" }
q274033
NaturalNamingInterface._add_generic
test
def _add_generic(self, start_node, type_name, group_type_name, args, kwargs, add_prefix=True, check_naming=True): """Adds a given item to the tree irrespective of the subtree. Infers the subtree from the arguments. :param start_node: The parental node the adding was initia...
python
{ "resource": "" }
q274034
NaturalNamingInterface._add_to_tree
test
def _add_to_tree(self, start_node, split_names, type_name, group_type_name, instance, constructor, args, kwargs): """Adds a new item to the tree. The item can be an already given instance or it is created new. :param start_node: Parental node the adding of the...
python
{ "resource": "" }
q274035
NaturalNamingInterface._create_link
test
def _create_link(self, act_node, name, instance): """Creates a link and checks if names are appropriate """ act_node._links[name] = instance act_node._children[name] = instance full_name = instance.v_full_name if full_name not in self._root_instance._linked_by: ...
python
{ "resource": "" }
q274036
NaturalNamingInterface._check_names
test
def _check_names(self, split_names, parent_node=None): """Checks if a list contains strings with invalid names. Returns a description of the name violations. If names are correct the empty string is returned. :param split_names: List of strings :param parent_node: ...
python
{ "resource": "" }
q274037
NaturalNamingInterface._create_any_group
test
def _create_any_group(self, parent_node, name, type_name, instance=None, constructor=None, args=None, kwargs=None): """Generically creates a new group inferring from the `type_name`.""" if args is None: args = [] if kwargs is None: kwargs = {} ...
python
{ "resource": "" }
q274038
NaturalNamingInterface._create_any_param_or_result
test
def _create_any_param_or_result(self, parent_node, name, type_name, instance, constructor, args, kwargs): """Generically creates a novel parameter or result instance inferring from the `type_name`. If the instance is already supplied it is NOT constructed new. ...
python
{ "resource": "" }
q274039
NaturalNamingInterface._set_details_tree_node
test
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 ...
python
{ "resource": "" }
q274040
NaturalNamingInterface._iter_nodes
test
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...
python
{ "resource": "" }
q274041
NaturalNamingInterface._make_child_iterator
test
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...
python
{ "resource": "" }
q274042
NaturalNamingInterface._recursive_traversal_bfs
test
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...
python
{ "resource": "" }
q274043
NaturalNamingInterface._very_fast_search
test
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 ...
python
{ "resource": "" }
q274044
NaturalNamingInterface._search
test
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...
python
{ "resource": "" }
q274045
NaturalNamingInterface._backwards_search
test
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....
python
{ "resource": "" }
q274046
NNGroupNode.kids
test
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
python
{ "resource": "" }
q274047
NNGroupNode._add_group_from_storage
test
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...
python
{ "resource": "" }
q274048
NNGroupNode._add_leaf_from_storage
test
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...
python
{ "resource": "" }
q274049
NNGroupNode.f_dir_data
test
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...
python
{ "resource": "" }
q274050
NNGroupNode._debug
test
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...
python
{ "resource": "" }
q274051
NNGroupNode.f_get_parent
test
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...
python
{ "resource": "" }
q274052
NNGroupNode.f_add_group
test
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...
python
{ "resource": "" }
q274053
NNGroupNode.f_add_link
test
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...
python
{ "resource": "" }
q274054
NNGroupNode.f_remove_link
test
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...
python
{ "resource": "" }
q274055
NNGroupNode.f_add_leaf
test
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...
python
{ "resource": "" }
q274056
NNGroupNode.f_remove
test
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...
python
{ "resource": "" }
q274057
NNGroupNode.f_remove_child
test
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 ...
python
{ "resource": "" }
q274058
NNGroupNode.f_contains
test
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...
python
{ "resource": "" }
q274059
NNGroupNode.f_get_default
test
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...
python
{ "resource": "" }
q274060
NNGroupNode.f_get_children
test
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 """ ...
python
{ "resource": "" }
q274061
NNGroupNode.f_get_groups
test
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...
python
{ "resource": "" }
q274062
NNGroupNode.f_get_leaves
test
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: ...
python
{ "resource": "" }
q274063
NNGroupNode.f_get_links
test
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...
python
{ "resource": "" }
q274064
NNGroupNode.f_store_child
test
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...
python
{ "resource": "" }
q274065
NNGroupNode.f_store
test
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 '...
python
{ "resource": "" }
q274066
NNGroupNode.f_load_child
test
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...
python
{ "resource": "" }
q274067
NNGroupNode.f_load
test
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...
python
{ "resource": "" }
q274068
ParameterGroup.f_add_parameter_group
test
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...
python
{ "resource": "" }
q274069
ParameterGroup.f_add_parameter
test
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...
python
{ "resource": "" }
q274070
ResultGroup.f_add_result_group
test
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...
python
{ "resource": "" }
q274071
ResultGroup.f_add_result
test
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) ...
python
{ "resource": "" }
q274072
DerivedParameterGroup.f_add_derived_parameter_group
test
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%'` ...
python
{ "resource": "" }
q274073
DerivedParameterGroup.f_add_derived_parameter
test
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...
python
{ "resource": "" }
q274074
ConfigGroup.f_add_config_group
test
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...
python
{ "resource": "" }
q274075
ConfigGroup.f_add_config
test
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...
python
{ "resource": "" }
q274076
eval_one_max
test
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,)
python
{ "resource": "" }
q274077
add_commit_variables
test
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...
python
{ "resource": "" }
q274078
make_git_commit
test
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. ...
python
{ "resource": "" }
q274079
flatten_dictionary
test
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,...
python
{ "resource": "" }
q274080
nest_dictionary
test
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 = ...
python
{ "resource": "" }
q274081
progressbar
test
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...
python
{ "resource": "" }
q274082
_get_argspec
test
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...
python
{ "resource": "" }
q274083
get_matching_kwargs
test
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) ...
python
{ "resource": "" }
q274084
format_time
test
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
python
{ "resource": "" }
q274085
port_to_tcp
test
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...
python
{ "resource": "" }
q274086
racedirs
test
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 ...
python
{ "resource": "" }
q274087
_Progressbar._reset
test
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) ...
python
{ "resource": "" }
q274088
_Progressbar._get_remaining
test
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: ...
python
{ "resource": "" }
q274089
Annotations.f_to_dict
test
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
python
{ "resource": "" }
q274090
Annotations.f_remove
test
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)
python
{ "resource": "" }
q274091
Annotations.f_ann_to_str
test
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]
python
{ "resource": "" }
q274092
make_ordinary_result
test
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...
python
{ "resource": "" }
q274093
make_shared_result
test
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...
python
{ "resource": "" }
q274094
SharedData.create_shared_data
test
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...
python
{ "resource": "" }
q274095
SharedData._request_data
test
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,)`` ...
python
{ "resource": "" }
q274096
SharedData.get_data_node
test
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, ' '...
python
{ "resource": "" }
q274097
SharedResult._supports
test
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
python
{ "resource": "" }
q274098
SharedResult.create_shared_data
test
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)
python
{ "resource": "" }
q274099
manipulate_multiproc_safe
test
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...
python
{ "resource": "" }