_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q228000 | ResolvedContext.execute_shell | train | def execute_shell(self, shell=None, parent_environ=None, rcfile=None,
norc=False, stdin=False, command=None, quiet=False,
block=None, actions_callback=None, post_actions_callback=None,
context_filepath=None, start_new_session=False, detached=False,
... | python | {
"resource": ""
} |
q228001 | ResolvedContext.to_dict | train | def to_dict(self, fields=None):
"""Convert context to dict containing only builtin types.
Args:
fields (list of str): If present, only write these fields into the
dict. This can be used to avoid constructing expensive fields
(such as 'graph') for some cases.
... | python | {
"resource": ""
} |
q228002 | add_sys_paths | train | def add_sys_paths(paths):
"""Add to sys.path, and revert on scope exit.
"""
original_syspath = sys.path[:]
sys.path.extend(paths)
try:
yield
finally:
sys.path = original_syspath | python | {
"resource": ""
} |
q228003 | popen | train | def popen(args, **kwargs):
"""Wrapper for `subprocess.Popen`.
Avoids python bug described here: https://bugs.python.org/issue3905. This
can arise when apps (maya) install a non-standard stdin handler.
In newer version of maya and katana, the sys.stdin object can also become
replaced by an object w... | python | {
"resource": ""
} |
q228004 | GitReleaseVCS.get_relative_to_remote | train | def get_relative_to_remote(self):
"""Return the number of commits we are relative to the remote. Negative
is behind, positive in front, zero means we are matched to remote.
"""
s = self.git("status", "--short", "-b")[0]
r = re.compile("\[([^\]]+)\]")
toks = r.findall(s)
... | python | {
"resource": ""
} |
q228005 | hypergraph.links | train | def links(self, obj):
"""
Return all nodes connected by the given hyperedge or all hyperedges
connected to the given hypernode.
@type obj: hyperedge
@param obj: Object identifier.
@rtype: list
@return: List of node objects linked to the given h... | python | {
"resource": ""
} |
q228006 | hypergraph.neighbors | train | def neighbors(self, obj):
"""
Return all neighbors adjacent to the given node.
@type obj: node
@param obj: Object identifier.
@rtype: list
@return: List of all node objects adjacent to the given node.
"""
neighbors = set([])
... | python | {
"resource": ""
} |
q228007 | hypergraph.del_node | train | def del_node(self, node):
"""
Delete a given node from the hypergraph.
@type node: node
@param node: Node identifier.
"""
if self.has_node(node):
for e in self.node_links[node]:
self.edge_links[e].remove(node)
self.node_l... | python | {
"resource": ""
} |
q228008 | hypergraph.add_hyperedge | train | def add_hyperedge(self, hyperedge):
"""
Add given hyperedge to the hypergraph.
@attention: While hyperedge-nodes can be of any type, it's strongly recommended to use only
numbers and single-line strings as node identifiers if you intend to use write().
@type hyperedge:... | python | {
"resource": ""
} |
q228009 | hypergraph.del_hyperedge | train | def del_hyperedge(self, hyperedge):
"""
Delete the given hyperedge.
@type hyperedge: hyperedge
@param hyperedge: Hyperedge identifier.
"""
if (hyperedge in self.hyperedges()):
for n in self.edge_links[hyperedge]:
self.node_links[n].re... | python | {
"resource": ""
} |
q228010 | hypergraph.link | train | def link(self, node, hyperedge):
"""
Link given node and hyperedge.
@type node: node
@param node: Node.
@type hyperedge: node
@param hyperedge: Hyperedge.
"""
if (hyperedge not in self.node_links[node]):
self.edge_links[hyperedge].append(no... | python | {
"resource": ""
} |
q228011 | hypergraph.unlink | train | def unlink(self, node, hyperedge):
"""
Unlink given node and hyperedge.
@type node: node
@param node: Node.
@type hyperedge: hyperedge
@param hyperedge: Hyperedge.
"""
self.node_links[node].remove(hyperedge)
self.edge_links[hyperedge].remove(no... | python | {
"resource": ""
} |
q228012 | hypergraph.rank | train | def rank(self):
"""
Return the rank of the given hypergraph.
@rtype: int
@return: Rank of graph.
"""
max_rank = 0
for each in self.hyperedges():
if len(self.edge_links[each]) > max_rank:
max_rank = len(self.edge_links... | python | {
"resource": ""
} |
q228013 | get_next_base26 | train | def get_next_base26(prev=None):
"""Increment letter-based IDs.
Generates IDs like ['a', 'b', ..., 'z', 'aa', ab', ..., 'az', 'ba', ...]
Returns:
str: Next base-26 ID.
"""
if not prev:
return 'a'
r = re.compile("^[a-z]*$")
if not r.match(prev):
raise ValueError("Inv... | python | {
"resource": ""
} |
q228014 | create_unique_base26_symlink | train | def create_unique_base26_symlink(path, source):
"""Create a base-26 symlink in `path` pointing to `source`.
If such a symlink already exists, it is returned. Note that there is a small
chance that this function may create a new symlink when there is already one
pointed at `source`.
Assumes `path` ... | python | {
"resource": ""
} |
q228015 | find_wheels | train | def find_wheels(projects, search_dirs):
"""Find wheels from which we can import PROJECTS.
Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
a list of the first wheel found for each PROJECT
"""
wheels = []
# Look through SEARCH_DIRS for the first suitable wheel. Don't bothe... | python | {
"resource": ""
} |
q228016 | relative_script | train | def relative_script(lines):
"Return a script that'll work in a relocatable environment."
activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, act... | python | {
"resource": ""
} |
q228017 | fixup_pth_and_egg_link | train | def fixup_pth_and_egg_link(home_dir, sys_path=None):
"""Makes .pth and .egg-link files use relative paths"""
home_dir = os.path.normcase(os.path.abspath(home_dir))
if sys_path is None:
sys_path = sys.path
for path in sys_path:
if not path:
path = '.'
if not os.path.is... | python | {
"resource": ""
} |
q228018 | make_relative_path | train | def make_relative_path(source, dest, dest_is_directory=True):
"""
Make a filename relative, where the filename is dest, and it is
being referred to from the filename source.
>>> make_relative_path('/usr/share/something/a-file.pth',
... '/usr/share/another-place/src/Direct... | python | {
"resource": ""
} |
q228019 | create_bootstrap_script | train | def create_bootstrap_script(extra_text, python_version=''):
"""
Creates a bootstrap script, which is like this script but with
extend_parser, adjust_options, and after_install hooks.
This returns a string that (written to disk of course) can be used
as a bootstrap script with your own customization... | python | {
"resource": ""
} |
q228020 | read_data | train | def read_data(file, endian, num=1):
"""
Read a given number of 32-bits unsigned integers from the given file
with the given endianness.
"""
res = struct.unpack(endian + 'L' * num, file.read(num * 4))
if len(res) == 1:
return res[0]
return res | python | {
"resource": ""
} |
q228021 | Logger._stdout_level | train | def _stdout_level(self):
"""Returns the level that stdout runs at"""
for level, consumer in self.consumers:
if consumer is sys.stdout:
return level
return self.FATAL | python | {
"resource": ""
} |
q228022 | ConfigOptionParser.get_config_section | train | def get_config_section(self, name):
"""
Get a section of a configuration
"""
if self.config.has_section(name):
return self.config.items(name)
return [] | python | {
"resource": ""
} |
q228023 | ConfigOptionParser.get_environ_vars | train | def get_environ_vars(self, prefix='VIRTUALENV_'):
"""
Returns a generator with all environmental vars with prefix VIRTUALENV
"""
for key, val in os.environ.items():
if key.startswith(prefix):
yield (key.replace(prefix, '').lower(), val) | python | {
"resource": ""
} |
q228024 | Config.copy | train | def copy(self, overrides=None, locked=False):
"""Create a separate copy of this config."""
other = copy.copy(self)
if overrides is not None:
other.overrides = overrides
other.locked = locked
other._uncache()
return other | python | {
"resource": ""
} |
q228025 | Config.override | train | def override(self, key, value):
"""Set a setting to the given value.
Note that `key` can be in dotted form, eg
'plugins.release_hook.emailer.sender'.
"""
keys = key.split('.')
if len(keys) > 1:
if keys[0] != "plugins":
raise AttributeError("no... | python | {
"resource": ""
} |
q228026 | Config.remove_override | train | def remove_override(self, key):
"""Remove a setting override, if one exists."""
keys = key.split('.')
if len(keys) > 1:
raise NotImplementedError
elif key in self.overrides:
del self.overrides[key]
self._uncache(key) | python | {
"resource": ""
} |
q228027 | Config.warn | train | def warn(self, key):
"""Returns True if the warning setting is enabled."""
return (not self.quiet and not self.warn_none and
(self.warn_all or getattr(self, "warn_%s" % key))) | python | {
"resource": ""
} |
q228028 | Config.debug | train | def debug(self, key):
"""Returns True if the debug setting is enabled."""
return (not self.quiet and not self.debug_none and
(self.debug_all or getattr(self, "debug_%s" % key))) | python | {
"resource": ""
} |
q228029 | Config.data | train | def data(self):
"""Returns the entire configuration as a dict.
Note that this will force all plugins to be loaded.
"""
d = {}
for key in self._data:
if key == "plugins":
d[key] = self.plugins.data()
else:
try:
... | python | {
"resource": ""
} |
q228030 | Config.nonlocal_packages_path | train | def nonlocal_packages_path(self):
"""Returns package search paths with local path removed."""
paths = self.packages_path[:]
if self.local_packages_path in paths:
paths.remove(self.local_packages_path)
return paths | python | {
"resource": ""
} |
q228031 | Config._swap | train | def _swap(self, other):
"""Swap this config with another.
This is used by the unit tests to swap the config to one that is
shielded from any user config updates. Do not use this method unless
you have good reason.
"""
self.__dict__, other.__dict__ = other.__dict__, self.... | python | {
"resource": ""
} |
q228032 | Config._create_main_config | train | def _create_main_config(cls, overrides=None):
"""See comment block at top of 'rezconfig' describing how the main
config is assembled."""
filepaths = []
filepaths.append(get_module_root_config())
filepath = os.getenv("REZ_CONFIG_FILE")
if filepath:
filepaths.ex... | python | {
"resource": ""
} |
q228033 | platform_mapped | train | def platform_mapped(func):
"""Decorates functions for lookups within a config.platform_map dictionary.
The first level key is mapped to the func.__name__ of the decorated function.
Regular expressions are used on the second level key, values.
Note that there is no guaranteed order within the dictionary... | python | {
"resource": ""
} |
q228034 | pagerank | train | def pagerank(graph, damping_factor=0.85, max_iterations=100, min_delta=0.00001):
"""
Compute and return the PageRank in an directed graph.
@type graph: digraph
@param graph: Digraph.
@type damping_factor: number
@param damping_factor: PageRank dumping factor.
@type max_... | python | {
"resource": ""
} |
q228035 | exec_command | train | def exec_command(attr, cmd):
"""Runs a subproc to calculate a package attribute.
"""
import subprocess
p = popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode:
from rez.exceptions import InvalidPackageError
raise InvalidPackageE... | python | {
"resource": ""
} |
q228036 | exec_python | train | def exec_python(attr, src, executable="python"):
"""Runs a python subproc to calculate a package attribute.
Args:
attr (str): Name of package attribute being created.
src (list of str): Python code to execute, will be converted into
semicolon-delimited single line of code.
Retu... | python | {
"resource": ""
} |
q228037 | find_site_python | train | def find_site_python(module_name, paths=None):
"""Find the rez native python package that contains the given module.
This function is used by python 'native' rez installers to find the native
rez python package that represents the python installation that this module
is installed into.
Note:
... | python | {
"resource": ""
} |
q228038 | _intersection | train | def _intersection(A,B):
"""
A simple function to find an intersection between two arrays.
@type A: List
@param A: First List
@type B: List
@param B: Second List
@rtype: List
@return: List of Intersections
"""
intersection = []
for i in A:
if i in B:
... | python | {
"resource": ""
} |
q228039 | critical_path | train | def critical_path(graph):
"""
Compute and return the critical path in an acyclic directed weighted graph.
@attention: This function is only meaningful for directed weighted acyclic graphs
@type graph: digraph
@param graph: Digraph
@rtype: List
@return: List containing all the... | python | {
"resource": ""
} |
q228040 | CustomBuildSystem.build | train | def build(self, context, variant, build_path, install_path, install=False,
build_type=BuildType.local):
"""Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables... | python | {
"resource": ""
} |
q228041 | HgReleaseVCS._create_tag_highlevel | train | def _create_tag_highlevel(self, tag_name, message=None):
"""Create a tag on the toplevel repo if there is no patch repo,
or a tag on the patch repo and bookmark on the top repo if there is a
patch repo
Returns a list where each entry is a dict for each bookmark or tag
created, w... | python | {
"resource": ""
} |
q228042 | HgReleaseVCS._create_tag_lowlevel | train | def _create_tag_lowlevel(self, tag_name, message=None, force=True,
patch=False):
"""Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commi... | python | {
"resource": ""
} |
q228043 | HgReleaseVCS.is_ancestor | train | def is_ancestor(self, commit1, commit2, patch=False):
"""Returns True if commit1 is a direct ancestor of commit2, or False
otherwise.
This method considers a commit to be a direct ancestor of itself"""
result = self.hg("log", "-r", "first(%s::%s)" % (commit1, commit2),
... | python | {
"resource": ""
} |
q228044 | get_patched_request | train | def get_patched_request(requires, patchlist):
"""Apply patch args to a request.
For example, consider:
>>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"])
["foo-6", "bah-8.1"]
>>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"])
["foo-5"]
The following ... | python | {
"resource": ""
} |
q228045 | AppLaunch.execute | train | def execute(self, app_path, app_args, version, **kwargs):
"""
The execute functon of the hook will be called to start the required application
:param app_path: (str) The path of the application executable
:param app_args: (str) Any arguments the application may require
:param ve... | python | {
"resource": ""
} |
q228046 | AppLaunch.check_rez | train | def check_rez(self, strict=True):
"""
Checks to see if a Rez package is available in the current environment.
If it is available, add it to the system path, exposing the Rez Python API
:param strict: (bool) If True, raise an error if Rez is not available as a package.
... | python | {
"resource": ""
} |
q228047 | get_last_changed_revision | train | def get_last_changed_revision(client, url):
"""
util func, get last revision of url
"""
try:
svn_entries = client.info2(url,
pysvn.Revision(pysvn.opt_revision_kind.head),
recurse=False)
if not svn_entries:
... | python | {
"resource": ""
} |
q228048 | get_svn_login | train | def get_svn_login(realm, username, may_save):
"""
provide svn with permissions. @TODO this will have to be updated to take
into account automated releases etc.
"""
import getpass
print "svn requires a password for the user %s:" % username
pwd = ''
while not pwd.strip():
pwd = ge... | python | {
"resource": ""
} |
q228049 | read | train | def read(string):
"""
Read a graph from a XML document and return it. Nodes and edges specified in the input will
be added to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: graph
@return: Graph
"""
dom = parseS... | python | {
"resource": ""
} |
q228050 | read_hypergraph | train | def read_hypergraph(string):
"""
Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph
"""
... | python | {
"resource": ""
} |
q228051 | diff_packages | train | def diff_packages(pkg1, pkg2=None):
"""Invoke a diff editor to show the difference between the source of two
packages.
Args:
pkg1 (`Package`): Package to diff.
pkg2 (`Package`): Package to diff against. If None, the next most recent
package version is used.
"""
if pkg2 i... | python | {
"resource": ""
} |
q228052 | sigint_handler | train | def sigint_handler(signum, frame):
"""Exit gracefully on ctrl-C."""
global _handled_int
if not _handled_int:
_handled_int = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Interrupted by user"
sigbase_handler(signum, frame) | python | {
"resource": ""
} |
q228053 | sigterm_handler | train | def sigterm_handler(signum, frame):
"""Exit gracefully on terminate."""
global _handled_term
if not _handled_term:
_handled_term = True
if not _env_var_true("_REZ_QUIET_ON_SIG"):
print >> sys.stderr, "Terminated by user"
sigbase_handler(signum, frame) | python | {
"resource": ""
} |
q228054 | LazyArgumentParser.format_help | train | def format_help(self):
"""Sets up all sub-parsers when help is requested."""
if self._subparsers:
for action in self._subparsers._actions:
if isinstance(action, LazySubParsersAction):
for parser_name, parser in action._name_parser_map.iteritems():
... | python | {
"resource": ""
} |
q228055 | is_valid_package_name | train | def is_valid_package_name(name, raise_error=False):
"""Test the validity of a package name string.
Args:
name (str): Name to test.
raise_error (bool): If True, raise an exception on failure
Returns:
bool.
"""
is_valid = PACKAGE_NAME_REGEX.match(name)
if raise_error and ... | python | {
"resource": ""
} |
q228056 | expand_abbreviations | train | def expand_abbreviations(txt, fields):
"""Expand abbreviations in a format string.
If an abbreviation does not match a field, or matches multiple fields, it
is left unchanged.
Example:
>>> fields = ("hey", "there", "dude")
>>> expand_abbreviations("hello {d}", fields)
'hello d... | python | {
"resource": ""
} |
q228057 | dict_to_attributes_code | train | def dict_to_attributes_code(dict_):
"""Given a nested dict, generate a python code equivalent.
Example:
>>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}}
>>> print dict_to_attributes_code(d)
foo = 'bah'
colors.red = 1
colors.blue = 2
Returns:
str.
... | python | {
"resource": ""
} |
q228058 | columnise | train | def columnise(rows, padding=2):
"""Print rows of entries in aligned columns."""
strs = []
maxwidths = {}
for row in rows:
for i, e in enumerate(row):
se = str(e)
nse = len(se)
w = maxwidths.get(i, -1)
if nse > w:
maxwidths[i] = nse... | python | {
"resource": ""
} |
q228059 | print_colored_columns | train | def print_colored_columns(printer, rows, padding=2):
"""Like `columnise`, but with colored rows.
Args:
printer (`colorize.Printer`): Printer object.
Note:
The last entry in each row is the row color, or None for no coloring.
"""
rows_ = [x[:-1] for x in rows]
colors = [x[-1] fo... | python | {
"resource": ""
} |
q228060 | expanduser | train | def expanduser(path):
"""Expand '~' to home directory in the given string.
Note that this function deliberately differs from the builtin
os.path.expanduser() on Linux systems, which expands strings such as
'~sclaus' to that user's homedir. This is problematic in rez because the
string '~packagename... | python | {
"resource": ""
} |
q228061 | as_block_string | train | def as_block_string(txt):
"""Return a string formatted as a python block comment string, like the one
you're currently reading. Special characters are escaped if necessary.
"""
import json
lines = []
for line in txt.split('\n'):
line_ = json.dumps(line)
line_ = line_[1:-1].rstri... | python | {
"resource": ""
} |
q228062 | StringFormatMixin.format | train | def format(self, s, pretty=None, expand=None):
"""Format a string.
Args:
s (str): String to format, eg "hello {name}"
pretty (bool): If True, references to non-string attributes such as
lists are converted to basic form, with characters such as
br... | python | {
"resource": ""
} |
q228063 | Version.copy | train | def copy(self):
"""Returns a copy of the version."""
other = Version(None)
other.tokens = self.tokens[:]
other.seps = self.seps[:]
return other | python | {
"resource": ""
} |
q228064 | Version.trim | train | def trim(self, len_):
"""Return a copy of the version, possibly with less tokens.
Args:
len_ (int): New version length. If >= current length, an
unchanged copy of the version is returned.
"""
other = Version(None)
other.tokens = self.tokens[:len_]
... | python | {
"resource": ""
} |
q228065 | VersionRange.union | train | def union(self, other):
"""OR together version ranges.
Calculates the union of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to OR with.
Returns:
New VersionRange object representing the union.
"""
if no... | python | {
"resource": ""
} |
q228066 | VersionRange.intersection | train | def intersection(self, other):
"""AND together version ranges.
Calculates the intersection of this range with one or more other ranges.
Args:
other: VersionRange object (or list of) to AND with.
Returns:
New VersionRange object representing the intersection, or... | python | {
"resource": ""
} |
q228067 | VersionRange.inverse | train | def inverse(self):
"""Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range).
"""
if self.is_any():
return None
else:
... | python | {
"resource": ""
} |
q228068 | VersionRange.split | train | def split(self):
"""Split into separate contiguous ranges.
Returns:
A list of VersionRange objects. For example, the range "3|5+" will
be split into ["3", "5+"].
"""
ranges = []
for bound in self.bounds:
range = VersionRange(None)
... | python | {
"resource": ""
} |
q228069 | VersionRange.as_span | train | def as_span(cls, lower_version=None, upper_version=None,
lower_inclusive=True, upper_inclusive=True):
"""Create a range from lower_version..upper_version.
Args:
lower_version: Version object representing lower bound of the range.
upper_version: Version object rep... | python | {
"resource": ""
} |
q228070 | VersionRange.from_version | train | def from_version(cls, version, op=None):
"""Create a range from a version.
Args:
version: Version object. This is used as the upper/lower bound of
the range.
op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<',
'lte'/'<=', 'eq'/'=='. I... | python | {
"resource": ""
} |
q228071 | VersionRange.from_versions | train | def from_versions(cls, versions):
"""Create a range from a list of versions.
This method creates a range that contains only the given versions and
no other. Typically the range looks like (for eg) "==3|==4|==5.1".
Args:
versions: List of Version objects.
Returns:
... | python | {
"resource": ""
} |
q228072 | VersionRange.to_versions | train | def to_versions(self):
"""Returns exact version ranges as Version objects, or None if there
are no exact version ranges present.
"""
versions = []
for bound in self.bounds:
if bound.lower.inclusive and bound.upper.inclusive \
and (bound.lower.versi... | python | {
"resource": ""
} |
q228073 | VersionRange.contains_version | train | def contains_version(self, version):
"""Returns True if version is contained in this range."""
if len(self.bounds) < 5:
# not worth overhead of binary search
for bound in self.bounds:
i = bound.version_containment(version)
if i == 0:
... | python | {
"resource": ""
} |
q228074 | VersionRange.iter_intersecting | train | def iter_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
... | python | {
"resource": ""
} |
q228075 | VersionRange.iter_non_intersecting | train | def iter_non_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns non-intersections only.
Returns:
An iterator that returns items from `iterable` that don't intersect.
"""
return _ContainsVersionIterator(self, iterable, key, de... | python | {
"resource": ""
} |
q228076 | VersionRange.span | train | def span(self):
"""Return a contiguous range that is a superset of this range.
Returns:
A VersionRange object representing the span of this range. For
example, the span of "2+<4|6+<8" would be "2+<8".
"""
other = VersionRange(None)
bound = _Bound(self.bou... | python | {
"resource": ""
} |
q228077 | VersionRange.visit_versions | train | def visit_versions(self, func):
"""Visit each version in the range, and apply a function to each.
This is for advanced usage only.
If `func` returns a `Version`, this call will change the versions in
place.
It is possible to change versions in a way that is nonsensical - for
... | python | {
"resource": ""
} |
q228078 | HTTPTransport.send | train | def send(self, url, data, headers):
"""
Sends a request to a remote webserver using HTTP POST.
"""
req = urllib2.Request(url, headers=headers)
try:
response = urlopen(
url=req,
data=data,
timeout=self.timeout,
... | python | {
"resource": ""
} |
q228079 | extract_auth_vars | train | def extract_auth_vars(request):
"""
raven-js will pass both Authorization and X-Sentry-Auth depending on the browser
and server configurations.
"""
if request.META.get('HTTP_X_SENTRY_AUTH', '').startswith('Sentry'):
return request.META['HTTP_X_SENTRY_AUTH']
elif request.META.get('HTTP_AU... | python | {
"resource": ""
} |
q228080 | Exception._get_value | train | def _get_value(self, exc_type, exc_value, exc_traceback):
"""
Convert exception info to a value for the values list.
"""
stack_info = get_stack_info(
iter_traceback_frames(exc_traceback),
transformer=self.transform,
capture_locals=self.client.capture_l... | python | {
"resource": ""
} |
q228081 | record | train | def record(message=None, timestamp=None, level=None, category=None,
data=None, type=None, processor=None):
"""Records a breadcrumb for all active clients. This is what integration
code should use rather than invoking the `captureBreadcrumb` method
on a specific client.
"""
if timestamp i... | python | {
"resource": ""
} |
q228082 | ignore_logger | train | def ignore_logger(name_or_logger, allow_level=None):
"""Ignores a logger during breadcrumb recording.
"""
def handler(logger, level, msg, args, kwargs):
if allow_level is not None and \
level >= allow_level:
return False
return True
register_special_log_handler(nam... | python | {
"resource": ""
} |
q228083 | Serializer.transform | train | def transform(self, value, **kwargs):
"""
Primary function which handles recursively transforming
values via their serializers
"""
if value is None:
return None
objid = id(value)
if objid in self.context:
return '<...>'
self.contex... | python | {
"resource": ""
} |
q228084 | AsyncSentryClient.send | train | def send(self, auth_header=None, callback=None, **data):
"""
Serializes the message and passes the payload onto ``send_encoded``.
"""
message = self.encode(data)
return self.send_encoded(message, auth_header=auth_header, callback=callback) | python | {
"resource": ""
} |
q228085 | AsyncSentryClient._send_remote | train | def _send_remote(self, url, data, headers=None, callback=None):
"""
Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response.
"""
if headers is None:
headers = {}
re... | python | {
"resource": ""
} |
q228086 | SentryMixin.get_sentry_data_from_request | train | def get_sentry_data_from_request(self):
"""
Extracts the data required for 'sentry.interfaces.Http' from the
current request being handled by the request handler
:param return: A dictionary.
"""
return {
'request': {
'url': self.request.full_u... | python | {
"resource": ""
} |
q228087 | Client.get_public_dsn | train | def get_public_dsn(self, scheme=None):
"""
Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https')
"""
if s... | python | {
"resource": ""
} |
q228088 | Client.capture | train | def capture(self, event_type, data=None, date=None, time_spent=None,
extra=None, stack=None, tags=None, sample_rate=None,
**kwargs):
"""
Captures and processes an event and pipes it off to SentryClient.send.
To use structured data (interfaces) with capture:
... | python | {
"resource": ""
} |
q228089 | Client._log_failed_submission | train | def _log_failed_submission(self, data):
"""
Log a reasonable representation of an event that should have been sent
to Sentry
"""
message = data.pop('message', '<no message value>')
output = [message]
if 'exception' in data and 'stacktrace' in data['exception']['va... | python | {
"resource": ""
} |
q228090 | Client.send_encoded | train | def send_encoded(self, message, auth_header=None, **kwargs):
"""
Given an already serialized message, signs the message and passes the
payload off to ``send_remote``.
"""
client_string = 'raven-python/%s' % (raven.VERSION,)
if not auth_header:
timestamp = tim... | python | {
"resource": ""
} |
q228091 | Client.captureQuery | train | def captureQuery(self, query, params=(), engine=None, **kwargs):
"""
Creates an event for a SQL query.
>>> client.captureQuery('SELECT * FROM foo')
"""
return self.capture(
'raven.events.Query', query=query, params=params, engine=engine,
**kwargs) | python | {
"resource": ""
} |
q228092 | Client.captureBreadcrumb | train | def captureBreadcrumb(self, *args, **kwargs):
"""
Records a breadcrumb with the current context. They will be
sent with the next event.
"""
# Note: framework integration should not call this method but
# instead use the raven.breadcrumbs.record_breadcrumb function
... | python | {
"resource": ""
} |
q228093 | TransportRegistry.register_scheme | train | def register_scheme(self, scheme, cls):
"""
It is possible to inject new schemes at runtime
"""
if scheme in self._schemes:
raise DuplicateScheme()
urlparse.register_scheme(scheme)
# TODO (vng): verify the interface of the new class
self._schemes[sche... | python | {
"resource": ""
} |
q228094 | Sentry.get_http_info | train | def get_http_info(self, request):
"""
Determine how to retrieve actual data by using request.mimetype.
"""
if self.is_json_type(request.mimetype):
retriever = self.get_json_data
else:
retriever = self.get_form_data
return self.get_http_info_with_re... | python | {
"resource": ""
} |
q228095 | setup_logging | train | def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS):
"""
Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logg... | python | {
"resource": ""
} |
q228096 | to_dict | train | def to_dict(dictish):
"""
Given something that closely resembles a dictionary, we attempt
to coerce it into a propery dictionary.
"""
if hasattr(dictish, 'iterkeys'):
m = dictish.iterkeys
elif hasattr(dictish, 'keys'):
m = dictish.keys
else:
raise ValueError(dictish)
... | python | {
"resource": ""
} |
q228097 | slim_frame_data | train | def slim_frame_data(frames, frame_allowance=25):
"""
Removes various excess metadata from middle frames which go beyond
``frame_allowance``.
Returns ``frames``.
"""
frames_len = 0
app_frames = []
system_frames = []
for frame in frames:
frames_len += 1
if frame.get('i... | python | {
"resource": ""
} |
q228098 | get_data_from_request | train | def get_data_from_request():
"""Returns request data extracted from web.ctx."""
return {
'request': {
'url': '%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path']),
'query_string': web.ctx.query,
'method': web.ctx.method,
'data': web.data(),... | python | {
"resource": ""
} |
q228099 | get_regex | train | def get_regex(resolver_or_pattern):
"""Utility method for django's deprecated resolver.regex"""
try:
regex = resolver_or_pattern.regex
except AttributeError:
regex = resolver_or_pattern.pattern.regex
return regex | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.