id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
232,500
nerdvegas/rez
src/rez/utils/platform_.py
Platform.logical_cores
def logical_cores(self): """Return the number of cpu cores as reported to the os. May be different from physical_cores if, ie, intel's hyperthreading is enabled. """ try: return self._logical_cores() except Exception as e: from rez.utils.logging_ import print_error print_error("Error detecting logical core count, defaulting to 1: %s" % str(e)) return 1
python
def logical_cores(self): """Return the number of cpu cores as reported to the os. May be different from physical_cores if, ie, intel's hyperthreading is enabled. """ try: return self._logical_cores() except Exception as e: from rez.utils.logging_ import print_error print_error("Error detecting logical core count, defaulting to 1: %s" % str(e)) return 1
[ "def", "logical_cores", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_logical_cores", "(", ")", "except", "Exception", "as", "e", ":", "from", "rez", ".", "utils", ".", "logging_", "import", "print_error", "print_error", "(", "\"Error detecting logical core count, defaulting to 1: %s\"", "%", "str", "(", "e", ")", ")", "return", "1" ]
Return the number of cpu cores as reported to the os. May be different from physical_cores if, ie, intel's hyperthreading is enabled.
[ "Return", "the", "number", "of", "cpu", "cores", "as", "reported", "to", "the", "os", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/platform_.py#L93-L105
232,501
nerdvegas/rez
src/rez/vendor/colorama/ansitowin32.py
AnsiToWin32.write_and_convert
def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 for match in self.ANSI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text))
python
def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 for match in self.ANSI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text))
[ "def", "write_and_convert", "(", "self", ",", "text", ")", ":", "cursor", "=", "0", "for", "match", "in", "self", ".", "ANSI_RE", ".", "finditer", "(", "text", ")", ":", "start", ",", "end", "=", "match", ".", "span", "(", ")", "self", ".", "write_plain_text", "(", "text", ",", "cursor", ",", "start", ")", "self", ".", "convert_ansi", "(", "*", "match", ".", "groups", "(", ")", ")", "cursor", "=", "end", "self", ".", "write_plain_text", "(", "text", ",", "cursor", ",", "len", "(", "text", ")", ")" ]
Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.
[ "Write", "the", "given", "text", "to", "our", "wrapped", "stream", "stripping", "any", "ANSI", "sequences", "from", "the", "text", "and", "optionally", "converting", "them", "into", "win32", "calls", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/colorama/ansitowin32.py#L131-L143
232,502
nerdvegas/rez
src/rezgui/models/ContextModel.py
ContextModel.copy
def copy(self): """Returns a copy of the context.""" other = ContextModel(self._context, self.parent()) other._stale = self._stale other._modified = self._modified other.request = self.request[:] other.packages_path = self.packages_path other.implicit_packages = self.implicit_packages other.package_filter = self.package_filter other.caching = self.caching other.default_patch_lock = self.default_patch_lock other.patch_locks = copy.deepcopy(self.patch_locks) return other
python
def copy(self): """Returns a copy of the context.""" other = ContextModel(self._context, self.parent()) other._stale = self._stale other._modified = self._modified other.request = self.request[:] other.packages_path = self.packages_path other.implicit_packages = self.implicit_packages other.package_filter = self.package_filter other.caching = self.caching other.default_patch_lock = self.default_patch_lock other.patch_locks = copy.deepcopy(self.patch_locks) return other
[ "def", "copy", "(", "self", ")", ":", "other", "=", "ContextModel", "(", "self", ".", "_context", ",", "self", ".", "parent", "(", ")", ")", "other", ".", "_stale", "=", "self", ".", "_stale", "other", ".", "_modified", "=", "self", ".", "_modified", "other", ".", "request", "=", "self", ".", "request", "[", ":", "]", "other", ".", "packages_path", "=", "self", ".", "packages_path", "other", ".", "implicit_packages", "=", "self", ".", "implicit_packages", "other", ".", "package_filter", "=", "self", ".", "package_filter", "other", ".", "caching", "=", "self", ".", "caching", "other", ".", "default_patch_lock", "=", "self", ".", "default_patch_lock", "other", ".", "patch_locks", "=", "copy", ".", "deepcopy", "(", "self", ".", "patch_locks", ")", "return", "other" ]
Returns a copy of the context.
[ "Returns", "a", "copy", "of", "the", "context", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/models/ContextModel.py#L51-L63
232,503
nerdvegas/rez
src/rezgui/models/ContextModel.py
ContextModel.get_lock_requests
def get_lock_requests(self): """Take the current context, and the current patch locks, and determine the effective requests that will be added to the main request. Returns: A dict of (PatchLock, [Requirement]) tuples. Each requirement will be a weak package reference. If there is no current context, an empty dict will be returned. """ d = defaultdict(list) if self._context: for variant in self._context.resolved_packages: name = variant.name version = variant.version lock = self.patch_locks.get(name) if lock is None: lock = self.default_patch_lock request = get_lock_request(name, version, lock) if request is not None: d[lock].append(request) return d
python
def get_lock_requests(self): """Take the current context, and the current patch locks, and determine the effective requests that will be added to the main request. Returns: A dict of (PatchLock, [Requirement]) tuples. Each requirement will be a weak package reference. If there is no current context, an empty dict will be returned. """ d = defaultdict(list) if self._context: for variant in self._context.resolved_packages: name = variant.name version = variant.version lock = self.patch_locks.get(name) if lock is None: lock = self.default_patch_lock request = get_lock_request(name, version, lock) if request is not None: d[lock].append(request) return d
[ "def", "get_lock_requests", "(", "self", ")", ":", "d", "=", "defaultdict", "(", "list", ")", "if", "self", ".", "_context", ":", "for", "variant", "in", "self", ".", "_context", ".", "resolved_packages", ":", "name", "=", "variant", ".", "name", "version", "=", "variant", ".", "version", "lock", "=", "self", ".", "patch_locks", ".", "get", "(", "name", ")", "if", "lock", "is", "None", ":", "lock", "=", "self", ".", "default_patch_lock", "request", "=", "get_lock_request", "(", "name", ",", "version", ",", "lock", ")", "if", "request", "is", "not", "None", ":", "d", "[", "lock", "]", ".", "append", "(", "request", ")", "return", "d" ]
Take the current context, and the current patch locks, and determine the effective requests that will be added to the main request. Returns: A dict of (PatchLock, [Requirement]) tuples. Each requirement will be a weak package reference. If there is no current context, an empty dict will be returned.
[ "Take", "the", "current", "context", "and", "the", "current", "patch", "locks", "and", "determine", "the", "effective", "requests", "that", "will", "be", "added", "to", "the", "main", "request", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/models/ContextModel.py#L113-L134
232,504
nerdvegas/rez
src/rezgui/models/ContextModel.py
ContextModel.resolve_context
def resolve_context(self, verbosity=0, max_fails=-1, timestamp=None, callback=None, buf=None, package_load_callback=None): """Update the current context by performing a re-resolve. The newly resolved context is only applied if it is a successful solve. Returns: `ResolvedContext` object, which may be a successful or failed solve. """ package_filter = PackageFilterList.from_pod(self.package_filter) context = ResolvedContext( self.request, package_paths=self.packages_path, package_filter=package_filter, verbosity=verbosity, max_fails=max_fails, timestamp=timestamp, buf=buf, callback=callback, package_load_callback=package_load_callback, caching=self.caching) if context.success: if self._context and self._context.load_path: context.set_load_path(self._context.load_path) self._set_context(context) self._modified = True return context
python
def resolve_context(self, verbosity=0, max_fails=-1, timestamp=None, callback=None, buf=None, package_load_callback=None): """Update the current context by performing a re-resolve. The newly resolved context is only applied if it is a successful solve. Returns: `ResolvedContext` object, which may be a successful or failed solve. """ package_filter = PackageFilterList.from_pod(self.package_filter) context = ResolvedContext( self.request, package_paths=self.packages_path, package_filter=package_filter, verbosity=verbosity, max_fails=max_fails, timestamp=timestamp, buf=buf, callback=callback, package_load_callback=package_load_callback, caching=self.caching) if context.success: if self._context and self._context.load_path: context.set_load_path(self._context.load_path) self._set_context(context) self._modified = True return context
[ "def", "resolve_context", "(", "self", ",", "verbosity", "=", "0", ",", "max_fails", "=", "-", "1", ",", "timestamp", "=", "None", ",", "callback", "=", "None", ",", "buf", "=", "None", ",", "package_load_callback", "=", "None", ")", ":", "package_filter", "=", "PackageFilterList", ".", "from_pod", "(", "self", ".", "package_filter", ")", "context", "=", "ResolvedContext", "(", "self", ".", "request", ",", "package_paths", "=", "self", ".", "packages_path", ",", "package_filter", "=", "package_filter", ",", "verbosity", "=", "verbosity", ",", "max_fails", "=", "max_fails", ",", "timestamp", "=", "timestamp", ",", "buf", "=", "buf", ",", "callback", "=", "callback", ",", "package_load_callback", "=", "package_load_callback", ",", "caching", "=", "self", ".", "caching", ")", "if", "context", ".", "success", ":", "if", "self", ".", "_context", "and", "self", ".", "_context", ".", "load_path", ":", "context", ".", "set_load_path", "(", "self", ".", "_context", ".", "load_path", ")", "self", ".", "_set_context", "(", "context", ")", "self", ".", "_modified", "=", "True", "return", "context" ]
Update the current context by performing a re-resolve. The newly resolved context is only applied if it is a successful solve. Returns: `ResolvedContext` object, which may be a successful or failed solve.
[ "Update", "the", "current", "context", "by", "performing", "a", "re", "-", "resolve", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/models/ContextModel.py#L175-L203
232,505
nerdvegas/rez
src/rezgui/models/ContextModel.py
ContextModel.set_context
def set_context(self, context): """Replace the current context with another.""" self._set_context(context, emit=False) self._modified = (not context.load_path) self.dataChanged.emit(self.CONTEXT_CHANGED | self.REQUEST_CHANGED | self.PACKAGES_PATH_CHANGED | self.LOCKS_CHANGED | self.LOADPATH_CHANGED | self.PACKAGE_FILTER_CHANGED | self.CACHING_CHANGED)
python
def set_context(self, context): """Replace the current context with another.""" self._set_context(context, emit=False) self._modified = (not context.load_path) self.dataChanged.emit(self.CONTEXT_CHANGED | self.REQUEST_CHANGED | self.PACKAGES_PATH_CHANGED | self.LOCKS_CHANGED | self.LOADPATH_CHANGED | self.PACKAGE_FILTER_CHANGED | self.CACHING_CHANGED)
[ "def", "set_context", "(", "self", ",", "context", ")", ":", "self", ".", "_set_context", "(", "context", ",", "emit", "=", "False", ")", "self", ".", "_modified", "=", "(", "not", "context", ".", "load_path", ")", "self", ".", "dataChanged", ".", "emit", "(", "self", ".", "CONTEXT_CHANGED", "|", "self", ".", "REQUEST_CHANGED", "|", "self", ".", "PACKAGES_PATH_CHANGED", "|", "self", ".", "LOCKS_CHANGED", "|", "self", ".", "LOADPATH_CHANGED", "|", "self", ".", "PACKAGE_FILTER_CHANGED", "|", "self", ".", "CACHING_CHANGED", ")" ]
Replace the current context with another.
[ "Replace", "the", "current", "context", "with", "another", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/models/ContextModel.py#L214-L224
232,506
nerdvegas/rez
src/rez/vendor/distlib/util.py
get_resources_dests
def get_resources_dests(resources_root, rules): """Find destinations for resources files""" def get_rel_path(base, path): # normalizes and returns a lstripped-/-separated path base = base.replace(os.path.sep, '/') path = path.replace(os.path.sep, '/') assert path.startswith(base) return path[len(base):].lstrip('/') destinations = {} for base, suffix, dest in rules: prefix = os.path.join(resources_root, base) for abs_base in iglob(prefix): abs_glob = os.path.join(abs_base, suffix) for abs_path in iglob(abs_glob): resource_file = get_rel_path(resources_root, abs_path) if dest is None: # remove the entry if it was here destinations.pop(resource_file, None) else: rel_path = get_rel_path(abs_base, abs_path) rel_dest = dest.replace(os.path.sep, '/').rstrip('/') destinations[resource_file] = rel_dest + '/' + rel_path return destinations
python
def get_resources_dests(resources_root, rules): """Find destinations for resources files""" def get_rel_path(base, path): # normalizes and returns a lstripped-/-separated path base = base.replace(os.path.sep, '/') path = path.replace(os.path.sep, '/') assert path.startswith(base) return path[len(base):].lstrip('/') destinations = {} for base, suffix, dest in rules: prefix = os.path.join(resources_root, base) for abs_base in iglob(prefix): abs_glob = os.path.join(abs_base, suffix) for abs_path in iglob(abs_glob): resource_file = get_rel_path(resources_root, abs_path) if dest is None: # remove the entry if it was here destinations.pop(resource_file, None) else: rel_path = get_rel_path(abs_base, abs_path) rel_dest = dest.replace(os.path.sep, '/').rstrip('/') destinations[resource_file] = rel_dest + '/' + rel_path return destinations
[ "def", "get_resources_dests", "(", "resources_root", ",", "rules", ")", ":", "def", "get_rel_path", "(", "base", ",", "path", ")", ":", "# normalizes and returns a lstripped-/-separated path", "base", "=", "base", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'/'", ")", "path", "=", "path", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'/'", ")", "assert", "path", ".", "startswith", "(", "base", ")", "return", "path", "[", "len", "(", "base", ")", ":", "]", ".", "lstrip", "(", "'/'", ")", "destinations", "=", "{", "}", "for", "base", ",", "suffix", ",", "dest", "in", "rules", ":", "prefix", "=", "os", ".", "path", ".", "join", "(", "resources_root", ",", "base", ")", "for", "abs_base", "in", "iglob", "(", "prefix", ")", ":", "abs_glob", "=", "os", ".", "path", ".", "join", "(", "abs_base", ",", "suffix", ")", "for", "abs_path", "in", "iglob", "(", "abs_glob", ")", ":", "resource_file", "=", "get_rel_path", "(", "resources_root", ",", "abs_path", ")", "if", "dest", "is", "None", ":", "# remove the entry if it was here", "destinations", ".", "pop", "(", "resource_file", ",", "None", ")", "else", ":", "rel_path", "=", "get_rel_path", "(", "abs_base", ",", "abs_path", ")", "rel_dest", "=", "dest", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'/'", ")", ".", "rstrip", "(", "'/'", ")", "destinations", "[", "resource_file", "]", "=", "rel_dest", "+", "'/'", "+", "rel_path", "return", "destinations" ]
Find destinations for resources files
[ "Find", "destinations", "for", "resources", "files" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/util.py#L123-L147
232,507
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/cycles.py
find_cycle
def find_cycle(graph): """ Find a cycle in the given graph. This function will return a list of nodes which form a cycle in the graph or an empty list if no cycle exists. @type graph: graph, digraph @param graph: Graph. @rtype: list @return: List of nodes. """ if (isinstance(graph, graph_class)): directed = False elif (isinstance(graph, digraph_class)): directed = True else: raise InvalidGraphType def find_cycle_to_ancestor(node, ancestor): """ Find a cycle containing both node and ancestor. """ path = [] while (node != ancestor): if (node is None): return [] path.append(node) node = spanning_tree[node] path.append(node) path.reverse() return path def dfs(node): """ Depth-first search subfunction. """ visited[node] = 1 # Explore recursively the connected component for each in graph[node]: if (cycle): return if (each not in visited): spanning_tree[each] = node dfs(each) else: if (directed or spanning_tree[node] != each): cycle.extend(find_cycle_to_ancestor(node, each)) recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) visited = {} # List for marking visited and non-visited nodes spanning_tree = {} # Spanning tree cycle = [] # Algorithm outer-loop for each in graph: # Select a non-visited node if (each not in visited): spanning_tree[each] = None # Explore node's connected component dfs(each) if (cycle): setrecursionlimit(recursionlimit) return cycle setrecursionlimit(recursionlimit) return []
python
def find_cycle(graph): """ Find a cycle in the given graph. This function will return a list of nodes which form a cycle in the graph or an empty list if no cycle exists. @type graph: graph, digraph @param graph: Graph. @rtype: list @return: List of nodes. """ if (isinstance(graph, graph_class)): directed = False elif (isinstance(graph, digraph_class)): directed = True else: raise InvalidGraphType def find_cycle_to_ancestor(node, ancestor): """ Find a cycle containing both node and ancestor. """ path = [] while (node != ancestor): if (node is None): return [] path.append(node) node = spanning_tree[node] path.append(node) path.reverse() return path def dfs(node): """ Depth-first search subfunction. """ visited[node] = 1 # Explore recursively the connected component for each in graph[node]: if (cycle): return if (each not in visited): spanning_tree[each] = node dfs(each) else: if (directed or spanning_tree[node] != each): cycle.extend(find_cycle_to_ancestor(node, each)) recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) visited = {} # List for marking visited and non-visited nodes spanning_tree = {} # Spanning tree cycle = [] # Algorithm outer-loop for each in graph: # Select a non-visited node if (each not in visited): spanning_tree[each] = None # Explore node's connected component dfs(each) if (cycle): setrecursionlimit(recursionlimit) return cycle setrecursionlimit(recursionlimit) return []
[ "def", "find_cycle", "(", "graph", ")", ":", "if", "(", "isinstance", "(", "graph", ",", "graph_class", ")", ")", ":", "directed", "=", "False", "elif", "(", "isinstance", "(", "graph", ",", "digraph_class", ")", ")", ":", "directed", "=", "True", "else", ":", "raise", "InvalidGraphType", "def", "find_cycle_to_ancestor", "(", "node", ",", "ancestor", ")", ":", "\"\"\"\n Find a cycle containing both node and ancestor.\n \"\"\"", "path", "=", "[", "]", "while", "(", "node", "!=", "ancestor", ")", ":", "if", "(", "node", "is", "None", ")", ":", "return", "[", "]", "path", ".", "append", "(", "node", ")", "node", "=", "spanning_tree", "[", "node", "]", "path", ".", "append", "(", "node", ")", "path", ".", "reverse", "(", ")", "return", "path", "def", "dfs", "(", "node", ")", ":", "\"\"\"\n Depth-first search subfunction.\n \"\"\"", "visited", "[", "node", "]", "=", "1", "# Explore recursively the connected component", "for", "each", "in", "graph", "[", "node", "]", ":", "if", "(", "cycle", ")", ":", "return", "if", "(", "each", "not", "in", "visited", ")", ":", "spanning_tree", "[", "each", "]", "=", "node", "dfs", "(", "each", ")", "else", ":", "if", "(", "directed", "or", "spanning_tree", "[", "node", "]", "!=", "each", ")", ":", "cycle", ".", "extend", "(", "find_cycle_to_ancestor", "(", "node", ",", "each", ")", ")", "recursionlimit", "=", "getrecursionlimit", "(", ")", "setrecursionlimit", "(", "max", "(", "len", "(", "graph", ".", "nodes", "(", ")", ")", "*", "2", ",", "recursionlimit", ")", ")", "visited", "=", "{", "}", "# List for marking visited and non-visited nodes", "spanning_tree", "=", "{", "}", "# Spanning tree", "cycle", "=", "[", "]", "# Algorithm outer-loop", "for", "each", "in", "graph", ":", "# Select a non-visited node", "if", "(", "each", "not", "in", "visited", ")", ":", "spanning_tree", "[", "each", "]", "=", "None", "# Explore node's connected component", "dfs", "(", "each", ")", "if", "(", "cycle", ")", ":", "setrecursionlimit", "(", "recursionlimit", ")", "return", "cycle", "setrecursionlimit", "(", "recursionlimit", ")", "return", "[", "]" ]
Find a cycle in the given graph. This function will return a list of nodes which form a cycle in the graph or an empty list if no cycle exists. @type graph: graph, digraph @param graph: Graph. @rtype: list @return: List of nodes.
[ "Find", "a", "cycle", "in", "the", "given", "graph", ".", "This", "function", "will", "return", "a", "list", "of", "nodes", "which", "form", "a", "cycle", "in", "the", "graph", "or", "an", "empty", "list", "if", "no", "cycle", "exists", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/cycles.py#L38-L108
232,508
nerdvegas/rez
src/rez/release_vcs.py
create_release_vcs
def create_release_vcs(path, vcs_name=None): """Return a new release VCS that can release from this source path.""" from rez.plugin_managers import plugin_manager vcs_types = get_release_vcs_types() if vcs_name: if vcs_name not in vcs_types: raise ReleaseVCSError("Unknown version control system: %r" % vcs_name) cls = plugin_manager.get_plugin_class('release_vcs', vcs_name) return cls(path) classes_by_level = {} for vcs_name in vcs_types: cls = plugin_manager.get_plugin_class('release_vcs', vcs_name) result = cls.find_vcs_root(path) if not result: continue vcs_path, levels_up = result classes_by_level.setdefault(levels_up, []).append((cls, vcs_path)) if not classes_by_level: raise ReleaseVCSError("No version control system for package " "releasing is associated with the path %s" % path) # it's ok to have multiple results, as long as there is only one at the # "closest" directory up from this dir - ie, if we start at: # /blah/foo/pkg_root # and these dirs exist: # /blah/.hg # /blah/foo/.git # ...then this is ok, because /blah/foo/.git is "closer" to the original # dir, and will be picked. However, if these two directories exist: # /blah/foo/.git # /blah/foo/.hg # ...then we error, because we can't decide which to use lowest_level = sorted(classes_by_level)[0] clss = classes_by_level[lowest_level] if len(clss) > 1: clss_str = ", ".join(x[0].name() for x in clss) raise ReleaseVCSError("Several version control systems are associated " "with the path %s: %s. Use rez-release --vcs to " "choose." % (path, clss_str)) else: cls, vcs_root = clss[0] return cls(pkg_root=path, vcs_root=vcs_root)
python
def create_release_vcs(path, vcs_name=None): """Return a new release VCS that can release from this source path.""" from rez.plugin_managers import plugin_manager vcs_types = get_release_vcs_types() if vcs_name: if vcs_name not in vcs_types: raise ReleaseVCSError("Unknown version control system: %r" % vcs_name) cls = plugin_manager.get_plugin_class('release_vcs', vcs_name) return cls(path) classes_by_level = {} for vcs_name in vcs_types: cls = plugin_manager.get_plugin_class('release_vcs', vcs_name) result = cls.find_vcs_root(path) if not result: continue vcs_path, levels_up = result classes_by_level.setdefault(levels_up, []).append((cls, vcs_path)) if not classes_by_level: raise ReleaseVCSError("No version control system for package " "releasing is associated with the path %s" % path) # it's ok to have multiple results, as long as there is only one at the # "closest" directory up from this dir - ie, if we start at: # /blah/foo/pkg_root # and these dirs exist: # /blah/.hg # /blah/foo/.git # ...then this is ok, because /blah/foo/.git is "closer" to the original # dir, and will be picked. However, if these two directories exist: # /blah/foo/.git # /blah/foo/.hg # ...then we error, because we can't decide which to use lowest_level = sorted(classes_by_level)[0] clss = classes_by_level[lowest_level] if len(clss) > 1: clss_str = ", ".join(x[0].name() for x in clss) raise ReleaseVCSError("Several version control systems are associated " "with the path %s: %s. Use rez-release --vcs to " "choose." % (path, clss_str)) else: cls, vcs_root = clss[0] return cls(pkg_root=path, vcs_root=vcs_root)
[ "def", "create_release_vcs", "(", "path", ",", "vcs_name", "=", "None", ")", ":", "from", "rez", ".", "plugin_managers", "import", "plugin_manager", "vcs_types", "=", "get_release_vcs_types", "(", ")", "if", "vcs_name", ":", "if", "vcs_name", "not", "in", "vcs_types", ":", "raise", "ReleaseVCSError", "(", "\"Unknown version control system: %r\"", "%", "vcs_name", ")", "cls", "=", "plugin_manager", ".", "get_plugin_class", "(", "'release_vcs'", ",", "vcs_name", ")", "return", "cls", "(", "path", ")", "classes_by_level", "=", "{", "}", "for", "vcs_name", "in", "vcs_types", ":", "cls", "=", "plugin_manager", ".", "get_plugin_class", "(", "'release_vcs'", ",", "vcs_name", ")", "result", "=", "cls", ".", "find_vcs_root", "(", "path", ")", "if", "not", "result", ":", "continue", "vcs_path", ",", "levels_up", "=", "result", "classes_by_level", ".", "setdefault", "(", "levels_up", ",", "[", "]", ")", ".", "append", "(", "(", "cls", ",", "vcs_path", ")", ")", "if", "not", "classes_by_level", ":", "raise", "ReleaseVCSError", "(", "\"No version control system for package \"", "\"releasing is associated with the path %s\"", "%", "path", ")", "# it's ok to have multiple results, as long as there is only one at the", "# \"closest\" directory up from this dir - ie, if we start at:", "# /blah/foo/pkg_root", "# and these dirs exist:", "# /blah/.hg", "# /blah/foo/.git", "# ...then this is ok, because /blah/foo/.git is \"closer\" to the original", "# dir, and will be picked. However, if these two directories exist:", "# /blah/foo/.git", "# /blah/foo/.hg", "# ...then we error, because we can't decide which to use", "lowest_level", "=", "sorted", "(", "classes_by_level", ")", "[", "0", "]", "clss", "=", "classes_by_level", "[", "lowest_level", "]", "if", "len", "(", "clss", ")", ">", "1", ":", "clss_str", "=", "\", \"", ".", "join", "(", "x", "[", "0", "]", ".", "name", "(", ")", "for", "x", "in", "clss", ")", "raise", "ReleaseVCSError", "(", "\"Several version control systems are associated \"", "\"with the path %s: %s. Use rez-release --vcs to \"", "\"choose.\"", "%", "(", "path", ",", "clss_str", ")", ")", "else", ":", "cls", ",", "vcs_root", "=", "clss", "[", "0", "]", "return", "cls", "(", "pkg_root", "=", "path", ",", "vcs_root", "=", "vcs_root", ")" ]
Return a new release VCS that can release from this source path.
[ "Return", "a", "new", "release", "VCS", "that", "can", "release", "from", "this", "source", "path", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_vcs.py#L17-L61
232,509
nerdvegas/rez
src/rez/release_vcs.py
ReleaseVCS.find_vcs_root
def find_vcs_root(cls, path): """Try to find a version control root directory of this type for the given path. If successful, returns (vcs_root, levels_up), where vcs_root is the path to the version control root directory it found, and levels_up is an integer indicating how many parent directories it had to search through to find it, where 0 means it was found in the indicated path, 1 means it was found in that path's parent, etc. If not sucessful, returns None """ if cls.search_parents_for_root(): valid_dirs = walk_up_dirs(path) else: valid_dirs = [path] for i, current_path in enumerate(valid_dirs): if cls.is_valid_root(current_path): return current_path, i return None
python
def find_vcs_root(cls, path): """Try to find a version control root directory of this type for the given path. If successful, returns (vcs_root, levels_up), where vcs_root is the path to the version control root directory it found, and levels_up is an integer indicating how many parent directories it had to search through to find it, where 0 means it was found in the indicated path, 1 means it was found in that path's parent, etc. If not sucessful, returns None """ if cls.search_parents_for_root(): valid_dirs = walk_up_dirs(path) else: valid_dirs = [path] for i, current_path in enumerate(valid_dirs): if cls.is_valid_root(current_path): return current_path, i return None
[ "def", "find_vcs_root", "(", "cls", ",", "path", ")", ":", "if", "cls", ".", "search_parents_for_root", "(", ")", ":", "valid_dirs", "=", "walk_up_dirs", "(", "path", ")", "else", ":", "valid_dirs", "=", "[", "path", "]", "for", "i", ",", "current_path", "in", "enumerate", "(", "valid_dirs", ")", ":", "if", "cls", ".", "is_valid_root", "(", "current_path", ")", ":", "return", "current_path", ",", "i", "return", "None" ]
Try to find a version control root directory of this type for the given path. If successful, returns (vcs_root, levels_up), where vcs_root is the path to the version control root directory it found, and levels_up is an integer indicating how many parent directories it had to search through to find it, where 0 means it was found in the indicated path, 1 means it was found in that path's parent, etc. If not sucessful, returns None
[ "Try", "to", "find", "a", "version", "control", "root", "directory", "of", "this", "type", "for", "the", "given", "path", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_vcs.py#L115-L132
232,510
nerdvegas/rez
src/rez/release_vcs.py
ReleaseVCS._cmd
def _cmd(self, *nargs): """Convenience function for executing a program such as 'git' etc.""" cmd_str = ' '.join(map(quote, nargs)) if self.package.config.debug("package_release"): print_debug("Running command: %s" % cmd_str) p = popen(nargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.pkg_root) out, err = p.communicate() if p.returncode: print_debug("command stdout:") print_debug(out) print_debug("command stderr:") print_debug(err) raise ReleaseVCSError("command failed: %s\n%s" % (cmd_str, err)) out = out.strip() if out: return [x.rstrip() for x in out.split('\n')] else: return []
python
def _cmd(self, *nargs): """Convenience function for executing a program such as 'git' etc.""" cmd_str = ' '.join(map(quote, nargs)) if self.package.config.debug("package_release"): print_debug("Running command: %s" % cmd_str) p = popen(nargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.pkg_root) out, err = p.communicate() if p.returncode: print_debug("command stdout:") print_debug(out) print_debug("command stderr:") print_debug(err) raise ReleaseVCSError("command failed: %s\n%s" % (cmd_str, err)) out = out.strip() if out: return [x.rstrip() for x in out.split('\n')] else: return []
[ "def", "_cmd", "(", "self", ",", "*", "nargs", ")", ":", "cmd_str", "=", "' '", ".", "join", "(", "map", "(", "quote", ",", "nargs", ")", ")", "if", "self", ".", "package", ".", "config", ".", "debug", "(", "\"package_release\"", ")", ":", "print_debug", "(", "\"Running command: %s\"", "%", "cmd_str", ")", "p", "=", "popen", "(", "nargs", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "cwd", "=", "self", ".", "pkg_root", ")", "out", ",", "err", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", ":", "print_debug", "(", "\"command stdout:\"", ")", "print_debug", "(", "out", ")", "print_debug", "(", "\"command stderr:\"", ")", "print_debug", "(", "err", ")", "raise", "ReleaseVCSError", "(", "\"command failed: %s\\n%s\"", "%", "(", "cmd_str", ",", "err", ")", ")", "out", "=", "out", ".", "strip", "(", ")", "if", "out", ":", "return", "[", "x", ".", "rstrip", "(", ")", "for", "x", "in", "out", ".", "split", "(", "'\\n'", ")", "]", "else", ":", "return", "[", "]" ]
Convenience function for executing a program such as 'git' etc.
[ "Convenience", "function", "for", "executing", "a", "program", "such", "as", "git", "etc", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_vcs.py#L203-L224
232,511
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._close
def _close(self, args): """Request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender provides the class and method id of the method which caused the exception. RULE: After sending this method any received method except Channel.Close-OK MUST be discarded. RULE: The peer sending this method MAY use a counter or timeout to detect failure of the other peer to respond correctly with Channel.Close-OK.. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. class_id: short failing method class When the close is provoked by a method exception, this is the class of the method. method_id: short failing method ID When the close is provoked by a method exception, this is the ID of the method. """ reply_code = args.read_short() reply_text = args.read_shortstr() class_id = args.read_short() method_id = args.read_short() self._send_method((20, 41)) self._do_revive() raise error_for_code( reply_code, reply_text, (class_id, method_id), ChannelError, )
python
def _close(self, args): """Request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender provides the class and method id of the method which caused the exception. RULE: After sending this method any received method except Channel.Close-OK MUST be discarded. RULE: The peer sending this method MAY use a counter or timeout to detect failure of the other peer to respond correctly with Channel.Close-OK.. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. class_id: short failing method class When the close is provoked by a method exception, this is the class of the method. method_id: short failing method ID When the close is provoked by a method exception, this is the ID of the method. """ reply_code = args.read_short() reply_text = args.read_shortstr() class_id = args.read_short() method_id = args.read_short() self._send_method((20, 41)) self._do_revive() raise error_for_code( reply_code, reply_text, (class_id, method_id), ChannelError, )
[ "def", "_close", "(", "self", ",", "args", ")", ":", "reply_code", "=", "args", ".", "read_short", "(", ")", "reply_text", "=", "args", ".", "read_shortstr", "(", ")", "class_id", "=", "args", ".", "read_short", "(", ")", "method_id", "=", "args", ".", "read_short", "(", ")", "self", ".", "_send_method", "(", "(", "20", ",", "41", ")", ")", "self", ".", "_do_revive", "(", ")", "raise", "error_for_code", "(", "reply_code", ",", "reply_text", ",", "(", "class_id", ",", "method_id", ")", ",", "ChannelError", ",", ")" ]
Request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender provides the class and method id of the method which caused the exception. RULE: After sending this method any received method except Channel.Close-OK MUST be discarded. RULE: The peer sending this method MAY use a counter or timeout to detect failure of the other peer to respond correctly with Channel.Close-OK.. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. class_id: short failing method class When the close is provoked by a method exception, this is the class of the method. method_id: short failing method ID When the close is provoked by a method exception, this is the ID of the method.
[ "Request", "a", "channel", "close" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L186-L244
232,512
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._x_flow_ok
def _x_flow_ok(self, active): """Confirm a flow method Confirms to the peer that a flow command was received and processed. PARAMETERS: active: boolean current flow setting Confirms the setting of the processed flow method: True means the peer will start sending or continue to send content frames; False means it will not. """ args = AMQPWriter() args.write_bit(active) self._send_method((20, 21), args)
python
def _x_flow_ok(self, active): """Confirm a flow method Confirms to the peer that a flow command was received and processed. PARAMETERS: active: boolean current flow setting Confirms the setting of the processed flow method: True means the peer will start sending or continue to send content frames; False means it will not. """ args = AMQPWriter() args.write_bit(active) self._send_method((20, 21), args)
[ "def", "_x_flow_ok", "(", "self", ",", "active", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_bit", "(", "active", ")", "self", ".", "_send_method", "(", "(", "20", ",", "21", ")", ",", "args", ")" ]
Confirm a flow method Confirms to the peer that a flow command was received and processed. PARAMETERS: active: boolean current flow setting Confirms the setting of the processed flow method: True means the peer will start sending or continue to send content frames; False means it will not.
[ "Confirm", "a", "flow", "method" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L364-L382
232,513
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._x_open
def _x_open(self): """Open a channel for use This method opens a virtual connection (a channel). RULE: This method MUST NOT be called when the channel is already open. PARAMETERS: out_of_band: shortstr (DEPRECATED) out-of-band settings Configures out-of-band transfers on this channel. The syntax and meaning of this field will be formally defined at a later date. """ if self.is_open: return args = AMQPWriter() args.write_shortstr('') # out_of_band: deprecated self._send_method((20, 10), args) return self.wait(allowed_methods=[ (20, 11), # Channel.open_ok ])
python
def _x_open(self): """Open a channel for use This method opens a virtual connection (a channel). RULE: This method MUST NOT be called when the channel is already open. PARAMETERS: out_of_band: shortstr (DEPRECATED) out-of-band settings Configures out-of-band transfers on this channel. The syntax and meaning of this field will be formally defined at a later date. """ if self.is_open: return args = AMQPWriter() args.write_shortstr('') # out_of_band: deprecated self._send_method((20, 10), args) return self.wait(allowed_methods=[ (20, 11), # Channel.open_ok ])
[ "def", "_x_open", "(", "self", ")", ":", "if", "self", ".", "is_open", ":", "return", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_shortstr", "(", "''", ")", "# out_of_band: deprecated", "self", ".", "_send_method", "(", "(", "20", ",", "10", ")", ",", "args", ")", "return", "self", ".", "wait", "(", "allowed_methods", "=", "[", "(", "20", ",", "11", ")", ",", "# Channel.open_ok", "]", ")" ]
Open a channel for use This method opens a virtual connection (a channel). RULE: This method MUST NOT be called when the channel is already open. PARAMETERS: out_of_band: shortstr (DEPRECATED) out-of-band settings Configures out-of-band transfers on this channel. The syntax and meaning of this field will be formally defined at a later date.
[ "Open", "a", "channel", "for", "use" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L402-L430
232,514
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.exchange_declare
def exchange_declare(self, exchange, type, passive=False, durable=False, auto_delete=True, nowait=False, arguments=None): """Declare exchange, create if needed This method creates an exchange if it does not already exist, and if the exchange exists, verifies that it is of the correct and expected class. RULE: The server SHOULD support a minimum of 16 exchanges per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: exchange: shortstr RULE: Exchange names starting with "amq." are reserved for predeclared and standardised exchanges. If the client attempts to create an exchange starting with "amq.", the server MUST raise a channel exception with reply code 403 (access refused). type: shortstr exchange type Each exchange belongs to one of a set of exchange types implemented by the server. The exchange types define the functionality of the exchange - i.e. how messages are routed through it. It is not valid or meaningful to attempt to change the type of an existing exchange. RULE: If the exchange already exists with a different type, the server MUST raise a connection exception with a reply code 507 (not allowed). RULE: If the server does not support the requested exchange type it MUST raise a connection exception with a reply code 503 (command invalid). passive: boolean do not create exchange If set, the server will not create the exchange. The client can use this to check whether an exchange exists without modifying the server state. RULE: If set, and the exchange does not already exist, the server MUST raise a channel exception with reply code 404 (not found). durable: boolean request a durable exchange If set when creating a new exchange, the exchange will be marked as durable. Durable exchanges remain active when a server restarts. Non-durable exchanges (transient exchanges) are purged if/when a server restarts. RULE: The server MUST support both durable and transient exchanges. RULE: The server MUST ignore the durable field if the exchange already exists. auto_delete: boolean auto-delete when unused If set, the exchange is deleted when all queues have finished using it. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that an exchange is not being used (or no longer used), and the point when it deletes the exchange. At the least it must allow a client to create an exchange and then bind a queue to it, with a small but non-zero delay between these two actions. RULE: The server MUST ignore the auto-delete field if the exchange already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True. """ arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(exchange) args.write_shortstr(type) args.write_bit(passive) args.write_bit(durable) args.write_bit(auto_delete) args.write_bit(False) # internal: deprecated args.write_bit(nowait) args.write_table(arguments) self._send_method((40, 10), args) if auto_delete: warn(VDeprecationWarning(EXCHANGE_AUTODELETE_DEPRECATED)) if not nowait: return self.wait(allowed_methods=[ (40, 11), # Channel.exchange_declare_ok ])
python
def exchange_declare(self, exchange, type, passive=False, durable=False, auto_delete=True, nowait=False, arguments=None): """Declare exchange, create if needed This method creates an exchange if it does not already exist, and if the exchange exists, verifies that it is of the correct and expected class. RULE: The server SHOULD support a minimum of 16 exchanges per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: exchange: shortstr RULE: Exchange names starting with "amq." are reserved for predeclared and standardised exchanges. If the client attempts to create an exchange starting with "amq.", the server MUST raise a channel exception with reply code 403 (access refused). type: shortstr exchange type Each exchange belongs to one of a set of exchange types implemented by the server. The exchange types define the functionality of the exchange - i.e. how messages are routed through it. It is not valid or meaningful to attempt to change the type of an existing exchange. RULE: If the exchange already exists with a different type, the server MUST raise a connection exception with a reply code 507 (not allowed). RULE: If the server does not support the requested exchange type it MUST raise a connection exception with a reply code 503 (command invalid). passive: boolean do not create exchange If set, the server will not create the exchange. The client can use this to check whether an exchange exists without modifying the server state. RULE: If set, and the exchange does not already exist, the server MUST raise a channel exception with reply code 404 (not found). durable: boolean request a durable exchange If set when creating a new exchange, the exchange will be marked as durable. Durable exchanges remain active when a server restarts. Non-durable exchanges (transient exchanges) are purged if/when a server restarts. RULE: The server MUST support both durable and transient exchanges. RULE: The server MUST ignore the durable field if the exchange already exists. auto_delete: boolean auto-delete when unused If set, the exchange is deleted when all queues have finished using it. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that an exchange is not being used (or no longer used), and the point when it deletes the exchange. At the least it must allow a client to create an exchange and then bind a queue to it, with a small but non-zero delay between these two actions. RULE: The server MUST ignore the auto-delete field if the exchange already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True. """ arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(exchange) args.write_shortstr(type) args.write_bit(passive) args.write_bit(durable) args.write_bit(auto_delete) args.write_bit(False) # internal: deprecated args.write_bit(nowait) args.write_table(arguments) self._send_method((40, 10), args) if auto_delete: warn(VDeprecationWarning(EXCHANGE_AUTODELETE_DEPRECATED)) if not nowait: return self.wait(allowed_methods=[ (40, 11), # Channel.exchange_declare_ok ])
[ "def", "exchange_declare", "(", "self", ",", "exchange", ",", "type", ",", "passive", "=", "False", ",", "durable", "=", "False", ",", "auto_delete", "=", "True", ",", "nowait", "=", "False", ",", "arguments", "=", "None", ")", ":", "arguments", "=", "{", "}", "if", "arguments", "is", "None", "else", "arguments", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "0", ")", "args", ".", "write_shortstr", "(", "exchange", ")", "args", ".", "write_shortstr", "(", "type", ")", "args", ".", "write_bit", "(", "passive", ")", "args", ".", "write_bit", "(", "durable", ")", "args", ".", "write_bit", "(", "auto_delete", ")", "args", ".", "write_bit", "(", "False", ")", "# internal: deprecated", "args", ".", "write_bit", "(", "nowait", ")", "args", ".", "write_table", "(", "arguments", ")", "self", ".", "_send_method", "(", "(", "40", ",", "10", ")", ",", "args", ")", "if", "auto_delete", ":", "warn", "(", "VDeprecationWarning", "(", "EXCHANGE_AUTODELETE_DEPRECATED", ")", ")", "if", "not", "nowait", ":", "return", "self", ".", "wait", "(", "allowed_methods", "=", "[", "(", "40", ",", "11", ")", ",", "# Channel.exchange_declare_ok", "]", ")" ]
Declare exchange, create if needed This method creates an exchange if it does not already exist, and if the exchange exists, verifies that it is of the correct and expected class. RULE: The server SHOULD support a minimum of 16 exchanges per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: exchange: shortstr RULE: Exchange names starting with "amq." are reserved for predeclared and standardised exchanges. If the client attempts to create an exchange starting with "amq.", the server MUST raise a channel exception with reply code 403 (access refused). type: shortstr exchange type Each exchange belongs to one of a set of exchange types implemented by the server. The exchange types define the functionality of the exchange - i.e. how messages are routed through it. It is not valid or meaningful to attempt to change the type of an existing exchange. RULE: If the exchange already exists with a different type, the server MUST raise a connection exception with a reply code 507 (not allowed). RULE: If the server does not support the requested exchange type it MUST raise a connection exception with a reply code 503 (command invalid). passive: boolean do not create exchange If set, the server will not create the exchange. The client can use this to check whether an exchange exists without modifying the server state. RULE: If set, and the exchange does not already exist, the server MUST raise a channel exception with reply code 404 (not found). durable: boolean request a durable exchange If set when creating a new exchange, the exchange will be marked as durable. Durable exchanges remain active when a server restarts. Non-durable exchanges (transient exchanges) are purged if/when a server restarts. RULE: The server MUST support both durable and transient exchanges. RULE: The server MUST ignore the durable field if the exchange already exists. auto_delete: boolean auto-delete when unused If set, the exchange is deleted when all queues have finished using it. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that an exchange is not being used (or no longer used), and the point when it deletes the exchange. At the least it must allow a client to create an exchange and then bind a queue to it, with a small but non-zero delay between these two actions. RULE: The server MUST ignore the auto-delete field if the exchange already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True.
[ "Declare", "exchange", "create", "if", "needed" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L481-L623
232,515
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.exchange_bind
def exchange_bind(self, destination, source='', routing_key='', nowait=False, arguments=None): """This method binds an exchange to an exchange. RULE: A server MUST allow and ignore duplicate bindings - that is, two or more bind methods for a specific exchanges, with identical arguments - without treating these as an error. RULE: A server MUST allow cycles of exchange bindings to be created including allowing an exchange to be bound to itself. RULE: A server MUST not deliver the same message more than once to a destination exchange, even if the topology of exchanges and bindings results in multiple (even infinite) routes to that exchange. PARAMETERS: reserved-1: short destination: shortstr Specifies the name of the destination exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent destination exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. source: shortstr Specifies the name of the source exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent source exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. routing-key: shortstr Specifies the routing key for the binding. The routing key is used for routing messages depending on the exchange configuration. Not all exchanges use a routing key - refer to the specific exchange documentation. no-wait: bit arguments: table A set of arguments for the binding. The syntax and semantics of these arguments depends on the exchange class. """ arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(destination) args.write_shortstr(source) args.write_shortstr(routing_key) args.write_bit(nowait) args.write_table(arguments) self._send_method((40, 30), args) if not nowait: return self.wait(allowed_methods=[ (40, 31), # Channel.exchange_bind_ok ])
python
def exchange_bind(self, destination, source='', routing_key='', nowait=False, arguments=None): """This method binds an exchange to an exchange. RULE: A server MUST allow and ignore duplicate bindings - that is, two or more bind methods for a specific exchanges, with identical arguments - without treating these as an error. RULE: A server MUST allow cycles of exchange bindings to be created including allowing an exchange to be bound to itself. RULE: A server MUST not deliver the same message more than once to a destination exchange, even if the topology of exchanges and bindings results in multiple (even infinite) routes to that exchange. PARAMETERS: reserved-1: short destination: shortstr Specifies the name of the destination exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent destination exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. source: shortstr Specifies the name of the source exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent source exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. routing-key: shortstr Specifies the routing key for the binding. The routing key is used for routing messages depending on the exchange configuration. Not all exchanges use a routing key - refer to the specific exchange documentation. no-wait: bit arguments: table A set of arguments for the binding. The syntax and semantics of these arguments depends on the exchange class. """ arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(destination) args.write_shortstr(source) args.write_shortstr(routing_key) args.write_bit(nowait) args.write_table(arguments) self._send_method((40, 30), args) if not nowait: return self.wait(allowed_methods=[ (40, 31), # Channel.exchange_bind_ok ])
[ "def", "exchange_bind", "(", "self", ",", "destination", ",", "source", "=", "''", ",", "routing_key", "=", "''", ",", "nowait", "=", "False", ",", "arguments", "=", "None", ")", ":", "arguments", "=", "{", "}", "if", "arguments", "is", "None", "else", "arguments", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "0", ")", "args", ".", "write_shortstr", "(", "destination", ")", "args", ".", "write_shortstr", "(", "source", ")", "args", ".", "write_shortstr", "(", "routing_key", ")", "args", ".", "write_bit", "(", "nowait", ")", "args", ".", "write_table", "(", "arguments", ")", "self", ".", "_send_method", "(", "(", "40", ",", "30", ")", ",", "args", ")", "if", "not", "nowait", ":", "return", "self", ".", "wait", "(", "allowed_methods", "=", "[", "(", "40", ",", "31", ")", ",", "# Channel.exchange_bind_ok", "]", ")" ]
This method binds an exchange to an exchange. RULE: A server MUST allow and ignore duplicate bindings - that is, two or more bind methods for a specific exchanges, with identical arguments - without treating these as an error. RULE: A server MUST allow cycles of exchange bindings to be created including allowing an exchange to be bound to itself. RULE: A server MUST not deliver the same message more than once to a destination exchange, even if the topology of exchanges and bindings results in multiple (even infinite) routes to that exchange. PARAMETERS: reserved-1: short destination: shortstr Specifies the name of the destination exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent destination exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. source: shortstr Specifies the name of the source exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent source exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. routing-key: shortstr Specifies the routing key for the binding. The routing key is used for routing messages depending on the exchange configuration. Not all exchanges use a routing key - refer to the specific exchange documentation. no-wait: bit arguments: table A set of arguments for the binding. The syntax and semantics of these arguments depends on the exchange class.
[ "This", "method", "binds", "an", "exchange", "to", "an", "exchange", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L697-L783
232,516
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.queue_declare
def queue_declare(self, queue='', passive=False, durable=False, exclusive=False, auto_delete=True, nowait=False, arguments=None): """Declare queue, create if needed This method creates or checks a queue. When creating a new queue the client can specify various properties that control the durability of the queue and its contents, and the level of sharing for the queue. RULE: The server MUST create a default binding for a newly- created queue to the default exchange, which is an exchange of type 'direct'. RULE: The server SHOULD support a minimum of 256 queues per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr RULE: The queue name MAY be empty, in which case the server MUST create a new queue with a unique generated name and return this to the client in the Declare-Ok method. RULE: Queue names starting with "amq." are reserved for predeclared and standardised server queues. If the queue name starts with "amq." and the passive option is False, the server MUST raise a connection exception with reply code 403 (access refused). passive: boolean do not create queue If set, the server will not create the queue. The client can use this to check whether a queue exists without modifying the server state. RULE: If set, and the queue does not already exist, the server MUST respond with a reply code 404 (not found) and raise a channel exception. durable: boolean request a durable queue If set when creating a new queue, the queue will be marked as durable. Durable queues remain active when a server restarts. Non-durable queues (transient queues) are purged if/when a server restarts. Note that durable queues do not necessarily hold persistent messages, although it does not make sense to send persistent messages to a transient queue. RULE: The server MUST recreate the durable queue after a restart. RULE: The server MUST support both durable and transient queues. RULE: The server MUST ignore the durable field if the queue already exists. exclusive: boolean request an exclusive queue Exclusive queues may only be consumed from by the current connection. Setting the 'exclusive' flag always implies 'auto-delete'. RULE: The server MUST support both exclusive (private) and non-exclusive (shared) queues. RULE: The server MUST raise a channel exception if 'exclusive' is specified and the queue already exists and is owned by a different connection. auto_delete: boolean auto-delete queue when unused If set, the queue is deleted when all consumers have finished using it. Last consumer can be cancelled either explicitly or because its channel is closed. If there was no consumer ever on the queue, it won't be deleted. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that a queue is not being used (or no longer used), and the point when it deletes the queue. At the least it must allow a client to create a queue and then create a consumer to read from it, with a small but non-zero delay between these two actions. The server should equally allow for clients that may be disconnected prematurely, and wish to re- consume from the same queue without losing messages. We would recommend a configurable timeout, with a suitable default value being one minute. RULE: The server MUST ignore the auto-delete field if the queue already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True. Returns a tuple containing 3 items: the name of the queue (essential for automatically-named queues) message count consumer count """ arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(passive) args.write_bit(durable) args.write_bit(exclusive) args.write_bit(auto_delete) args.write_bit(nowait) args.write_table(arguments) self._send_method((50, 10), args) if not nowait: return self.wait(allowed_methods=[ (50, 11), # Channel.queue_declare_ok ])
python
def queue_declare(self, queue='', passive=False, durable=False, exclusive=False, auto_delete=True, nowait=False, arguments=None): """Declare queue, create if needed This method creates or checks a queue. When creating a new queue the client can specify various properties that control the durability of the queue and its contents, and the level of sharing for the queue. RULE: The server MUST create a default binding for a newly- created queue to the default exchange, which is an exchange of type 'direct'. RULE: The server SHOULD support a minimum of 256 queues per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr RULE: The queue name MAY be empty, in which case the server MUST create a new queue with a unique generated name and return this to the client in the Declare-Ok method. RULE: Queue names starting with "amq." are reserved for predeclared and standardised server queues. If the queue name starts with "amq." and the passive option is False, the server MUST raise a connection exception with reply code 403 (access refused). passive: boolean do not create queue If set, the server will not create the queue. The client can use this to check whether a queue exists without modifying the server state. RULE: If set, and the queue does not already exist, the server MUST respond with a reply code 404 (not found) and raise a channel exception. durable: boolean request a durable queue If set when creating a new queue, the queue will be marked as durable. Durable queues remain active when a server restarts. Non-durable queues (transient queues) are purged if/when a server restarts. Note that durable queues do not necessarily hold persistent messages, although it does not make sense to send persistent messages to a transient queue. RULE: The server MUST recreate the durable queue after a restart. RULE: The server MUST support both durable and transient queues. RULE: The server MUST ignore the durable field if the queue already exists. exclusive: boolean request an exclusive queue Exclusive queues may only be consumed from by the current connection. Setting the 'exclusive' flag always implies 'auto-delete'. RULE: The server MUST support both exclusive (private) and non-exclusive (shared) queues. RULE: The server MUST raise a channel exception if 'exclusive' is specified and the queue already exists and is owned by a different connection. auto_delete: boolean auto-delete queue when unused If set, the queue is deleted when all consumers have finished using it. Last consumer can be cancelled either explicitly or because its channel is closed. If there was no consumer ever on the queue, it won't be deleted. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that a queue is not being used (or no longer used), and the point when it deletes the queue. At the least it must allow a client to create a queue and then create a consumer to read from it, with a small but non-zero delay between these two actions. The server should equally allow for clients that may be disconnected prematurely, and wish to re- consume from the same queue without losing messages. We would recommend a configurable timeout, with a suitable default value being one minute. RULE: The server MUST ignore the auto-delete field if the queue already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True. Returns a tuple containing 3 items: the name of the queue (essential for automatically-named queues) message count consumer count """ arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(passive) args.write_bit(durable) args.write_bit(exclusive) args.write_bit(auto_delete) args.write_bit(nowait) args.write_table(arguments) self._send_method((50, 10), args) if not nowait: return self.wait(allowed_methods=[ (50, 11), # Channel.queue_declare_ok ])
[ "def", "queue_declare", "(", "self", ",", "queue", "=", "''", ",", "passive", "=", "False", ",", "durable", "=", "False", ",", "exclusive", "=", "False", ",", "auto_delete", "=", "True", ",", "nowait", "=", "False", ",", "arguments", "=", "None", ")", ":", "arguments", "=", "{", "}", "if", "arguments", "is", "None", "else", "arguments", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "0", ")", "args", ".", "write_shortstr", "(", "queue", ")", "args", ".", "write_bit", "(", "passive", ")", "args", ".", "write_bit", "(", "durable", ")", "args", ".", "write_bit", "(", "exclusive", ")", "args", ".", "write_bit", "(", "auto_delete", ")", "args", ".", "write_bit", "(", "nowait", ")", "args", ".", "write_table", "(", "arguments", ")", "self", ".", "_send_method", "(", "(", "50", ",", "10", ")", ",", "args", ")", "if", "not", "nowait", ":", "return", "self", ".", "wait", "(", "allowed_methods", "=", "[", "(", "50", ",", "11", ")", ",", "# Channel.queue_declare_ok", "]", ")" ]
Declare queue, create if needed This method creates or checks a queue. When creating a new queue the client can specify various properties that control the durability of the queue and its contents, and the level of sharing for the queue. RULE: The server MUST create a default binding for a newly- created queue to the default exchange, which is an exchange of type 'direct'. RULE: The server SHOULD support a minimum of 256 queues per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr RULE: The queue name MAY be empty, in which case the server MUST create a new queue with a unique generated name and return this to the client in the Declare-Ok method. RULE: Queue names starting with "amq." are reserved for predeclared and standardised server queues. If the queue name starts with "amq." and the passive option is False, the server MUST raise a connection exception with reply code 403 (access refused). passive: boolean do not create queue If set, the server will not create the queue. The client can use this to check whether a queue exists without modifying the server state. RULE: If set, and the queue does not already exist, the server MUST respond with a reply code 404 (not found) and raise a channel exception. durable: boolean request a durable queue If set when creating a new queue, the queue will be marked as durable. Durable queues remain active when a server restarts. Non-durable queues (transient queues) are purged if/when a server restarts. Note that durable queues do not necessarily hold persistent messages, although it does not make sense to send persistent messages to a transient queue. RULE: The server MUST recreate the durable queue after a restart. RULE: The server MUST support both durable and transient queues. RULE: The server MUST ignore the durable field if the queue already exists. exclusive: boolean request an exclusive queue Exclusive queues may only be consumed from by the current connection. Setting the 'exclusive' flag always implies 'auto-delete'. RULE: The server MUST support both exclusive (private) and non-exclusive (shared) queues. RULE: The server MUST raise a channel exception if 'exclusive' is specified and the queue already exists and is owned by a different connection. auto_delete: boolean auto-delete queue when unused If set, the queue is deleted when all consumers have finished using it. Last consumer can be cancelled either explicitly or because its channel is closed. If there was no consumer ever on the queue, it won't be deleted. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that a queue is not being used (or no longer used), and the point when it deletes the queue. At the least it must allow a client to create a queue and then create a consumer to read from it, with a small but non-zero delay between these two actions. The server should equally allow for clients that may be disconnected prematurely, and wish to re- consume from the same queue without losing messages. We would recommend a configurable timeout, with a suitable default value being one minute. RULE: The server MUST ignore the auto-delete field if the queue already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True. Returns a tuple containing 3 items: the name of the queue (essential for automatically-named queues) message count consumer count
[ "Declare", "queue", "create", "if", "needed" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1090-L1260
232,517
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._queue_declare_ok
def _queue_declare_ok(self, args): """Confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this field contains that name. message_count: long number of messages in queue Reports the number of messages in the queue, which will be zero for newly-created queues. consumer_count: long number of consumers Reports the number of active consumers for the queue. Note that consumers can suspend activity (Channel.Flow) in which case they do not appear in this count. """ return queue_declare_ok_t( args.read_shortstr(), args.read_long(), args.read_long(), )
python
def _queue_declare_ok(self, args): """Confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this field contains that name. message_count: long number of messages in queue Reports the number of messages in the queue, which will be zero for newly-created queues. consumer_count: long number of consumers Reports the number of active consumers for the queue. Note that consumers can suspend activity (Channel.Flow) in which case they do not appear in this count. """ return queue_declare_ok_t( args.read_shortstr(), args.read_long(), args.read_long(), )
[ "def", "_queue_declare_ok", "(", "self", ",", "args", ")", ":", "return", "queue_declare_ok_t", "(", "args", ".", "read_shortstr", "(", ")", ",", "args", ".", "read_long", "(", ")", ",", "args", ".", "read_long", "(", ")", ",", ")" ]
Confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this field contains that name. message_count: long number of messages in queue Reports the number of messages in the queue, which will be zero for newly-created queues. consumer_count: long number of consumers Reports the number of active consumers for the queue. Note that consumers can suspend activity (Channel.Flow) in which case they do not appear in this count.
[ "Confirms", "a", "queue", "definition" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1262-L1295
232,518
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.queue_delete
def queue_delete(self, queue='', if_unused=False, if_empty=False, nowait=False): """Delete a queue This method deletes a queue. When a queue is deleted any pending messages are sent to a dead-letter queue if this is defined in the server configuration, and all consumers on the queue are cancelled. RULE: The server SHOULD use a dead-letter queue to hold messages that were pending on a deleted queue, and MAY provide facilities for a system administrator to move these messages back to an active queue. PARAMETERS: queue: shortstr Specifies the name of the queue to delete. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to delete a non- existing queue causes a channel exception. if_unused: boolean delete only if unused If set, the server will only delete the queue if it has no consumers. If the queue has consumers the server does does not delete it but raises a channel exception instead. RULE: The server MUST respect the if-unused flag when deleting a queue. if_empty: boolean delete only if empty If set, the server will only delete the queue if it has no messages. If the queue is not empty the server raises a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. """ args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(if_unused) args.write_bit(if_empty) args.write_bit(nowait) self._send_method((50, 40), args) if not nowait: return self.wait(allowed_methods=[ (50, 41), # Channel.queue_delete_ok ])
python
def queue_delete(self, queue='', if_unused=False, if_empty=False, nowait=False): """Delete a queue This method deletes a queue. When a queue is deleted any pending messages are sent to a dead-letter queue if this is defined in the server configuration, and all consumers on the queue are cancelled. RULE: The server SHOULD use a dead-letter queue to hold messages that were pending on a deleted queue, and MAY provide facilities for a system administrator to move these messages back to an active queue. PARAMETERS: queue: shortstr Specifies the name of the queue to delete. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to delete a non- existing queue causes a channel exception. if_unused: boolean delete only if unused If set, the server will only delete the queue if it has no consumers. If the queue has consumers the server does does not delete it but raises a channel exception instead. RULE: The server MUST respect the if-unused flag when deleting a queue. if_empty: boolean delete only if empty If set, the server will only delete the queue if it has no messages. If the queue is not empty the server raises a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. """ args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(if_unused) args.write_bit(if_empty) args.write_bit(nowait) self._send_method((50, 40), args) if not nowait: return self.wait(allowed_methods=[ (50, 41), # Channel.queue_delete_ok ])
[ "def", "queue_delete", "(", "self", ",", "queue", "=", "''", ",", "if_unused", "=", "False", ",", "if_empty", "=", "False", ",", "nowait", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "0", ")", "args", ".", "write_shortstr", "(", "queue", ")", "args", ".", "write_bit", "(", "if_unused", ")", "args", ".", "write_bit", "(", "if_empty", ")", "args", ".", "write_bit", "(", "nowait", ")", "self", ".", "_send_method", "(", "(", "50", ",", "40", ")", ",", "args", ")", "if", "not", "nowait", ":", "return", "self", ".", "wait", "(", "allowed_methods", "=", "[", "(", "50", ",", "41", ")", ",", "# Channel.queue_delete_ok", "]", ")" ]
Delete a queue This method deletes a queue. When a queue is deleted any pending messages are sent to a dead-letter queue if this is defined in the server configuration, and all consumers on the queue are cancelled. RULE: The server SHOULD use a dead-letter queue to hold messages that were pending on a deleted queue, and MAY provide facilities for a system administrator to move these messages back to an active queue. PARAMETERS: queue: shortstr Specifies the name of the queue to delete. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to delete a non- existing queue causes a channel exception. if_unused: boolean delete only if unused If set, the server will only delete the queue if it has no consumers. If the queue has consumers the server does does not delete it but raises a channel exception instead. RULE: The server MUST respect the if-unused flag when deleting a queue. if_empty: boolean delete only if empty If set, the server will only delete the queue if it has no messages. If the queue is not empty the server raises a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception.
[ "Delete", "a", "queue" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1297-L1375
232,519
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.queue_purge
def queue_purge(self, queue='', nowait=False): """Purge a queue This method removes all messages from a queue. It does not cancel consumers. Purged messages are deleted without any formal "undo" mechanism. RULE: A call to purge MUST result in an empty queue. RULE: On transacted channels the server MUST not purge messages that have already been sent to a client but not yet acknowledged. RULE: The server MAY implement a purge queue or log that allows system administrators to recover accidentally-purged messages. The server SHOULD NOT keep purged messages in the same storage spaces as the live messages since the volumes of purged messages may get very large. PARAMETERS: queue: shortstr Specifies the name of the queue to purge. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to purge a non- existing queue causes a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. if nowait is False, returns a message_count """ args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(nowait) self._send_method((50, 30), args) if not nowait: return self.wait(allowed_methods=[ (50, 31), # Channel.queue_purge_ok ])
python
def queue_purge(self, queue='', nowait=False): """Purge a queue This method removes all messages from a queue. It does not cancel consumers. Purged messages are deleted without any formal "undo" mechanism. RULE: A call to purge MUST result in an empty queue. RULE: On transacted channels the server MUST not purge messages that have already been sent to a client but not yet acknowledged. RULE: The server MAY implement a purge queue or log that allows system administrators to recover accidentally-purged messages. The server SHOULD NOT keep purged messages in the same storage spaces as the live messages since the volumes of purged messages may get very large. PARAMETERS: queue: shortstr Specifies the name of the queue to purge. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to purge a non- existing queue causes a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. if nowait is False, returns a message_count """ args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(nowait) self._send_method((50, 30), args) if not nowait: return self.wait(allowed_methods=[ (50, 31), # Channel.queue_purge_ok ])
[ "def", "queue_purge", "(", "self", ",", "queue", "=", "''", ",", "nowait", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "0", ")", "args", ".", "write_shortstr", "(", "queue", ")", "args", ".", "write_bit", "(", "nowait", ")", "self", ".", "_send_method", "(", "(", "50", ",", "30", ")", ",", "args", ")", "if", "not", "nowait", ":", "return", "self", ".", "wait", "(", "allowed_methods", "=", "[", "(", "50", ",", "31", ")", ",", "# Channel.queue_purge_ok", "]", ")" ]
Purge a queue This method removes all messages from a queue. It does not cancel consumers. Purged messages are deleted without any formal "undo" mechanism. RULE: A call to purge MUST result in an empty queue. RULE: On transacted channels the server MUST not purge messages that have already been sent to a client but not yet acknowledged. RULE: The server MAY implement a purge queue or log that allows system administrators to recover accidentally-purged messages. The server SHOULD NOT keep purged messages in the same storage spaces as the live messages since the volumes of purged messages may get very large. PARAMETERS: queue: shortstr Specifies the name of the queue to purge. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to purge a non- existing queue causes a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. if nowait is False, returns a message_count
[ "Purge", "a", "queue" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1392-L1457
232,520
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_ack
def basic_ack(self, delivery_tag, multiple=False): """Acknowledge one or more messages This method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. The client can ask to confirm a single message or a set of messages up to and including a specific message. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". multiple: boolean acknowledge multiple messages If set to True, the delivery tag is treated as "up to and including", so that the client can acknowledge multiple messages with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is True, and the delivery tag is zero, tells the server to acknowledge all outstanding mesages. RULE: The server MUST validate that a non-zero delivery- tag refers to an delivered message, and raise a channel exception if this is not the case. """ args = AMQPWriter() args.write_longlong(delivery_tag) args.write_bit(multiple) self._send_method((60, 80), args)
python
def basic_ack(self, delivery_tag, multiple=False): """Acknowledge one or more messages This method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. The client can ask to confirm a single message or a set of messages up to and including a specific message. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". multiple: boolean acknowledge multiple messages If set to True, the delivery tag is treated as "up to and including", so that the client can acknowledge multiple messages with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is True, and the delivery tag is zero, tells the server to acknowledge all outstanding mesages. RULE: The server MUST validate that a non-zero delivery- tag refers to an delivered message, and raise a channel exception if this is not the case. """ args = AMQPWriter() args.write_longlong(delivery_tag) args.write_bit(multiple) self._send_method((60, 80), args)
[ "def", "basic_ack", "(", "self", ",", "delivery_tag", ",", "multiple", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_longlong", "(", "delivery_tag", ")", "args", ".", "write_bit", "(", "multiple", ")", "self", ".", "_send_method", "(", "(", "60", ",", "80", ")", ",", "args", ")" ]
Acknowledge one or more messages This method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. The client can ask to confirm a single message or a set of messages up to and including a specific message. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". multiple: boolean acknowledge multiple messages If set to True, the delivery tag is treated as "up to and including", so that the client can acknowledge multiple messages with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is True, and the delivery tag is zero, tells the server to acknowledge all outstanding mesages. RULE: The server MUST validate that a non-zero delivery- tag refers to an delivered message, and raise a channel exception if this is not the case.
[ "Acknowledge", "one", "or", "more", "messages" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1534-L1584
232,521
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_cancel
def basic_cancel(self, consumer_tag, nowait=False): """End a queue consumer This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an abitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. RULE: If the queue no longer exists when the client sends a cancel command, or the consumer has been cancelled for other reasons, this command has no effect. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. """ if self.connection is not None: self.no_ack_consumers.discard(consumer_tag) args = AMQPWriter() args.write_shortstr(consumer_tag) args.write_bit(nowait) self._send_method((60, 30), args) return self.wait(allowed_methods=[ (60, 31), # Channel.basic_cancel_ok ])
python
def basic_cancel(self, consumer_tag, nowait=False): """End a queue consumer This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an abitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. RULE: If the queue no longer exists when the client sends a cancel command, or the consumer has been cancelled for other reasons, this command has no effect. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. """ if self.connection is not None: self.no_ack_consumers.discard(consumer_tag) args = AMQPWriter() args.write_shortstr(consumer_tag) args.write_bit(nowait) self._send_method((60, 30), args) return self.wait(allowed_methods=[ (60, 31), # Channel.basic_cancel_ok ])
[ "def", "basic_cancel", "(", "self", ",", "consumer_tag", ",", "nowait", "=", "False", ")", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "self", ".", "no_ack_consumers", ".", "discard", "(", "consumer_tag", ")", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_shortstr", "(", "consumer_tag", ")", "args", ".", "write_bit", "(", "nowait", ")", "self", ".", "_send_method", "(", "(", "60", ",", "30", ")", ",", "args", ")", "return", "self", ".", "wait", "(", "allowed_methods", "=", "[", "(", "60", ",", "31", ")", ",", "# Channel.basic_cancel_ok", "]", ")" ]
End a queue consumer This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an abitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. RULE: If the queue no longer exists when the client sends a cancel command, or the consumer has been cancelled for other reasons, this command has no effect. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception.
[ "End", "a", "queue", "consumer" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1586-L1634
232,522
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_cancel_notify
def _basic_cancel_notify(self, args): """Consumer cancelled by server. Most likely the queue was deleted. """ consumer_tag = args.read_shortstr() callback = self._on_cancel(consumer_tag) if callback: callback(consumer_tag) else: raise ConsumerCancelled(consumer_tag, (60, 30))
python
def _basic_cancel_notify(self, args): """Consumer cancelled by server. Most likely the queue was deleted. """ consumer_tag = args.read_shortstr() callback = self._on_cancel(consumer_tag) if callback: callback(consumer_tag) else: raise ConsumerCancelled(consumer_tag, (60, 30))
[ "def", "_basic_cancel_notify", "(", "self", ",", "args", ")", ":", "consumer_tag", "=", "args", ".", "read_shortstr", "(", ")", "callback", "=", "self", ".", "_on_cancel", "(", "consumer_tag", ")", "if", "callback", ":", "callback", "(", "consumer_tag", ")", "else", ":", "raise", "ConsumerCancelled", "(", "consumer_tag", ",", "(", "60", ",", "30", ")", ")" ]
Consumer cancelled by server. Most likely the queue was deleted.
[ "Consumer", "cancelled", "by", "server", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1636-L1647
232,523
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_consume
def basic_consume(self, queue='', consumer_tag='', no_local=False, no_ack=False, exclusive=False, nowait=False, callback=None, arguments=None, on_cancel=None): """Start a queue consumer This method asks the server to start a "consumer", which is a transient request for messages from a specific queue. Consumers last as long as the channel they were created on, or until the client cancels them. RULE: The server SHOULD support at least 16 consumers per queue, unless the queue was declared as private, and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr Specifies the name of the queue to consume from. If the queue name is null, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). consumer_tag: shortstr Specifies the identifier for the consumer. The consumer tag is local to a connection, so two clients can use the same consumer tags. If this field is empty the server will generate a unique tag. RULE: The tag MUST NOT refer to an existing consumer. If the client attempts to create two consumers with the same non-empty tag the server MUST raise a connection exception with reply code 530 (not allowed). no_local: boolean do not deliver own messages If the no-local field is set the server will not send messages to the client that published them. no_ack: boolean no acknowledgement needed If this field is set the server does not expect acknowledgments for messages. That is, when a message is delivered to the client the server automatically and silently acknowledges it on behalf of the client. This functionality increases performance but at the cost of reliability. Messages can get lost if a client dies before it can deliver them to the application. exclusive: boolean request exclusive access Request exclusive consumer access, meaning only this consumer can access the queue. RULE: If the server cannot grant exclusive access to the queue when asked, - because there are other consumers active - it MUST raise a channel exception with return code 403 (access refused). nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. callback: Python callable function/method called with each delivered message For each message delivered by the broker, the callable will be called with a Message object as the single argument. If no callable is specified, messages are quietly discarded, no_ack should probably be set to True in that case. """ args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_shortstr(consumer_tag) args.write_bit(no_local) args.write_bit(no_ack) args.write_bit(exclusive) args.write_bit(nowait) args.write_table(arguments or {}) self._send_method((60, 20), args) if not nowait: consumer_tag = self.wait(allowed_methods=[ (60, 21), # Channel.basic_consume_ok ]) self.callbacks[consumer_tag] = callback if on_cancel: self.cancel_callbacks[consumer_tag] = on_cancel if no_ack: self.no_ack_consumers.add(consumer_tag) return consumer_tag
python
def basic_consume(self, queue='', consumer_tag='', no_local=False, no_ack=False, exclusive=False, nowait=False, callback=None, arguments=None, on_cancel=None): """Start a queue consumer This method asks the server to start a "consumer", which is a transient request for messages from a specific queue. Consumers last as long as the channel they were created on, or until the client cancels them. RULE: The server SHOULD support at least 16 consumers per queue, unless the queue was declared as private, and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr Specifies the name of the queue to consume from. If the queue name is null, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). consumer_tag: shortstr Specifies the identifier for the consumer. The consumer tag is local to a connection, so two clients can use the same consumer tags. If this field is empty the server will generate a unique tag. RULE: The tag MUST NOT refer to an existing consumer. If the client attempts to create two consumers with the same non-empty tag the server MUST raise a connection exception with reply code 530 (not allowed). no_local: boolean do not deliver own messages If the no-local field is set the server will not send messages to the client that published them. no_ack: boolean no acknowledgement needed If this field is set the server does not expect acknowledgments for messages. That is, when a message is delivered to the client the server automatically and silently acknowledges it on behalf of the client. This functionality increases performance but at the cost of reliability. Messages can get lost if a client dies before it can deliver them to the application. exclusive: boolean request exclusive access Request exclusive consumer access, meaning only this consumer can access the queue. RULE: If the server cannot grant exclusive access to the queue when asked, - because there are other consumers active - it MUST raise a channel exception with return code 403 (access refused). nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. callback: Python callable function/method called with each delivered message For each message delivered by the broker, the callable will be called with a Message object as the single argument. If no callable is specified, messages are quietly discarded, no_ack should probably be set to True in that case. """ args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_shortstr(consumer_tag) args.write_bit(no_local) args.write_bit(no_ack) args.write_bit(exclusive) args.write_bit(nowait) args.write_table(arguments or {}) self._send_method((60, 20), args) if not nowait: consumer_tag = self.wait(allowed_methods=[ (60, 21), # Channel.basic_consume_ok ]) self.callbacks[consumer_tag] = callback if on_cancel: self.cancel_callbacks[consumer_tag] = on_cancel if no_ack: self.no_ack_consumers.add(consumer_tag) return consumer_tag
[ "def", "basic_consume", "(", "self", ",", "queue", "=", "''", ",", "consumer_tag", "=", "''", ",", "no_local", "=", "False", ",", "no_ack", "=", "False", ",", "exclusive", "=", "False", ",", "nowait", "=", "False", ",", "callback", "=", "None", ",", "arguments", "=", "None", ",", "on_cancel", "=", "None", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "0", ")", "args", ".", "write_shortstr", "(", "queue", ")", "args", ".", "write_shortstr", "(", "consumer_tag", ")", "args", ".", "write_bit", "(", "no_local", ")", "args", ".", "write_bit", "(", "no_ack", ")", "args", ".", "write_bit", "(", "exclusive", ")", "args", ".", "write_bit", "(", "nowait", ")", "args", ".", "write_table", "(", "arguments", "or", "{", "}", ")", "self", ".", "_send_method", "(", "(", "60", ",", "20", ")", ",", "args", ")", "if", "not", "nowait", ":", "consumer_tag", "=", "self", ".", "wait", "(", "allowed_methods", "=", "[", "(", "60", ",", "21", ")", ",", "# Channel.basic_consume_ok", "]", ")", "self", ".", "callbacks", "[", "consumer_tag", "]", "=", "callback", "if", "on_cancel", ":", "self", ".", "cancel_callbacks", "[", "consumer_tag", "]", "=", "on_cancel", "if", "no_ack", ":", "self", ".", "no_ack_consumers", ".", "add", "(", "consumer_tag", ")", "return", "consumer_tag" ]
Start a queue consumer This method asks the server to start a "consumer", which is a transient request for messages from a specific queue. Consumers last as long as the channel they were created on, or until the client cancels them. RULE: The server SHOULD support at least 16 consumers per queue, unless the queue was declared as private, and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr Specifies the name of the queue to consume from. If the queue name is null, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). consumer_tag: shortstr Specifies the identifier for the consumer. The consumer tag is local to a connection, so two clients can use the same consumer tags. If this field is empty the server will generate a unique tag. RULE: The tag MUST NOT refer to an existing consumer. If the client attempts to create two consumers with the same non-empty tag the server MUST raise a connection exception with reply code 530 (not allowed). no_local: boolean do not deliver own messages If the no-local field is set the server will not send messages to the client that published them. no_ack: boolean no acknowledgement needed If this field is set the server does not expect acknowledgments for messages. That is, when a message is delivered to the client the server automatically and silently acknowledges it on behalf of the client. This functionality increases performance but at the cost of reliability. Messages can get lost if a client dies before it can deliver them to the application. exclusive: boolean request exclusive access Request exclusive consumer access, meaning only this consumer can access the queue. RULE: If the server cannot grant exclusive access to the queue when asked, - because there are other consumers active - it MUST raise a channel exception with return code 403 (access refused). nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. callback: Python callable function/method called with each delivered message For each message delivered by the broker, the callable will be called with a Message object as the single argument. If no callable is specified, messages are quietly discarded, no_ack should probably be set to True in that case.
[ "Start", "a", "queue", "consumer" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1677-L1798
232,524
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_deliver
def _basic_deliver(self, args, msg): """Notify the client of a consumer message This method delivers a message to the client, via a consumer. In the asynchronous message delivery model, the client starts a consumer using the Consume method, then the server responds with Deliver methods as and when messages arrive for that consumer. RULE: The server SHOULD track the number of times a message has been delivered to clients and when a message is redelivered a certain number of times - e.g. 5 times - without being acknowledged, the server SHOULD consider the message to be unprocessable (possibly causing client applications to abort), and move the message to a dead letter queue. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. """ consumer_tag = args.read_shortstr() delivery_tag = args.read_longlong() redelivered = args.read_bit() exchange = args.read_shortstr() routing_key = args.read_shortstr() msg.channel = self msg.delivery_info = { 'consumer_tag': consumer_tag, 'delivery_tag': delivery_tag, 'redelivered': redelivered, 'exchange': exchange, 'routing_key': routing_key, } try: fun = self.callbacks[consumer_tag] except KeyError: pass else: fun(msg)
python
def _basic_deliver(self, args, msg): """Notify the client of a consumer message This method delivers a message to the client, via a consumer. In the asynchronous message delivery model, the client starts a consumer using the Consume method, then the server responds with Deliver methods as and when messages arrive for that consumer. RULE: The server SHOULD track the number of times a message has been delivered to clients and when a message is redelivered a certain number of times - e.g. 5 times - without being acknowledged, the server SHOULD consider the message to be unprocessable (possibly causing client applications to abort), and move the message to a dead letter queue. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. """ consumer_tag = args.read_shortstr() delivery_tag = args.read_longlong() redelivered = args.read_bit() exchange = args.read_shortstr() routing_key = args.read_shortstr() msg.channel = self msg.delivery_info = { 'consumer_tag': consumer_tag, 'delivery_tag': delivery_tag, 'redelivered': redelivered, 'exchange': exchange, 'routing_key': routing_key, } try: fun = self.callbacks[consumer_tag] except KeyError: pass else: fun(msg)
[ "def", "_basic_deliver", "(", "self", ",", "args", ",", "msg", ")", ":", "consumer_tag", "=", "args", ".", "read_shortstr", "(", ")", "delivery_tag", "=", "args", ".", "read_longlong", "(", ")", "redelivered", "=", "args", ".", "read_bit", "(", ")", "exchange", "=", "args", ".", "read_shortstr", "(", ")", "routing_key", "=", "args", ".", "read_shortstr", "(", ")", "msg", ".", "channel", "=", "self", "msg", ".", "delivery_info", "=", "{", "'consumer_tag'", ":", "consumer_tag", ",", "'delivery_tag'", ":", "delivery_tag", ",", "'redelivered'", ":", "redelivered", ",", "'exchange'", ":", "exchange", ",", "'routing_key'", ":", "routing_key", ",", "}", "try", ":", "fun", "=", "self", ".", "callbacks", "[", "consumer_tag", "]", "except", "KeyError", ":", "pass", "else", ":", "fun", "(", "msg", ")" ]
Notify the client of a consumer message This method delivers a message to the client, via a consumer. In the asynchronous message delivery model, the client starts a consumer using the Consume method, then the server responds with Deliver methods as and when messages arrive for that consumer. RULE: The server SHOULD track the number of times a message has been delivered to clients and when a message is redelivered a certain number of times - e.g. 5 times - without being acknowledged, the server SHOULD consider the message to be unprocessable (possibly causing client applications to abort), and move the message to a dead letter queue. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published.
[ "Notify", "the", "client", "of", "a", "consumer", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1816-L1909
232,525
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_get_ok
def _basic_get_ok(self, args, msg): """Provide client with a message This method delivers a message to the client following a get method. A message delivered by 'get-ok' must be acknowledged unless the no-ack option was set in the get method. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. If empty, the message was published to the default exchange. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. message_count: long number of messages pending This field reports the number of messages pending on the queue, excluding the message being delivered. Note that this figure is indicative, not reliable, and can change arbitrarily as messages are added to the queue and removed by other clients. """ delivery_tag = args.read_longlong() redelivered = args.read_bit() exchange = args.read_shortstr() routing_key = args.read_shortstr() message_count = args.read_long() msg.channel = self msg.delivery_info = { 'delivery_tag': delivery_tag, 'redelivered': redelivered, 'exchange': exchange, 'routing_key': routing_key, 'message_count': message_count } return msg
python
def _basic_get_ok(self, args, msg): """Provide client with a message This method delivers a message to the client following a get method. A message delivered by 'get-ok' must be acknowledged unless the no-ack option was set in the get method. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. If empty, the message was published to the default exchange. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. message_count: long number of messages pending This field reports the number of messages pending on the queue, excluding the message being delivered. Note that this figure is indicative, not reliable, and can change arbitrarily as messages are added to the queue and removed by other clients. """ delivery_tag = args.read_longlong() redelivered = args.read_bit() exchange = args.read_shortstr() routing_key = args.read_shortstr() message_count = args.read_long() msg.channel = self msg.delivery_info = { 'delivery_tag': delivery_tag, 'redelivered': redelivered, 'exchange': exchange, 'routing_key': routing_key, 'message_count': message_count } return msg
[ "def", "_basic_get_ok", "(", "self", ",", "args", ",", "msg", ")", ":", "delivery_tag", "=", "args", ".", "read_longlong", "(", ")", "redelivered", "=", "args", ".", "read_bit", "(", ")", "exchange", "=", "args", ".", "read_shortstr", "(", ")", "routing_key", "=", "args", ".", "read_shortstr", "(", ")", "message_count", "=", "args", ".", "read_long", "(", ")", "msg", ".", "channel", "=", "self", "msg", ".", "delivery_info", "=", "{", "'delivery_tag'", ":", "delivery_tag", ",", "'redelivered'", ":", "redelivered", ",", "'exchange'", ":", "exchange", ",", "'routing_key'", ":", "routing_key", ",", "'message_count'", ":", "message_count", "}", "return", "msg" ]
Provide client with a message This method delivers a message to the client following a get method. A message delivered by 'get-ok' must be acknowledged unless the no-ack option was set in the get method. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. If empty, the message was published to the default exchange. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. message_count: long number of messages pending This field reports the number of messages pending on the queue, excluding the message being delivered. Note that this figure is indicative, not reliable, and can change arbitrarily as messages are added to the queue and removed by other clients.
[ "Provide", "client", "with", "a", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1975-L2047
232,526
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_publish
def _basic_publish(self, msg, exchange='', routing_key='', mandatory=False, immediate=False): """Publish a message This method publishes a message to a specific exchange. The message will be routed to queues as defined by the exchange configuration and distributed to any active consumers when the transaction, if any, is committed. PARAMETERS: exchange: shortstr Specifies the name of the exchange to publish to. The exchange name can be empty, meaning the default exchange. If the exchange name is specified, and that exchange does not exist, the server will raise a channel exception. RULE: The server MUST accept a blank exchange name to mean the default exchange. RULE: The exchange MAY refuse basic content in which case it MUST raise a channel exception with reply code 540 (not implemented). routing_key: shortstr Message routing key Specifies the routing key for the message. The routing key is used for routing messages depending on the exchange configuration. mandatory: boolean indicate mandatory routing This flag tells the server how to react if the message cannot be routed to a queue. If this flag is True, the server will return an unroutable message with a Return method. If this flag is False, the server silently drops the message. RULE: The server SHOULD implement the mandatory flag. immediate: boolean request immediate delivery This flag tells the server how to react if the message cannot be routed to a queue consumer immediately. If this flag is set, the server will return an undeliverable message with a Return method. If this flag is zero, the server will queue the message, but with no guarantee that it will ever be consumed. RULE: The server SHOULD implement the immediate flag. """ args = AMQPWriter() args.write_short(0) args.write_shortstr(exchange) args.write_shortstr(routing_key) args.write_bit(mandatory) args.write_bit(immediate) self._send_method((60, 40), args, msg)
python
def _basic_publish(self, msg, exchange='', routing_key='', mandatory=False, immediate=False): """Publish a message This method publishes a message to a specific exchange. The message will be routed to queues as defined by the exchange configuration and distributed to any active consumers when the transaction, if any, is committed. PARAMETERS: exchange: shortstr Specifies the name of the exchange to publish to. The exchange name can be empty, meaning the default exchange. If the exchange name is specified, and that exchange does not exist, the server will raise a channel exception. RULE: The server MUST accept a blank exchange name to mean the default exchange. RULE: The exchange MAY refuse basic content in which case it MUST raise a channel exception with reply code 540 (not implemented). routing_key: shortstr Message routing key Specifies the routing key for the message. The routing key is used for routing messages depending on the exchange configuration. mandatory: boolean indicate mandatory routing This flag tells the server how to react if the message cannot be routed to a queue. If this flag is True, the server will return an unroutable message with a Return method. If this flag is False, the server silently drops the message. RULE: The server SHOULD implement the mandatory flag. immediate: boolean request immediate delivery This flag tells the server how to react if the message cannot be routed to a queue consumer immediately. If this flag is set, the server will return an undeliverable message with a Return method. If this flag is zero, the server will queue the message, but with no guarantee that it will ever be consumed. RULE: The server SHOULD implement the immediate flag. """ args = AMQPWriter() args.write_short(0) args.write_shortstr(exchange) args.write_shortstr(routing_key) args.write_bit(mandatory) args.write_bit(immediate) self._send_method((60, 40), args, msg)
[ "def", "_basic_publish", "(", "self", ",", "msg", ",", "exchange", "=", "''", ",", "routing_key", "=", "''", ",", "mandatory", "=", "False", ",", "immediate", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "0", ")", "args", ".", "write_shortstr", "(", "exchange", ")", "args", ".", "write_shortstr", "(", "routing_key", ")", "args", ".", "write_bit", "(", "mandatory", ")", "args", ".", "write_bit", "(", "immediate", ")", "self", ".", "_send_method", "(", "(", "60", ",", "40", ")", ",", "args", ",", "msg", ")" ]
Publish a message This method publishes a message to a specific exchange. The message will be routed to queues as defined by the exchange configuration and distributed to any active consumers when the transaction, if any, is committed. PARAMETERS: exchange: shortstr Specifies the name of the exchange to publish to. The exchange name can be empty, meaning the default exchange. If the exchange name is specified, and that exchange does not exist, the server will raise a channel exception. RULE: The server MUST accept a blank exchange name to mean the default exchange. RULE: The exchange MAY refuse basic content in which case it MUST raise a channel exception with reply code 540 (not implemented). routing_key: shortstr Message routing key Specifies the routing key for the message. The routing key is used for routing messages depending on the exchange configuration. mandatory: boolean indicate mandatory routing This flag tells the server how to react if the message cannot be routed to a queue. If this flag is True, the server will return an unroutable message with a Return method. If this flag is False, the server silently drops the message. RULE: The server SHOULD implement the mandatory flag. immediate: boolean request immediate delivery This flag tells the server how to react if the message cannot be routed to a queue consumer immediately. If this flag is set, the server will return an undeliverable message with a Return method. If this flag is zero, the server will queue the message, but with no guarantee that it will ever be consumed. RULE: The server SHOULD implement the immediate flag.
[ "Publish", "a", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2049-L2123
232,527
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_qos
def basic_qos(self, prefetch_size, prefetch_count, a_global): """Specify quality of service This method requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and semantics of a qos method always depend on the content class semantics. Though the qos method could in principle apply to both peers, it is currently meaningful only for the server. PARAMETERS: prefetch_size: long prefetch window in octets The client can request that messages be sent in advance so that when the client finishes processing a message, the following message is already held locally, rather than needing to be sent down the channel. Prefetching gives a performance improvement. This field specifies the prefetch window size in octets. The server will send a message in advance if it is equal to or smaller in size than the available prefetch size (and also falls into other prefetch limits). May be set to zero, meaning "no specific limit", although other prefetch limits may still apply. The prefetch-size is ignored if the no-ack option is set. RULE: The server MUST ignore this setting when the client is not processing any messages - i.e. the prefetch size does not limit the transfer of single messages to a client, only the sending in advance of more messages while the client still has one or more unacknowledged messages. prefetch_count: short prefetch window in messages Specifies a prefetch window in terms of whole messages. This field may be used in combination with the prefetch-size field; a message will only be sent in advance if both prefetch windows (and those at the channel and connection level) allow it. The prefetch- count is ignored if the no-ack option is set. RULE: The server MAY send less data in advance than allowed by the client's specified prefetch windows but it MUST NOT send more. a_global: boolean apply to entire connection By default the QoS settings apply to the current channel only. If this field is set, they are applied to the entire connection. """ args = AMQPWriter() args.write_long(prefetch_size) args.write_short(prefetch_count) args.write_bit(a_global) self._send_method((60, 10), args) return self.wait(allowed_methods=[ (60, 11), # Channel.basic_qos_ok ])
python
def basic_qos(self, prefetch_size, prefetch_count, a_global): """Specify quality of service This method requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and semantics of a qos method always depend on the content class semantics. Though the qos method could in principle apply to both peers, it is currently meaningful only for the server. PARAMETERS: prefetch_size: long prefetch window in octets The client can request that messages be sent in advance so that when the client finishes processing a message, the following message is already held locally, rather than needing to be sent down the channel. Prefetching gives a performance improvement. This field specifies the prefetch window size in octets. The server will send a message in advance if it is equal to or smaller in size than the available prefetch size (and also falls into other prefetch limits). May be set to zero, meaning "no specific limit", although other prefetch limits may still apply. The prefetch-size is ignored if the no-ack option is set. RULE: The server MUST ignore this setting when the client is not processing any messages - i.e. the prefetch size does not limit the transfer of single messages to a client, only the sending in advance of more messages while the client still has one or more unacknowledged messages. prefetch_count: short prefetch window in messages Specifies a prefetch window in terms of whole messages. This field may be used in combination with the prefetch-size field; a message will only be sent in advance if both prefetch windows (and those at the channel and connection level) allow it. The prefetch- count is ignored if the no-ack option is set. RULE: The server MAY send less data in advance than allowed by the client's specified prefetch windows but it MUST NOT send more. a_global: boolean apply to entire connection By default the QoS settings apply to the current channel only. If this field is set, they are applied to the entire connection. """ args = AMQPWriter() args.write_long(prefetch_size) args.write_short(prefetch_count) args.write_bit(a_global) self._send_method((60, 10), args) return self.wait(allowed_methods=[ (60, 11), # Channel.basic_qos_ok ])
[ "def", "basic_qos", "(", "self", ",", "prefetch_size", ",", "prefetch_count", ",", "a_global", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_long", "(", "prefetch_size", ")", "args", ".", "write_short", "(", "prefetch_count", ")", "args", ".", "write_bit", "(", "a_global", ")", "self", ".", "_send_method", "(", "(", "60", ",", "10", ")", ",", "args", ")", "return", "self", ".", "wait", "(", "allowed_methods", "=", "[", "(", "60", ",", "11", ")", ",", "# Channel.basic_qos_ok", "]", ")" ]
Specify quality of service This method requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and semantics of a qos method always depend on the content class semantics. Though the qos method could in principle apply to both peers, it is currently meaningful only for the server. PARAMETERS: prefetch_size: long prefetch window in octets The client can request that messages be sent in advance so that when the client finishes processing a message, the following message is already held locally, rather than needing to be sent down the channel. Prefetching gives a performance improvement. This field specifies the prefetch window size in octets. The server will send a message in advance if it is equal to or smaller in size than the available prefetch size (and also falls into other prefetch limits). May be set to zero, meaning "no specific limit", although other prefetch limits may still apply. The prefetch-size is ignored if the no-ack option is set. RULE: The server MUST ignore this setting when the client is not processing any messages - i.e. the prefetch size does not limit the transfer of single messages to a client, only the sending in advance of more messages while the client still has one or more unacknowledged messages. prefetch_count: short prefetch window in messages Specifies a prefetch window in terms of whole messages. This field may be used in combination with the prefetch-size field; a message will only be sent in advance if both prefetch windows (and those at the channel and connection level) allow it. The prefetch- count is ignored if the no-ack option is set. RULE: The server MAY send less data in advance than allowed by the client's specified prefetch windows but it MUST NOT send more. a_global: boolean apply to entire connection By default the QoS settings apply to the current channel only. If this field is set, they are applied to the entire connection.
[ "Specify", "quality", "of", "service" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2135-L2206
232,528
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_recover
def basic_recover(self, requeue=False): """Redeliver unacknowledged messages This method asks the broker to redeliver all unacknowledged messages on a specified channel. Zero or more messages may be redelivered. This method is only allowed on non-transacted channels. RULE: The server MUST set the redelivered flag on all messages that are resent. RULE: The server MUST raise a channel exception if this is called on a transacted channel. PARAMETERS: requeue: boolean requeue the message If this field is False, the message will be redelivered to the original recipient. If this field is True, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber. """ args = AMQPWriter() args.write_bit(requeue) self._send_method((60, 110), args)
python
def basic_recover(self, requeue=False): """Redeliver unacknowledged messages This method asks the broker to redeliver all unacknowledged messages on a specified channel. Zero or more messages may be redelivered. This method is only allowed on non-transacted channels. RULE: The server MUST set the redelivered flag on all messages that are resent. RULE: The server MUST raise a channel exception if this is called on a transacted channel. PARAMETERS: requeue: boolean requeue the message If this field is False, the message will be redelivered to the original recipient. If this field is True, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber. """ args = AMQPWriter() args.write_bit(requeue) self._send_method((60, 110), args)
[ "def", "basic_recover", "(", "self", ",", "requeue", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_bit", "(", "requeue", ")", "self", ".", "_send_method", "(", "(", "60", ",", "110", ")", ",", "args", ")" ]
Redeliver unacknowledged messages This method asks the broker to redeliver all unacknowledged messages on a specified channel. Zero or more messages may be redelivered. This method is only allowed on non-transacted channels. RULE: The server MUST set the redelivered flag on all messages that are resent. RULE: The server MUST raise a channel exception if this is called on a transacted channel. PARAMETERS: requeue: boolean requeue the message If this field is False, the message will be redelivered to the original recipient. If this field is True, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber.
[ "Redeliver", "unacknowledged", "messages" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2218-L2250
232,529
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_reject
def basic_reject(self, delivery_tag, requeue): """Reject an incoming message This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue. RULE: The server SHOULD be capable of accepting and process the Reject method while sending message content with a Deliver or Get-Ok method. I.e. the server should read and process incoming methods while sending output frames. To cancel a partially-send content, the server sends a content body frame of size 1 (i.e. with no data except the frame-end octet). RULE: The server SHOULD interpret this method as meaning that the client is unable to process the message at this time. RULE: A client MUST NOT use this method as a means of selecting messages to process. A rejected message MAY be discarded or dead-lettered, not necessarily passed to another client. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". requeue: boolean requeue the message If this field is False, the message will be discarded. If this field is True, the server will attempt to requeue the message. RULE: The server MUST NOT deliver the message to the same client within the context of the current channel. The recommended strategy is to attempt to deliver the message to an alternative consumer, and if that is not possible, to move the message to a dead-letter queue. The server MAY use more sophisticated tracking to hold the message on the queue and redeliver it to the same client at a later stage. """ args = AMQPWriter() args.write_longlong(delivery_tag) args.write_bit(requeue) self._send_method((60, 90), args)
python
def basic_reject(self, delivery_tag, requeue): """Reject an incoming message This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue. RULE: The server SHOULD be capable of accepting and process the Reject method while sending message content with a Deliver or Get-Ok method. I.e. the server should read and process incoming methods while sending output frames. To cancel a partially-send content, the server sends a content body frame of size 1 (i.e. with no data except the frame-end octet). RULE: The server SHOULD interpret this method as meaning that the client is unable to process the message at this time. RULE: A client MUST NOT use this method as a means of selecting messages to process. A rejected message MAY be discarded or dead-lettered, not necessarily passed to another client. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". requeue: boolean requeue the message If this field is False, the message will be discarded. If this field is True, the server will attempt to requeue the message. RULE: The server MUST NOT deliver the message to the same client within the context of the current channel. The recommended strategy is to attempt to deliver the message to an alternative consumer, and if that is not possible, to move the message to a dead-letter queue. The server MAY use more sophisticated tracking to hold the message on the queue and redeliver it to the same client at a later stage. """ args = AMQPWriter() args.write_longlong(delivery_tag) args.write_bit(requeue) self._send_method((60, 90), args)
[ "def", "basic_reject", "(", "self", ",", "delivery_tag", ",", "requeue", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_longlong", "(", "delivery_tag", ")", "args", ".", "write_bit", "(", "requeue", ")", "self", ".", "_send_method", "(", "(", "60", ",", "90", ")", ",", "args", ")" ]
Reject an incoming message This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue. RULE: The server SHOULD be capable of accepting and process the Reject method while sending message content with a Deliver or Get-Ok method. I.e. the server should read and process incoming methods while sending output frames. To cancel a partially-send content, the server sends a content body frame of size 1 (i.e. with no data except the frame-end octet). RULE: The server SHOULD interpret this method as meaning that the client is unable to process the message at this time. RULE: A client MUST NOT use this method as a means of selecting messages to process. A rejected message MAY be discarded or dead-lettered, not necessarily passed to another client. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". requeue: boolean requeue the message If this field is False, the message will be discarded. If this field is True, the server will attempt to requeue the message. RULE: The server MUST NOT deliver the message to the same client within the context of the current channel. The recommended strategy is to attempt to deliver the message to an alternative consumer, and if that is not possible, to move the message to a dead-letter queue. The server MAY use more sophisticated tracking to hold the message on the queue and redeliver it to the same client at a later stage.
[ "Reject", "an", "incoming", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2261-L2334
232,530
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_return
def _basic_return(self, args, msg): """Return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide information about the reason that the message was undeliverable. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. """ self.returned_messages.put(basic_return_t( args.read_short(), args.read_shortstr(), args.read_shortstr(), args.read_shortstr(), msg, ))
python
def _basic_return(self, args, msg): """Return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide information about the reason that the message was undeliverable. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. """ self.returned_messages.put(basic_return_t( args.read_short(), args.read_shortstr(), args.read_shortstr(), args.read_shortstr(), msg, ))
[ "def", "_basic_return", "(", "self", ",", "args", ",", "msg", ")", ":", "self", ".", "returned_messages", ".", "put", "(", "basic_return_t", "(", "args", ".", "read_short", "(", ")", ",", "args", ".", "read_shortstr", "(", ")", ",", "args", ".", "read_shortstr", "(", ")", ",", "args", ".", "read_shortstr", "(", ")", ",", "msg", ",", ")", ")" ]
Return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide information about the reason that the message was undeliverable. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published.
[ "Return", "a", "failed", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2336-L2375
232,531
nerdvegas/rez
src/rez/build_process_.py
create_build_process
def create_build_process(process_type, working_dir, build_system, package=None, vcs=None, ensure_latest=True, skip_repo_errors=False, ignore_existing_tag=False, verbose=False, quiet=False): """Create a `BuildProcess` instance.""" from rez.plugin_managers import plugin_manager process_types = get_build_process_types() if process_type not in process_types: raise BuildProcessError("Unknown build process: %r" % process_type) cls = plugin_manager.get_plugin_class('build_process', process_type) return cls(working_dir, # ignored (deprecated) build_system, package=package, # ignored (deprecated) vcs=vcs, ensure_latest=ensure_latest, skip_repo_errors=skip_repo_errors, ignore_existing_tag=ignore_existing_tag, verbose=verbose, quiet=quiet)
python
def create_build_process(process_type, working_dir, build_system, package=None, vcs=None, ensure_latest=True, skip_repo_errors=False, ignore_existing_tag=False, verbose=False, quiet=False): """Create a `BuildProcess` instance.""" from rez.plugin_managers import plugin_manager process_types = get_build_process_types() if process_type not in process_types: raise BuildProcessError("Unknown build process: %r" % process_type) cls = plugin_manager.get_plugin_class('build_process', process_type) return cls(working_dir, # ignored (deprecated) build_system, package=package, # ignored (deprecated) vcs=vcs, ensure_latest=ensure_latest, skip_repo_errors=skip_repo_errors, ignore_existing_tag=ignore_existing_tag, verbose=verbose, quiet=quiet)
[ "def", "create_build_process", "(", "process_type", ",", "working_dir", ",", "build_system", ",", "package", "=", "None", ",", "vcs", "=", "None", ",", "ensure_latest", "=", "True", ",", "skip_repo_errors", "=", "False", ",", "ignore_existing_tag", "=", "False", ",", "verbose", "=", "False", ",", "quiet", "=", "False", ")", ":", "from", "rez", ".", "plugin_managers", "import", "plugin_manager", "process_types", "=", "get_build_process_types", "(", ")", "if", "process_type", "not", "in", "process_types", ":", "raise", "BuildProcessError", "(", "\"Unknown build process: %r\"", "%", "process_type", ")", "cls", "=", "plugin_manager", ".", "get_plugin_class", "(", "'build_process'", ",", "process_type", ")", "return", "cls", "(", "working_dir", ",", "# ignored (deprecated)", "build_system", ",", "package", "=", "package", ",", "# ignored (deprecated)", "vcs", "=", "vcs", ",", "ensure_latest", "=", "ensure_latest", ",", "skip_repo_errors", "=", "skip_repo_errors", ",", "ignore_existing_tag", "=", "ignore_existing_tag", ",", "verbose", "=", "verbose", ",", "quiet", "=", "quiet", ")" ]
Create a `BuildProcess` instance.
[ "Create", "a", "BuildProcess", "instance", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_process_.py#L26-L45
232,532
nerdvegas/rez
src/rez/build_process_.py
BuildProcessHelper.visit_variants
def visit_variants(self, func, variants=None, **kwargs): """Iterate over variants and call a function on each.""" if variants: present_variants = range(self.package.num_variants) invalid_variants = set(variants) - set(present_variants) if invalid_variants: raise BuildError( "The package does not contain the variants: %s" % ", ".join(str(x) for x in sorted(invalid_variants))) # iterate over variants results = [] num_visited = 0 for variant in self.package.iter_variants(): if variants and variant.index not in variants: self._print_header( "Skipping variant %s (%s)..." % (variant.index, self._n_of_m(variant))) continue # visit the variant result = func(variant, **kwargs) results.append(result) num_visited += 1 return num_visited, results
python
def visit_variants(self, func, variants=None, **kwargs): """Iterate over variants and call a function on each.""" if variants: present_variants = range(self.package.num_variants) invalid_variants = set(variants) - set(present_variants) if invalid_variants: raise BuildError( "The package does not contain the variants: %s" % ", ".join(str(x) for x in sorted(invalid_variants))) # iterate over variants results = [] num_visited = 0 for variant in self.package.iter_variants(): if variants and variant.index not in variants: self._print_header( "Skipping variant %s (%s)..." % (variant.index, self._n_of_m(variant))) continue # visit the variant result = func(variant, **kwargs) results.append(result) num_visited += 1 return num_visited, results
[ "def", "visit_variants", "(", "self", ",", "func", ",", "variants", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "variants", ":", "present_variants", "=", "range", "(", "self", ".", "package", ".", "num_variants", ")", "invalid_variants", "=", "set", "(", "variants", ")", "-", "set", "(", "present_variants", ")", "if", "invalid_variants", ":", "raise", "BuildError", "(", "\"The package does not contain the variants: %s\"", "%", "\", \"", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "sorted", "(", "invalid_variants", ")", ")", ")", "# iterate over variants", "results", "=", "[", "]", "num_visited", "=", "0", "for", "variant", "in", "self", ".", "package", ".", "iter_variants", "(", ")", ":", "if", "variants", "and", "variant", ".", "index", "not", "in", "variants", ":", "self", ".", "_print_header", "(", "\"Skipping variant %s (%s)...\"", "%", "(", "variant", ".", "index", ",", "self", ".", "_n_of_m", "(", "variant", ")", ")", ")", "continue", "# visit the variant", "result", "=", "func", "(", "variant", ",", "*", "*", "kwargs", ")", "results", ".", "append", "(", "result", ")", "num_visited", "+=", "1", "return", "num_visited", ",", "results" ]
Iterate over variants and call a function on each.
[ "Iterate", "over", "variants", "and", "call", "a", "function", "on", "each", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_process_.py#L175-L201
232,533
nerdvegas/rez
src/rez/build_process_.py
BuildProcessHelper.create_build_context
def create_build_context(self, variant, build_type, build_path): """Create a context to build the variant within.""" request = variant.get_requires(build_requires=True, private_build_requires=True) req_strs = map(str, request) quoted_req_strs = map(quote, req_strs) self._print("Resolving build environment: %s", ' '.join(quoted_req_strs)) if build_type == BuildType.local: packages_path = self.package.config.packages_path else: packages_path = self.package.config.nonlocal_packages_path if self.package.config.is_overridden("package_filter"): from rez.package_filter import PackageFilterList data = self.package.config.package_filter package_filter = PackageFilterList.from_pod(data) else: package_filter = None context = ResolvedContext(request, package_paths=packages_path, package_filter=package_filter, building=True) if self.verbose: context.print_info() # save context before possible fail, so user can debug rxt_filepath = os.path.join(build_path, "build.rxt") context.save(rxt_filepath) if context.status != ResolverStatus.solved: raise BuildContextResolveError(context) return context, rxt_filepath
python
def create_build_context(self, variant, build_type, build_path): """Create a context to build the variant within.""" request = variant.get_requires(build_requires=True, private_build_requires=True) req_strs = map(str, request) quoted_req_strs = map(quote, req_strs) self._print("Resolving build environment: %s", ' '.join(quoted_req_strs)) if build_type == BuildType.local: packages_path = self.package.config.packages_path else: packages_path = self.package.config.nonlocal_packages_path if self.package.config.is_overridden("package_filter"): from rez.package_filter import PackageFilterList data = self.package.config.package_filter package_filter = PackageFilterList.from_pod(data) else: package_filter = None context = ResolvedContext(request, package_paths=packages_path, package_filter=package_filter, building=True) if self.verbose: context.print_info() # save context before possible fail, so user can debug rxt_filepath = os.path.join(build_path, "build.rxt") context.save(rxt_filepath) if context.status != ResolverStatus.solved: raise BuildContextResolveError(context) return context, rxt_filepath
[ "def", "create_build_context", "(", "self", ",", "variant", ",", "build_type", ",", "build_path", ")", ":", "request", "=", "variant", ".", "get_requires", "(", "build_requires", "=", "True", ",", "private_build_requires", "=", "True", ")", "req_strs", "=", "map", "(", "str", ",", "request", ")", "quoted_req_strs", "=", "map", "(", "quote", ",", "req_strs", ")", "self", ".", "_print", "(", "\"Resolving build environment: %s\"", ",", "' '", ".", "join", "(", "quoted_req_strs", ")", ")", "if", "build_type", "==", "BuildType", ".", "local", ":", "packages_path", "=", "self", ".", "package", ".", "config", ".", "packages_path", "else", ":", "packages_path", "=", "self", ".", "package", ".", "config", ".", "nonlocal_packages_path", "if", "self", ".", "package", ".", "config", ".", "is_overridden", "(", "\"package_filter\"", ")", ":", "from", "rez", ".", "package_filter", "import", "PackageFilterList", "data", "=", "self", ".", "package", ".", "config", ".", "package_filter", "package_filter", "=", "PackageFilterList", ".", "from_pod", "(", "data", ")", "else", ":", "package_filter", "=", "None", "context", "=", "ResolvedContext", "(", "request", ",", "package_paths", "=", "packages_path", ",", "package_filter", "=", "package_filter", ",", "building", "=", "True", ")", "if", "self", ".", "verbose", ":", "context", ".", "print_info", "(", ")", "# save context before possible fail, so user can debug", "rxt_filepath", "=", "os", ".", "path", ".", "join", "(", "build_path", ",", "\"build.rxt\"", ")", "context", ".", "save", "(", "rxt_filepath", ")", "if", "context", ".", "status", "!=", "ResolverStatus", ".", "solved", ":", "raise", "BuildContextResolveError", "(", "context", ")", "return", "context", ",", "rxt_filepath" ]
Create a context to build the variant within.
[ "Create", "a", "context", "to", "build", "the", "variant", "within", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_process_.py#L218-L253
232,534
nerdvegas/rez
src/rez/build_process_.py
BuildProcessHelper.get_release_data
def get_release_data(self): """Get release data for this release. Returns: dict. """ previous_package = self.get_previous_release() if previous_package: previous_version = previous_package.version previous_revision = previous_package.revision else: previous_version = None previous_revision = None if self.vcs is None: return dict(vcs="None", previous_version=previous_version) revision = None with self.repo_operation(): revision = self.vcs.get_current_revision() changelog = self.get_changelog() # truncate changelog - very large changelogs can cause package load # times to be very high, we don't want that maxlen = config.max_package_changelog_chars if maxlen and changelog and len(changelog) > maxlen + 3: changelog = changelog[:maxlen] + "..." return dict(vcs=self.vcs.name(), revision=revision, changelog=changelog, previous_version=previous_version, previous_revision=previous_revision)
python
def get_release_data(self): """Get release data for this release. Returns: dict. """ previous_package = self.get_previous_release() if previous_package: previous_version = previous_package.version previous_revision = previous_package.revision else: previous_version = None previous_revision = None if self.vcs is None: return dict(vcs="None", previous_version=previous_version) revision = None with self.repo_operation(): revision = self.vcs.get_current_revision() changelog = self.get_changelog() # truncate changelog - very large changelogs can cause package load # times to be very high, we don't want that maxlen = config.max_package_changelog_chars if maxlen and changelog and len(changelog) > maxlen + 3: changelog = changelog[:maxlen] + "..." return dict(vcs=self.vcs.name(), revision=revision, changelog=changelog, previous_version=previous_version, previous_revision=previous_revision)
[ "def", "get_release_data", "(", "self", ")", ":", "previous_package", "=", "self", ".", "get_previous_release", "(", ")", "if", "previous_package", ":", "previous_version", "=", "previous_package", ".", "version", "previous_revision", "=", "previous_package", ".", "revision", "else", ":", "previous_version", "=", "None", "previous_revision", "=", "None", "if", "self", ".", "vcs", "is", "None", ":", "return", "dict", "(", "vcs", "=", "\"None\"", ",", "previous_version", "=", "previous_version", ")", "revision", "=", "None", "with", "self", ".", "repo_operation", "(", ")", ":", "revision", "=", "self", ".", "vcs", ".", "get_current_revision", "(", ")", "changelog", "=", "self", ".", "get_changelog", "(", ")", "# truncate changelog - very large changelogs can cause package load", "# times to be very high, we don't want that", "maxlen", "=", "config", ".", "max_package_changelog_chars", "if", "maxlen", "and", "changelog", "and", "len", "(", "changelog", ")", ">", "maxlen", "+", "3", ":", "changelog", "=", "changelog", "[", ":", "maxlen", "]", "+", "\"...\"", "return", "dict", "(", "vcs", "=", "self", ".", "vcs", ".", "name", "(", ")", ",", "revision", "=", "revision", ",", "changelog", "=", "changelog", ",", "previous_version", "=", "previous_version", ",", "previous_revision", "=", "previous_revision", ")" ]
Get release data for this release. Returns: dict.
[ "Get", "release", "data", "for", "this", "release", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_process_.py#L368-L402
232,535
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/minmax.py
minimal_spanning_tree
def minimal_spanning_tree(graph, root=None): """ Minimal spanning tree. @attention: Minimal spanning tree is meaningful only for weighted graphs. @type graph: graph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: dictionary @return: Generated spanning tree. """ visited = [] # List for marking visited and non-visited nodes spanning_tree = {} # MInimal Spanning tree # Initialization if (root is not None): visited.append(root) nroot = root spanning_tree[root] = None else: nroot = 1 # Algorithm loop while (nroot is not None): ledge = _lightest_edge(graph, visited) if (ledge == None): if (root is not None): break nroot = _first_unvisited(graph, visited) if (nroot is not None): spanning_tree[nroot] = None visited.append(nroot) else: spanning_tree[ledge[1]] = ledge[0] visited.append(ledge[1]) return spanning_tree
python
def minimal_spanning_tree(graph, root=None): """ Minimal spanning tree. @attention: Minimal spanning tree is meaningful only for weighted graphs. @type graph: graph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: dictionary @return: Generated spanning tree. """ visited = [] # List for marking visited and non-visited nodes spanning_tree = {} # MInimal Spanning tree # Initialization if (root is not None): visited.append(root) nroot = root spanning_tree[root] = None else: nroot = 1 # Algorithm loop while (nroot is not None): ledge = _lightest_edge(graph, visited) if (ledge == None): if (root is not None): break nroot = _first_unvisited(graph, visited) if (nroot is not None): spanning_tree[nroot] = None visited.append(nroot) else: spanning_tree[ledge[1]] = ledge[0] visited.append(ledge[1]) return spanning_tree
[ "def", "minimal_spanning_tree", "(", "graph", ",", "root", "=", "None", ")", ":", "visited", "=", "[", "]", "# List for marking visited and non-visited nodes", "spanning_tree", "=", "{", "}", "# MInimal Spanning tree", "# Initialization", "if", "(", "root", "is", "not", "None", ")", ":", "visited", ".", "append", "(", "root", ")", "nroot", "=", "root", "spanning_tree", "[", "root", "]", "=", "None", "else", ":", "nroot", "=", "1", "# Algorithm loop", "while", "(", "nroot", "is", "not", "None", ")", ":", "ledge", "=", "_lightest_edge", "(", "graph", ",", "visited", ")", "if", "(", "ledge", "==", "None", ")", ":", "if", "(", "root", "is", "not", "None", ")", ":", "break", "nroot", "=", "_first_unvisited", "(", "graph", ",", "visited", ")", "if", "(", "nroot", "is", "not", "None", ")", ":", "spanning_tree", "[", "nroot", "]", "=", "None", "visited", ".", "append", "(", "nroot", ")", "else", ":", "spanning_tree", "[", "ledge", "[", "1", "]", "]", "=", "ledge", "[", "0", "]", "visited", ".", "append", "(", "ledge", "[", "1", "]", ")", "return", "spanning_tree" ]
Minimal spanning tree. @attention: Minimal spanning tree is meaningful only for weighted graphs. @type graph: graph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: dictionary @return: Generated spanning tree.
[ "Minimal", "spanning", "tree", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/minmax.py#L46-L86
232,536
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/minmax.py
cut_value
def cut_value(graph, flow, cut): """ Calculate the value of a cut. @type graph: digraph @param graph: Graph @type flow: dictionary @param flow: Dictionary containing a flow for each edge. @type cut: dictionary @param cut: Dictionary mapping each node to a subset index. The function only considers the flow between nodes with 0 and 1. @rtype: float @return: The value of the flow between the subsets 0 and 1 """ #max flow/min cut value calculation S = [] T = [] for node in cut.keys(): if cut[node] == 0: S.append(node) elif cut[node] == 1: T.append(node) value = 0 for node in S: for neigh in graph.neighbors(node): if neigh in T: value = value + flow[(node,neigh)] for inc in graph.incidents(node): if inc in T: value = value - flow[(inc,node)] return value
python
def cut_value(graph, flow, cut): """ Calculate the value of a cut. @type graph: digraph @param graph: Graph @type flow: dictionary @param flow: Dictionary containing a flow for each edge. @type cut: dictionary @param cut: Dictionary mapping each node to a subset index. The function only considers the flow between nodes with 0 and 1. @rtype: float @return: The value of the flow between the subsets 0 and 1 """ #max flow/min cut value calculation S = [] T = [] for node in cut.keys(): if cut[node] == 0: S.append(node) elif cut[node] == 1: T.append(node) value = 0 for node in S: for neigh in graph.neighbors(node): if neigh in T: value = value + flow[(node,neigh)] for inc in graph.incidents(node): if inc in T: value = value - flow[(inc,node)] return value
[ "def", "cut_value", "(", "graph", ",", "flow", ",", "cut", ")", ":", "#max flow/min cut value calculation", "S", "=", "[", "]", "T", "=", "[", "]", "for", "node", "in", "cut", ".", "keys", "(", ")", ":", "if", "cut", "[", "node", "]", "==", "0", ":", "S", ".", "append", "(", "node", ")", "elif", "cut", "[", "node", "]", "==", "1", ":", "T", ".", "append", "(", "node", ")", "value", "=", "0", "for", "node", "in", "S", ":", "for", "neigh", "in", "graph", ".", "neighbors", "(", "node", ")", ":", "if", "neigh", "in", "T", ":", "value", "=", "value", "+", "flow", "[", "(", "node", ",", "neigh", ")", "]", "for", "inc", "in", "graph", ".", "incidents", "(", "node", ")", ":", "if", "inc", "in", "T", ":", "value", "=", "value", "-", "flow", "[", "(", "inc", ",", "node", ")", "]", "return", "value" ]
Calculate the value of a cut. @type graph: digraph @param graph: Graph @type flow: dictionary @param flow: Dictionary containing a flow for each edge. @type cut: dictionary @param cut: Dictionary mapping each node to a subset index. The function only considers the flow between nodes with 0 and 1. @rtype: float @return: The value of the flow between the subsets 0 and 1
[ "Calculate", "the", "value", "of", "a", "cut", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/minmax.py#L412-L445
232,537
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/minmax.py
cut_tree
def cut_tree(igraph, caps = None): """ Construct a Gomory-Hu cut tree by applying the algorithm of Gusfield. @type igraph: graph @param igraph: Graph @type caps: dictionary @param caps: Dictionary specifying a maximum capacity for each edge. If not given, the weight of the edge will be used as its capacity. Otherwise, for each edge (a,b), caps[(a,b)] should be given. @rtype: dictionary @return: Gomory-Hu cut tree as a dictionary, where each edge is associated with its weight """ #maximum flow needs a digraph, we get a graph #I think this conversion relies on implementation details outside the api and may break in the future graph = digraph() graph.add_graph(igraph) #handle optional argument if not caps: caps = {} for edge in graph.edges(): caps[edge] = igraph.edge_weight(edge) #temporary flow variable f = {} #we use a numbering of the nodes for easier handling n = {} N = 0 for node in graph.nodes(): n[N] = node N = N + 1 #predecessor function p = {}.fromkeys(range(N),0) p[0] = None for s in range(1,N): t = p[s] S = [] #max flow calculation (flow,cut) = maximum_flow(graph,n[s],n[t],caps) for i in range(N): if cut[n[i]] == 0: S.append(i) value = cut_value(graph,flow,cut) f[s] = value for i in range(N): if i == s: continue if i in S and p[i] == t: p[i] = s if p[t] in S: p[s] = p[t] p[t] = s f[s] = f[t] f[t] = value #cut tree is a dictionary, where each edge is associated with its weight b = {} for i in range(1,N): b[(n[i],n[p[i]])] = f[i] return b
python
def cut_tree(igraph, caps = None): """ Construct a Gomory-Hu cut tree by applying the algorithm of Gusfield. @type igraph: graph @param igraph: Graph @type caps: dictionary @param caps: Dictionary specifying a maximum capacity for each edge. If not given, the weight of the edge will be used as its capacity. Otherwise, for each edge (a,b), caps[(a,b)] should be given. @rtype: dictionary @return: Gomory-Hu cut tree as a dictionary, where each edge is associated with its weight """ #maximum flow needs a digraph, we get a graph #I think this conversion relies on implementation details outside the api and may break in the future graph = digraph() graph.add_graph(igraph) #handle optional argument if not caps: caps = {} for edge in graph.edges(): caps[edge] = igraph.edge_weight(edge) #temporary flow variable f = {} #we use a numbering of the nodes for easier handling n = {} N = 0 for node in graph.nodes(): n[N] = node N = N + 1 #predecessor function p = {}.fromkeys(range(N),0) p[0] = None for s in range(1,N): t = p[s] S = [] #max flow calculation (flow,cut) = maximum_flow(graph,n[s],n[t],caps) for i in range(N): if cut[n[i]] == 0: S.append(i) value = cut_value(graph,flow,cut) f[s] = value for i in range(N): if i == s: continue if i in S and p[i] == t: p[i] = s if p[t] in S: p[s] = p[t] p[t] = s f[s] = f[t] f[t] = value #cut tree is a dictionary, where each edge is associated with its weight b = {} for i in range(1,N): b[(n[i],n[p[i]])] = f[i] return b
[ "def", "cut_tree", "(", "igraph", ",", "caps", "=", "None", ")", ":", "#maximum flow needs a digraph, we get a graph", "#I think this conversion relies on implementation details outside the api and may break in the future", "graph", "=", "digraph", "(", ")", "graph", ".", "add_graph", "(", "igraph", ")", "#handle optional argument", "if", "not", "caps", ":", "caps", "=", "{", "}", "for", "edge", "in", "graph", ".", "edges", "(", ")", ":", "caps", "[", "edge", "]", "=", "igraph", ".", "edge_weight", "(", "edge", ")", "#temporary flow variable", "f", "=", "{", "}", "#we use a numbering of the nodes for easier handling", "n", "=", "{", "}", "N", "=", "0", "for", "node", "in", "graph", ".", "nodes", "(", ")", ":", "n", "[", "N", "]", "=", "node", "N", "=", "N", "+", "1", "#predecessor function", "p", "=", "{", "}", ".", "fromkeys", "(", "range", "(", "N", ")", ",", "0", ")", "p", "[", "0", "]", "=", "None", "for", "s", "in", "range", "(", "1", ",", "N", ")", ":", "t", "=", "p", "[", "s", "]", "S", "=", "[", "]", "#max flow calculation", "(", "flow", ",", "cut", ")", "=", "maximum_flow", "(", "graph", ",", "n", "[", "s", "]", ",", "n", "[", "t", "]", ",", "caps", ")", "for", "i", "in", "range", "(", "N", ")", ":", "if", "cut", "[", "n", "[", "i", "]", "]", "==", "0", ":", "S", ".", "append", "(", "i", ")", "value", "=", "cut_value", "(", "graph", ",", "flow", ",", "cut", ")", "f", "[", "s", "]", "=", "value", "for", "i", "in", "range", "(", "N", ")", ":", "if", "i", "==", "s", ":", "continue", "if", "i", "in", "S", "and", "p", "[", "i", "]", "==", "t", ":", "p", "[", "i", "]", "=", "s", "if", "p", "[", "t", "]", "in", "S", ":", "p", "[", "s", "]", "=", "p", "[", "t", "]", "p", "[", "t", "]", "=", "s", "f", "[", "s", "]", "=", "f", "[", "t", "]", "f", "[", "t", "]", "=", "value", "#cut tree is a dictionary, where each edge is associated with its weight", "b", "=", "{", "}", "for", "i", "in", "range", "(", "1", ",", "N", ")", ":", "b", "[", "(", "n", "[", "i", "]", ",", "n", "[", "p", "[", "i", "]", "]", ")", "]", "=", "f", "[", "i", "]", "return", "b" ]
Construct a Gomory-Hu cut tree by applying the algorithm of Gusfield. @type igraph: graph @param igraph: Graph @type caps: dictionary @param caps: Dictionary specifying a maximum capacity for each edge. If not given, the weight of the edge will be used as its capacity. Otherwise, for each edge (a,b), caps[(a,b)] should be given. @rtype: dictionary @return: Gomory-Hu cut tree as a dictionary, where each edge is associated with its weight
[ "Construct", "a", "Gomory", "-", "Hu", "cut", "tree", "by", "applying", "the", "algorithm", "of", "Gusfield", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/minmax.py#L447-L515
232,538
nerdvegas/rez
src/rez/vendor/distlib/locators.py
Locator.locate
def locate(self, requirement, prereleases=False): """ Find the most recent distribution which matches the given requirement. :param requirement: A requirement of the form 'foo (1.0)' or perhaps 'foo (>= 1.0, < 2.0, != 1.3)' :param prereleases: If ``True``, allow pre-release versions to be located. Otherwise, pre-release versions are not returned. :return: A :class:`Distribution` instance, or ``None`` if no such distribution could be located. """ result = None r = parse_requirement(requirement) if r is None: raise DistlibException('Not a valid requirement: %r' % requirement) scheme = get_scheme(self.scheme) self.matcher = matcher = scheme.matcher(r.requirement) logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__) versions = self.get_project(r.name) if len(versions) > 2: # urls and digests keys are present # sometimes, versions are invalid slist = [] vcls = matcher.version_class for k in versions: if k in ('urls', 'digests'): continue try: if not matcher.match(k): logger.debug('%s did not match %r', matcher, k) else: if prereleases or not vcls(k).is_prerelease: slist.append(k) else: logger.debug('skipping pre-release ' 'version %s of %s', k, matcher.name) except Exception: # pragma: no cover logger.warning('error matching %s with %r', matcher, k) pass # slist.append(k) if len(slist) > 1: slist = sorted(slist, key=scheme.key) if slist: logger.debug('sorted list: %s', slist) version = slist[-1] result = versions[version] if result: if r.extras: result.extras = r.extras result.download_urls = versions.get('urls', {}).get(version, set()) d = {} sd = versions.get('digests', {}) for url in result.download_urls: if url in sd: d[url] = sd[url] result.digests = d self.matcher = None return result
python
def locate(self, requirement, prereleases=False): """ Find the most recent distribution which matches the given requirement. :param requirement: A requirement of the form 'foo (1.0)' or perhaps 'foo (>= 1.0, < 2.0, != 1.3)' :param prereleases: If ``True``, allow pre-release versions to be located. Otherwise, pre-release versions are not returned. :return: A :class:`Distribution` instance, or ``None`` if no such distribution could be located. """ result = None r = parse_requirement(requirement) if r is None: raise DistlibException('Not a valid requirement: %r' % requirement) scheme = get_scheme(self.scheme) self.matcher = matcher = scheme.matcher(r.requirement) logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__) versions = self.get_project(r.name) if len(versions) > 2: # urls and digests keys are present # sometimes, versions are invalid slist = [] vcls = matcher.version_class for k in versions: if k in ('urls', 'digests'): continue try: if not matcher.match(k): logger.debug('%s did not match %r', matcher, k) else: if prereleases or not vcls(k).is_prerelease: slist.append(k) else: logger.debug('skipping pre-release ' 'version %s of %s', k, matcher.name) except Exception: # pragma: no cover logger.warning('error matching %s with %r', matcher, k) pass # slist.append(k) if len(slist) > 1: slist = sorted(slist, key=scheme.key) if slist: logger.debug('sorted list: %s', slist) version = slist[-1] result = versions[version] if result: if r.extras: result.extras = r.extras result.download_urls = versions.get('urls', {}).get(version, set()) d = {} sd = versions.get('digests', {}) for url in result.download_urls: if url in sd: d[url] = sd[url] result.digests = d self.matcher = None return result
[ "def", "locate", "(", "self", ",", "requirement", ",", "prereleases", "=", "False", ")", ":", "result", "=", "None", "r", "=", "parse_requirement", "(", "requirement", ")", "if", "r", "is", "None", ":", "raise", "DistlibException", "(", "'Not a valid requirement: %r'", "%", "requirement", ")", "scheme", "=", "get_scheme", "(", "self", ".", "scheme", ")", "self", ".", "matcher", "=", "matcher", "=", "scheme", ".", "matcher", "(", "r", ".", "requirement", ")", "logger", ".", "debug", "(", "'matcher: %s (%s)'", ",", "matcher", ",", "type", "(", "matcher", ")", ".", "__name__", ")", "versions", "=", "self", ".", "get_project", "(", "r", ".", "name", ")", "if", "len", "(", "versions", ")", ">", "2", ":", "# urls and digests keys are present", "# sometimes, versions are invalid", "slist", "=", "[", "]", "vcls", "=", "matcher", ".", "version_class", "for", "k", "in", "versions", ":", "if", "k", "in", "(", "'urls'", ",", "'digests'", ")", ":", "continue", "try", ":", "if", "not", "matcher", ".", "match", "(", "k", ")", ":", "logger", ".", "debug", "(", "'%s did not match %r'", ",", "matcher", ",", "k", ")", "else", ":", "if", "prereleases", "or", "not", "vcls", "(", "k", ")", ".", "is_prerelease", ":", "slist", ".", "append", "(", "k", ")", "else", ":", "logger", ".", "debug", "(", "'skipping pre-release '", "'version %s of %s'", ",", "k", ",", "matcher", ".", "name", ")", "except", "Exception", ":", "# pragma: no cover", "logger", ".", "warning", "(", "'error matching %s with %r'", ",", "matcher", ",", "k", ")", "pass", "# slist.append(k)", "if", "len", "(", "slist", ")", ">", "1", ":", "slist", "=", "sorted", "(", "slist", ",", "key", "=", "scheme", ".", "key", ")", "if", "slist", ":", "logger", ".", "debug", "(", "'sorted list: %s'", ",", "slist", ")", "version", "=", "slist", "[", "-", "1", "]", "result", "=", "versions", "[", "version", "]", "if", "result", ":", "if", "r", ".", "extras", ":", "result", ".", "extras", "=", "r", ".", "extras", "result", ".", "download_urls", "=", "versions", ".", "get", "(", "'urls'", ",", "{", "}", ")", ".", "get", "(", "version", ",", "set", "(", ")", ")", "d", "=", "{", "}", "sd", "=", "versions", ".", "get", "(", "'digests'", ",", "{", "}", ")", "for", "url", "in", "result", ".", "download_urls", ":", "if", "url", "in", "sd", ":", "d", "[", "url", "]", "=", "sd", "[", "url", "]", "result", ".", "digests", "=", "d", "self", ".", "matcher", "=", "None", "return", "result" ]
Find the most recent distribution which matches the given requirement. :param requirement: A requirement of the form 'foo (1.0)' or perhaps 'foo (>= 1.0, < 2.0, != 1.3)' :param prereleases: If ``True``, allow pre-release versions to be located. Otherwise, pre-release versions are not returned. :return: A :class:`Distribution` instance, or ``None`` if no such distribution could be located.
[ "Find", "the", "most", "recent", "distribution", "which", "matches", "the", "given", "requirement", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/locators.py#L313-L370
232,539
nerdvegas/rez
src/rez/package_bind.py
get_bind_modules
def get_bind_modules(verbose=False): """Get available bind modules. Returns: dict: Map of (name, filepath) listing all bind modules. """ builtin_path = os.path.join(module_root_path, "bind") searchpaths = config.bind_module_path + [builtin_path] bindnames = {} for path in searchpaths: if verbose: print "searching %s..." % path if not os.path.isdir(path): continue for filename in os.listdir(path): fpath = os.path.join(path, filename) fname, ext = os.path.splitext(filename) if os.path.isfile(fpath) and ext == ".py" \ and not fname.startswith('_'): bindnames[fname] = fpath return bindnames
python
def get_bind_modules(verbose=False): """Get available bind modules. Returns: dict: Map of (name, filepath) listing all bind modules. """ builtin_path = os.path.join(module_root_path, "bind") searchpaths = config.bind_module_path + [builtin_path] bindnames = {} for path in searchpaths: if verbose: print "searching %s..." % path if not os.path.isdir(path): continue for filename in os.listdir(path): fpath = os.path.join(path, filename) fname, ext = os.path.splitext(filename) if os.path.isfile(fpath) and ext == ".py" \ and not fname.startswith('_'): bindnames[fname] = fpath return bindnames
[ "def", "get_bind_modules", "(", "verbose", "=", "False", ")", ":", "builtin_path", "=", "os", ".", "path", ".", "join", "(", "module_root_path", ",", "\"bind\"", ")", "searchpaths", "=", "config", ".", "bind_module_path", "+", "[", "builtin_path", "]", "bindnames", "=", "{", "}", "for", "path", "in", "searchpaths", ":", "if", "verbose", ":", "print", "\"searching %s...\"", "%", "path", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "continue", "for", "filename", "in", "os", ".", "listdir", "(", "path", ")", ":", "fpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "fname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "fpath", ")", "and", "ext", "==", "\".py\"", "and", "not", "fname", ".", "startswith", "(", "'_'", ")", ":", "bindnames", "[", "fname", "]", "=", "fpath", "return", "bindnames" ]
Get available bind modules. Returns: dict: Map of (name, filepath) listing all bind modules.
[ "Get", "available", "bind", "modules", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_bind.py#L13-L36
232,540
nerdvegas/rez
src/rez/package_bind.py
find_bind_module
def find_bind_module(name, verbose=False): """Find the bind module matching the given name. Args: name (str): Name of package to find bind module for. verbose (bool): If True, print extra output. Returns: str: Filepath to bind module .py file, or None if not found. """ bindnames = get_bind_modules(verbose=verbose) bindfile = bindnames.get(name) if bindfile: return bindfile if not verbose: return None # suggest close matches fuzzy_matches = get_close_pkgs(name, bindnames.keys()) if fuzzy_matches: rows = [(x[0], bindnames[x[0]]) for x in fuzzy_matches] print "'%s' not found. Close matches:" % name print '\n'.join(columnise(rows)) else: print "No matches." return None
python
def find_bind_module(name, verbose=False): """Find the bind module matching the given name. Args: name (str): Name of package to find bind module for. verbose (bool): If True, print extra output. Returns: str: Filepath to bind module .py file, or None if not found. """ bindnames = get_bind_modules(verbose=verbose) bindfile = bindnames.get(name) if bindfile: return bindfile if not verbose: return None # suggest close matches fuzzy_matches = get_close_pkgs(name, bindnames.keys()) if fuzzy_matches: rows = [(x[0], bindnames[x[0]]) for x in fuzzy_matches] print "'%s' not found. Close matches:" % name print '\n'.join(columnise(rows)) else: print "No matches." return None
[ "def", "find_bind_module", "(", "name", ",", "verbose", "=", "False", ")", ":", "bindnames", "=", "get_bind_modules", "(", "verbose", "=", "verbose", ")", "bindfile", "=", "bindnames", ".", "get", "(", "name", ")", "if", "bindfile", ":", "return", "bindfile", "if", "not", "verbose", ":", "return", "None", "# suggest close matches", "fuzzy_matches", "=", "get_close_pkgs", "(", "name", ",", "bindnames", ".", "keys", "(", ")", ")", "if", "fuzzy_matches", ":", "rows", "=", "[", "(", "x", "[", "0", "]", ",", "bindnames", "[", "x", "[", "0", "]", "]", ")", "for", "x", "in", "fuzzy_matches", "]", "print", "\"'%s' not found. Close matches:\"", "%", "name", "print", "'\\n'", ".", "join", "(", "columnise", "(", "rows", ")", ")", "else", ":", "print", "\"No matches.\"", "return", "None" ]
Find the bind module matching the given name. Args: name (str): Name of package to find bind module for. verbose (bool): If True, print extra output. Returns: str: Filepath to bind module .py file, or None if not found.
[ "Find", "the", "bind", "module", "matching", "the", "given", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_bind.py#L39-L68
232,541
nerdvegas/rez
src/rez/package_bind.py
bind_package
def bind_package(name, path=None, version_range=None, no_deps=False, bind_args=None, quiet=False): """Bind software available on the current system, as a rez package. Note: `bind_args` is provided when software is bound via the 'rez-bind' command line tool. Bind modules can define their own command line options, and they will be present in `bind_args` if applicable. Args: name (str): Package name. path (str): Package path to install into; local packages path if None. version_range (`VersionRange`): If provided, only bind the software if it falls within this version range. no_deps (bool): If True, don't bind dependencies. bind_args (list of str): Command line options. quiet (bool): If True, suppress superfluous output. Returns: List of `Variant`: The variant(s) that were installed as a result of binding this package. """ pending = set([name]) installed_variants = [] installed_package_names = set() primary = True # bind package and possibly dependencies while pending: pending_ = pending pending = set() exc_type = None for name_ in pending_: # turn error on binding of dependencies into a warning - we don't # want to skip binding some dependencies because others failed try: variants_ = _bind_package(name_, path=path, version_range=version_range, bind_args=bind_args, quiet=quiet) except exc_type as e: print_error("Could not bind '%s': %s: %s" % (name_, e.__class__.__name__, str(e))) continue installed_variants.extend(variants_) for variant in variants_: installed_package_names.add(variant.name) # add dependencies if not no_deps: for variant in variants_: for requirement in variant.requires: if not requirement.conflict: pending.add(requirement.name) # non-primary packages are treated a little differently primary = False version_range = None bind_args = None exc_type = RezBindError if installed_variants and not quiet: print "The following packages were installed:" print _print_package_list(installed_variants) return installed_variants
python
def bind_package(name, path=None, version_range=None, no_deps=False, bind_args=None, quiet=False): """Bind software available on the current system, as a rez package. Note: `bind_args` is provided when software is bound via the 'rez-bind' command line tool. Bind modules can define their own command line options, and they will be present in `bind_args` if applicable. Args: name (str): Package name. path (str): Package path to install into; local packages path if None. version_range (`VersionRange`): If provided, only bind the software if it falls within this version range. no_deps (bool): If True, don't bind dependencies. bind_args (list of str): Command line options. quiet (bool): If True, suppress superfluous output. Returns: List of `Variant`: The variant(s) that were installed as a result of binding this package. """ pending = set([name]) installed_variants = [] installed_package_names = set() primary = True # bind package and possibly dependencies while pending: pending_ = pending pending = set() exc_type = None for name_ in pending_: # turn error on binding of dependencies into a warning - we don't # want to skip binding some dependencies because others failed try: variants_ = _bind_package(name_, path=path, version_range=version_range, bind_args=bind_args, quiet=quiet) except exc_type as e: print_error("Could not bind '%s': %s: %s" % (name_, e.__class__.__name__, str(e))) continue installed_variants.extend(variants_) for variant in variants_: installed_package_names.add(variant.name) # add dependencies if not no_deps: for variant in variants_: for requirement in variant.requires: if not requirement.conflict: pending.add(requirement.name) # non-primary packages are treated a little differently primary = False version_range = None bind_args = None exc_type = RezBindError if installed_variants and not quiet: print "The following packages were installed:" print _print_package_list(installed_variants) return installed_variants
[ "def", "bind_package", "(", "name", ",", "path", "=", "None", ",", "version_range", "=", "None", ",", "no_deps", "=", "False", ",", "bind_args", "=", "None", ",", "quiet", "=", "False", ")", ":", "pending", "=", "set", "(", "[", "name", "]", ")", "installed_variants", "=", "[", "]", "installed_package_names", "=", "set", "(", ")", "primary", "=", "True", "# bind package and possibly dependencies", "while", "pending", ":", "pending_", "=", "pending", "pending", "=", "set", "(", ")", "exc_type", "=", "None", "for", "name_", "in", "pending_", ":", "# turn error on binding of dependencies into a warning - we don't", "# want to skip binding some dependencies because others failed", "try", ":", "variants_", "=", "_bind_package", "(", "name_", ",", "path", "=", "path", ",", "version_range", "=", "version_range", ",", "bind_args", "=", "bind_args", ",", "quiet", "=", "quiet", ")", "except", "exc_type", "as", "e", ":", "print_error", "(", "\"Could not bind '%s': %s: %s\"", "%", "(", "name_", ",", "e", ".", "__class__", ".", "__name__", ",", "str", "(", "e", ")", ")", ")", "continue", "installed_variants", ".", "extend", "(", "variants_", ")", "for", "variant", "in", "variants_", ":", "installed_package_names", ".", "add", "(", "variant", ".", "name", ")", "# add dependencies", "if", "not", "no_deps", ":", "for", "variant", "in", "variants_", ":", "for", "requirement", "in", "variant", ".", "requires", ":", "if", "not", "requirement", ".", "conflict", ":", "pending", ".", "add", "(", "requirement", ".", "name", ")", "# non-primary packages are treated a little differently", "primary", "=", "False", "version_range", "=", "None", "bind_args", "=", "None", "exc_type", "=", "RezBindError", "if", "installed_variants", "and", "not", "quiet", ":", "print", "\"The following packages were installed:\"", "print", "_print_package_list", "(", "installed_variants", ")", "return", "installed_variants" ]
Bind software available on the current system, as a rez package. Note: `bind_args` is provided when software is bound via the 'rez-bind' command line tool. Bind modules can define their own command line options, and they will be present in `bind_args` if applicable. Args: name (str): Package name. path (str): Package path to install into; local packages path if None. version_range (`VersionRange`): If provided, only bind the software if it falls within this version range. no_deps (bool): If True, don't bind dependencies. bind_args (list of str): Command line options. quiet (bool): If True, suppress superfluous output. Returns: List of `Variant`: The variant(s) that were installed as a result of binding this package.
[ "Bind", "software", "available", "on", "the", "current", "system", "as", "a", "rez", "package", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_bind.py#L71-L141
232,542
nerdvegas/rez
src/rez/release_hook.py
create_release_hook
def create_release_hook(name, source_path): """Return a new release hook of the given type.""" from rez.plugin_managers import plugin_manager return plugin_manager.create_instance('release_hook', name, source_path=source_path)
python
def create_release_hook(name, source_path): """Return a new release hook of the given type.""" from rez.plugin_managers import plugin_manager return plugin_manager.create_instance('release_hook', name, source_path=source_path)
[ "def", "create_release_hook", "(", "name", ",", "source_path", ")", ":", "from", "rez", ".", "plugin_managers", "import", "plugin_manager", "return", "plugin_manager", ".", "create_instance", "(", "'release_hook'", ",", "name", ",", "source_path", "=", "source_path", ")" ]
Return a new release hook of the given type.
[ "Return", "a", "new", "release", "hook", "of", "the", "given", "type", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_hook.py#L12-L17
232,543
nerdvegas/rez
src/rez/release_hook.py
ReleaseHook.pre_build
def pre_build(self, user, install_path, variants=None, release_message=None, changelog=None, previous_version=None, previous_revision=None, **kwargs): """Pre-build hook. Args: user: Name of person who did the release. install_path: Directory the package was installed into. variants: List of variant indices we are attempting to build, or None release_message: User-supplied release message. changelog: List of strings describing changes since last release. previous_version: Version object - previously-release package, or None if no previous release. previous_revision: Revision of previously-released package (type depends on repo - see ReleaseVCS.get_current_revision(). kwargs: Reserved. Note: This method should raise a `ReleaseHookCancellingError` if the release process should be cancelled. """ pass
python
def pre_build(self, user, install_path, variants=None, release_message=None, changelog=None, previous_version=None, previous_revision=None, **kwargs): """Pre-build hook. Args: user: Name of person who did the release. install_path: Directory the package was installed into. variants: List of variant indices we are attempting to build, or None release_message: User-supplied release message. changelog: List of strings describing changes since last release. previous_version: Version object - previously-release package, or None if no previous release. previous_revision: Revision of previously-released package (type depends on repo - see ReleaseVCS.get_current_revision(). kwargs: Reserved. Note: This method should raise a `ReleaseHookCancellingError` if the release process should be cancelled. """ pass
[ "def", "pre_build", "(", "self", ",", "user", ",", "install_path", ",", "variants", "=", "None", ",", "release_message", "=", "None", ",", "changelog", "=", "None", ",", "previous_version", "=", "None", ",", "previous_revision", "=", "None", ",", "*", "*", "kwargs", ")", ":", "pass" ]
Pre-build hook. Args: user: Name of person who did the release. install_path: Directory the package was installed into. variants: List of variant indices we are attempting to build, or None release_message: User-supplied release message. changelog: List of strings describing changes since last release. previous_version: Version object - previously-release package, or None if no previous release. previous_revision: Revision of previously-released package (type depends on repo - see ReleaseVCS.get_current_revision(). kwargs: Reserved. Note: This method should raise a `ReleaseHookCancellingError` if the release process should be cancelled.
[ "Pre", "-", "build", "hook", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_hook.py#L56-L78
232,544
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/traversal.py
traversal
def traversal(graph, node, order): """ Graph traversal iterator. @type graph: graph, digraph @param graph: Graph. @type node: node @param node: Node. @type order: string @param order: traversal ordering. Possible values are: 2. 'pre' - Preordering (default) 1. 'post' - Postordering @rtype: iterator @return: Traversal iterator. """ visited = {} if (order == 'pre'): pre = 1 post = 0 elif (order == 'post'): pre = 0 post = 1 for each in _dfs(graph, visited, node, pre, post): yield each
python
def traversal(graph, node, order): """ Graph traversal iterator. @type graph: graph, digraph @param graph: Graph. @type node: node @param node: Node. @type order: string @param order: traversal ordering. Possible values are: 2. 'pre' - Preordering (default) 1. 'post' - Postordering @rtype: iterator @return: Traversal iterator. """ visited = {} if (order == 'pre'): pre = 1 post = 0 elif (order == 'post'): pre = 0 post = 1 for each in _dfs(graph, visited, node, pre, post): yield each
[ "def", "traversal", "(", "graph", ",", "node", ",", "order", ")", ":", "visited", "=", "{", "}", "if", "(", "order", "==", "'pre'", ")", ":", "pre", "=", "1", "post", "=", "0", "elif", "(", "order", "==", "'post'", ")", ":", "pre", "=", "0", "post", "=", "1", "for", "each", "in", "_dfs", "(", "graph", ",", "visited", ",", "node", ",", "pre", ",", "post", ")", ":", "yield", "each" ]
Graph traversal iterator. @type graph: graph, digraph @param graph: Graph. @type node: node @param node: Node. @type order: string @param order: traversal ordering. Possible values are: 2. 'pre' - Preordering (default) 1. 'post' - Postordering @rtype: iterator @return: Traversal iterator.
[ "Graph", "traversal", "iterator", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/traversal.py#L34-L61
232,545
nerdvegas/rez
src/rez/backport/zipfile.py
is_zipfile
def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number.""" try: fpin = open(filename, "rb") endrec = _EndRecData(fpin) fpin.close() if endrec: return True # file has correct magic number except IOError: pass return False
python
def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number.""" try: fpin = open(filename, "rb") endrec = _EndRecData(fpin) fpin.close() if endrec: return True # file has correct magic number except IOError: pass return False
[ "def", "is_zipfile", "(", "filename", ")", ":", "try", ":", "fpin", "=", "open", "(", "filename", ",", "\"rb\"", ")", "endrec", "=", "_EndRecData", "(", "fpin", ")", "fpin", ".", "close", "(", ")", "if", "endrec", ":", "return", "True", "# file has correct magic number", "except", "IOError", ":", "pass", "return", "False" ]
Quickly see if file is a ZIP file by checking the magic number.
[ "Quickly", "see", "if", "file", "is", "a", "ZIP", "file", "by", "checking", "the", "magic", "number", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L133-L143
232,546
nerdvegas/rez
src/rez/backport/zipfile.py
_EndRecData
def _EndRecData(fpin): """Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.""" # Determine file size fpin.seek(0, 2) filesize = fpin.tell() # Check to see if this is ZIP file with no archive comment (the # "end of central directory" structure should be the last item in the # file if this is the case). try: fpin.seek(-sizeEndCentDir, 2) except IOError: return None data = fpin.read() if data[0:4] == stringEndArchive and data[-2:] == "\000\000": # the signature is correct and there's no comment, unpack structure endrec = struct.unpack(structEndArchive, data) endrec=list(endrec) # Append a blank comment and record start offset endrec.append("") endrec.append(filesize - sizeEndCentDir) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, -sizeEndCentDir, endrec) # Either this is not a ZIP file, or it is a ZIP file with an archive # comment. Search the end of the file for the "end of central directory" # record signature. The comment is the last item in the ZIP file and may be # up to 64K long. It is assumed that the "end of central directory" magic # number does not appear in the comment. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0) fpin.seek(maxCommentStart, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] endrec = list(struct.unpack(structEndArchive, recData)) comment = data[start+sizeEndCentDir:] # check that comment length is correct if endrec[_ECD_COMMENT_SIZE] == len(comment): # Append the archive comment and start offset endrec.append(comment) endrec.append(maxCommentStart + start) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, maxCommentStart + start - filesize, endrec) # Unable to find a valid end of central directory structure return
python
def _EndRecData(fpin): """Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.""" # Determine file size fpin.seek(0, 2) filesize = fpin.tell() # Check to see if this is ZIP file with no archive comment (the # "end of central directory" structure should be the last item in the # file if this is the case). try: fpin.seek(-sizeEndCentDir, 2) except IOError: return None data = fpin.read() if data[0:4] == stringEndArchive and data[-2:] == "\000\000": # the signature is correct and there's no comment, unpack structure endrec = struct.unpack(structEndArchive, data) endrec=list(endrec) # Append a blank comment and record start offset endrec.append("") endrec.append(filesize - sizeEndCentDir) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, -sizeEndCentDir, endrec) # Either this is not a ZIP file, or it is a ZIP file with an archive # comment. Search the end of the file for the "end of central directory" # record signature. The comment is the last item in the ZIP file and may be # up to 64K long. It is assumed that the "end of central directory" magic # number does not appear in the comment. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0) fpin.seek(maxCommentStart, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] endrec = list(struct.unpack(structEndArchive, recData)) comment = data[start+sizeEndCentDir:] # check that comment length is correct if endrec[_ECD_COMMENT_SIZE] == len(comment): # Append the archive comment and start offset endrec.append(comment) endrec.append(maxCommentStart + start) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, maxCommentStart + start - filesize, endrec) # Unable to find a valid end of central directory structure return
[ "def", "_EndRecData", "(", "fpin", ")", ":", "# Determine file size", "fpin", ".", "seek", "(", "0", ",", "2", ")", "filesize", "=", "fpin", ".", "tell", "(", ")", "# Check to see if this is ZIP file with no archive comment (the", "# \"end of central directory\" structure should be the last item in the", "# file if this is the case).", "try", ":", "fpin", ".", "seek", "(", "-", "sizeEndCentDir", ",", "2", ")", "except", "IOError", ":", "return", "None", "data", "=", "fpin", ".", "read", "(", ")", "if", "data", "[", "0", ":", "4", "]", "==", "stringEndArchive", "and", "data", "[", "-", "2", ":", "]", "==", "\"\\000\\000\"", ":", "# the signature is correct and there's no comment, unpack structure", "endrec", "=", "struct", ".", "unpack", "(", "structEndArchive", ",", "data", ")", "endrec", "=", "list", "(", "endrec", ")", "# Append a blank comment and record start offset", "endrec", ".", "append", "(", "\"\"", ")", "endrec", ".", "append", "(", "filesize", "-", "sizeEndCentDir", ")", "# Try to read the \"Zip64 end of central directory\" structure", "return", "_EndRecData64", "(", "fpin", ",", "-", "sizeEndCentDir", ",", "endrec", ")", "# Either this is not a ZIP file, or it is a ZIP file with an archive", "# comment. Search the end of the file for the \"end of central directory\"", "# record signature. The comment is the last item in the ZIP file and may be", "# up to 64K long. It is assumed that the \"end of central directory\" magic", "# number does not appear in the comment.", "maxCommentStart", "=", "max", "(", "filesize", "-", "(", "1", "<<", "16", ")", "-", "sizeEndCentDir", ",", "0", ")", "fpin", ".", "seek", "(", "maxCommentStart", ",", "0", ")", "data", "=", "fpin", ".", "read", "(", ")", "start", "=", "data", ".", "rfind", "(", "stringEndArchive", ")", "if", "start", ">=", "0", ":", "# found the magic number; attempt to unpack and interpret", "recData", "=", "data", "[", "start", ":", "start", "+", "sizeEndCentDir", "]", "endrec", "=", "list", "(", "struct", ".", "unpack", "(", "structEndArchive", ",", "recData", ")", ")", "comment", "=", "data", "[", "start", "+", "sizeEndCentDir", ":", "]", "# check that comment length is correct", "if", "endrec", "[", "_ECD_COMMENT_SIZE", "]", "==", "len", "(", "comment", ")", ":", "# Append the archive comment and start offset", "endrec", ".", "append", "(", "comment", ")", "endrec", ".", "append", "(", "maxCommentStart", "+", "start", ")", "# Try to read the \"Zip64 end of central directory\" structure", "return", "_EndRecData64", "(", "fpin", ",", "maxCommentStart", "+", "start", "-", "filesize", ",", "endrec", ")", "# Unable to find a valid end of central directory structure", "return" ]
Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.
[ "Return", "data", "from", "the", "End", "of", "Central", "Directory", "record", "or", "None", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L178-L233
232,547
nerdvegas/rez
src/rez/backport/zipfile.py
_ZipDecrypter._GenerateCRCTable
def _GenerateCRCTable(): """Generate a CRC-32 table. ZIP encryption uses the CRC32 one-byte primitive for scrambling some internal keys. We noticed that a direct implementation is faster than relying on binascii.crc32(). """ poly = 0xedb88320 table = [0] * 256 for i in range(256): crc = i for j in range(8): if crc & 1: crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly else: crc = ((crc >> 1) & 0x7FFFFFFF) table[i] = crc return table
python
def _GenerateCRCTable(): """Generate a CRC-32 table. ZIP encryption uses the CRC32 one-byte primitive for scrambling some internal keys. We noticed that a direct implementation is faster than relying on binascii.crc32(). """ poly = 0xedb88320 table = [0] * 256 for i in range(256): crc = i for j in range(8): if crc & 1: crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly else: crc = ((crc >> 1) & 0x7FFFFFFF) table[i] = crc return table
[ "def", "_GenerateCRCTable", "(", ")", ":", "poly", "=", "0xedb88320", "table", "=", "[", "0", "]", "*", "256", "for", "i", "in", "range", "(", "256", ")", ":", "crc", "=", "i", "for", "j", "in", "range", "(", "8", ")", ":", "if", "crc", "&", "1", ":", "crc", "=", "(", "(", "crc", ">>", "1", ")", "&", "0x7FFFFFFF", ")", "^", "poly", "else", ":", "crc", "=", "(", "(", "crc", ">>", "1", ")", "&", "0x7FFFFFFF", ")", "table", "[", "i", "]", "=", "crc", "return", "table" ]
Generate a CRC-32 table. ZIP encryption uses the CRC32 one-byte primitive for scrambling some internal keys. We noticed that a direct implementation is faster than relying on binascii.crc32().
[ "Generate", "a", "CRC", "-", "32", "table", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L398-L415
232,548
nerdvegas/rez
src/rez/backport/zipfile.py
_ZipDecrypter._crc32
def _crc32(self, ch, crc): """Compute the CRC32 primitive on one byte.""" return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff]
python
def _crc32(self, ch, crc): """Compute the CRC32 primitive on one byte.""" return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff]
[ "def", "_crc32", "(", "self", ",", "ch", ",", "crc", ")", ":", "return", "(", "(", "crc", ">>", "8", ")", "&", "0xffffff", ")", "^", "self", ".", "crctable", "[", "(", "crc", "^", "ord", "(", "ch", ")", ")", "&", "0xff", "]" ]
Compute the CRC32 primitive on one byte.
[ "Compute", "the", "CRC32", "primitive", "on", "one", "byte", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L418-L420
232,549
nerdvegas/rez
src/rez/backport/zipfile.py
ZipExtFile.readline
def readline(self, size = -1): """Read a line with approx. size. If size is negative, read a whole line. """ if size < 0: size = sys.maxint elif size == 0: return '' # check for a newline already in buffer nl, nllen = self._checkfornewline() if nl >= 0: # the next line was already in the buffer nl = min(nl, size) else: # no line break in buffer - try to read more size -= len(self.linebuffer) while nl < 0 and size > 0: buf = self.read(min(size, 100)) if not buf: break self.linebuffer += buf size -= len(buf) # check for a newline in buffer nl, nllen = self._checkfornewline() # we either ran out of bytes in the file, or # met the specified size limit without finding a newline, # so return current buffer if nl < 0: s = self.linebuffer self.linebuffer = '' return s buf = self.linebuffer[:nl] self.lastdiscard = self.linebuffer[nl:nl + nllen] self.linebuffer = self.linebuffer[nl + nllen:] # line is always returned with \n as newline char (except possibly # for a final incomplete line in the file, which is handled above). return buf + "\n"
python
def readline(self, size = -1): """Read a line with approx. size. If size is negative, read a whole line. """ if size < 0: size = sys.maxint elif size == 0: return '' # check for a newline already in buffer nl, nllen = self._checkfornewline() if nl >= 0: # the next line was already in the buffer nl = min(nl, size) else: # no line break in buffer - try to read more size -= len(self.linebuffer) while nl < 0 and size > 0: buf = self.read(min(size, 100)) if not buf: break self.linebuffer += buf size -= len(buf) # check for a newline in buffer nl, nllen = self._checkfornewline() # we either ran out of bytes in the file, or # met the specified size limit without finding a newline, # so return current buffer if nl < 0: s = self.linebuffer self.linebuffer = '' return s buf = self.linebuffer[:nl] self.lastdiscard = self.linebuffer[nl:nl + nllen] self.linebuffer = self.linebuffer[nl + nllen:] # line is always returned with \n as newline char (except possibly # for a final incomplete line in the file, which is handled above). return buf + "\n"
[ "def", "readline", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "<", "0", ":", "size", "=", "sys", ".", "maxint", "elif", "size", "==", "0", ":", "return", "''", "# check for a newline already in buffer", "nl", ",", "nllen", "=", "self", ".", "_checkfornewline", "(", ")", "if", "nl", ">=", "0", ":", "# the next line was already in the buffer", "nl", "=", "min", "(", "nl", ",", "size", ")", "else", ":", "# no line break in buffer - try to read more", "size", "-=", "len", "(", "self", ".", "linebuffer", ")", "while", "nl", "<", "0", "and", "size", ">", "0", ":", "buf", "=", "self", ".", "read", "(", "min", "(", "size", ",", "100", ")", ")", "if", "not", "buf", ":", "break", "self", ".", "linebuffer", "+=", "buf", "size", "-=", "len", "(", "buf", ")", "# check for a newline in buffer", "nl", ",", "nllen", "=", "self", ".", "_checkfornewline", "(", ")", "# we either ran out of bytes in the file, or", "# met the specified size limit without finding a newline,", "# so return current buffer", "if", "nl", "<", "0", ":", "s", "=", "self", ".", "linebuffer", "self", ".", "linebuffer", "=", "''", "return", "s", "buf", "=", "self", ".", "linebuffer", "[", ":", "nl", "]", "self", ".", "lastdiscard", "=", "self", ".", "linebuffer", "[", "nl", ":", "nl", "+", "nllen", "]", "self", ".", "linebuffer", "=", "self", ".", "linebuffer", "[", "nl", "+", "nllen", ":", "]", "# line is always returned with \\n as newline char (except possibly", "# for a final incomplete line in the file, which is handled above).", "return", "buf", "+", "\"\\n\"" ]
Read a line with approx. size. If size is negative, read a whole line.
[ "Read", "a", "line", "with", "approx", ".", "size", ".", "If", "size", "is", "negative", "read", "a", "whole", "line", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L511-L553
232,550
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile._GetContents
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
python
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
[ "def", "_GetContents", "(", "self", ")", ":", "try", ":", "self", ".", "_RealGetContents", "(", ")", "except", "BadZipfile", ":", "if", "not", "self", ".", "_filePassed", ":", "self", ".", "fp", ".", "close", "(", ")", "self", ".", "fp", "=", "None", "raise" ]
Read the directory, making sure we close the file if the format is bad.
[ "Read", "the", "directory", "making", "sure", "we", "close", "the", "file", "if", "the", "format", "is", "bad", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L714-L723
232,551
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile.namelist
def namelist(self): """Return a list of file names in the archive.""" l = [] for data in self.filelist: l.append(data.filename) return l
python
def namelist(self): """Return a list of file names in the archive.""" l = [] for data in self.filelist: l.append(data.filename) return l
[ "def", "namelist", "(", "self", ")", ":", "l", "=", "[", "]", "for", "data", "in", "self", ".", "filelist", ":", "l", ".", "append", "(", "data", ".", "filename", ")", "return", "l" ]
Return a list of file names in the archive.
[ "Return", "a", "list", "of", "file", "names", "in", "the", "archive", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L789-L794
232,552
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile.printdir
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, zinfo.file_size)
python
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, zinfo.file_size)
[ "def", "printdir", "(", "self", ")", ":", "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", ",", "zinfo", ".", "file_size", ")" ]
Print a table of contents for the zip file.
[ "Print", "a", "table", "of", "contents", "for", "the", "zip", "file", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L801-L806
232,553
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile.getinfo
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
python
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
[ "def", "getinfo", "(", "self", ",", "name", ")", ":", "info", "=", "self", ".", "NameToInfo", ".", "get", "(", "name", ")", "if", "info", "is", "None", ":", "raise", "KeyError", "(", "'There is no item named %r in the archive'", "%", "name", ")", "return", "info" ]
Return the instance of ZipInfo given 'name'.
[ "Return", "the", "instance", "of", "ZipInfo", "given", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L821-L828
232,554
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile.extract
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 directory using `path'. """ if not isinstance(member, ZipInfo): member = self.getinfo(member) if path is None: path = os.getcwd() return self._extract_member(member, path, pwd)
python
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 directory using `path'. """ if not isinstance(member, ZipInfo): member = self.getinfo(member) if path is None: path = os.getcwd() return self._extract_member(member, path, pwd)
[ "def", "extract", "(", "self", ",", "member", ",", "path", "=", "None", ",", "pwd", "=", "None", ")", ":", "if", "not", "isinstance", "(", "member", ",", "ZipInfo", ")", ":", "member", "=", "self", ".", "getinfo", "(", "member", ")", "if", "path", "is", "None", ":", "path", "=", "os", ".", "getcwd", "(", ")", "return", "self", ".", "_extract_member", "(", "member", ",", "path", ",", "pwd", ")" ]
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'.
[ "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", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L916-L928
232,555
nerdvegas/rez
src/rez/backport/zipfile.py
PyZipFile.writepy
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 directory, listdir *.py and enter all modules. Else, pathname must be a Python *.py file and the module will be put into the archive. Added modules are always module.pyo or module.pyc. This method will compile the module.py into module.pyc if necessary. """ dir, name = os.path.split(pathname) if os.path.isdir(pathname): initname = os.path.join(pathname, "__init__.py") if os.path.isfile(initname): # This is a package directory, add it if basename: basename = "%s/%s" % (basename, name) else: basename = name if self.debug: print "Adding package in", pathname, "as", basename fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) dirlist = os.listdir(pathname) dirlist.remove("__init__.py") # Add all *.py files and package subdirectories for filename in dirlist: path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if os.path.isdir(path): if os.path.isfile(os.path.join(path, "__init__.py")): # This is a package directory, add it self.writepy(path, basename) # Recursive call elif ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: print "Adding files from directory", pathname for filename in os.listdir(pathname): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: if pathname[-3:] != ".py": raise RuntimeError, \ 'Files added with writepy() must end with ".py"' fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: print "Adding file", arcname self.write(fname, arcname)
python
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 directory, listdir *.py and enter all modules. Else, pathname must be a Python *.py file and the module will be put into the archive. Added modules are always module.pyo or module.pyc. This method will compile the module.py into module.pyc if necessary. """ dir, name = os.path.split(pathname) if os.path.isdir(pathname): initname = os.path.join(pathname, "__init__.py") if os.path.isfile(initname): # This is a package directory, add it if basename: basename = "%s/%s" % (basename, name) else: basename = name if self.debug: print "Adding package in", pathname, "as", basename fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) dirlist = os.listdir(pathname) dirlist.remove("__init__.py") # Add all *.py files and package subdirectories for filename in dirlist: path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if os.path.isdir(path): if os.path.isfile(os.path.join(path, "__init__.py")): # This is a package directory, add it self.writepy(path, basename) # Recursive call elif ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: print "Adding files from directory", pathname for filename in os.listdir(pathname): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: if pathname[-3:] != ".py": raise RuntimeError, \ 'Files added with writepy() must end with ".py"' fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: print "Adding file", arcname self.write(fname, arcname)
[ "def", "writepy", "(", "self", ",", "pathname", ",", "basename", "=", "\"\"", ")", ":", "dir", ",", "name", "=", "os", ".", "path", ".", "split", "(", "pathname", ")", "if", "os", ".", "path", ".", "isdir", "(", "pathname", ")", ":", "initname", "=", "os", ".", "path", ".", "join", "(", "pathname", ",", "\"__init__.py\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "initname", ")", ":", "# This is a package directory, add it", "if", "basename", ":", "basename", "=", "\"%s/%s\"", "%", "(", "basename", ",", "name", ")", "else", ":", "basename", "=", "name", "if", "self", ".", "debug", ":", "print", "\"Adding package in\"", ",", "pathname", ",", "\"as\"", ",", "basename", "fname", ",", "arcname", "=", "self", ".", "_get_codename", "(", "initname", "[", "0", ":", "-", "3", "]", ",", "basename", ")", "if", "self", ".", "debug", ":", "print", "\"Adding\"", ",", "arcname", "self", ".", "write", "(", "fname", ",", "arcname", ")", "dirlist", "=", "os", ".", "listdir", "(", "pathname", ")", "dirlist", ".", "remove", "(", "\"__init__.py\"", ")", "# Add all *.py files and package subdirectories", "for", "filename", "in", "dirlist", ":", "path", "=", "os", ".", "path", ".", "join", "(", "pathname", ",", "filename", ")", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "\"__init__.py\"", ")", ")", ":", "# This is a package directory, add it", "self", ".", "writepy", "(", "path", ",", "basename", ")", "# Recursive call", "elif", "ext", "==", "\".py\"", ":", "fname", ",", "arcname", "=", "self", ".", "_get_codename", "(", "path", "[", "0", ":", "-", "3", "]", ",", "basename", ")", "if", "self", ".", "debug", ":", "print", "\"Adding\"", ",", "arcname", "self", ".", "write", "(", "fname", ",", "arcname", ")", "else", ":", "# This is NOT a package directory, add its files at top level", "if", "self", ".", "debug", ":", "print", "\"Adding files from directory\"", ",", "pathname", "for", "filename", "in", "os", ".", "listdir", "(", "pathname", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "pathname", ",", "filename", ")", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "==", "\".py\"", ":", "fname", ",", "arcname", "=", "self", ".", "_get_codename", "(", "path", "[", "0", ":", "-", "3", "]", ",", "basename", ")", "if", "self", ".", "debug", ":", "print", "\"Adding\"", ",", "arcname", "self", ".", "write", "(", "fname", ",", "arcname", ")", "else", ":", "if", "pathname", "[", "-", "3", ":", "]", "!=", "\".py\"", ":", "raise", "RuntimeError", ",", "'Files added with writepy() must end with \".py\"'", "fname", ",", "arcname", "=", "self", ".", "_get_codename", "(", "pathname", "[", "0", ":", "-", "3", "]", ",", "basename", ")", "if", "self", ".", "debug", ":", "print", "\"Adding file\"", ",", "arcname", "self", ".", "write", "(", "fname", ",", "arcname", ")" ]
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, pathname must be a Python *.py file and the module will be put into the archive. Added modules are always module.pyo or module.pyc. This method will compile the module.py into module.pyc if necessary.
[ "Add", "all", "files", "from", "pathname", "to", "the", "ZIP", "archive", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L1241-L1304
232,556
nerdvegas/rez
src/rez/vendor/atomicwrites/__init__.py
AtomicWriter.get_fileobject
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 # the name later for commit()/replace_atomic() and couldn't find a way # to get the filename from the descriptor. os.close(descriptor) kwargs['mode'] = self._mode kwargs['file'] = name return io.open(**kwargs)
python
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 # the name later for commit()/replace_atomic() and couldn't find a way # to get the filename from the descriptor. os.close(descriptor) kwargs['mode'] = self._mode kwargs['file'] = name return io.open(**kwargs)
[ "def", "get_fileobject", "(", "self", ",", "dir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "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", "# the name later for commit()/replace_atomic() and couldn't find a way", "# to get the filename from the descriptor.", "os", ".", "close", "(", "descriptor", ")", "kwargs", "[", "'mode'", "]", "=", "self", ".", "_mode", "kwargs", "[", "'file'", "]", "=", "name", "return", "io", ".", "open", "(", "*", "*", "kwargs", ")" ]
Return the temporary file to use.
[ "Return", "the", "temporary", "file", "to", "use", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/atomicwrites/__init__.py#L163-L174
232,557
nerdvegas/rez
src/rez/vendor/atomicwrites/__init__.py
AtomicWriter.commit
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)
python
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)
[ "def", "commit", "(", "self", ",", "f", ")", ":", "if", "self", ".", "_overwrite", ":", "replace_atomic", "(", "f", ".", "name", ",", "self", ".", "_path", ")", "else", ":", "move_atomic", "(", "f", ".", "name", ",", "self", ".", "_path", ")" ]
Move the temporary file to the target location.
[ "Move", "the", "temporary", "file", "to", "the", "target", "location", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/atomicwrites/__init__.py#L182-L187
232,558
nerdvegas/rez
src/rez/vendor/lockfile/pidlockfile.py
read_pid_from_pidfile
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: pidfile = open(pidfile_path, 'r') except IOError: pass else: # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. # # Programs that read PID files should be somewhat flexible # in what they accept; i.e., they should ignore extra # whitespace, leading zeroes, absence of the trailing # newline, or additional lines in the PID file. line = pidfile.readline().strip() try: pid = int(line) except ValueError: pass pidfile.close() return pid
python
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: pidfile = open(pidfile_path, 'r') except IOError: pass else: # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. # # Programs that read PID files should be somewhat flexible # in what they accept; i.e., they should ignore extra # whitespace, leading zeroes, absence of the trailing # newline, or additional lines in the PID file. line = pidfile.readline().strip() try: pid = int(line) except ValueError: pass pidfile.close() return pid
[ "def", "read_pid_from_pidfile", "(", "pidfile_path", ")", ":", "pid", "=", "None", "try", ":", "pidfile", "=", "open", "(", "pidfile_path", ",", "'r'", ")", "except", "IOError", ":", "pass", "else", ":", "# According to the FHS 2.3 section on PID files in /var/run:", "# ", "# The file must consist of the process identifier in", "# ASCII-encoded decimal, followed by a newline character.", "# ", "# Programs that read PID files should be somewhat flexible", "# in what they accept; i.e., they should ignore extra", "# whitespace, leading zeroes, absence of the trailing", "# newline, or additional lines in the PID file.", "line", "=", "pidfile", ".", "readline", "(", ")", ".", "strip", "(", ")", "try", ":", "pid", "=", "int", "(", "line", ")", "except", "ValueError", ":", "pass", "pidfile", ".", "close", "(", ")", "return", "pid" ]
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``.
[ "Read", "the", "PID", "recorded", "in", "the", "named", "PID", "file", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/lockfile/pidlockfile.py#L120-L151
232,559
nerdvegas/rez
src/rezgui/widgets/ConfiguredSplitter.py
ConfiguredSplitter.apply_saved_layout
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) size = self.config.get(key, int) sizes.append(size) self.setSizes(sizes) return True return False
python
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) size = self.config.get(key, int) sizes.append(size) self.setSizes(sizes) return True return False
[ "def", "apply_saved_layout", "(", "self", ")", ":", "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", ")", "size", "=", "self", ".", "config", ".", "get", "(", "key", ",", "int", ")", "sizes", ".", "append", "(", "size", ")", "self", ".", "setSizes", "(", "sizes", ")", "return", "True", "return", "False" ]
Call this after adding your child widgets.
[ "Call", "this", "after", "adding", "your", "child", "widgets", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/ConfiguredSplitter.py#L14-L25
232,560
nerdvegas/rez
src/rez/utils/data_utils.py
remove_nones
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)
python
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)
[ "def", "remove_nones", "(", "*", "*", "kwargs", ")", ":", "return", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ")", "if", "v", "is", "not", "None", ")" ]
Return diict copy with nones removed.
[ "Return", "diict", "copy", "with", "nones", "removed", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L33-L36
232,561
nerdvegas/rez
src/rez/utils/data_utils.py
deep_update
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): return dict((k, flatten(v_)) for k, v_ in v.iteritems()) else: return v def merge(v1, v2): if isinstance(v1, dict) and isinstance(v2, dict): deep_update(v1, v2) return v1 elif isinstance(v2, ModifyList): v1 = flatten(v1) return v2.apply(v1) else: return flatten(v2) for k1, v1 in dict1.iteritems(): if k1 not in dict2: dict1[k1] = flatten(v1) for k2, v2 in dict2.iteritems(): v1 = dict1.get(k2) if v1 is KeyError: dict1[k2] = flatten(v2) else: dict1[k2] = merge(v1, v2)
python
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): return dict((k, flatten(v_)) for k, v_ in v.iteritems()) else: return v def merge(v1, v2): if isinstance(v1, dict) and isinstance(v2, dict): deep_update(v1, v2) return v1 elif isinstance(v2, ModifyList): v1 = flatten(v1) return v2.apply(v1) else: return flatten(v2) for k1, v1 in dict1.iteritems(): if k1 not in dict2: dict1[k1] = flatten(v1) for k2, v2 in dict2.iteritems(): v1 = dict1.get(k2) if v1 is KeyError: dict1[k2] = flatten(v2) else: dict1[k2] = merge(v1, v2)
[ "def", "deep_update", "(", "dict1", ",", "dict2", ")", ":", "def", "flatten", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "ModifyList", ")", ":", "return", "v", ".", "apply", "(", "[", "]", ")", "elif", "isinstance", "(", "v", ",", "dict", ")", ":", "return", "dict", "(", "(", "k", ",", "flatten", "(", "v_", ")", ")", "for", "k", ",", "v_", "in", "v", ".", "iteritems", "(", ")", ")", "else", ":", "return", "v", "def", "merge", "(", "v1", ",", "v2", ")", ":", "if", "isinstance", "(", "v1", ",", "dict", ")", "and", "isinstance", "(", "v2", ",", "dict", ")", ":", "deep_update", "(", "v1", ",", "v2", ")", "return", "v1", "elif", "isinstance", "(", "v2", ",", "ModifyList", ")", ":", "v1", "=", "flatten", "(", "v1", ")", "return", "v2", ".", "apply", "(", "v1", ")", "else", ":", "return", "flatten", "(", "v2", ")", "for", "k1", ",", "v1", "in", "dict1", ".", "iteritems", "(", ")", ":", "if", "k1", "not", "in", "dict2", ":", "dict1", "[", "k1", "]", "=", "flatten", "(", "v1", ")", "for", "k2", ",", "v2", "in", "dict2", ".", "iteritems", "(", ")", ":", "v1", "=", "dict1", ".", "get", "(", "k2", ")", "if", "v1", "is", "KeyError", ":", "dict1", "[", "k2", "]", "=", "flatten", "(", "v2", ")", "else", ":", "dict1", "[", "k2", "]", "=", "merge", "(", "v1", ",", "v2", ")" ]
Perform a deep merge of `dict2` into `dict1`. Note that `dict2` and any nested dicts are unchanged. Supports `ModifyList` instances.
[ "Perform", "a", "deep", "merge", "of", "dict2", "into", "dict1", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L39-L74
232,562
nerdvegas/rez
src/rez/utils/data_utils.py
deep_del
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): result[k] = deep_del(v, fn) else: result[k] = v return result
python
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): result[k] = deep_del(v, fn) else: result[k] = v return result
[ "def", "deep_del", "(", "data", ",", "fn", ")", ":", "result", "=", "{", "}", "for", "k", ",", "v", "in", "data", ".", "iteritems", "(", ")", ":", "if", "not", "fn", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "result", "[", "k", "]", "=", "deep_del", "(", "v", ",", "fn", ")", "else", ":", "result", "[", "k", "]", "=", "v", "return", "result" ]
Create dict copy with removed items. Recursively remove items where fn(value) is True. Returns: dict: New dict with matching items removed.
[ "Create", "dict", "copy", "with", "removed", "items", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L77-L94
232,563
nerdvegas/rez
src/rez/utils/data_utils.py
get_dict_diff_str
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: lines.append("Removed attributes: %s" % ['.'.join(x) for x in removed]) if changed: lines.append("Changed attributes: %s" % ['.'.join(x) for x in changed]) return '\n'.join(lines)
python
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: lines.append("Removed attributes: %s" % ['.'.join(x) for x in removed]) if changed: lines.append("Changed attributes: %s" % ['.'.join(x) for x in changed]) return '\n'.join(lines)
[ "def", "get_dict_diff_str", "(", "d1", ",", "d2", ",", "title", ")", ":", "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", ":", "lines", ".", "append", "(", "\"Removed attributes: %s\"", "%", "[", "'.'", ".", "join", "(", "x", ")", "for", "x", "in", "removed", "]", ")", "if", "changed", ":", "lines", ".", "append", "(", "\"Changed attributes: %s\"", "%", "[", "'.'", ".", "join", "(", "x", ")", "for", "x", "in", "changed", "]", ")", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
Returns same as `get_dict_diff`, but as a readable string.
[ "Returns", "same", "as", "get_dict_diff", "but", "as", "a", "readable", "string", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L138-L154
232,564
nerdvegas/rez
src/rez/utils/data_utils.py
convert_dicts
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 convert values from. If a tuple, multiple types are converted. Returns: Converted data as `to_class` instance. """ d_ = to_class() for key, value in d.iteritems(): if isinstance(value, from_class): d_[key] = convert_dicts(value, to_class=to_class, from_class=from_class) else: d_[key] = value return d_
python
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 convert values from. If a tuple, multiple types are converted. Returns: Converted data as `to_class` instance. """ d_ = to_class() for key, value in d.iteritems(): if isinstance(value, from_class): d_[key] = convert_dicts(value, to_class=to_class, from_class=from_class) else: d_[key] = value return d_
[ "def", "convert_dicts", "(", "d", ",", "to_class", "=", "AttrDictWrapper", ",", "from_class", "=", "dict", ")", ":", "d_", "=", "to_class", "(", ")", "for", "key", ",", "value", "in", "d", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "value", ",", "from_class", ")", ":", "d_", "[", "key", "]", "=", "convert_dicts", "(", "value", ",", "to_class", "=", "to_class", ",", "from_class", "=", "from_class", ")", "else", ":", "d_", "[", "key", "]", "=", "value", "return", "d_" ]
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. Returns: Converted data as `to_class` instance.
[ "Recursively", "convert", "dict", "and", "UserDict", "types", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L319-L340
232,565
nerdvegas/rez
src/rez/package_repository.py
PackageRepositoryGlobalStats.package_loading
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
python
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
[ "def", "package_loading", "(", "self", ")", ":", "t1", "=", "time", ".", "time", "(", ")", "yield", "None", "t2", "=", "time", ".", "time", "(", ")", "self", ".", "package_load_time", "+=", "t2", "-", "t1" ]
Use this around code in your package repository that is loading a package, for example from file or cache.
[ "Use", "this", "around", "code", "in", "your", "package", "repository", "that", "is", "loading", "a", "package", "for", "example", "from", "file", "or", "cache", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L42-L50
232,566
nerdvegas/rez
src/rez/package_repository.py
PackageRepository.is_empty
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 return True
python
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 return True
[ "def", "is_empty", "(", "self", ")", ":", "for", "family", "in", "self", ".", "iter_package_families", "(", ")", ":", "for", "pkg", "in", "self", ".", "iter_packages", "(", "family", ")", ":", "return", "False", "return", "True" ]
Determine if the repository contains any packages. Returns: True if there are no packages, False if there are at least one.
[ "Determine", "if", "the", "repository", "contains", "any", "packages", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L119-L129
232,567
nerdvegas/rez
src/rez/package_repository.py
PackageRepository.make_resource_handle
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 / etc. """ if variables.get("repository_type", self.name()) != self.name(): raise ResourceError("repository_type mismatch - requested %r, " "repository_type is %r" % (variables["repository_type"], self.name())) variables["repository_type"] = self.name() if variables.get("location", self.location) != self.location: raise ResourceError("location mismatch - requested %r, repository " "location is %r" % (variables["location"], self.location)) variables["location"] = self.location resource_cls = self.pool.get_resource_class(resource_key) variables = resource_cls.normalize_variables(variables) return ResourceHandle(resource_key, variables)
python
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 / etc. """ if variables.get("repository_type", self.name()) != self.name(): raise ResourceError("repository_type mismatch - requested %r, " "repository_type is %r" % (variables["repository_type"], self.name())) variables["repository_type"] = self.name() if variables.get("location", self.location) != self.location: raise ResourceError("location mismatch - requested %r, repository " "location is %r" % (variables["location"], self.location)) variables["location"] = self.location resource_cls = self.pool.get_resource_class(resource_key) variables = resource_cls.normalize_variables(variables) return ResourceHandle(resource_key, variables)
[ "def", "make_resource_handle", "(", "self", ",", "resource_key", ",", "*", "*", "variables", ")", ":", "if", "variables", ".", "get", "(", "\"repository_type\"", ",", "self", ".", "name", "(", ")", ")", "!=", "self", ".", "name", "(", ")", ":", "raise", "ResourceError", "(", "\"repository_type mismatch - requested %r, \"", "\"repository_type is %r\"", "%", "(", "variables", "[", "\"repository_type\"", "]", ",", "self", ".", "name", "(", ")", ")", ")", "variables", "[", "\"repository_type\"", "]", "=", "self", ".", "name", "(", ")", "if", "variables", ".", "get", "(", "\"location\"", ",", "self", ".", "location", ")", "!=", "self", ".", "location", ":", "raise", "ResourceError", "(", "\"location mismatch - requested %r, repository \"", "\"location is %r\"", "%", "(", "variables", "[", "\"location\"", "]", ",", "self", ".", "location", ")", ")", "variables", "[", "\"location\"", "]", "=", "self", ".", "location", "resource_cls", "=", "self", ".", "pool", ".", "get_resource_class", "(", "resource_key", ")", "variables", "=", "resource_cls", ".", "normalize_variables", "(", "variables", ")", "return", "ResourceHandle", "(", "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 / etc.
[ "Create", "a", "ResourceHandle" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L256-L278
232,568
nerdvegas/rez
src/rez/package_repository.py
PackageRepositoryManager.get_repository
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", where 'type' identifies the repository plugin type to use. Returns: `PackageRepository` instance. """ # normalise parts = path.split('@', 1) if len(parts) == 1: parts = ("filesystem", parts[0]) repo_type, location = parts if repo_type == "filesystem": # choice of abspath here vs realpath is deliberate. Realpath gives # canonical path, which can be a problem if two studios are sharing # packages, and have mirrored package paths, but some are actually # different paths, symlinked to look the same. It happened! location = os.path.abspath(location) normalised_path = "%s@%s" % (repo_type, location) return self._get_repository(normalised_path)
python
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", where 'type' identifies the repository plugin type to use. Returns: `PackageRepository` instance. """ # normalise parts = path.split('@', 1) if len(parts) == 1: parts = ("filesystem", parts[0]) repo_type, location = parts if repo_type == "filesystem": # choice of abspath here vs realpath is deliberate. Realpath gives # canonical path, which can be a problem if two studios are sharing # packages, and have mirrored package paths, but some are actually # different paths, symlinked to look the same. It happened! location = os.path.abspath(location) normalised_path = "%s@%s" % (repo_type, location) return self._get_repository(normalised_path)
[ "def", "get_repository", "(", "self", ",", "path", ")", ":", "# normalise", "parts", "=", "path", ".", "split", "(", "'@'", ",", "1", ")", "if", "len", "(", "parts", ")", "==", "1", ":", "parts", "=", "(", "\"filesystem\"", ",", "parts", "[", "0", "]", ")", "repo_type", ",", "location", "=", "parts", "if", "repo_type", "==", "\"filesystem\"", ":", "# choice of abspath here vs realpath is deliberate. Realpath gives", "# canonical path, which can be a problem if two studios are sharing", "# packages, and have mirrored package paths, but some are actually", "# different paths, symlinked to look the same. It happened!", "location", "=", "os", ".", "path", ".", "abspath", "(", "location", ")", "normalised_path", "=", "\"%s@%s\"", "%", "(", "repo_type", ",", "location", ")", "return", "self", ".", "_get_repository", "(", "normalised_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", where 'type' identifies the repository plugin type to use. Returns: `PackageRepository` instance.
[ "Get", "a", "package", "repository", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L368-L394
232,569
nerdvegas/rez
src/rez/package_repository.py
PackageRepositoryManager.are_same
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 example, eg '//svr/foo', '/svr/foo'). Returns: True if the paths refer to the same repository, False otherwise. """ if path_1 == path_2: return True repo_1 = self.get_repository(path_1) repo_2 = self.get_repository(path_2) return (repo_1.uid == repo_2.uid)
python
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 example, eg '//svr/foo', '/svr/foo'). Returns: True if the paths refer to the same repository, False otherwise. """ if path_1 == path_2: return True repo_1 = self.get_repository(path_1) repo_2 = self.get_repository(path_2) return (repo_1.uid == repo_2.uid)
[ "def", "are_same", "(", "self", ",", "path_1", ",", "path_2", ")", ":", "if", "path_1", "==", "path_2", ":", "return", "True", "repo_1", "=", "self", ".", "get_repository", "(", "path_1", ")", "repo_2", "=", "self", ".", "get_repository", "(", "path_2", ")", "return", "(", "repo_1", ".", "uid", "==", "repo_2", ".", "uid", ")" ]
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'). Returns: True if the paths refer to the same repository, False otherwise.
[ "Test", "that", "path_1", "and", "path_2", "refer", "to", "the", "same", "repository", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L396-L411
232,570
nerdvegas/rez
src/rez/vendor/amqp/transport.py
create_transport
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)
python
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)
[ "def", "create_transport", "(", "host", ",", "connect_timeout", ",", "ssl", "=", "False", ")", ":", "if", "ssl", ":", "return", "SSLTransport", "(", "host", ",", "connect_timeout", ",", "ssl", ")", "else", ":", "return", "TCPTransport", "(", "host", ",", "connect_timeout", ")" ]
Given a few parameters from the Connection constructor, select and create a subclass of _AbstractTransport.
[ "Given", "a", "few", "parameters", "from", "the", "Connection", "constructor", "select", "and", "create", "a", "subclass", "of", "_AbstractTransport", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/transport.py#L293-L299
232,571
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginType.get_plugin_class
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_name, plugin_name))
python
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_name, plugin_name))
[ "def", "get_plugin_class", "(", "self", ",", "plugin_name", ")", ":", "try", ":", "return", "self", ".", "plugin_classes", "[", "plugin_name", "]", "except", "KeyError", ":", "raise", "RezPluginError", "(", "\"Unrecognised %s plugin: '%s'\"", "%", "(", "self", ".", "pretty_type_name", ",", "plugin_name", ")", ")" ]
Returns the class registered under the given plugin name.
[ "Returns", "the", "class", "registered", "under", "the", "given", "plugin", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L157-L163
232,572
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginType.get_plugin_module
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_type_name, plugin_name))
python
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_type_name, plugin_name))
[ "def", "get_plugin_module", "(", "self", ",", "plugin_name", ")", ":", "try", ":", "return", "self", ".", "plugin_modules", "[", "plugin_name", "]", "except", "KeyError", ":", "raise", "RezPluginError", "(", "\"Unrecognised %s plugin: '%s'\"", "%", "(", "self", ".", "pretty_type_name", ",", "plugin_name", ")", ")" ]
Returns the module containing the plugin of the given name.
[ "Returns", "the", "module", "containing", "the", "plugin", "of", "the", "given", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L165-L171
232,573
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginType.config_schema
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_class, "schema_dict") \ and plugin_class.schema_dict: d_ = {name: plugin_class.schema_dict} deep_update(d, d_) return dict_to_schema(d, required=True, modifier=expand_system_vars)
python
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_class, "schema_dict") \ and plugin_class.schema_dict: d_ = {name: plugin_class.schema_dict} deep_update(d, d_) return dict_to_schema(d, required=True, modifier=expand_system_vars)
[ "def", "config_schema", "(", "self", ")", ":", "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_class", ",", "\"schema_dict\"", ")", "and", "plugin_class", ".", "schema_dict", ":", "d_", "=", "{", "name", ":", "plugin_class", ".", "schema_dict", "}", "deep_update", "(", "d", ",", "d_", ")", "return", "dict_to_schema", "(", "d", ",", "required", "=", "True", ",", "modifier", "=", "expand_system_vars", ")" ]
Returns the merged configuration data schema for this plugin type.
[ "Returns", "the", "merged", "configuration", "data", "schema", "for", "this", "plugin", "type", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L174-L185
232,574
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginManager.get_plugin_class
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)
python
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)
[ "def", "get_plugin_class", "(", "self", ",", "plugin_type", ",", "plugin_name", ")", ":", "plugin", "=", "self", ".", "_get_plugin_type", "(", "plugin_type", ")", "return", "plugin", ".", "get_plugin_class", "(", "plugin_name", ")" ]
Return the class registered under the given plugin name.
[ "Return", "the", "class", "registered", "under", "the", "given", "plugin", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L278-L281
232,575
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginManager.get_plugin_module
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)
python
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)
[ "def", "get_plugin_module", "(", "self", ",", "plugin_type", ",", "plugin_name", ")", ":", "plugin", "=", "self", ".", "_get_plugin_type", "(", "plugin_type", ")", "return", "plugin", ".", "get_plugin_module", "(", "plugin_name", ")" ]
Return the module defining the class registered under the given plugin name.
[ "Return", "the", "module", "defining", "the", "class", "registered", "under", "the", "given", "plugin", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L283-L287
232,576
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginManager.create_instance
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)
python
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)
[ "def", "create_instance", "(", "self", ",", "plugin_type", ",", "plugin_name", ",", "*", "*", "instance_kwargs", ")", ":", "plugin_type", "=", "self", ".", "_get_plugin_type", "(", "plugin_type", ")", "return", "plugin_type", ".", "create_instance", "(", "plugin_name", ",", "*", "*", "instance_kwargs", ")" ]
Create and return an instance of the given plugin.
[ "Create", "and", "return", "an", "instance", "of", "the", "given", "plugin", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L308-L311
232,577
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginManager.get_summary_string
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_name = plugin_type.replace('_', ' ') for name in sorted(self.get_plugins(plugin_type)): module = self.get_plugin_module(plugin_type, name) desc = (getattr(module, "__doc__", None) or '').strip() rows.append((type_name, name, desc, "loaded")) for (name, reason) in sorted(self.get_failed_plugins(plugin_type)): msg = "FAILED: %s" % reason rows.append((type_name, name, '', msg)) return '\n'.join(columnise(rows))
python
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_name = plugin_type.replace('_', ' ') for name in sorted(self.get_plugins(plugin_type)): module = self.get_plugin_module(plugin_type, name) desc = (getattr(module, "__doc__", None) or '').strip() rows.append((type_name, name, desc, "loaded")) for (name, reason) in sorted(self.get_failed_plugins(plugin_type)): msg = "FAILED: %s" % reason rows.append((type_name, name, '', msg)) return '\n'.join(columnise(rows))
[ "def", "get_summary_string", "(", "self", ")", ":", "rows", "=", "[", "[", "\"PLUGIN TYPE\"", ",", "\"NAME\"", ",", "\"DESCRIPTION\"", ",", "\"STATUS\"", "]", ",", "[", "\"-----------\"", ",", "\"----\"", ",", "\"-----------\"", ",", "\"------\"", "]", "]", "for", "plugin_type", "in", "sorted", "(", "self", ".", "get_plugin_types", "(", ")", ")", ":", "type_name", "=", "plugin_type", ".", "replace", "(", "'_'", ",", "' '", ")", "for", "name", "in", "sorted", "(", "self", ".", "get_plugins", "(", "plugin_type", ")", ")", ":", "module", "=", "self", ".", "get_plugin_module", "(", "plugin_type", ",", "name", ")", "desc", "=", "(", "getattr", "(", "module", ",", "\"__doc__\"", ",", "None", ")", "or", "''", ")", ".", "strip", "(", ")", "rows", ".", "append", "(", "(", "type_name", ",", "name", ",", "desc", ",", "\"loaded\"", ")", ")", "for", "(", "name", ",", "reason", ")", "in", "sorted", "(", "self", ".", "get_failed_plugins", "(", "plugin_type", ")", ")", ":", "msg", "=", "\"FAILED: %s\"", "%", "reason", "rows", ".", "append", "(", "(", "type_name", ",", "name", ",", "''", ",", "msg", ")", ")", "return", "'\\n'", ".", "join", "(", "columnise", "(", "rows", ")", ")" ]
Get a formatted string summarising the plugins that were loaded.
[ "Get", "a", "formatted", "string", "summarising", "the", "plugins", "that", "were", "loaded", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L313-L326
232,578
nerdvegas/rez
src/rez/vendor/distlib/markers.py
Evaluator.get_fragment
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
python
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
[ "def", "get_fragment", "(", "self", ",", "offset", ")", ":", "fragment_len", "=", "10", "s", "=", "'%r'", "%", "(", "self", ".", "source", "[", "offset", ":", "offset", "+", "fragment_len", "]", ")", "if", "offset", "+", "fragment_len", "<", "len", "(", "self", ".", "source", ")", ":", "s", "+=", "'...'", "return", "s" ]
Get the part of the source which is causing a problem.
[ "Get", "the", "part", "of", "the", "source", "which", "is", "causing", "a", "problem", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/markers.py#L60-L68
232,579
nerdvegas/rez
src/rez/vendor/distlib/markers.py
Evaluator.evaluate
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['filename'] = filename try: node = ast.parse(node, **kwargs) except SyntaxError as e: s = self.get_fragment(e.offset) raise SyntaxError('syntax error %s' % s) node_type = node.__class__.__name__.lower() handler = self.get_handler(node_type) if handler is None: if self.source is None: s = '(source not available)' else: s = self.get_fragment(node.col_offset) raise SyntaxError("don't know how to evaluate %r %s" % ( node_type, s)) return handler(node)
python
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['filename'] = filename try: node = ast.parse(node, **kwargs) except SyntaxError as e: s = self.get_fragment(e.offset) raise SyntaxError('syntax error %s' % s) node_type = node.__class__.__name__.lower() handler = self.get_handler(node_type) if handler is None: if self.source is None: s = '(source not available)' else: s = self.get_fragment(node.col_offset) raise SyntaxError("don't know how to evaluate %r %s" % ( node_type, s)) return handler(node)
[ "def", "evaluate", "(", "self", ",", "node", ",", "filename", "=", "None", ")", ":", "if", "isinstance", "(", "node", ",", "string_types", ")", ":", "self", ".", "source", "=", "node", "kwargs", "=", "{", "'mode'", ":", "'eval'", "}", "if", "filename", ":", "kwargs", "[", "'filename'", "]", "=", "filename", "try", ":", "node", "=", "ast", ".", "parse", "(", "node", ",", "*", "*", "kwargs", ")", "except", "SyntaxError", "as", "e", ":", "s", "=", "self", ".", "get_fragment", "(", "e", ".", "offset", ")", "raise", "SyntaxError", "(", "'syntax error %s'", "%", "s", ")", "node_type", "=", "node", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", "handler", "=", "self", ".", "get_handler", "(", "node_type", ")", "if", "handler", "is", "None", ":", "if", "self", ".", "source", "is", "None", ":", "s", "=", "'(source not available)'", "else", ":", "s", "=", "self", ".", "get_fragment", "(", "node", ".", "col_offset", ")", "raise", "SyntaxError", "(", "\"don't know how to evaluate %r %s\"", "%", "(", "node_type", ",", "s", ")", ")", "return", "handler", "(", "node", ")" ]
Evaluate a source string or node, using ``filename`` when displaying errors.
[ "Evaluate", "a", "source", "string", "or", "node", "using", "filename", "when", "displaying", "errors", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/markers.py#L76-L100
232,580
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
recursive_repr
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_running.add(key) try: return func(self) finally: repr_running.discard(key) return wrapper
python
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_running.add(key) try: return func(self) finally: repr_running.discard(key) return wrapper
[ "def", "recursive_repr", "(", "func", ")", ":", "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_running", ".", "add", "(", "key", ")", "try", ":", "return", "func", "(", "self", ")", "finally", ":", "repr_running", ".", "discard", "(", "key", ")", "return", "wrapper" ]
Decorator to prevent infinite repr recursion.
[ "Decorator", "to", "prevent", "infinite", "repr", "recursion", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L33-L52
232,581
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
SortedList._reset
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. With billions of elements, the best load factor depends on your usage. It's best to leave the load factor at the default until you start benchmarking. """ values = reduce(iadd, self._lists, []) self._clear() self._load = load self._half = load >> 1 self._dual = load << 1 self._update(values)
python
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. With billions of elements, the best load factor depends on your usage. It's best to leave the load factor at the default until you start benchmarking. """ values = reduce(iadd, self._lists, []) self._clear() self._load = load self._half = load >> 1 self._dual = load << 1 self._update(values)
[ "def", "_reset", "(", "self", ",", "load", ")", ":", "values", "=", "reduce", "(", "iadd", ",", "self", ".", "_lists", ",", "[", "]", ")", "self", ".", "_clear", "(", ")", "self", ".", "_load", "=", "load", "self", ".", "_half", "=", "load", ">>", "1", "self", ".", "_dual", "=", "load", "<<", "1", "self", ".", "_update", "(", "values", ")" ]
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 factor depends on your usage. It's best to leave the load factor at the default until you start benchmarking.
[ "Reset", "sorted", "list", "load", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L105-L121
232,582
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
SortedList._build_index
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 [3]: 10 11 12 13 14 The first transformation maps the sub-lists by their length. The first row of the index is the length of the sub-lists. [0]: 3 2 4 5 Each row after that is the sum of consecutive pairs of the previous row: [1]: 5 9 [2]: 14 Finally, the index is built by concatenating these lists together: _index = 14 5 9 3 2 4 5 An offset storing the start of the first row is also stored: _offset = 3 When built, the index can be used for efficient indexing into the list. See the comment and notes on self._pos for details. """ row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log_e(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1
python
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 [3]: 10 11 12 13 14 The first transformation maps the sub-lists by their length. The first row of the index is the length of the sub-lists. [0]: 3 2 4 5 Each row after that is the sum of consecutive pairs of the previous row: [1]: 5 9 [2]: 14 Finally, the index is built by concatenating these lists together: _index = 14 5 9 3 2 4 5 An offset storing the start of the first row is also stored: _offset = 3 When built, the index can be used for efficient indexing into the list. See the comment and notes on self._pos for details. """ row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log_e(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1
[ "def", "_build_index", "(", "self", ")", ":", "row0", "=", "list", "(", "map", "(", "len", ",", "self", ".", "_lists", ")", ")", "if", "len", "(", "row0", ")", "==", "1", ":", "self", ".", "_index", "[", ":", "]", "=", "row0", "self", ".", "_offset", "=", "0", "return", "head", "=", "iter", "(", "row0", ")", "tail", "=", "iter", "(", "head", ")", "row1", "=", "list", "(", "starmap", "(", "add", ",", "zip", "(", "head", ",", "tail", ")", ")", ")", "if", "len", "(", "row0", ")", "&", "1", ":", "row1", ".", "append", "(", "row0", "[", "-", "1", "]", ")", "if", "len", "(", "row1", ")", "==", "1", ":", "self", ".", "_index", "[", ":", "]", "=", "row1", "+", "row0", "self", ".", "_offset", "=", "1", "return", "size", "=", "2", "**", "(", "int", "(", "log_e", "(", "len", "(", "row1", ")", "-", "1", ",", "2", ")", ")", "+", "1", ")", "row1", ".", "extend", "(", "repeat", "(", "0", ",", "size", "-", "len", "(", "row1", ")", ")", ")", "tree", "=", "[", "row0", ",", "row1", "]", "while", "len", "(", "tree", "[", "-", "1", "]", ")", ">", "1", ":", "head", "=", "iter", "(", "tree", "[", "-", "1", "]", ")", "tail", "=", "iter", "(", "head", ")", "row", "=", "list", "(", "starmap", "(", "add", ",", "zip", "(", "head", ",", "tail", ")", ")", ")", "tree", ".", "append", "(", "row", ")", "reduce", "(", "iadd", ",", "reversed", "(", "tree", ")", ",", "self", ".", "_index", ")", "self", ".", "_offset", "=", "size", "*", "2", "-", "1" ]
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 The first transformation maps the sub-lists by their length. The first row of the index is the length of the sub-lists. [0]: 3 2 4 5 Each row after that is the sum of consecutive pairs of the previous row: [1]: 5 9 [2]: 14 Finally, the index is built by concatenating these lists together: _index = 14 5 9 3 2 4 5 An offset storing the start of the first row is also stored: _offset = 3 When built, the index can be used for efficient indexing into the list. See the comment and notes on self._pos for details.
[ "Build", "an", "index", "for", "indexing", "the", "sorted", "list", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L494-L558
232,583
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
SortedListWithKey.irange_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 range, respectively. The default is (True, True) such that the range is inclusive of both `min_key` and `max_key`. Both `min_key` and `max_key` default to `None` which is automatically inclusive of the start and end of the list, respectively. When `reverse` is `True` the values are yielded from the iterator in reverse order; `reverse` defaults to `False`. """ _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
python
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 range, respectively. The default is (True, True) such that the range is inclusive of both `min_key` and `max_key`. Both `min_key` and `max_key` default to `None` which is automatically inclusive of the start and end of the list, respectively. When `reverse` is `True` the values are yielded from the iterator in reverse order; `reverse` defaults to `False`. """ _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
[ "def", "irange_key", "(", "self", ",", "min_key", "=", "None", ",", "max_key", "=", "None", ",", "inclusive", "=", "(", "True", ",", "True", ")", ",", "reverse", "=", "False", ")", ":", "_maxes", "=", "self", ".", "_maxes", "if", "not", "_maxes", ":", "return", "iter", "(", "(", ")", ")", "_keys", "=", "self", ".", "_keys", "# Calculate the minimum (pos, idx) pair. By default this location", "# will be inclusive in our calculation.", "if", "min_key", "is", "None", ":", "min_pos", "=", "0", "min_idx", "=", "0", "else", ":", "if", "inclusive", "[", "0", "]", ":", "min_pos", "=", "bisect_left", "(", "_maxes", ",", "min_key", ")", "if", "min_pos", "==", "len", "(", "_maxes", ")", ":", "return", "iter", "(", "(", ")", ")", "min_idx", "=", "bisect_left", "(", "_keys", "[", "min_pos", "]", ",", "min_key", ")", "else", ":", "min_pos", "=", "bisect_right", "(", "_maxes", ",", "min_key", ")", "if", "min_pos", "==", "len", "(", "_maxes", ")", ":", "return", "iter", "(", "(", ")", ")", "min_idx", "=", "bisect_right", "(", "_keys", "[", "min_pos", "]", ",", "min_key", ")", "# Calculate the maximum (pos, idx) pair. By default this location", "# will be exclusive in our calculation.", "if", "max_key", "is", "None", ":", "max_pos", "=", "len", "(", "_maxes", ")", "-", "1", "max_idx", "=", "len", "(", "_keys", "[", "max_pos", "]", ")", "else", ":", "if", "inclusive", "[", "1", "]", ":", "max_pos", "=", "bisect_right", "(", "_maxes", ",", "max_key", ")", "if", "max_pos", "==", "len", "(", "_maxes", ")", ":", "max_pos", "-=", "1", "max_idx", "=", "len", "(", "_keys", "[", "max_pos", "]", ")", "else", ":", "max_idx", "=", "bisect_right", "(", "_keys", "[", "max_pos", "]", ",", "max_key", ")", "else", ":", "max_pos", "=", "bisect_left", "(", "_maxes", ",", "max_key", ")", "if", "max_pos", "==", "len", "(", "_maxes", ")", ":", "max_pos", "-=", "1", "max_idx", "=", "len", "(", "_keys", "[", "max_pos", "]", ")", "else", ":", "max_idx", "=", "bisect_left", "(", "_keys", "[", "max_pos", "]", ",", "max_key", ")", "return", "self", ".", "_islice", "(", "min_pos", ",", "min_idx", ",", "max_pos", ",", "max_idx", ",", "reverse", ")" ]
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`. Both `min_key` and `max_key` default to `None` which is automatically inclusive of the start and end of the list, respectively. When `reverse` is `True` the values are yielded from the iterator in reverse order; `reverse` defaults to `False`.
[ "Create", "an", "iterator", "of", "values", "between", "min_key", "and", "max_key", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L1966-L2035
232,584
nerdvegas/rez
src/rezgui/dialogs/WriteGraphDialog.py
view_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 not os.path.exists(filepath): filepath = None # write graph to tempfile if filepath is None: suffix = ".%s" % config.dot_image_format fd, filepath = tempfile.mkstemp(suffix=suffix, prefix="rez-graph-") os.close(fd) dlg = WriteGraphDialog(graph_str, filepath, parent, prune_to=prune_to) if not dlg.write_graph(): return # display graph graph_file_lookup[h] = filepath dlg = ImageViewerDialog(filepath, parent) dlg.exec_()
python
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 not os.path.exists(filepath): filepath = None # write graph to tempfile if filepath is None: suffix = ".%s" % config.dot_image_format fd, filepath = tempfile.mkstemp(suffix=suffix, prefix="rez-graph-") os.close(fd) dlg = WriteGraphDialog(graph_str, filepath, parent, prune_to=prune_to) if not dlg.write_graph(): return # display graph graph_file_lookup[h] = filepath dlg = ImageViewerDialog(filepath, parent) dlg.exec_()
[ "def", "view_graph", "(", "graph_str", ",", "parent", "=", "None", ",", "prune_to", "=", "None", ")", ":", "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", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "filepath", "=", "None", "# write graph to tempfile", "if", "filepath", "is", "None", ":", "suffix", "=", "\".%s\"", "%", "config", ".", "dot_image_format", "fd", ",", "filepath", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "suffix", ",", "prefix", "=", "\"rez-graph-\"", ")", "os", ".", "close", "(", "fd", ")", "dlg", "=", "WriteGraphDialog", "(", "graph_str", ",", "filepath", ",", "parent", ",", "prune_to", "=", "prune_to", ")", "if", "not", "dlg", ".", "write_graph", "(", ")", ":", "return", "# display graph", "graph_file_lookup", "[", "h", "]", "=", "filepath", "dlg", "=", "ImageViewerDialog", "(", "filepath", ",", "parent", ")", "dlg", ".", "exec_", "(", ")" ]
View a graph.
[ "View", "a", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/dialogs/WriteGraphDialog.py#L109-L133
232,585
nerdvegas/rez
src/rezgui/widgets/PackageVersionsTable.py
PackageVersionsTable.select_version
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 version_range \ and (version is None or version < package.version): version = package.version row = i self.clearSelection() if row != -1: self.selectRow(row) return version
python
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 version_range \ and (version is None or version < package.version): version = package.version row = i self.clearSelection() if row != -1: self.selectRow(row) return version
[ "def", "select_version", "(", "self", ",", "version_range", ")", ":", "row", "=", "-", "1", "version", "=", "None", "for", "i", ",", "package", "in", "self", ".", "packages", ".", "iteritems", "(", ")", ":", "if", "package", ".", "version", "in", "version_range", "and", "(", "version", "is", "None", "or", "version", "<", "package", ".", "version", ")", ":", "version", "=", "package", ".", "version", "row", "=", "i", "self", ".", "clearSelection", "(", ")", "if", "row", "!=", "-", "1", ":", "self", ".", "selectRow", "(", "row", ")", "return", "version" ]
Select the latest versioned package in the given range. If there are no packages in the range, the selection is cleared.
[ "Select", "the", "latest", "versioned", "package", "in", "the", "given", "range", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/PackageVersionsTable.py#L46-L62
232,586
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedset.py
SortedSet._fromset
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
python
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
[ "def", "_fromset", "(", "cls", ",", "values", ",", "key", "=", "None", ")", ":", "sorted_set", "=", "object", ".", "__new__", "(", "cls", ")", "sorted_set", ".", "_set", "=", "values", "# pylint: disable=protected-access", "sorted_set", ".", "__init__", "(", "key", "=", "key", ")", "return", "sorted_set" ]
Initialize sorted set from existing set.
[ "Initialize", "sorted", "set", "from", "existing", "set", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedset.py#L73-L78
232,587
nerdvegas/rez
src/rez/cli/build.py
setup_parser_common
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, choices=process_types, default="local", help="the build process to use (default: %(default)s).") # add build system choices valid for this package package = get_current_developer_package() clss = get_valid_build_systems(os.getcwd(), package=package) if clss: if len(clss) == 1: cls_ = clss[0] title = "%s build system arguments" % cls_.name() group = parser.add_argument_group(title) cls_.bind_cli(parser, group) types = [x.name() for x in clss] else: types = None parser.add_argument( "-b", "--build-system", dest="buildsys", choices=types, help="the build system to use. If not specified, it is detected. Set " "'build_system' or 'build_command' to specify the build system in the " "package itself.") parser.add_argument( "--variants", nargs='+', type=int, metavar="INDEX", help="select variants to build (zero-indexed).") parser.add_argument( "--ba", "--build-args", dest="build_args", metavar="ARGS", help="arguments to pass to the build system. Alternatively, list these " "after a '--'.") parser.add_argument( "--cba", "--child-build-args", dest="child_build_args", metavar="ARGS", help="arguments to pass to the child build system, if any. " "Alternatively, list these after a second '--'.")
python
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, choices=process_types, default="local", help="the build process to use (default: %(default)s).") # add build system choices valid for this package package = get_current_developer_package() clss = get_valid_build_systems(os.getcwd(), package=package) if clss: if len(clss) == 1: cls_ = clss[0] title = "%s build system arguments" % cls_.name() group = parser.add_argument_group(title) cls_.bind_cli(parser, group) types = [x.name() for x in clss] else: types = None parser.add_argument( "-b", "--build-system", dest="buildsys", choices=types, help="the build system to use. If not specified, it is detected. Set " "'build_system' or 'build_command' to specify the build system in the " "package itself.") parser.add_argument( "--variants", nargs='+', type=int, metavar="INDEX", help="select variants to build (zero-indexed).") parser.add_argument( "--ba", "--build-args", dest="build_args", metavar="ARGS", help="arguments to pass to the build system. Alternatively, list these " "after a '--'.") parser.add_argument( "--cba", "--child-build-args", dest="child_build_args", metavar="ARGS", help="arguments to pass to the child build system, if any. " "Alternatively, list these after a second '--'.")
[ "def", "setup_parser_common", "(", "parser", ")", ":", "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", ",", "choices", "=", "process_types", ",", "default", "=", "\"local\"", ",", "help", "=", "\"the build process to use (default: %(default)s).\"", ")", "# add build system choices valid for this package", "package", "=", "get_current_developer_package", "(", ")", "clss", "=", "get_valid_build_systems", "(", "os", ".", "getcwd", "(", ")", ",", "package", "=", "package", ")", "if", "clss", ":", "if", "len", "(", "clss", ")", "==", "1", ":", "cls_", "=", "clss", "[", "0", "]", "title", "=", "\"%s build system arguments\"", "%", "cls_", ".", "name", "(", ")", "group", "=", "parser", ".", "add_argument_group", "(", "title", ")", "cls_", ".", "bind_cli", "(", "parser", ",", "group", ")", "types", "=", "[", "x", ".", "name", "(", ")", "for", "x", "in", "clss", "]", "else", ":", "types", "=", "None", "parser", ".", "add_argument", "(", "\"-b\"", ",", "\"--build-system\"", ",", "dest", "=", "\"buildsys\"", ",", "choices", "=", "types", ",", "help", "=", "\"the build system to use. If not specified, it is detected. Set \"", "\"'build_system' or 'build_command' to specify the build system in the \"", "\"package itself.\"", ")", "parser", ".", "add_argument", "(", "\"--variants\"", ",", "nargs", "=", "'+'", ",", "type", "=", "int", ",", "metavar", "=", "\"INDEX\"", ",", "help", "=", "\"select variants to build (zero-indexed).\"", ")", "parser", ".", "add_argument", "(", "\"--ba\"", ",", "\"--build-args\"", ",", "dest", "=", "\"build_args\"", ",", "metavar", "=", "\"ARGS\"", ",", "help", "=", "\"arguments to pass to the build system. Alternatively, list these \"", "\"after a '--'.\"", ")", "parser", ".", "add_argument", "(", "\"--cba\"", ",", "\"--child-build-args\"", ",", "dest", "=", "\"child_build_args\"", ",", "metavar", "=", "\"ARGS\"", ",", "help", "=", "\"arguments to pass to the child build system, if any. \"", "\"Alternatively, list these after a second '--'.\"", ")" ]
Parser setup common to both rez-build and rez-release.
[ "Parser", "setup", "common", "to", "both", "rez", "-", "build", "and", "rez", "-", "release", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/build.py#L30-L71
232,588
nerdvegas/rez
src/rez/utils/scope.py
scoped_format
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: objects (dict): Dict of objects to format with. If a value is a dict, its values, and any further neted dicts, will also format with dot notation. pretty (bool): See `ObjectStringFormatter`. expand (bool): See `ObjectStringFormatter`. """ pretty = objects.pop("pretty", RecursiveAttribute.format_pretty) expand = objects.pop("expand", RecursiveAttribute.format_expand) attr = RecursiveAttribute(objects, read_only=True) formatter = scoped_formatter(**objects) return formatter.format(txt, pretty=pretty, expand=expand)
python
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: objects (dict): Dict of objects to format with. If a value is a dict, its values, and any further neted dicts, will also format with dot notation. pretty (bool): See `ObjectStringFormatter`. expand (bool): See `ObjectStringFormatter`. """ pretty = objects.pop("pretty", RecursiveAttribute.format_pretty) expand = objects.pop("expand", RecursiveAttribute.format_expand) attr = RecursiveAttribute(objects, read_only=True) formatter = scoped_formatter(**objects) return formatter.format(txt, pretty=pretty, expand=expand)
[ "def", "scoped_format", "(", "txt", ",", "*", "*", "objects", ")", ":", "pretty", "=", "objects", ".", "pop", "(", "\"pretty\"", ",", "RecursiveAttribute", ".", "format_pretty", ")", "expand", "=", "objects", ".", "pop", "(", "\"expand\"", ",", "RecursiveAttribute", ".", "format_expand", ")", "attr", "=", "RecursiveAttribute", "(", "objects", ",", "read_only", "=", "True", ")", "formatter", "=", "scoped_formatter", "(", "*", "*", "objects", ")", "return", "formatter", ".", "format", "(", "txt", ",", "pretty", "=", "pretty", ",", "expand", "=", "expand", ")" ]
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 format with. If a value is a dict, its values, and any further neted dicts, will also format with dot notation. pretty (bool): See `ObjectStringFormatter`. expand (bool): See `ObjectStringFormatter`.
[ "Format", "a", "string", "with", "respect", "to", "a", "set", "of", "objects", "attributes", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/scope.py#L238-L260
232,589
nerdvegas/rez
src/rez/utils/scope.py
RecursiveAttribute.to_dict
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
python
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
[ "def", "to_dict", "(", "self", ")", ":", "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 an equivalent dict representation.
[ "Get", "an", "equivalent", "dict", "representation", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/scope.py#L89-L97
232,590
nerdvegas/rez
src/rezgui/objects/Config.py
Config.value
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: default = self._default_value(key) val = self._value(key, default) if type(val) == type(default): return val else: return self._convert_value(val, type(default)) else: val = self._value(key, None) if val is None: return None return self._convert_value(val, type_)
python
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: default = self._default_value(key) val = self._value(key, default) if type(val) == type(default): return val else: return self._convert_value(val, type(default)) else: val = self._value(key, None) if val is None: return None return self._convert_value(val, type_)
[ "def", "value", "(", "self", ",", "key", ",", "type_", "=", "None", ")", ":", "if", "type_", "is", "None", ":", "default", "=", "self", ".", "_default_value", "(", "key", ")", "val", "=", "self", ".", "_value", "(", "key", ",", "default", ")", "if", "type", "(", "val", ")", "==", "type", "(", "default", ")", ":", "return", "val", "else", ":", "return", "self", ".", "_convert_value", "(", "val", ",", "type", "(", "default", ")", ")", "else", ":", "val", "=", "self", ".", "_value", "(", "key", ",", "None", ")", "if", "val", "is", "None", ":", "return", "None", "return", "self", ".", "_convert_value", "(", "val", ",", "type_", ")" ]
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.
[ "Get", "the", "value", "of", "a", "setting", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/objects/Config.py#L15-L33
232,591
nerdvegas/rez
src/rezgui/objects/Config.py
Config.get_string_list
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
python
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
[ "def", "get_string_list", "(", "self", ",", "key", ")", ":", "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" ]
Get a list of strings.
[ "Get", "a", "list", "of", "strings", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/objects/Config.py#L38-L47
232,592
nerdvegas/rez
src/rezgui/objects/Config.py
Config.prepend_string_list
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' entry. """ max_len = self.get(max_length_key) strings = self.get_string_list(key) strings = [value] + [x for x in strings if x != value] strings = strings[:max_len] self.beginWriteArray(key) for i in range(len(strings)): self.setArrayIndex(i) self.setValue("entry", strings[i]) self.endArray()
python
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' entry. """ max_len = self.get(max_length_key) strings = self.get_string_list(key) strings = [value] + [x for x in strings if x != value] strings = strings[:max_len] self.beginWriteArray(key) for i in range(len(strings)): self.setArrayIndex(i) self.setValue("entry", strings[i]) self.endArray()
[ "def", "prepend_string_list", "(", "self", ",", "key", ",", "value", ",", "max_length_key", ")", ":", "max_len", "=", "self", ".", "get", "(", "max_length_key", ")", "strings", "=", "self", ".", "get_string_list", "(", "key", ")", "strings", "=", "[", "value", "]", "+", "[", "x", "for", "x", "in", "strings", "if", "x", "!=", "value", "]", "strings", "=", "strings", "[", ":", "max_len", "]", "self", ".", "beginWriteArray", "(", "key", ")", "for", "i", "in", "range", "(", "len", "(", "strings", ")", ")", ":", "self", ".", "setArrayIndex", "(", "i", ")", "self", ".", "setValue", "(", "\"entry\"", ",", "strings", "[", "i", "]", ")", "self", ".", "endArray", "(", ")" ]
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.
[ "Prepend", "a", "fixed", "-", "length", "string", "list", "with", "a", "new", "string", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/objects/Config.py#L49-L65
232,593
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/utils.py
priority_queue.insert
def insert(self, item, priority): """ Insert item into the queue, with the given priority. """ heappush(self.heap, HeapItem(item, priority))
python
def insert(self, item, priority): """ Insert item into the queue, with the given priority. """ heappush(self.heap, HeapItem(item, priority))
[ "def", "insert", "(", "self", ",", "item", ",", "priority", ")", ":", "heappush", "(", "self", ".", "heap", ",", "HeapItem", "(", "item", ",", "priority", ")", ")" ]
Insert item into the queue, with the given priority.
[ "Insert", "item", "into", "the", "queue", "with", "the", "given", "priority", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/utils.py#L57-L61
232,594
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/accessibility.py
connected_components
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())*2,recursionlimit)) visited = {} count = 1 # For 'each' node not found to belong to a connected component, find its connected # component. for each in graph: if (each not in visited): _dfs(graph, visited, count, each) count = count + 1 setrecursionlimit(recursionlimit) return visited
python
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())*2,recursionlimit)) visited = {} count = 1 # For 'each' node not found to belong to a connected component, find its connected # component. for each in graph: if (each not in visited): _dfs(graph, visited, count, each) count = count + 1 setrecursionlimit(recursionlimit) return visited
[ "def", "connected_components", "(", "graph", ")", ":", "recursionlimit", "=", "getrecursionlimit", "(", ")", "setrecursionlimit", "(", "max", "(", "len", "(", "graph", ".", "nodes", "(", ")", ")", "*", "2", ",", "recursionlimit", ")", ")", "visited", "=", "{", "}", "count", "=", "1", "# For 'each' node not found to belong to a connected component, find its connected", "# component.", "for", "each", "in", "graph", ":", "if", "(", "each", "not", "in", "visited", ")", ":", "_dfs", "(", "graph", ",", "visited", ",", "count", ",", "each", ")", "count", "=", "count", "+", "1", "setrecursionlimit", "(", "recursionlimit", ")", "return", "visited" ]
Connected components. @type graph: graph, hypergraph @param graph: Graph. @rtype: dictionary @return: Pairing that associates each node to its connected component.
[ "Connected", "components", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L114-L138
232,595
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/accessibility.py
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-edges. """ recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) # Dispatch if we have a hypergraph if 'hypergraph' == graph.__class__.__name__: return _cut_hyperedges(graph) pre = {} # Pre-ordering low = {} # Lowest pre[] reachable from this node going down the spanning tree + one backedge spanning_tree = {} reply = [] pre[None] = 0 for each in graph: if (each not in pre): spanning_tree[each] = None _cut_dfs(graph, spanning_tree, pre, low, reply, each) setrecursionlimit(recursionlimit) return reply
python
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-edges. """ recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) # Dispatch if we have a hypergraph if 'hypergraph' == graph.__class__.__name__: return _cut_hyperedges(graph) pre = {} # Pre-ordering low = {} # Lowest pre[] reachable from this node going down the spanning tree + one backedge spanning_tree = {} reply = [] pre[None] = 0 for each in graph: if (each not in pre): spanning_tree[each] = None _cut_dfs(graph, spanning_tree, pre, low, reply, each) setrecursionlimit(recursionlimit) return reply
[ "def", "cut_edges", "(", "graph", ")", ":", "recursionlimit", "=", "getrecursionlimit", "(", ")", "setrecursionlimit", "(", "max", "(", "len", "(", "graph", ".", "nodes", "(", ")", ")", "*", "2", ",", "recursionlimit", ")", ")", "# Dispatch if we have a hypergraph", "if", "'hypergraph'", "==", "graph", ".", "__class__", ".", "__name__", ":", "return", "_cut_hyperedges", "(", "graph", ")", "pre", "=", "{", "}", "# Pre-ordering", "low", "=", "{", "}", "# Lowest pre[] reachable from this node going down the spanning tree + one backedge", "spanning_tree", "=", "{", "}", "reply", "=", "[", "]", "pre", "[", "None", "]", "=", "0", "for", "each", "in", "graph", ":", "if", "(", "each", "not", "in", "pre", ")", ":", "spanning_tree", "[", "each", "]", "=", "None", "_cut_dfs", "(", "graph", ",", "spanning_tree", ",", "pre", ",", "low", ",", "reply", ",", "each", ")", "setrecursionlimit", "(", "recursionlimit", ")", "return", "reply" ]
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.
[ "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", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L182-L214
232,596
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/accessibility.py
_cut_hyperedges
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_: if (each[1] == 'h'): edges.append(each[0]) return edges
python
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_: if (each[1] == 'h'): edges.append(each[0]) return edges
[ "def", "_cut_hyperedges", "(", "hypergraph", ")", ":", "edges_", "=", "cut_nodes", "(", "hypergraph", ".", "graph", ")", "edges", "=", "[", "]", "for", "each", "in", "edges_", ":", "if", "(", "each", "[", "1", "]", "==", "'h'", ")", ":", "edges", ".", "append", "(", "each", "[", "0", "]", ")", "return", "edges" ]
Return the cut-hyperedges of the given hypergraph. @type hypergraph: hypergraph @param hypergraph: Hypergraph @rtype: list @return: List of cut-nodes.
[ "Return", "the", "cut", "-", "hyperedges", "of", "the", "given", "hypergraph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L217-L234
232,597
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/accessibility.py
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 @return: List of cut-nodes. """ recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) # Dispatch if we have a hypergraph if 'hypergraph' == graph.__class__.__name__: return _cut_hypernodes(graph) pre = {} # Pre-ordering low = {} # Lowest pre[] reachable from this node going down the spanning tree + one backedge reply = {} spanning_tree = {} pre[None] = 0 # Create spanning trees, calculate pre[], low[] for each in graph: if (each not in pre): spanning_tree[each] = None _cut_dfs(graph, spanning_tree, pre, low, [], each) # Find cuts for each in graph: # If node is not a root if (spanning_tree[each] is not None): for other in graph[each]: # If there is no back-edge from descendent to a ancestral of each if (low[other] >= pre[each] and spanning_tree[other] == each): reply[each] = 1 # If node is a root else: children = 0 for other in graph: if (spanning_tree[other] == each): children = children + 1 # root is cut-vertex iff it has two or more children if (children >= 2): reply[each] = 1 setrecursionlimit(recursionlimit) return list(reply.keys())
python
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 @return: List of cut-nodes. """ recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) # Dispatch if we have a hypergraph if 'hypergraph' == graph.__class__.__name__: return _cut_hypernodes(graph) pre = {} # Pre-ordering low = {} # Lowest pre[] reachable from this node going down the spanning tree + one backedge reply = {} spanning_tree = {} pre[None] = 0 # Create spanning trees, calculate pre[], low[] for each in graph: if (each not in pre): spanning_tree[each] = None _cut_dfs(graph, spanning_tree, pre, low, [], each) # Find cuts for each in graph: # If node is not a root if (spanning_tree[each] is not None): for other in graph[each]: # If there is no back-edge from descendent to a ancestral of each if (low[other] >= pre[each] and spanning_tree[other] == each): reply[each] = 1 # If node is a root else: children = 0 for other in graph: if (spanning_tree[other] == each): children = children + 1 # root is cut-vertex iff it has two or more children if (children >= 2): reply[each] = 1 setrecursionlimit(recursionlimit) return list(reply.keys())
[ "def", "cut_nodes", "(", "graph", ")", ":", "recursionlimit", "=", "getrecursionlimit", "(", ")", "setrecursionlimit", "(", "max", "(", "len", "(", "graph", ".", "nodes", "(", ")", ")", "*", "2", ",", "recursionlimit", ")", ")", "# Dispatch if we have a hypergraph", "if", "'hypergraph'", "==", "graph", ".", "__class__", ".", "__name__", ":", "return", "_cut_hypernodes", "(", "graph", ")", "pre", "=", "{", "}", "# Pre-ordering", "low", "=", "{", "}", "# Lowest pre[] reachable from this node going down the spanning tree + one backedge", "reply", "=", "{", "}", "spanning_tree", "=", "{", "}", "pre", "[", "None", "]", "=", "0", "# Create spanning trees, calculate pre[], low[]", "for", "each", "in", "graph", ":", "if", "(", "each", "not", "in", "pre", ")", ":", "spanning_tree", "[", "each", "]", "=", "None", "_cut_dfs", "(", "graph", ",", "spanning_tree", ",", "pre", ",", "low", ",", "[", "]", ",", "each", ")", "# Find cuts", "for", "each", "in", "graph", ":", "# If node is not a root", "if", "(", "spanning_tree", "[", "each", "]", "is", "not", "None", ")", ":", "for", "other", "in", "graph", "[", "each", "]", ":", "# If there is no back-edge from descendent to a ancestral of each", "if", "(", "low", "[", "other", "]", ">=", "pre", "[", "each", "]", "and", "spanning_tree", "[", "other", "]", "==", "each", ")", ":", "reply", "[", "each", "]", "=", "1", "# If node is a root", "else", ":", "children", "=", "0", "for", "other", "in", "graph", ":", "if", "(", "spanning_tree", "[", "other", "]", "==", "each", ")", ":", "children", "=", "children", "+", "1", "# root is cut-vertex iff it has two or more children", "if", "(", "children", ">=", "2", ")", ":", "reply", "[", "each", "]", "=", "1", "setrecursionlimit", "(", "recursionlimit", ")", "return", "list", "(", "reply", ".", "keys", "(", ")", ")" ]
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.
[ "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", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L237-L288
232,598
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/accessibility.py
_cut_hypernodes
def _cut_hypernodes(hypergraph): """ Return the cut-nodes of the given hypergraph. @type hypergraph: hypergraph @param hypergraph: Hypergraph @rtype: list @return: List of cut-nodes. """ nodes_ = cut_nodes(hypergraph.graph) nodes = [] for each in nodes_: if (each[1] == 'n'): nodes.append(each[0]) return nodes
python
def _cut_hypernodes(hypergraph): """ Return the cut-nodes of the given hypergraph. @type hypergraph: hypergraph @param hypergraph: Hypergraph @rtype: list @return: List of cut-nodes. """ nodes_ = cut_nodes(hypergraph.graph) nodes = [] for each in nodes_: if (each[1] == 'n'): nodes.append(each[0]) return nodes
[ "def", "_cut_hypernodes", "(", "hypergraph", ")", ":", "nodes_", "=", "cut_nodes", "(", "hypergraph", ".", "graph", ")", "nodes", "=", "[", "]", "for", "each", "in", "nodes_", ":", "if", "(", "each", "[", "1", "]", "==", "'n'", ")", ":", "nodes", ".", "append", "(", "each", "[", "0", "]", ")", "return", "nodes" ]
Return the cut-nodes of the given hypergraph. @type hypergraph: hypergraph @param hypergraph: Hypergraph @rtype: list @return: List of cut-nodes.
[ "Return", "the", "cut", "-", "nodes", "of", "the", "given", "hypergraph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L291-L308
232,599
nerdvegas/rez
src/rez/vendor/pygraph/classes/graph.py
graph.del_edge
def del_edge(self, edge): """ Remove an edge from the graph. @type edge: tuple @param edge: Edge. """ u, v = edge self.node_neighbors[u].remove(v) self.del_edge_labeling((u, v)) if (u != v): self.node_neighbors[v].remove(u) self.del_edge_labeling((v, u))
python
def del_edge(self, edge): """ Remove an edge from the graph. @type edge: tuple @param edge: Edge. """ u, v = edge self.node_neighbors[u].remove(v) self.del_edge_labeling((u, v)) if (u != v): self.node_neighbors[v].remove(u) self.del_edge_labeling((v, u))
[ "def", "del_edge", "(", "self", ",", "edge", ")", ":", "u", ",", "v", "=", "edge", "self", ".", "node_neighbors", "[", "u", "]", ".", "remove", "(", "v", ")", "self", ".", "del_edge_labeling", "(", "(", "u", ",", "v", ")", ")", "if", "(", "u", "!=", "v", ")", ":", "self", ".", "node_neighbors", "[", "v", "]", ".", "remove", "(", "u", ")", "self", ".", "del_edge_labeling", "(", "(", "v", ",", "u", ")", ")" ]
Remove an edge from the graph. @type edge: tuple @param edge: Edge.
[ "Remove", "an", "edge", "from", "the", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/graph.py#L170-L182