INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return a list with all (following) lines. The sizehint parameter is ignored in this implementation.
def readlines(self, sizehint = -1): """Return a list with all (following) lines. The sizehint parameter is ignored in this implementation. """ result = [] while True: line = self.readline() if not line: break result.append(line) return ...
Read the directory, making sure we close the file if the format is bad.
def _GetContents(self): """Read the directory, making sure we close the file if the format is bad.""" try: self._RealGetContents() except BadZipfile: if not self._filePassed: self.fp.close() self.fp = None raise
Return a list of file names in the archive.
def namelist(self): """Return a list of file names in the archive.""" l = [] for data in self.filelist: l.append(data.filename) return l
Print a table of contents for the zip file.
def printdir(self): """Print a table of contents for the zip file.""" print "%-46s %19s %12s" % ("File Name", "Modified ", "Size") for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6] print "%-46s %s %12d" % (zinfo.filename, date, zinf...
Return the instance of ZipInfo given 'name'.
def getinfo(self, name): """Return the instance of ZipInfo given 'name'.""" info = self.NameToInfo.get(name) if info is None: raise KeyError( 'There is no item named %r in the archive' % name) return info
Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a ZipInfo object. You can specify a different directory using `path'.
def extract(self, member, path=None, pwd=None): """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a ZipInfo object. You can specify a different di...
Extract all members from the archive to the current working directory. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by namelist().
def extractall(self, path=None, members=None, pwd=None): """Extract all members from the archive to the current working directory. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by namelist(). """ ...
Extract the ZipInfo object 'member' to a physical file on the path targetpath.
def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. # Strip trailing path separator, unl...
Check for errors before writing a file to the archive.
def _writecheck(self, zinfo): """Check for errors before writing a file to the archive.""" if zinfo.filename in self.NameToInfo: if self.debug: # Warning for duplicate names print "Duplicate name:", zinfo.filename if self.mode not in ("w", "a"): raise...
Put the bytes from filename into the archive under the name arcname.
def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" if not self.fp: raise RuntimeError( "Attempt to write to ZIP archive that was already closed") st = os.stat(filename) ...
Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain directory, listdir *.py and enter all modules. Else, pathna...
def writepy(self, pathname, basename = ""): """Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain direc...
Return the temporary file to use.
def get_fileobject(self, dir=None, **kwargs): '''Return the temporary file to use.''' if dir is None: dir = os.path.normpath(os.path.dirname(self._path)) descriptor, name = tempfile.mkstemp(dir=dir) # io.open() will take either the descriptor or the name, but we need ...
Move the temporary file to the target location.
def commit(self, f): '''Move the temporary file to the target location.''' if self._overwrite: replace_atomic(f.name, self._path) else: move_atomic(f.name, self._path)
Read the PID recorded in the named PID file. Read and return the numeric PID recorded as text in the named PID file. If the PID file cannot be read, or if the content is not a valid PID, return ``None``.
def read_pid_from_pidfile(pidfile_path): """ Read the PID recorded in the named PID file. Read and return the numeric PID recorded as text in the named PID file. If the PID file cannot be read, or if the content is not a valid PID, return ``None``. """ pid = None try: ...
Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired.
def acquire(self, timeout=None): """ Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired. """ timeout = timeout is not None and timeout or self.timeout end_time = time.time() if timeout is not None and timeo...
Call this after adding your child widgets.
def apply_saved_layout(self): """Call this after adding your child widgets.""" num_widgets = self.config.get(self.config_key + "/num_widgets", int) if num_widgets: sizes = [] for i in range(num_widgets): key = "%s/size_%d" % (self.config_key, i) ...
Return diict copy with nones removed.
def remove_nones(**kwargs): """Return diict copy with nones removed. """ return dict((k, v) for k, v in kwargs.iteritems() if v is not None)
Perform a deep merge of `dict2` into `dict1`. Note that `dict2` and any nested dicts are unchanged. Supports `ModifyList` instances.
def deep_update(dict1, dict2): """Perform a deep merge of `dict2` into `dict1`. Note that `dict2` and any nested dicts are unchanged. Supports `ModifyList` instances. """ def flatten(v): if isinstance(v, ModifyList): return v.apply([]) elif isinstance(v, dict): ...
Create dict copy with removed items. Recursively remove items where fn(value) is True. Returns: dict: New dict with matching items removed.
def deep_del(data, fn): """Create dict copy with removed items. Recursively remove items where fn(value) is True. Returns: dict: New dict with matching items removed. """ result = {} for k, v in data.iteritems(): if not fn(v): if isinstance(v, dict): ...
Get added/removed/changed keys between two dicts. Each key in the return value is a list, which is the namespaced key that was affected. Returns: 3-tuple: - list of added keys; - list of removed key; - list of changed keys.
def get_dict_diff(d1, d2): """Get added/removed/changed keys between two dicts. Each key in the return value is a list, which is the namespaced key that was affected. Returns: 3-tuple: - list of added keys; - list of removed key; - list of changed keys. """ def ...
Returns same as `get_dict_diff`, but as a readable string.
def get_dict_diff_str(d1, d2, title): """Returns same as `get_dict_diff`, but as a readable string. """ added, removed, changed = get_dict_diff(d1, d2) lines = [title] if added: lines.append("Added attributes: %s" % ['.'.join(x) for x in added]) if removed: ...
Recursively convert dict and UserDict types. Note that `d` is unchanged. Args: to_class (type): Dict-like type to convert values to, usually UserDict subclass, or dict. from_class (type): Dict-like type to convert values from. If a tuple, multiple types are converted. ...
def convert_dicts(d, to_class=AttrDictWrapper, from_class=dict): """Recursively convert dict and UserDict types. Note that `d` is unchanged. Args: to_class (type): Dict-like type to convert values to, usually UserDict subclass, or dict. from_class (type): Dict-like type to conv...
Get completion strings based on an object's attributes/keys. Completion also works on dynamic attributes (eg implemented via __getattr__) if they are iterable. Args: instance (object): Object to introspect. prefix (str): Prefix to match, can be dot-separated to access nested at...
def get_object_completions(instance, prefix, types=None, instance_types=None): """Get completion strings based on an object's attributes/keys. Completion also works on dynamic attributes (eg implemented via __getattr__) if they are iterable. Args: instance (object): Object to introspect. ...
tab_index = self.tabs["help"] if self.help_widget.success: self.setTabEnabled(tab_index, True) else: self.setTabEnabled(tab_index, False) disabled_tabs.add(tab_index)
def _set_packagebase(self, variant): self.setEnabled(variant is not None) self.variant = variant is_package = isinstance(variant, Package) prev_index = self.currentIndex() disabled_tabs = set() for d in self.tabs.itervalues(): index = d["index"] i...
Use this around code in your package repository that is loading a package, for example from file or cache.
def package_loading(self): """Use this around code in your package repository that is loading a package, for example from file or cache. """ t1 = time.time() yield None t2 = time.time() self.package_load_time += t2 - t1
Determine if the repository contains any packages. Returns: True if there are no packages, False if there are at least one.
def is_empty(self): """Determine if the repository contains any packages. Returns: True if there are no packages, False if there are at least one. """ for family in self.iter_package_families(): for pkg in self.iter_packages(family): return False ...
Create a `ResourceHandle` Nearly all `ResourceHandle` creation should go through here, because it gives the various resource classes a chance to normalize / standardize the resource handles, to improve caching / comparison / etc.
def make_resource_handle(self, resource_key, **variables): """Create a `ResourceHandle` Nearly all `ResourceHandle` creation should go through here, because it gives the various resource classes a chance to normalize / standardize the resource handles, to improve caching / comparison / ...
Get a resource. Attempts to get and return a cached version of the resource if available, otherwise a new resource object is created and returned. Args: resource_key (`str`): Name of the type of `Resources` to find variables: data to identify / store on the resource ...
def get_resource(self, resource_key, **variables): """Get a resource. Attempts to get and return a cached version of the resource if available, otherwise a new resource object is created and returned. Args: resource_key (`str`): Name of the type of `Resources` to find ...
Get a resource. Args: resource_handle (`ResourceHandle`): Handle of the resource. Returns: `PackageRepositoryResource` instance.
def get_resource_from_handle(self, resource_handle, verify_repo=True): """Get a resource. Args: resource_handle (`ResourceHandle`): Handle of the resource. Returns: `PackageRepositoryResource` instance. """ if verify_repo: # we could fix the ...
Get a package repository. Args: path (str): Entry from the 'packages_path' config setting. This may simply be a path (which is managed by the 'filesystem' package repository plugin), or a string in the form "type@location", where 'type' identifies the...
def get_repository(self, path): """Get a package repository. Args: path (str): Entry from the 'packages_path' config setting. This may simply be a path (which is managed by the 'filesystem' package repository plugin), or a string in the form "type@location", ...
Test that `path_1` and `path_2` refer to the same repository. This is more reliable than testing that the strings match, since slightly different strings might refer to the same repository (consider small differences in a filesystem path for example, eg '//svr/foo', '/svr/foo'). Return...
def are_same(self, path_1, path_2): """Test that `path_1` and `path_2` refer to the same repository. This is more reliable than testing that the strings match, since slightly different strings might refer to the same repository (consider small differences in a filesystem path for exampl...
Get a resource. Attempts to get and return a cached version of the resource if available, otherwise a new resource object is created and returned. Args: resource_key (`str`): Name of the type of `Resources` to find repository_type (`str`): What sort of repository to lo...
def get_resource(self, resource_key, repository_type, location, **variables): """Get a resource. Attempts to get and return a cached version of the resource if available, otherwise a new resource object is created and returned. Args: resource_key (`str`...
Get a resource. Args: resource_handle (`ResourceHandle`): Handle of the resource. Returns: `PackageRepositoryResource` instance.
def get_resource_from_handle(self, resource_handle): """Get a resource. Args: resource_handle (`ResourceHandle`): Handle of the resource. Returns: `PackageRepositoryResource` instance. """ repo_type = resource_handle.get("repository_type") locati...
Clear all cached data.
def clear_caches(self): """Clear all cached data.""" self.get_repository.cache_clear() self._get_repository.cache_clear() self.pool.clear_caches()
Given a few parameters from the Connection constructor, select and create a subclass of _AbstractTransport.
def create_transport(host, connect_timeout, ssl=False): """Given a few parameters from the Connection constructor, select and create a subclass of _AbstractTransport.""" if ssl: return SSLTransport(host, connect_timeout, ssl) else: return TCPTransport(host, connect_timeout)
Wrap the socket in an SSL object.
def _setup_transport(self): """Wrap the socket in an SSL object.""" if hasattr(self, 'sslopts'): self.sock = ssl.wrap_socket(self.sock, **self.sslopts) else: self.sock = ssl.wrap_socket(self.sock) self.sock.do_handshake() self._quick_recv = self.sock.read
Write a string out to the SSL socket fully.
def _write(self, s): """Write a string out to the SSL socket fully.""" try: write = self.sock.write except AttributeError: # Works around a bug in python socket library raise IOError('Socket closed') else: while s: n = write...
Setup to _write() directly to the socket, and do our own buffered reads.
def _setup_transport(self): """Setup to _write() directly to the socket, and do our own buffered reads.""" self._write = self.sock.sendall self._read_buffer = EMPTY_BUFFER self._quick_recv = self.sock.recv
Read exactly n bytes from the socket
def _read(self, n, initial=False, _errnos=(errno.EAGAIN, errno.EINTR)): """Read exactly n bytes from the socket""" recv = self._quick_recv rbuf = self._read_buffer try: while len(rbuf) < n: try: s = recv(n - len(rbuf)) excep...
Return (pyver, abi, arch) tuples compatible with this Python.
def compatible_tags(): """ Return (pyver, abi, arch) tuples compatible with this Python. """ versions = [VER_SUFFIX] major = VER_SUFFIX[0] for minor in range(sys.version_info[1] - 1, - 1, -1): versions.append(''.join([major, str(minor)])) abis = [] for suffix, _, _ in imp.get_su...
Extend a package's path. Intended use is to place the following code in a package's __init__.py: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) This will add to the package's __path__ all subdirectories of directories on 'config.plugin_path' named after the pac...
def extend_path(path, name): """Extend a package's path. Intended use is to place the following code in a package's __init__.py: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) This will add to the package's __path__ all subdirectories of directories on 'con...
Returns the class registered under the given plugin name.
def get_plugin_class(self, plugin_name): """Returns the class registered under the given plugin name.""" try: return self.plugin_classes[plugin_name] except KeyError: raise RezPluginError("Unrecognised %s plugin: '%s'" % (self.pretty_type_...
Returns the module containing the plugin of the given name.
def get_plugin_module(self, plugin_name): """Returns the module containing the plugin of the given name.""" try: return self.plugin_modules[plugin_name] except KeyError: raise RezPluginError("Unrecognised %s plugin: '%s'" % (self.pretty_ty...
Returns the merged configuration data schema for this plugin type.
def config_schema(self): """Returns the merged configuration data schema for this plugin type.""" from rez.config import _plugin_config_dict d = _plugin_config_dict.get(self.type_name, {}) for name, plugin_class in self.plugin_classes.iteritems(): if hasattr(plugin_c...
Return the class registered under the given plugin name.
def get_plugin_class(self, plugin_type, plugin_name): """Return the class registered under the given plugin name.""" plugin = self._get_plugin_type(plugin_type) return plugin.get_plugin_class(plugin_name)
Return the module defining the class registered under the given plugin name.
def get_plugin_module(self, plugin_type, plugin_name): """Return the module defining the class registered under the given plugin name.""" plugin = self._get_plugin_type(plugin_type) return plugin.get_plugin_module(plugin_name)
Create and return an instance of the given plugin.
def create_instance(self, plugin_type, plugin_name, **instance_kwargs): """Create and return an instance of the given plugin.""" plugin_type = self._get_plugin_type(plugin_type) return plugin_type.create_instance(plugin_name, **instance_kwargs)
Get a formatted string summarising the plugins that were loaded.
def get_summary_string(self): """Get a formatted string summarising the plugins that were loaded.""" rows = [["PLUGIN TYPE", "NAME", "DESCRIPTION", "STATUS"], ["-----------", "----", "-----------", "------"]] for plugin_type in sorted(self.get_plugin_types()): type_na...
Get the part of the source which is causing a problem.
def get_fragment(self, offset): """ Get the part of the source which is causing a problem. """ fragment_len = 10 s = '%r' % (self.source[offset:offset + fragment_len]) if offset + fragment_len < len(self.source): s += '...' return s
Evaluate a source string or node, using ``filename`` when displaying errors.
def evaluate(self, node, filename=None): """ Evaluate a source string or node, using ``filename`` when displaying errors. """ if isinstance(node, string_types): self.source = node kwargs = {'mode': 'eval'} if filename: kwargs['f...
Decorator to prevent infinite repr recursion.
def recursive_repr(func): """Decorator to prevent infinite repr recursion.""" repr_running = set() @wraps(func) def wrapper(self): "Return ellipsis on recursive re-entry to function." key = id(self), get_ident() if key in repr_running: return '...' repr_run...
Reset sorted list load. The *load* specifies the load-factor of the list. The default load factor of '1000' works well for lists from tens to tens of millions of elements. Good practice is to use a value that is the cube root of the list size. With billions of elements, the best load ...
def _reset(self, load): """ Reset sorted list load. The *load* specifies the load-factor of the list. The default load factor of '1000' works well for lists from tens to tens of millions of elements. Good practice is to use a value that is the cube root of the list size...
Splits sublists that are more than double the load level. Updates the index when the sublist length is less than double the load level. This requires incrementing the nodes in a traversal from the leaf node to the root. For an example traversal see self._loc.
def _expand(self, pos): """Splits sublists that are more than double the load level. Updates the index when the sublist length is less than double the load level. This requires incrementing the nodes in a traversal from the leaf node to the root. For an example traversal see self._loc. ...
Update the list by adding all elements from *iterable*.
def update(self, iterable): """Update the list by adding all elements from *iterable*.""" _lists = self._lists _maxes = self._maxes values = sorted(iterable) if _maxes: if len(values) * 4 >= self._len: values.extend(chain.from_iterable(_lists)) ...
Remove the first occurrence of *val*. If *val* is not a member, does nothing.
def discard(self, val): """ Remove the first occurrence of *val*. If *val* is not a member, does nothing. """ _maxes = self._maxes if not _maxes: return pos = bisect_left(_maxes, val) if pos == len(_maxes): return _list...
Convert an index into a pair (alpha, beta) that can be used to access the corresponding _lists[alpha][beta] position. Most queries require the index be built. Details of the index are described in self._build_index. Indexing requires traversing the tree to a leaf node. Each node has ...
def _pos(self, idx): """Convert an index into a pair (alpha, beta) that can be used to access the corresponding _lists[alpha][beta] position. Most queries require the index be built. Details of the index are described in self._build_index. Indexing requires traversing the tree ...
Build an index for indexing the sorted list. Indexes are represented as binary trees in a dense array notation similar to a binary heap. For example, given a _lists representation storing integers: [0]: 1 2 3 [1]: 4 5 [2]: 6 7 8 9 [3]: 10 11 12 13 14 T...
def _build_index(self): """Build an index for indexing the sorted list. Indexes are represented as binary trees in a dense array notation similar to a binary heap. For example, given a _lists representation storing integers: [0]: 1 2 3 [1]: 4 5 [2]: 6 7 8 9 ...
Returns an iterator that slices `self` using two index pairs, `(min_pos, min_idx)` and `(max_pos, max_idx)`; the first inclusive and the latter exclusive. See `_pos` for details on how an index is converted to an index pair. When `reverse` is `True`, values are yielded from the iterator...
def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): """ Returns an iterator that slices `self` using two index pairs, `(min_pos, min_idx)` and `(max_pos, max_idx)`; the first inclusive and the latter exclusive. See `_pos` for details on how an index is converted to an...
Create an iterator of values between `minimum` and `maximum`. `inclusive` is a pair of booleans that indicates whether the minimum and maximum ought to be included in the range, respectively. The default is (True, True) such that the range is inclusive of both minimum and maximum. ...
def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): """ Create an iterator of values between `minimum` and `maximum`. `inclusive` is a pair of booleans that indicates whether the minimum and maximum ought to be included in the range, respe...
Similar to the *bisect* module in the standard library, this returns an appropriate index to insert *val*. If *val* is already present, the insertion point will be before (to the left of) any existing entries.
def bisect_left(self, val): """ Similar to the *bisect* module in the standard library, this returns an appropriate index to insert *val*. If *val* is already present, the insertion point will be before (to the left of) any existing entries. """ _maxes = self._maxes ...
Return the number of occurrences of *val* in the list.
def count(self, val): """Return the number of occurrences of *val* in the list.""" # pylint: disable=arguments-differ _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, val) if pos_left == len(_maxes): return 0 ...
Append the element *val* to the list. Raises a ValueError if the *val* would violate the sort order.
def append(self, val): """ Append the element *val* to the list. Raises a ValueError if the *val* would violate the sort order. """ # pylint: disable=arguments-differ _lists = self._lists _maxes = self._maxes if not _maxes: _maxes.append(val) ...
Remove and return item at *idx* (default last). Raises IndexError if list is empty or index is out of range. Negative indices are supported, as for slice indices.
def pop(self, idx=-1): """ Remove and return item at *idx* (default last). Raises IndexError if list is empty or index is out of range. Negative indices are supported, as for slice indices. """ # pylint: disable=arguments-differ if not self._len: rai...
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice indices.
def index(self, val, start=None, stop=None): """ Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice ind...
Add the element *val* to the list.
def add(self, val): """Add the element *val* to the list.""" _lists = self._lists _keys = self._keys _maxes = self._maxes key = self._key(val) if _maxes: pos = bisect_right(_maxes, key) if pos == len(_maxes): pos -= 1 ...
Splits sublists that are more than double the load level. Updates the index when the sublist length is less than double the load level. This requires incrementing the nodes in a traversal from the leaf node to the root. For an example traversal see self._loc.
def _expand(self, pos): """Splits sublists that are more than double the load level. Updates the index when the sublist length is less than double the load level. This requires incrementing the nodes in a traversal from the leaf node to the root. For an example traversal see self._loc. ...
Create an iterator of values between `min_key` and `max_key`. `inclusive` is a pair of booleans that indicates whether the min_key and max_key ought to be included in the range, respectively. The default is (True, True) such that the range is inclusive of both `min_key` and `max_key`. ...
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False): """ Create an iterator of values between `min_key` and `max_key`. `inclusive` is a pair of booleans that indicates whether the min_key and max_key ought to be included in the rang...
Similar to the *bisect* module in the standard library, this returns an appropriate index to insert a value with a given *key*. If values with *key* are already present, the insertion point will be before (to the left of) any existing entries.
def bisect_key_left(self, key): """ Similar to the *bisect* module in the standard library, this returns an appropriate index to insert a value with a given *key*. If values with *key* are already present, the insertion point will be before (to the left of) any existing entries. ...
Same as *bisect_key_left*, but if *key* is already present, the insertion point will be after (to the right of) any existing entries.
def bisect_key_right(self, key): """ Same as *bisect_key_left*, but if *key* is already present, the insertion point will be after (to the right of) any existing entries. """ _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, key...
Return the number of occurrences of *val* in the list.
def count(self, val): """Return the number of occurrences of *val* in the list.""" _maxes = self._maxes if not _maxes: return 0 key = self._key(val) pos = bisect_left(_maxes, key) if pos == len(_maxes): return 0 _lists = self._lists ...
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice indices.
def index(self, val, start=None, stop=None): """ Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice ind...
View a graph.
def view_graph(graph_str, parent=None, prune_to=None): """View a graph.""" from rezgui.dialogs.ImageViewerDialog import ImageViewerDialog from rez.config import config # check for already written tempfile h = hash((graph_str, prune_to)) filepath = graph_file_lookup.get(h) if filepath and no...
Select the latest versioned package in the given range. If there are no packages in the range, the selection is cleared.
def select_version(self, version_range): """Select the latest versioned package in the given range. If there are no packages in the range, the selection is cleared. """ row = -1 version = None for i, package in self.packages.iteritems(): if package.version in...
Initialize sorted set from existing set.
def _fromset(cls, values, key=None): """Initialize sorted set from existing set.""" sorted_set = object.__new__(cls) sorted_set._set = values # pylint: disable=protected-access sorted_set.__init__(key=key) return sorted_set
Create a shallow copy of the sorted set.
def copy(self): """Create a shallow copy of the sorted set.""" return self._fromset(set(self._set), key=self._key)
Remove the first occurrence of *value*. If *value* is not a member, does nothing.
def discard(self, value): """ Remove the first occurrence of *value*. If *value* is not a member, does nothing. """ _set = self._set if value in _set: _set.remove(value) self._list.discard(value)
Remove and return item at *index* (default last). Raises IndexError if set is empty or index is out of range. Negative indexes are supported, as for slice indices.
def pop(self, index=-1): """ Remove and return item at *index* (default last). Raises IndexError if set is empty or index is out of range. Negative indexes are supported, as for slice indices. """ # pylint: disable=arguments-differ value = self._list.pop(index) ...
Remove first occurrence of *value*. Raises ValueError if *value* is not present.
def remove(self, value): """ Remove first occurrence of *value*. Raises ValueError if *value* is not present. """ self._set.remove(value) self._list.remove(value)
Return a new set with elements in the set that are not in the *iterables*.
def difference(self, *iterables): """ Return a new set with elements in the set that are not in the *iterables*. """ diff = self._set.difference(*iterables) return self._fromset(diff, key=self._key)
Update the set, removing elements found in keeping only elements found in any of the *iterables*.
def difference_update(self, *iterables): """ Update the set, removing elements found in keeping only elements found in any of the *iterables*. """ _set = self._set values = set(chain(*iterables)) if (4 * len(values)) > len(_set): _list = self._list ...
Return a new set with elements common to the set and all *iterables*.
def intersection(self, *iterables): """ Return a new set with elements common to the set and all *iterables*. """ comb = self._set.intersection(*iterables) return self._fromset(comb, key=self._key)
Update the set, keeping only elements found in it and all *iterables*.
def intersection_update(self, *iterables): """ Update the set, keeping only elements found in it and all *iterables*. """ _set = self._set _list = self._list _set.intersection_update(*iterables) _list.clear() _list.update(_set) return self
Return a new set with elements in either *self* or *that* but not both.
def symmetric_difference(self, that): """ Return a new set with elements in either *self* or *that* but not both. """ diff = self._set.symmetric_difference(that) return self._fromset(diff, key=self._key)
Update the set, keeping only elements found in either *self* or *that*, but not in both.
def symmetric_difference_update(self, that): """ Update the set, keeping only elements found in either *self* or *that*, but not in both. """ _set = self._set _list = self._list _set.symmetric_difference_update(that) _list.clear() _list.update(_set...
Return a new SortedSet with elements from the set and all *iterables*.
def union(self, *iterables): """ Return a new SortedSet with elements from the set and all *iterables*. """ return self.__class__(chain(iter(self), *iterables), key=self._key)
Update the set, adding elements from all *iterables*.
def update(self, *iterables): """Update the set, adding elements from all *iterables*.""" _set = self._set values = set(chain(*iterables)) if (4 * len(values)) > len(_set): _list = self._list _set.update(values) _list.clear() _list.update(_...
Parser setup common to both rez-build and rez-release.
def setup_parser_common(parser): """Parser setup common to both rez-build and rez-release.""" from rez.build_process_ import get_build_process_types from rez.build_system import get_valid_build_systems process_types = get_build_process_types() parser.add_argument( "--process", type=str, cho...
Format a string with respect to a set of objects' attributes. Example: >>> Class Foo(object): >>> def __init__(self): >>> self.name = "Dave" >>> print scoped_format("hello {foo.name}", foo=Foo()) hello Dave Args: objects (dict): Dict of objects to f...
def scoped_format(txt, **objects): """Format a string with respect to a set of objects' attributes. Example: >>> Class Foo(object): >>> def __init__(self): >>> self.name = "Dave" >>> print scoped_format("hello {foo.name}", foo=Foo()) hello Dave Args: ...
Get an equivalent dict representation.
def to_dict(self): """Get an equivalent dict representation.""" d = {} for k, v in self.__dict__["data"].iteritems(): if isinstance(v, RecursiveAttribute): d[k] = v.to_dict() else: d[k] = v return d
Get the value of a setting. If `type` is not provided, the key must be for a known setting, present in `self.default_settings`. Conversely if `type` IS provided, the key must be for an unknown setting.
def value(self, key, type_=None): """Get the value of a setting. If `type` is not provided, the key must be for a known setting, present in `self.default_settings`. Conversely if `type` IS provided, the key must be for an unknown setting. """ if type_ is None: ...
Get a list of strings.
def get_string_list(self, key): """Get a list of strings.""" strings = [] size = self.beginReadArray(key) for i in range(size): self.setArrayIndex(i) entry = str(self._value("entry")) strings.append(entry) self.endArray() return strings
Prepend a fixed-length string list with a new string. The oldest string will be removed from the list. If the string is already in the list, it is shuffled to the top. Use this to implement things like a 'most recent files' entry.
def prepend_string_list(self, key, value, max_length_key): """Prepend a fixed-length string list with a new string. The oldest string will be removed from the list. If the string is already in the list, it is shuffled to the top. Use this to implement things like a 'most recent files' e...
Insert item into the queue, with the given priority.
def insert(self, item, priority): """ Insert item into the queue, with the given priority. """ heappush(self.heap, HeapItem(item, priority))
Accessibility matrix (transitive closure). @type graph: graph, digraph, hypergraph @param graph: Graph. @rtype: dictionary @return: Accessibility information for each node.
def accessibility(graph): """ Accessibility matrix (transitive closure). @type graph: graph, digraph, hypergraph @param graph: Graph. @rtype: dictionary @return: Accessibility information for each node. """ recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.node...
Mutual-accessibility matrix (strongly connected components). @type graph: graph, digraph @param graph: Graph. @rtype: dictionary @return: Mutual-accessibility information for each node.
def mutual_accessibility(graph): """ Mutual-accessibility matrix (strongly connected components). @type graph: graph, digraph @param graph: Graph. @rtype: dictionary @return: Mutual-accessibility information for each node. """ recursionlimit = getrecursionlimit() setrecursionlimi...
Connected components. @type graph: graph, hypergraph @param graph: Graph. @rtype: dictionary @return: Pairing that associates each node to its connected component.
def connected_components(graph): """ Connected components. @type graph: graph, hypergraph @param graph: Graph. @rtype: dictionary @return: Pairing that associates each node to its connected component. """ recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes(...
Depth-first search subfunction adapted for accessibility algorithms. @type graph: graph, digraph, hypergraph @param graph: Graph. @type visited: dictionary @param visited: List of nodes (visited nodes are marked non-zero). @type count: number @param count: Counter of connected componen...
def _dfs(graph, visited, count, node): """ Depth-first search subfunction adapted for accessibility algorithms. @type graph: graph, digraph, hypergraph @param graph: Graph. @type visited: dictionary @param visited: List of nodes (visited nodes are marked non-zero). @type count: num...
Return the cut-edges of the given graph. A cut edge, or bridge, is an edge of a graph whose removal increases the number of connected components in the graph. @type graph: graph, hypergraph @param graph: Graph. @rtype: list @return: List of cut-edges.
def cut_edges(graph): """ Return the cut-edges of the given graph. A cut edge, or bridge, is an edge of a graph whose removal increases the number of connected components in the graph. @type graph: graph, hypergraph @param graph: Graph. @rtype: list @return: List of cut-...
Return the cut-hyperedges of the given hypergraph. @type hypergraph: hypergraph @param hypergraph: Hypergraph @rtype: list @return: List of cut-nodes.
def _cut_hyperedges(hypergraph): """ Return the cut-hyperedges of the given hypergraph. @type hypergraph: hypergraph @param hypergraph: Hypergraph @rtype: list @return: List of cut-nodes. """ edges_ = cut_nodes(hypergraph.graph) edges = [] for each in edges_: ...
Return the cut-nodes of the given graph. A cut node, or articulation point, is a node of a graph whose removal increases the number of connected components in the graph. @type graph: graph, hypergraph @param graph: Graph. @rtype: list @return: List of cut-nodes.
def cut_nodes(graph): """ Return the cut-nodes of the given graph. A cut node, or articulation point, is a node of a graph whose removal increases the number of connected components in the graph. @type graph: graph, hypergraph @param graph: Graph. @rtype: list @retur...