INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Perform copy that overwrites any existing target.
Will copy/copytree `src` to `dest`, and will remove `dest` if it exists,
regardless of what it is.
If `follow_symlinks` is False, symlinks are preserved, otherwise their
contents are copied.
Note that this behavior is different to `shutil.copy`, w... | def replacing_copy(src, dest, follow_symlinks=False):
"""Perform copy that overwrites any existing target.
Will copy/copytree `src` to `dest`, and will remove `dest` if it exists,
regardless of what it is.
If `follow_symlinks` is False, symlinks are preserved, otherwise their
contents are copied.
... |
Replace `dest` with `source`.
Acts like an `os.rename` if `dest` does not exist. Otherwise, `dest` is
deleted and `src` is renamed to `dest`. | def replace_file_or_dir(dest, source):
"""Replace `dest` with `source`.
Acts like an `os.rename` if `dest` does not exist. Otherwise, `dest` is
deleted and `src` is renamed to `dest`.
"""
from rez.vendor.atomicwrites import replace_atomic
if not os.path.exists(dest):
try:
o... |
Generates a tmp name for a file or dir.
This is a tempname that sits in the same dir as `name`. If it exists on
disk at context exit time, it is deleted. | def make_tmp_name(name):
"""Generates a tmp name for a file or dir.
This is a tempname that sits in the same dir as `name`. If it exists on
disk at context exit time, it is deleted.
"""
path, base = os.path.split(name)
tmp_base = ".tmp-%s-%s" % (base, uuid4().hex)
tmp_name = os.path.join(pa... |
Returns True if `path_a` is a subdirectory of `path_b`. | def is_subdirectory(path_a, path_b):
"""Returns True if `path_a` is a subdirectory of `path_b`."""
path_a = os.path.realpath(path_a)
path_b = os.path.realpath(path_b)
relative = os.path.relpath(path_a, path_b)
return (not relative.startswith(os.pardir + os.sep)) |
Find a symlink under `path` that points at `source`.
If source is relative, it is considered relative to `path`.
Returns:
str: Name of symlink found, or None. | def find_matching_symlink(path, source):
"""Find a symlink under `path` that points at `source`.
If source is relative, it is considered relative to `path`.
Returns:
str: Name of symlink found, or None.
"""
def to_abs(target):
if os.path.isabs(target):
return target
... |
try to copy with mode, and if it fails, try replacing | def copy_or_replace(src, dst):
'''try to copy with mode, and if it fails, try replacing
'''
try:
shutil.copy(src, dst)
except (OSError, IOError), e:
# It's possible that the file existed, but was owned by someone
# else - in that situation, shutil.copy might then fail when it
... |
Attempts a move, and falls back to a copy+delete if this fails | def movetree(src, dst):
"""Attempts a move, and falls back to a copy+delete if this fails
"""
try:
shutil.move(src, dst)
except:
copytree(src, dst, symlinks=True, hardlinks=True)
shutil.rmtree(src) |
Set the permissions mode on path, but only if it differs from the current mode. | def safe_chmod(path, mode):
"""Set the permissions mode on path, but only if it differs from the current mode.
"""
if stat.S_IMODE(os.stat(path).st_mode) != mode:
os.chmod(path, mode) |
Encodes an arbitrary unicode string to a generic filesystem-compatible
non-unicode filename.
The result after encoding will only contain the standard ascii lowercase
letters (a-z), the digits (0-9), or periods, underscores, or dashes
(".", "_", or "-"). No uppercase letters will be used, for
comap... | def encode_filesystem_name(input_str):
"""Encodes an arbitrary unicode string to a generic filesystem-compatible
non-unicode filename.
The result after encoding will only contain the standard ascii lowercase
letters (a-z), the digits (0-9), or periods, underscores, or dashes
(".", "_", or "-"). No... |
Decodes a filename encoded using the rules given in encode_filesystem_name
to a unicode string. | def decode_filesystem_name(filename):
"""Decodes a filename encoded using the rules given in encode_filesystem_name
to a unicode string.
"""
result = []
remain = filename
i = 0
while remain:
# use match, to ensure it matches from the start of the string...
match = _FILESYSTEM... |
Yields absolute directories starting with the given path, and iterating
up through all it's parents, until it reaches a root directory | def walk_up_dirs(path):
"""Yields absolute directories starting with the given path, and iterating
up through all it's parents, until it reaches a root directory"""
prev_path = None
current_path = os.path.abspath(path)
while current_path != prev_path:
yield current_path
prev_path = c... |
Invoke the wrapped script.
Returns:
Return code of the command, or 0 if the command is not run. | def run(self, *args):
"""Invoke the wrapped script.
Returns:
Return code of the command, or 0 if the command is not run.
"""
if self.prefix_char is None:
prefix_char = config.suite_alias_prefix_char
else:
prefix_char = self.prefix_char
... |
Print an info message about the tool. | def print_about(self):
"""Print an info message about the tool."""
filepath = os.path.join(self.suite_path, "bin", self.tool_name)
print "Tool: %s" % self.tool_name
print "Path: %s" % filepath
print "Suite: %s" % self.suite_path
msg = "%s (%r)" % (self.context... |
Print a list of versions of the package this tool comes from, and
indicate which version this tool is from. | def print_package_versions(self):
"""Print a list of versions of the package this tool comes from, and
indicate which version this tool is from."""
variants = self.context.get_tool_variants(self.tool_name)
if variants:
if len(variants) > 1:
self._print_conflic... |
Create a random graph.
@type num_nodes: number
@param num_nodes: Number of nodes.
@type num_edges: number
@param num_edges: Number of edges.
@type directed: bool
@param directed: Whether the generated graph should be directed or not.
@type weight_range: tuple
@param... | def generate(num_nodes, num_edges, directed=False, weight_range=(1, 1)):
"""
Create a random graph.
@type num_nodes: number
@param num_nodes: Number of nodes.
@type num_edges: number
@param num_edges: Number of edges.
@type directed: bool
@param directed: Whether the ge... |
Create a random hyper graph.
@type num_nodes: number
@param num_nodes: Number of nodes.
@type num_edges: number
@param num_edges: Number of edges.
@type r: number
@param r: Uniform edges of size r. | def generate_hypergraph(num_nodes, num_edges, r = 0):
"""
Create a random hyper graph.
@type num_nodes: number
@param num_nodes: Number of nodes.
@type num_edges: number
@param num_edges: Number of edges.
@type r: number
@param r: Uniform edges of size r.
"""
# ... |
Check that the found software version is within supplied range.
Args:
version: Version of the package as a Version object.
range_: Allowable version range as a VersionRange object. | def check_version(version, range_=None):
"""Check that the found software version is within supplied range.
Args:
version: Version of the package as a Version object.
range_: Allowable version range as a VersionRange object.
"""
if range_ and version not in range_:
raise RezBind... |
Find an executable.
Args:
name: Name of the program, eg 'python'.
filepath: Path to executable, a search is performed if None.
Returns:
Path to the executable if found, otherwise an error is raised. | def find_exe(name, filepath=None):
"""Find an executable.
Args:
name: Name of the program, eg 'python'.
filepath: Path to executable, a search is performed if None.
Returns:
Path to the executable if found, otherwise an error is raised.
"""
if filepath:
if not os.pa... |
Run an executable and get the program version.
Args:
exepath: Filepath to executable.
version_arg: Arg to pass to program, eg "-V". Can also be a list.
word_index: Expect the Nth word of output to be the version.
version_rank: Cap the version to this many tokens.
Returns:
... | def extract_version(exepath, version_arg, word_index=-1, version_rank=3):
"""Run an executable and get the program version.
Args:
exepath: Filepath to executable.
version_arg: Arg to pass to program, eg "-V". Can also be a list.
word_index: Expect the Nth word of output to be the versio... |
Create a VersionedObject directly from an object name and version.
Args:
name: Object name string.
version: Version object. | def construct(cls, name, version=None):
"""Create a VersionedObject directly from an object name and version.
Args:
name: Object name string.
version: Version object.
"""
other = VersionedObject(None)
other.name_ = name
other.version_ = Version() ... |
Create a requirement directly from an object name and VersionRange.
Args:
name: Object name string.
range: VersionRange object. If None, an unversioned requirement is
created. | def construct(cls, name, range=None):
"""Create a requirement directly from an object name and VersionRange.
Args:
name: Object name string.
range: VersionRange object. If None, an unversioned requirement is
created.
"""
other = Requirement(None)
... |
Returns True if this requirement conflicts with another `Requirement`
or `VersionedObject`. | def conflicts_with(self, other):
"""Returns True if this requirement conflicts with another `Requirement`
or `VersionedObject`."""
if isinstance(other, Requirement):
if (self.name_ != other.name_) or (self.range is None) \
or (other.range is None):
... |
Returns the merged result of two requirements.
Two requirements can be in conflict and if so, this function returns
None. For example, requests for "foo-4" and "foo-6" are in conflict,
since both cannot be satisfied with a single version of foo.
Some example successful requirements mer... | def merged(self, other):
"""Returns the merged result of two requirements.
Two requirements can be in conflict and if so, this function returns
None. For example, requests for "foo-4" and "foo-6" are in conflict,
since both cannot be satisfied with a single version of foo.
Some... |
Read a graph from a string, either in dot format, or our own
compressed format.
Returns:
`pygraph.digraph`: Graph object. | def read_graph_from_string(txt):
"""Read a graph from a string, either in dot format, or our own
compressed format.
Returns:
`pygraph.digraph`: Graph object.
"""
if not txt.startswith('{'):
return read_dot(txt) # standard dot format
def conv(value):
if isinstance(value... |
Write a graph in our own compacted format.
Returns:
str. | def write_compacted(g):
"""Write a graph in our own compacted format.
Returns:
str.
"""
d_nodes = {}
d_edges = {}
def conv(value):
if isinstance(value, basestring):
return value.strip('"')
else:
return value
for node in g.nodes():
la... |
Replacement for pygraph.readwrite.dot.write, which is dog slow.
Note:
This isn't a general replacement. It will work for the graphs that
Rez generates, but there are no guarantees beyond that.
Args:
g (`pygraph.digraph`): Input graph.
Returns:
str: Graph in dot format. | def write_dot(g):
"""Replacement for pygraph.readwrite.dot.write, which is dog slow.
Note:
This isn't a general replacement. It will work for the graphs that
Rez generates, but there are no guarantees beyond that.
Args:
g (`pygraph.digraph`): Input graph.
Returns:
str:... |
Prune a package graph so it only contains nodes accessible from the
given package.
Args:
graph_str (str): Dot-language graph string.
package_name (str): Name of package of interest.
Returns:
Pruned graph, as a string. | def prune_graph(graph_str, package_name):
"""Prune a package graph so it only contains nodes accessible from the
given package.
Args:
graph_str (str): Dot-language graph string.
package_name (str): Name of package of interest.
Returns:
Pruned graph, as a string.
"""
# f... |
Render a graph to an image file.
Args:
graph_str (str): Dot-language graph string.
dest_file (str): Filepath to save the graph to.
fmt (str): Format, eg "png", "jpg".
image_ratio (float): Image ratio.
Returns:
String representing format that was written, such as 'png'. | def save_graph(graph_str, dest_file, fmt=None, image_ratio=None):
"""Render a graph to an image file.
Args:
graph_str (str): Dot-language graph string.
dest_file (str): Filepath to save the graph to.
fmt (str): Format, eg "png", "jpg".
image_ratio (float): Image ratio.
Retu... |
View a dot graph in an image viewer. | def view_graph(graph_str, dest_file=None):
"""View a dot graph in an image viewer."""
from rez.system import system
from rez.config import config
if (system.platform == "linux") and (not os.getenv("DISPLAY")):
print >> sys.stderr, "Unable to open display."
sys.exit(1)
dest_file = _... |
Return the number of physical cpu cores on the system. | def physical_cores(self):
"""Return the number of physical cpu cores on the system."""
try:
return self._physical_cores_base()
except Exception as e:
from rez.utils.logging_ import print_error
print_error("Error detecting physical core count, defaulting to 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. | 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_ ... |
Given a simple text output where each line gives a key-value pair
of the form "key: value", parse and return a dict | def _parse_colon_table_to_dict(cls, table_text):
'''Given a simple text output where each line gives a key-value pair
of the form "key: value", parse and return a dict'''
lines = [l.strip() for l in table_text.splitlines()]
lines = [l for l in lines if l]
pairs = [l.split(':', 1) f... |
Write the given text to our wrapped stream, stripping any ANSI
sequences from the text, and optionally converting them into win32
calls. | 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.... |
Returns a copy of the context. | 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 = s... |
Returns dependency information about two packages:
0: A does not depend, directly or indirectly, on B;
1: A depends indirectly on B;
2: A depends directly on B. | def package_depends_on(self, name_a, name_b):
"""Returns dependency information about two packages:
0: A does not depend, directly or indirectly, on B;
1: A depends indirectly on B;
2: A depends directly on B.
"""
assert self._context
if self._depende... |
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
... | 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... |
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. | 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:
... |
Replace the current context with another. | 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 |
... |
Find destinations for resources files | 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... |
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. | 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.
"""
... |
Return a new release VCS that can release from this source path. | 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 con... |
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 thro... | 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... |
Convenience function for executing a program such as 'git' etc. | 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=... |
Tear down this object, after we've agreed to close
with the server. | def _do_close(self):
"""Tear down this object, after we've agreed to close
with the server."""
AMQP_LOGGER.debug('Closed channel #%d', self.channel_id)
self.is_open = False
channel_id, self.channel_id = self.channel_id, None
connection, self.connection = self.connection, ... |
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 ... | 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 exce... |
Enable/disable flow from peer
This method asks the peer to pause or restart the flow of
content data. This is a simple flow-control mechanism that a
peer can use to avoid oveflowing its queues or otherwise
finding itself receiving more messages than it can process.
Note that thi... | def flow(self, active):
"""Enable/disable flow from peer
This method asks the peer to pause or restart the flow of
content data. This is a simple flow-control mechanism that a
peer can use to avoid oveflowing its queues or otherwise
finding itself receiving more messages than it... |
Enable/disable flow from peer
This method asks the peer to pause or restart the flow of
content data. This is a simple flow-control mechanism that a
peer can use to avoid oveflowing its queues or otherwise
finding itself receiving more messages than it can process.
Note that thi... | def _flow(self, args):
"""Enable/disable flow from peer
This method asks the peer to pause or restart the flow of
content data. This is a simple flow-control mechanism that a
peer can use to avoid oveflowing its queues or otherwise
finding itself receiving more messages than it ... |
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... | 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:
... |
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
Configur... | 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 sett... |
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 id... | 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 ... |
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 serve... | 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 excha... |
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 crea... | 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 speci... |
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 fie... | 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 ge... |
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 t... | 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 cons... |
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 ... | 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.
... |
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: longlon... | 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 m... |
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 re... | 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 ... |
Consumer cancelled by server.
Most likely the queue was deleted. | 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 Con... |
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 ... | 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
tra... |
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
... | 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 ... |
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 d... | 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_t... |
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... | 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... |
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 t... | 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 ... |
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 redeliver... | 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.
R... |
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
... | 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 S... |
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 undeliverabl... | 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 r... |
Enables publisher confirms for this channel (an RabbitMQ
extension).
Can now be used if the channel is in transactional mode.
:param nowait:
If set, the server will not respond to the method.
The client should not wait for a reply method. If the
server could... | def confirm_select(self, nowait=False):
"""Enables publisher confirms for this channel (an RabbitMQ
extension).
Can now be used if the channel is in transactional mode.
:param nowait:
If set, the server will not respond to the method.
The client should not wait ... |
Create a `BuildProcess` instance. | 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 ... |
Iterate over variants and call a function on each. | 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:
... |
Return the installation path for a package (where its payload goes).
Args:
path (str): Package repository path. | def get_package_install_path(self, path):
"""Return the installation path for a package (where its payload goes).
Args:
path (str): Package repository path.
"""
from rez.package_repository import package_repository_manager
pkg_repo = package_repository_manager.get_r... |
Create a context to build the variant within. | 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... |
Get release data for this release.
Returns:
dict. | 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
... |
If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not in
the dictionary, a KeyError is raised. | def pop(self, key, default=NONE):
"""
If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not in
the dictionary, a KeyError is raised.
"""
if key in self:
self._list_remove(key)
... |
Return (key, value) item pair at index.
Unlike ``popitem``, the sorted dictionary is not modified. Index
defaults to -1, the last/greatest key in the dictionary. Specify
``index=0`` to lookup the first/least key in the dictiony.
If index is out of range, raise IndexError. | def peekitem(self, index=-1):
"""Return (key, value) item pair at index.
Unlike ``popitem``, the sorted dictionary is not modified. Index
defaults to -1, the last/greatest key in the dictionary. Specify
``index=0`` to lookup the first/least key in the dictiony.
If index is out ... |
Update the dictionary with the key/value pairs from *other*, overwriting
existing keys.
*update* accepts either another dictionary object or an iterable of
key/value pairs (as a tuple or other iterable of length two). If
keyword arguments are specified, the dictionary is then updated w... | def update(self, *args, **kwargs):
"""
Update the dictionary with the key/value pairs from *other*, overwriting
existing keys.
*update* accepts either another dictionary object or an iterable of
key/value pairs (as a tuple or other iterable of length two). If
keyword ar... |
Return index of *value* in self.
Raises ValueError if *value* is not found. | def index(self, value):
"""
Return index of *value* in self.
Raises ValueError if *value* is not found.
"""
# pylint: disable=arguments-differ
for idx, val in enumerate(self):
if value == val:
return idx
raise ValueError('{0!r} is not ... |
Return the smallest *k* such that `itemssview[k] == key` and `start <= k
< end`. Raises `KeyError` if *key* is not present. *stop* defaults
to the end of the set. *start* defaults to the beginning. Negative
indexes are supported, as for slice indices. | def index(self, key, start=None, stop=None):
"""
Return the smallest *k* such that `itemssview[k] == key` and `start <= k
< end`. Raises `KeyError` if *key* is not present. *stop* defaults
to the end of the set. *start* defaults to the beginning. Negative
indexes are supporte... |
Return the number of occurrences of *item* in the set. | def count(self, item):
"""Return the number of occurrences of *item* in the set."""
# pylint: disable=arguments-differ
key, value = item
return 1 if key in self._dict and self._dict[key] == value else 0 |
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 t... | 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)
... |
A* search algorithm.
A set of heuristics is available under C{graph.algorithms.heuristics}. User-created heuristics
are allowed too.
@type graph: graph, digraph
@param graph: Graph
@type start: node
@param start: Start node
@type goal: node
@param goal: Goal node
... | def heuristic_search(graph, start, goal, heuristic):
"""
A* search algorithm.
A set of heuristics is available under C{graph.algorithms.heuristics}. User-created heuristics
are allowed too.
@type graph: graph, digraph
@param graph: Graph
@type start: node
@param start: Sta... |
Find a maximum flow and minimum cut of a directed graph by the Edmonds-Karp algorithm.
@type graph: digraph
@param graph: Graph
@type source: node
@param source: Source of the flow
@type sink: node
@param sink: Sink of the flow
@type caps: dictionary
@param caps: Dictionary specifyin... | def maximum_flow(graph, source, sink, caps = None):
"""
Find a maximum flow and minimum cut of a directed graph by the Edmonds-Karp algorithm.
@type graph: digraph
@param graph: Graph
@type source: node
@param source: Source of the flow
@type sink: node
@param sink: Sink of the flow
... |
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 ... | 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 on... |
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,... | 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 use... |
See if a URL is a candidate for a download URL for a project (the URL
has typically been scraped from an HTML page).
If it is, a dictionary is returned with keys "name", "version",
"filename" and "url"; otherwise, None is returned. | def convert_url_to_download_info(self, url, project_name):
"""
See if a URL is a candidate for a download URL for a project (the URL
has typically been scraped from an HTML page).
If it is, a dictionary is returned with keys "name", "version",
"filename" and "url"; otherwise, No... |
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 loc... | 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 ``Tr... |
Get available bind modules.
Returns:
dict: Map of (name, filepath) listing all 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 searchpat... |
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. | 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.
"""
bind... |
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 ... | 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 def... |
Return priority for a given object. | def priority(s):
"""Return priority for a given object."""
# REZ: Previously this value was calculated in place many times which is
# expensive. Do it once early.
# REZ: Changed this to output a list, so that can nicely sort "validate"
# items by the sub-priority of their schema
type_... |
Return a new release hook of the given type. | 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_pat... |
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.
... | 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 t... |
Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise. | def action_is_satisfied(action):
''' Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise.
'''
num_consumed_args = getattr(action, 'num_consumed_args', 0)
if action.nargs == ONE_OR_MORE and num_consumed_args < 1:
return False
else:
... |
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: iter... | 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)
... |
Depth-first search subfunction for traversals.
@type graph: graph, digraph
@param graph: Graph.
@type visited: dictionary
@param visited: List of nodes (visited nodes are marked non-zero).
@type node: node
@param node: Node to be explored by DFS. | def _dfs(graph, visited, node, pre, post):
"""
Depth-first search subfunction for traversals.
@type graph: graph, digraph
@param graph: Graph.
@type visited: dictionary
@param visited: List of nodes (visited nodes are marked non-zero).
@type node: node
@param node: Node to be e... |
Quickly see if file is a ZIP file by checking the magic number. | 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:
... |
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. | 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()
... |
Return the per-file header as a string. | def FileHeader(self):
"""Return the per-file header as a string."""
dt = self.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
if self.flag_bits & 0x08:
# Set these to zero because we write them after the f... |
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(). | 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
... |
Compute the CRC32 primitive on one byte. | def _crc32(self, ch, crc):
"""Compute the CRC32 primitive on one byte."""
return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] |
Read a line with approx. size. If size is negative,
read a whole line. | 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._checkfornewl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.