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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
246,500 | nerdvegas/rez | src/rez/config.py | Config.copy | 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 | def copy(self, overrides=None, locked=False):
other = copy.copy(self)
if overrides is not None:
other.overrides = overrides
other.locked = locked
other._uncache()
return other | [
"def",
"copy",
"(",
"self",
",",
"overrides",
"=",
"None",
",",
"locked",
"=",
"False",
")",
":",
"other",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"if",
"overrides",
"is",
"not",
"None",
":",
"other",
".",
"overrides",
"=",
"overrides",
"other",
... | Create a separate copy of this config. | [
"Create",
"a",
"separate",
"copy",
"of",
"this",
"config",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L429-L439 |
246,501 | nerdvegas/rez | src/rez/config.py | Config.override | 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 such setting: %r" % key)
self.plugins.override(keys[1:], value)
else:
self.overrides[key] = value
self._uncache(key) | python | def override(self, key, value):
keys = key.split('.')
if len(keys) > 1:
if keys[0] != "plugins":
raise AttributeError("no such setting: %r" % key)
self.plugins.override(keys[1:], value)
else:
self.overrides[key] = value
self._uncache(key) | [
"def",
"override",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"keys",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"keys",
")",
">",
"1",
":",
"if",
"keys",
"[",
"0",
"]",
"!=",
"\"plugins\"",
":",
"raise",
"AttributeError",... | Set a setting to the given value.
Note that `key` can be in dotted form, eg
'plugins.release_hook.emailer.sender'. | [
"Set",
"a",
"setting",
"to",
"the",
"given",
"value",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L441-L454 |
246,502 | nerdvegas/rez | src/rez/config.py | Config.remove_override | 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 | def remove_override(self, key):
keys = key.split('.')
if len(keys) > 1:
raise NotImplementedError
elif key in self.overrides:
del self.overrides[key]
self._uncache(key) | [
"def",
"remove_override",
"(",
"self",
",",
"key",
")",
":",
"keys",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"keys",
")",
">",
"1",
":",
"raise",
"NotImplementedError",
"elif",
"key",
"in",
"self",
".",
"overrides",
":",
"del",
... | Remove a setting override, if one exists. | [
"Remove",
"a",
"setting",
"override",
"if",
"one",
"exists",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L459-L466 |
246,503 | nerdvegas/rez | src/rez/config.py | Config.warn | 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 | def warn(self, key):
return (not self.quiet and not self.warn_none and
(self.warn_all or getattr(self, "warn_%s" % key))) | [
"def",
"warn",
"(",
"self",
",",
"key",
")",
":",
"return",
"(",
"not",
"self",
".",
"quiet",
"and",
"not",
"self",
".",
"warn_none",
"and",
"(",
"self",
".",
"warn_all",
"or",
"getattr",
"(",
"self",
",",
"\"warn_%s\"",
"%",
"key",
")",
")",
")"
] | Returns True if the warning setting is enabled. | [
"Returns",
"True",
"if",
"the",
"warning",
"setting",
"is",
"enabled",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L468-L471 |
246,504 | nerdvegas/rez | src/rez/config.py | Config.debug | 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 | def debug(self, key):
return (not self.quiet and not self.debug_none and
(self.debug_all or getattr(self, "debug_%s" % key))) | [
"def",
"debug",
"(",
"self",
",",
"key",
")",
":",
"return",
"(",
"not",
"self",
".",
"quiet",
"and",
"not",
"self",
".",
"debug_none",
"and",
"(",
"self",
".",
"debug_all",
"or",
"getattr",
"(",
"self",
",",
"\"debug_%s\"",
"%",
"key",
")",
")",
"... | Returns True if the debug setting is enabled. | [
"Returns",
"True",
"if",
"the",
"debug",
"setting",
"is",
"enabled",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L473-L476 |
246,505 | nerdvegas/rez | src/rez/config.py | Config.data | 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:
d[key] = getattr(self, key)
except AttributeError:
pass # unknown key, just leave it unchanged
return d | python | def data(self):
d = {}
for key in self._data:
if key == "plugins":
d[key] = self.plugins.data()
else:
try:
d[key] = getattr(self, key)
except AttributeError:
pass # unknown key, just leave it unchanged
return d | [
"def",
"data",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_data",
":",
"if",
"key",
"==",
"\"plugins\"",
":",
"d",
"[",
"key",
"]",
"=",
"self",
".",
"plugins",
".",
"data",
"(",
")",
"else",
":",
"try",
":",... | Returns the entire configuration as a dict.
Note that this will force all plugins to be loaded. | [
"Returns",
"the",
"entire",
"configuration",
"as",
"a",
"dict",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L507-L521 |
246,506 | nerdvegas/rez | src/rez/config.py | Config.nonlocal_packages_path | 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 | def nonlocal_packages_path(self):
paths = self.packages_path[:]
if self.local_packages_path in paths:
paths.remove(self.local_packages_path)
return paths | [
"def",
"nonlocal_packages_path",
"(",
"self",
")",
":",
"paths",
"=",
"self",
".",
"packages_path",
"[",
":",
"]",
"if",
"self",
".",
"local_packages_path",
"in",
"paths",
":",
"paths",
".",
"remove",
"(",
"self",
".",
"local_packages_path",
")",
"return",
... | Returns package search paths with local path removed. | [
"Returns",
"package",
"search",
"paths",
"with",
"local",
"path",
"removed",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L524-L529 |
246,507 | nerdvegas/rez | src/rez/config.py | Config._swap | 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.__dict__ | python | def _swap(self, other):
self.__dict__, other.__dict__ = other.__dict__, self.__dict__ | [
"def",
"_swap",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"__dict__",
",",
"other",
".",
"__dict__",
"=",
"other",
".",
"__dict__",
",",
"self",
".",
"__dict__"
] | 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. | [
"Swap",
"this",
"config",
"with",
"another",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L568-L575 |
246,508 | nerdvegas/rez | src/rez/config.py | Config._create_main_config | 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.extend(filepath.split(os.pathsep))
filepath = os.path.expanduser("~/.rezconfig")
filepaths.append(filepath)
return Config(filepaths, overrides) | python | def _create_main_config(cls, overrides=None):
filepaths = []
filepaths.append(get_module_root_config())
filepath = os.getenv("REZ_CONFIG_FILE")
if filepath:
filepaths.extend(filepath.split(os.pathsep))
filepath = os.path.expanduser("~/.rezconfig")
filepaths.append(filepath)
return Config(filepaths, overrides) | [
"def",
"_create_main_config",
"(",
"cls",
",",
"overrides",
"=",
"None",
")",
":",
"filepaths",
"=",
"[",
"]",
"filepaths",
".",
"append",
"(",
"get_module_root_config",
"(",
")",
")",
"filepath",
"=",
"os",
".",
"getenv",
"(",
"\"REZ_CONFIG_FILE\"",
")",
... | See comment block at top of 'rezconfig' describing how the main
config is assembled. | [
"See",
"comment",
"block",
"at",
"top",
"of",
"rezconfig",
"describing",
"how",
"the",
"main",
"config",
"is",
"assembled",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L600-L612 |
246,509 | nerdvegas/rez | src/rez/utils/platform_mapped.py | platform_mapped | 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 evaluation. Only the first matching
regular expression is being used.
For example:
config.platform_map = {
"os": {
r"Scientific Linux-(.*)": r"Scientific-\1", # Scientific Linux-x.x -> Scientific-x.x
r"Ubuntu-14.\d": r"Ubuntu-14", # Any Ubuntu-14.x -> Ubuntu-14
},
"arch": {
"x86_64": "64bit", # Maps both x86_64 and amd64 -> 64bit (don't)
"amd64": "64bit",
},
}
"""
def inner(*args, **kwargs):
# Since platform is being used within config lazy import config to prevent
# circular dependencies
from rez.config import config
# Original result
result = func(*args, **kwargs)
# The function name is used as primary key
entry = config.platform_map.get(func.__name__)
if entry:
for key, value in entry.iteritems():
result, changes = re.subn(key, value, result)
if changes > 0:
break
return result
return inner | python | def platform_mapped(func):
def inner(*args, **kwargs):
# Since platform is being used within config lazy import config to prevent
# circular dependencies
from rez.config import config
# Original result
result = func(*args, **kwargs)
# The function name is used as primary key
entry = config.platform_map.get(func.__name__)
if entry:
for key, value in entry.iteritems():
result, changes = re.subn(key, value, result)
if changes > 0:
break
return result
return inner | [
"def",
"platform_mapped",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Since platform is being used within config lazy import config to prevent",
"# circular dependencies",
"from",
"rez",
".",
"config",
"import",
"conf... | 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 evaluation. Only the first matching
regular expression is being used.
For example:
config.platform_map = {
"os": {
r"Scientific Linux-(.*)": r"Scientific-\1", # Scientific Linux-x.x -> Scientific-x.x
r"Ubuntu-14.\d": r"Ubuntu-14", # Any Ubuntu-14.x -> Ubuntu-14
},
"arch": {
"x86_64": "64bit", # Maps both x86_64 and amd64 -> 64bit (don't)
"amd64": "64bit",
},
} | [
"Decorates",
"functions",
"for",
"lookups",
"within",
"a",
"config",
".",
"platform_map",
"dictionary",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/platform_mapped.py#L4-L42 |
246,510 | nerdvegas/rez | src/rez/vendor/pygraph/algorithms/pagerank.py | pagerank | 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_iterations: number
@param max_iterations: Maximum number of iterations.
@type min_delta: number
@param min_delta: Smallest variation required to have a new iteration.
@rtype: Dict
@return: Dict containing all the nodes PageRank.
"""
nodes = graph.nodes()
graph_size = len(nodes)
if graph_size == 0:
return {}
min_value = (1.0-damping_factor)/graph_size #value for nodes without inbound links
# itialize the page rank dict with 1/N for all nodes
pagerank = dict.fromkeys(nodes, 1.0/graph_size)
for i in range(max_iterations):
diff = 0 #total difference compared to last iteraction
# computes each node PageRank based on inbound links
for node in nodes:
rank = min_value
for referring_page in graph.incidents(node):
rank += damping_factor * pagerank[referring_page] / len(graph.neighbors(referring_page))
diff += abs(pagerank[node] - rank)
pagerank[node] = rank
#stop if PageRank has converged
if diff < min_delta:
break
return pagerank | python | def pagerank(graph, damping_factor=0.85, max_iterations=100, min_delta=0.00001):
nodes = graph.nodes()
graph_size = len(nodes)
if graph_size == 0:
return {}
min_value = (1.0-damping_factor)/graph_size #value for nodes without inbound links
# itialize the page rank dict with 1/N for all nodes
pagerank = dict.fromkeys(nodes, 1.0/graph_size)
for i in range(max_iterations):
diff = 0 #total difference compared to last iteraction
# computes each node PageRank based on inbound links
for node in nodes:
rank = min_value
for referring_page in graph.incidents(node):
rank += damping_factor * pagerank[referring_page] / len(graph.neighbors(referring_page))
diff += abs(pagerank[node] - rank)
pagerank[node] = rank
#stop if PageRank has converged
if diff < min_delta:
break
return pagerank | [
"def",
"pagerank",
"(",
"graph",
",",
"damping_factor",
"=",
"0.85",
",",
"max_iterations",
"=",
"100",
",",
"min_delta",
"=",
"0.00001",
")",
":",
"nodes",
"=",
"graph",
".",
"nodes",
"(",
")",
"graph_size",
"=",
"len",
"(",
"nodes",
")",
"if",
"graph... | 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_iterations: number
@param max_iterations: Maximum number of iterations.
@type min_delta: number
@param min_delta: Smallest variation required to have a new iteration.
@rtype: Dict
@return: Dict containing all the nodes PageRank. | [
"Compute",
"and",
"return",
"the",
"PageRank",
"in",
"an",
"directed",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/pagerank.py#L32-L76 |
246,511 | nerdvegas/rez | src/rez/package_py_utils.py | exec_command | 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 InvalidPackageError(
"Error determining package attribute '%s':\n%s" % (attr, err))
return out.strip(), err.strip() | python | def exec_command(attr, cmd):
import subprocess
p = popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode:
from rez.exceptions import InvalidPackageError
raise InvalidPackageError(
"Error determining package attribute '%s':\n%s" % (attr, err))
return out.strip(), err.strip() | [
"def",
"exec_command",
"(",
"attr",
",",
"cmd",
")",
":",
"import",
"subprocess",
"p",
"=",
"popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"err",
"=",
"p",
".",
"c... | Runs a subproc to calculate a package attribute. | [
"Runs",
"a",
"subproc",
"to",
"calculate",
"a",
"package",
"attribute",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_py_utils.py#L163-L176 |
246,512 | nerdvegas/rez | src/rez/package_py_utils.py | exec_python | 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.
Returns:
str: Output of python process.
"""
import subprocess
if isinstance(src, basestring):
src = [src]
p = popen([executable, "-c", "; ".join(src)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode:
from rez.exceptions import InvalidPackageError
raise InvalidPackageError(
"Error determining package attribute '%s':\n%s" % (attr, err))
return out.strip() | python | def exec_python(attr, src, executable="python"):
import subprocess
if isinstance(src, basestring):
src = [src]
p = popen([executable, "-c", "; ".join(src)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode:
from rez.exceptions import InvalidPackageError
raise InvalidPackageError(
"Error determining package attribute '%s':\n%s" % (attr, err))
return out.strip() | [
"def",
"exec_python",
"(",
"attr",
",",
"src",
",",
"executable",
"=",
"\"python\"",
")",
":",
"import",
"subprocess",
"if",
"isinstance",
"(",
"src",
",",
"basestring",
")",
":",
"src",
"=",
"[",
"src",
"]",
"p",
"=",
"popen",
"(",
"[",
"executable",
... | 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.
Returns:
str: Output of python process. | [
"Runs",
"a",
"python",
"subproc",
"to",
"calculate",
"a",
"package",
"attribute",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_py_utils.py#L179-L204 |
246,513 | nerdvegas/rez | src/rez/package_py_utils.py | find_site_python | 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:
This function is dependent on the behavior found in the python '_native'
package found in the 'rez-recipes' repository. Specifically, it expects
to find a python package with a '_site_paths' list attribute listing
the site directories associated with the python installation.
Args:
module_name (str): Target python module.
paths (list of str, optional): paths to search for packages,
defaults to `config.packages_path`.
Returns:
`Package`: Native python package containing the named module.
"""
from rez.packages_ import iter_packages
import subprocess
import ast
import os
py_cmd = 'import {x}; print {x}.__path__'.format(x=module_name)
p = popen(["python", "-c", py_cmd], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode:
raise InvalidPackageError(
"Failed to find installed python module '%s':\n%s"
% (module_name, err))
module_paths = ast.literal_eval(out.strip())
def issubdir(path, parent_path):
return path.startswith(parent_path + os.sep)
for package in iter_packages("python", paths=paths):
if not hasattr(package, "_site_paths"):
continue
contained = True
for module_path in module_paths:
if not any(issubdir(module_path, x) for x in package._site_paths):
contained = False
if contained:
return package
raise InvalidPackageError(
"Failed to find python installation containing the module '%s'. Has "
"python been installed as a rez package?" % module_name) | python | def find_site_python(module_name, paths=None):
from rez.packages_ import iter_packages
import subprocess
import ast
import os
py_cmd = 'import {x}; print {x}.__path__'.format(x=module_name)
p = popen(["python", "-c", py_cmd], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode:
raise InvalidPackageError(
"Failed to find installed python module '%s':\n%s"
% (module_name, err))
module_paths = ast.literal_eval(out.strip())
def issubdir(path, parent_path):
return path.startswith(parent_path + os.sep)
for package in iter_packages("python", paths=paths):
if not hasattr(package, "_site_paths"):
continue
contained = True
for module_path in module_paths:
if not any(issubdir(module_path, x) for x in package._site_paths):
contained = False
if contained:
return package
raise InvalidPackageError(
"Failed to find python installation containing the module '%s'. Has "
"python been installed as a rez package?" % module_name) | [
"def",
"find_site_python",
"(",
"module_name",
",",
"paths",
"=",
"None",
")",
":",
"from",
"rez",
".",
"packages_",
"import",
"iter_packages",
"import",
"subprocess",
"import",
"ast",
"import",
"os",
"py_cmd",
"=",
"'import {x}; print {x}.__path__'",
".",
"format... | 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:
This function is dependent on the behavior found in the python '_native'
package found in the 'rez-recipes' repository. Specifically, it expects
to find a python package with a '_site_paths' list attribute listing
the site directories associated with the python installation.
Args:
module_name (str): Target python module.
paths (list of str, optional): paths to search for packages,
defaults to `config.packages_path`.
Returns:
`Package`: Native python package containing the named module. | [
"Find",
"the",
"rez",
"native",
"python",
"package",
"that",
"contains",
"the",
"given",
"module",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_py_utils.py#L207-L264 |
246,514 | nerdvegas/rez | src/rez/vendor/pygraph/algorithms/critical.py | _intersection | 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:
intersection.append(i)
return intersection | python | def _intersection(A,B):
intersection = []
for i in A:
if i in B:
intersection.append(i)
return intersection | [
"def",
"_intersection",
"(",
"A",
",",
"B",
")",
":",
"intersection",
"=",
"[",
"]",
"for",
"i",
"in",
"A",
":",
"if",
"i",
"in",
"B",
":",
"intersection",
".",
"append",
"(",
"i",
")",
"return",
"intersection"
] | 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 | [
"A",
"simple",
"function",
"to",
"find",
"an",
"intersection",
"between",
"two",
"arrays",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/critical.py#L38-L55 |
246,515 | nerdvegas/rez | src/rez/vendor/pygraph/algorithms/critical.py | critical_path | 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 nodes in the path (or an empty array if the graph
contains a cycle)
"""
#if the graph contains a cycle we return an empty array
if not len(find_cycle(graph)) == 0:
return []
#this empty dictionary will contain a tuple for every single node
#the tuple contains the information about the most costly predecessor
#of the given node and the cost of the path to this node
#(predecessor, cost)
node_tuples = {}
topological_nodes = topological_sorting(graph)
#all the tuples must be set to a default value for every node in the graph
for node in topological_nodes:
node_tuples.update( {node :(None, 0)} )
#run trough all the nodes in a topological order
for node in topological_nodes:
predecessors =[]
#we must check all the predecessors
for pre in graph.incidents(node):
max_pre = node_tuples[pre][1]
predecessors.append( (pre, graph.edge_weight( (pre, node) ) + max_pre ) )
max = 0; max_tuple = (None, 0)
for i in predecessors:#look for the most costly predecessor
if i[1] >= max:
max = i[1]
max_tuple = i
#assign the maximum value to the given node in the node_tuples dictionary
node_tuples[node] = max_tuple
#find the critical node
max = 0; critical_node = None
for k,v in list(node_tuples.items()):
if v[1] >= max:
max= v[1]
critical_node = k
path = []
#find the critical path with backtracking trought the dictionary
def mid_critical_path(end):
if node_tuples[end][0] != None:
path.append(end)
mid_critical_path(node_tuples[end][0])
else:
path.append(end)
#call the recursive function
mid_critical_path(critical_node)
path.reverse()
return path | python | def critical_path(graph):
#if the graph contains a cycle we return an empty array
if not len(find_cycle(graph)) == 0:
return []
#this empty dictionary will contain a tuple for every single node
#the tuple contains the information about the most costly predecessor
#of the given node and the cost of the path to this node
#(predecessor, cost)
node_tuples = {}
topological_nodes = topological_sorting(graph)
#all the tuples must be set to a default value for every node in the graph
for node in topological_nodes:
node_tuples.update( {node :(None, 0)} )
#run trough all the nodes in a topological order
for node in topological_nodes:
predecessors =[]
#we must check all the predecessors
for pre in graph.incidents(node):
max_pre = node_tuples[pre][1]
predecessors.append( (pre, graph.edge_weight( (pre, node) ) + max_pre ) )
max = 0; max_tuple = (None, 0)
for i in predecessors:#look for the most costly predecessor
if i[1] >= max:
max = i[1]
max_tuple = i
#assign the maximum value to the given node in the node_tuples dictionary
node_tuples[node] = max_tuple
#find the critical node
max = 0; critical_node = None
for k,v in list(node_tuples.items()):
if v[1] >= max:
max= v[1]
critical_node = k
path = []
#find the critical path with backtracking trought the dictionary
def mid_critical_path(end):
if node_tuples[end][0] != None:
path.append(end)
mid_critical_path(node_tuples[end][0])
else:
path.append(end)
#call the recursive function
mid_critical_path(critical_node)
path.reverse()
return path | [
"def",
"critical_path",
"(",
"graph",
")",
":",
"#if the graph contains a cycle we return an empty array",
"if",
"not",
"len",
"(",
"find_cycle",
"(",
"graph",
")",
")",
"==",
"0",
":",
"return",
"[",
"]",
"#this empty dictionary will contain a tuple for every single node... | 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 nodes in the path (or an empty array if the graph
contains a cycle) | [
"Compute",
"and",
"return",
"the",
"critical",
"path",
"in",
"an",
"acyclic",
"directed",
"weighted",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/critical.py#L98-L163 |
246,516 | nerdvegas/rez | src/rezplugins/build_system/custom.py | CustomBuildSystem.build | 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.
"""
ret = {}
if self.write_build_scripts:
# write out the script that places the user in a build env, where
# they can run bez directly themselves.
build_env_script = os.path.join(build_path, "build-env")
create_forwarding_script(build_env_script,
module=("build_system", "custom"),
func_name="_FWD__spawn_build_shell",
working_dir=self.working_dir,
build_path=build_path,
variant_index=variant.index,
install=install,
install_path=install_path)
ret["success"] = True
ret["build_env_script"] = build_env_script
return ret
# get build command
command = self.package.build_command
# False just means no build command
if command is False:
ret["success"] = True
return ret
def expand(txt):
root = self.package.root
install_ = "install" if install else ''
return txt.format(root=root, install=install_).strip()
if isinstance(command, basestring):
if self.build_args:
command = command + ' ' + ' '.join(map(quote, self.build_args))
command = expand(command)
cmd_str = command
else: # list
command = command + self.build_args
command = map(expand, command)
cmd_str = ' '.join(map(quote, command))
if self.verbose:
pr = Printer(sys.stdout)
pr("Running build command: %s" % cmd_str, heading)
# run the build command
def _callback(executor):
self._add_build_actions(executor,
context=context,
package=self.package,
variant=variant,
build_type=build_type,
install=install,
build_path=build_path,
install_path=install_path)
if self.opts:
# write args defined in ./parse_build_args.py out as env vars
extra_args = getattr(self.opts.parser, "_rezbuild_extra_args", [])
for key, value in vars(self.opts).iteritems():
if key in extra_args:
varname = "__PARSE_ARG_%s" % key.upper()
# do some value conversions
if isinstance(value, bool):
value = 1 if value else 0
elif isinstance(value, (list, tuple)):
value = map(str, value)
value = map(quote, value)
value = ' '.join(value)
executor.env[varname] = value
retcode, _, _ = context.execute_shell(command=command,
block=True,
cwd=build_path,
actions_callback=_callback)
ret["success"] = (not retcode)
return ret | python | def build(self, context, variant, build_path, install_path, install=False,
build_type=BuildType.local):
ret = {}
if self.write_build_scripts:
# write out the script that places the user in a build env, where
# they can run bez directly themselves.
build_env_script = os.path.join(build_path, "build-env")
create_forwarding_script(build_env_script,
module=("build_system", "custom"),
func_name="_FWD__spawn_build_shell",
working_dir=self.working_dir,
build_path=build_path,
variant_index=variant.index,
install=install,
install_path=install_path)
ret["success"] = True
ret["build_env_script"] = build_env_script
return ret
# get build command
command = self.package.build_command
# False just means no build command
if command is False:
ret["success"] = True
return ret
def expand(txt):
root = self.package.root
install_ = "install" if install else ''
return txt.format(root=root, install=install_).strip()
if isinstance(command, basestring):
if self.build_args:
command = command + ' ' + ' '.join(map(quote, self.build_args))
command = expand(command)
cmd_str = command
else: # list
command = command + self.build_args
command = map(expand, command)
cmd_str = ' '.join(map(quote, command))
if self.verbose:
pr = Printer(sys.stdout)
pr("Running build command: %s" % cmd_str, heading)
# run the build command
def _callback(executor):
self._add_build_actions(executor,
context=context,
package=self.package,
variant=variant,
build_type=build_type,
install=install,
build_path=build_path,
install_path=install_path)
if self.opts:
# write args defined in ./parse_build_args.py out as env vars
extra_args = getattr(self.opts.parser, "_rezbuild_extra_args", [])
for key, value in vars(self.opts).iteritems():
if key in extra_args:
varname = "__PARSE_ARG_%s" % key.upper()
# do some value conversions
if isinstance(value, bool):
value = 1 if value else 0
elif isinstance(value, (list, tuple)):
value = map(str, value)
value = map(quote, value)
value = ' '.join(value)
executor.env[varname] = value
retcode, _, _ = context.execute_shell(command=command,
block=True,
cwd=build_path,
actions_callback=_callback)
ret["success"] = (not retcode)
return ret | [
"def",
"build",
"(",
"self",
",",
"context",
",",
"variant",
",",
"build_path",
",",
"install_path",
",",
"install",
"=",
"False",
",",
"build_type",
"=",
"BuildType",
".",
"local",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"self",
".",
"write_build_scripts"... | 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. | [
"Perform",
"the",
"build",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/build_system/custom.py#L87-L176 |
246,517 | nerdvegas/rez | src/rezplugins/release_vcs/hg.py | HgReleaseVCS._create_tag_highlevel | 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, which looks like {'type': ('bookmark' or 'tag'), 'patch': bool}
"""
results = []
if self.patch_path:
# make a tag on the patch queue
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=True)
if tagged:
results.append({'type': 'tag', 'patch': True})
# use a bookmark on the main repo since we can't change it
self.hg('bookmark', '-f', tag_name)
results.append({'type': 'bookmark', 'patch': False})
else:
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=False)
if tagged:
results.append({'type': 'tag', 'patch': False})
return results | python | def _create_tag_highlevel(self, tag_name, message=None):
results = []
if self.patch_path:
# make a tag on the patch queue
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=True)
if tagged:
results.append({'type': 'tag', 'patch': True})
# use a bookmark on the main repo since we can't change it
self.hg('bookmark', '-f', tag_name)
results.append({'type': 'bookmark', 'patch': False})
else:
tagged = self._create_tag_lowlevel(tag_name, message=message,
patch=False)
if tagged:
results.append({'type': 'tag', 'patch': False})
return results | [
"def",
"_create_tag_highlevel",
"(",
"self",
",",
"tag_name",
",",
"message",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"self",
".",
"patch_path",
":",
"# make a tag on the patch queue",
"tagged",
"=",
"self",
".",
"_create_tag_lowlevel",
"(",
"ta... | 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, which looks like {'type': ('bookmark' or 'tag'), 'patch': bool} | [
"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"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/hg.py#L58-L82 |
246,518 | nerdvegas/rez | src/rezplugins/release_vcs/hg.py | HgReleaseVCS._create_tag_lowlevel | 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 commit,
and there is no difference in filestate between the current commit
and the tagged commit, no tag is made. Otherwise, the old tag is
overwritten to point at the current commit.
Returns True or False indicating whether the tag was actually committed
"""
# check if tag already exists, and if it does, if it is a direct
# ancestor, and there is NO difference in the files between the tagged
# state and current state
#
# This check is mainly to avoid re-creating the same tag over and over
# on what is essentially the same commit, since tagging will
# technically create a new commit, and update the working copy to it.
#
# Without this check, say you were releasing to three different
# locations, one right after another; the first would create the tag,
# and a new tag commit. The second would then recreate the exact same
# tag, but now pointing at the commit that made the first tag.
# The third would create the tag a THIRD time, but now pointing at the
# commit that created the 2nd tag.
tags = self.get_tags(patch=patch)
old_commit = tags.get(tag_name)
if old_commit is not None:
if not force:
return False
old_rev = old_commit['rev']
# ok, now check to see if direct ancestor...
if self.is_ancestor(old_rev, '.', patch=patch):
# ...and if filestates are same
altered = self.hg('status', '--rev', old_rev, '--rev', '.',
'--no-status')
if not altered or altered == ['.hgtags']:
force = False
if not force:
return False
tag_args = ['tag', tag_name]
if message:
tag_args += ['--message', message]
# we should be ok with ALWAYS having force flag on now, since we should
# have already checked if the commit exists.. but be paranoid, in case
# we've missed some edge case...
if force:
tag_args += ['--force']
self.hg(patch=patch, *tag_args)
return True | python | def _create_tag_lowlevel(self, tag_name, message=None, force=True,
patch=False):
# check if tag already exists, and if it does, if it is a direct
# ancestor, and there is NO difference in the files between the tagged
# state and current state
#
# This check is mainly to avoid re-creating the same tag over and over
# on what is essentially the same commit, since tagging will
# technically create a new commit, and update the working copy to it.
#
# Without this check, say you were releasing to three different
# locations, one right after another; the first would create the tag,
# and a new tag commit. The second would then recreate the exact same
# tag, but now pointing at the commit that made the first tag.
# The third would create the tag a THIRD time, but now pointing at the
# commit that created the 2nd tag.
tags = self.get_tags(patch=patch)
old_commit = tags.get(tag_name)
if old_commit is not None:
if not force:
return False
old_rev = old_commit['rev']
# ok, now check to see if direct ancestor...
if self.is_ancestor(old_rev, '.', patch=patch):
# ...and if filestates are same
altered = self.hg('status', '--rev', old_rev, '--rev', '.',
'--no-status')
if not altered or altered == ['.hgtags']:
force = False
if not force:
return False
tag_args = ['tag', tag_name]
if message:
tag_args += ['--message', message]
# we should be ok with ALWAYS having force flag on now, since we should
# have already checked if the commit exists.. but be paranoid, in case
# we've missed some edge case...
if force:
tag_args += ['--force']
self.hg(patch=patch, *tag_args)
return True | [
"def",
"_create_tag_lowlevel",
"(",
"self",
",",
"tag_name",
",",
"message",
"=",
"None",
",",
"force",
"=",
"True",
",",
"patch",
"=",
"False",
")",
":",
"# check if tag already exists, and if it does, if it is a direct",
"# ancestor, and there is NO difference in the file... | 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 commit,
and there is no difference in filestate between the current commit
and the tagged commit, no tag is made. Otherwise, the old tag is
overwritten to point at the current commit.
Returns True or False indicating whether the tag was actually committed | [
"Create",
"a",
"tag",
"on",
"the",
"toplevel",
"or",
"patch",
"repo"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/hg.py#L84-L137 |
246,519 | nerdvegas/rez | src/rezplugins/release_vcs/hg.py | HgReleaseVCS.is_ancestor | 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),
"--template", "exists", patch=patch)
return "exists" in result | python | def is_ancestor(self, commit1, commit2, patch=False):
result = self.hg("log", "-r", "first(%s::%s)" % (commit1, commit2),
"--template", "exists", patch=patch)
return "exists" in result | [
"def",
"is_ancestor",
"(",
"self",
",",
"commit1",
",",
"commit2",
",",
"patch",
"=",
"False",
")",
":",
"result",
"=",
"self",
".",
"hg",
"(",
"\"log\"",
",",
"\"-r\"",
",",
"\"first(%s::%s)\"",
"%",
"(",
"commit1",
",",
"commit2",
")",
",",
"\"--temp... | 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 | [
"Returns",
"True",
"if",
"commit1",
"is",
"a",
"direct",
"ancestor",
"of",
"commit2",
"or",
"False",
"otherwise",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/hg.py#L159-L166 |
246,520 | nerdvegas/rez | src/rez/utils/patching.py | get_patched_request | 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 rules apply wrt how normal/conflict/weak patches override
(note though that the new request is always added, even if it doesn't
override an existing request):
PATCH OVERRIDES: foo !foo ~foo
----- ---------- --- ---- -----
foo Y Y Y
!foo N N N
~foo N N Y
^foo Y Y Y
Args:
requires (list of str or `version.Requirement`): Request.
patchlist (list of str): List of patch requests.
Returns:
List of `version.Requirement`: Patched request.
"""
# rules from table in docstring above
rules = {
'': (True, True, True ),
'!': (False, False, False),
'~': (False, False, True ),
'^': (True, True, True )
}
requires = [Requirement(x) if not isinstance(x, Requirement) else x
for x in requires]
appended = []
for patch in patchlist:
if patch and patch[0] in ('!', '~', '^'):
ch = patch[0]
name = Requirement(patch[1:]).name
else:
ch = ''
name = Requirement(patch).name
rule = rules[ch]
replaced = (ch == '^')
for i, req in enumerate(requires):
if req is None or req.name != name:
continue
if not req.conflict:
replace = rule[0] # foo
elif not req.weak:
replace = rule[1] # !foo
else:
replace = rule[2] # ~foo
if replace:
if replaced:
requires[i] = None
else:
requires[i] = Requirement(patch)
replaced = True
if not replaced:
appended.append(Requirement(patch))
result = [x for x in requires if x is not None] + appended
return result | python | def get_patched_request(requires, patchlist):
# rules from table in docstring above
rules = {
'': (True, True, True ),
'!': (False, False, False),
'~': (False, False, True ),
'^': (True, True, True )
}
requires = [Requirement(x) if not isinstance(x, Requirement) else x
for x in requires]
appended = []
for patch in patchlist:
if patch and patch[0] in ('!', '~', '^'):
ch = patch[0]
name = Requirement(patch[1:]).name
else:
ch = ''
name = Requirement(patch).name
rule = rules[ch]
replaced = (ch == '^')
for i, req in enumerate(requires):
if req is None or req.name != name:
continue
if not req.conflict:
replace = rule[0] # foo
elif not req.weak:
replace = rule[1] # !foo
else:
replace = rule[2] # ~foo
if replace:
if replaced:
requires[i] = None
else:
requires[i] = Requirement(patch)
replaced = True
if not replaced:
appended.append(Requirement(patch))
result = [x for x in requires if x is not None] + appended
return result | [
"def",
"get_patched_request",
"(",
"requires",
",",
"patchlist",
")",
":",
"# rules from table in docstring above",
"rules",
"=",
"{",
"''",
":",
"(",
"True",
",",
"True",
",",
"True",
")",
",",
"'!'",
":",
"(",
"False",
",",
"False",
",",
"False",
")",
... | 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 rules apply wrt how normal/conflict/weak patches override
(note though that the new request is always added, even if it doesn't
override an existing request):
PATCH OVERRIDES: foo !foo ~foo
----- ---------- --- ---- -----
foo Y Y Y
!foo N N N
~foo N N Y
^foo Y Y Y
Args:
requires (list of str or `version.Requirement`): Request.
patchlist (list of str): List of patch requests.
Returns:
List of `version.Requirement`: Patched request. | [
"Apply",
"patch",
"args",
"to",
"a",
"request",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/patching.py#L4-L78 |
246,521 | nerdvegas/rez | src/support/shotgun_toolkit/rez_app_launch.py | AppLaunch.execute | 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 version: (str) version of the application being run if set in the "versions" settings
of the Launcher instance, otherwise None
:returns: (dict) The two valid keys are 'command' (str) and 'return_code' (int).
"""
multi_launchapp = self.parent
extra = multi_launchapp.get_setting("extra")
use_rez = False
if self.check_rez():
from rez.resolved_context import ResolvedContext
from rez.config import config
# Define variables used to bootstrap tank from overwrite on first reference
# PYTHONPATH is used by tk-maya
# NUKE_PATH is used by tk-nuke
# HIERO_PLUGIN_PATH is used by tk-nuke (nukestudio)
# KATANA_RESOURCES is used by tk-katana
config.parent_variables = ["PYTHONPATH", "HOUDINI_PATH", "NUKE_PATH", "HIERO_PLUGIN_PATH", "KATANA_RESOURCES"]
rez_packages = extra["rez_packages"]
context = ResolvedContext(rez_packages)
use_rez = True
system = sys.platform
shell_type = 'bash'
if system == "linux2":
# on linux, we just run the executable directly
cmd = "%s %s &" % (app_path, app_args)
elif self.parent.get_setting("engine") in ["tk-flame", "tk-flare"]:
# flame and flare works in a different way from other DCCs
# on both linux and mac, they run unix-style command line
# and on the mac the more standardized "open" command cannot
# be utilized.
cmd = "%s %s &" % (app_path, app_args)
elif system == "darwin":
# on the mac, the executable paths are normally pointing
# to the application bundle and not to the binary file
# embedded in the bundle, meaning that we should use the
# built-in mac open command to execute it
cmd = "open -n \"%s\"" % (app_path)
if app_args:
cmd += " --args \"%s\"" % app_args.replace("\"", "\\\"")
elif system == "win32":
# on windows, we run the start command in order to avoid
# any command shells popping up as part of the application launch.
cmd = "start /B \"App\" \"%s\" %s" % (app_path, app_args)
shell_type = 'cmd'
# Execute App in a Rez context
if use_rez:
n_env = os.environ.copy()
proc = context.execute_shell(
command=cmd,
parent_environ=n_env,
shell=shell_type,
stdin=False,
block=False
)
exit_code = proc.wait()
context.print_info(verbosity=True)
else:
# run the command to launch the app
exit_code = os.system(cmd)
return {
"command": cmd,
"return_code": exit_code
} | python | def execute(self, app_path, app_args, version, **kwargs):
multi_launchapp = self.parent
extra = multi_launchapp.get_setting("extra")
use_rez = False
if self.check_rez():
from rez.resolved_context import ResolvedContext
from rez.config import config
# Define variables used to bootstrap tank from overwrite on first reference
# PYTHONPATH is used by tk-maya
# NUKE_PATH is used by tk-nuke
# HIERO_PLUGIN_PATH is used by tk-nuke (nukestudio)
# KATANA_RESOURCES is used by tk-katana
config.parent_variables = ["PYTHONPATH", "HOUDINI_PATH", "NUKE_PATH", "HIERO_PLUGIN_PATH", "KATANA_RESOURCES"]
rez_packages = extra["rez_packages"]
context = ResolvedContext(rez_packages)
use_rez = True
system = sys.platform
shell_type = 'bash'
if system == "linux2":
# on linux, we just run the executable directly
cmd = "%s %s &" % (app_path, app_args)
elif self.parent.get_setting("engine") in ["tk-flame", "tk-flare"]:
# flame and flare works in a different way from other DCCs
# on both linux and mac, they run unix-style command line
# and on the mac the more standardized "open" command cannot
# be utilized.
cmd = "%s %s &" % (app_path, app_args)
elif system == "darwin":
# on the mac, the executable paths are normally pointing
# to the application bundle and not to the binary file
# embedded in the bundle, meaning that we should use the
# built-in mac open command to execute it
cmd = "open -n \"%s\"" % (app_path)
if app_args:
cmd += " --args \"%s\"" % app_args.replace("\"", "\\\"")
elif system == "win32":
# on windows, we run the start command in order to avoid
# any command shells popping up as part of the application launch.
cmd = "start /B \"App\" \"%s\" %s" % (app_path, app_args)
shell_type = 'cmd'
# Execute App in a Rez context
if use_rez:
n_env = os.environ.copy()
proc = context.execute_shell(
command=cmd,
parent_environ=n_env,
shell=shell_type,
stdin=False,
block=False
)
exit_code = proc.wait()
context.print_info(verbosity=True)
else:
# run the command to launch the app
exit_code = os.system(cmd)
return {
"command": cmd,
"return_code": exit_code
} | [
"def",
"execute",
"(",
"self",
",",
"app_path",
",",
"app_args",
",",
"version",
",",
"*",
"*",
"kwargs",
")",
":",
"multi_launchapp",
"=",
"self",
".",
"parent",
"extra",
"=",
"multi_launchapp",
".",
"get_setting",
"(",
"\"extra\"",
")",
"use_rez",
"=",
... | 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 version: (str) version of the application being run if set in the "versions" settings
of the Launcher instance, otherwise None
:returns: (dict) The two valid keys are 'command' (str) and 'return_code' (int). | [
"The",
"execute",
"functon",
"of",
"the",
"hook",
"will",
"be",
"called",
"to",
"start",
"the",
"required",
"application"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/support/shotgun_toolkit/rez_app_launch.py#L37-L117 |
246,522 | nerdvegas/rez | src/support/shotgun_toolkit/rez_app_launch.py | AppLaunch.check_rez | 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.
This will prevent the app from being launched.
:returns: A path to the Rez package.
"""
system = sys.platform
if system == "win32":
rez_cmd = 'rez-env rez -- echo %REZ_REZ_ROOT%'
else:
rez_cmd = 'rez-env rez -- printenv REZ_REZ_ROOT'
process = subprocess.Popen(rez_cmd, stdout=subprocess.PIPE, shell=True)
rez_path, err = process.communicate()
if err or not rez_path:
if strict:
raise ImportError("Failed to find Rez as a package in the current "
"environment! Try 'rez-bind rez'!")
else:
print >> sys.stderr, ("WARNING: Failed to find a Rez package in the current "
"environment. Unable to request Rez packages.")
rez_path = ""
else:
rez_path = rez_path.strip()
print "Found Rez:", rez_path
print "Adding Rez to system path..."
sys.path.append(rez_path)
return rez_path | python | def check_rez(self, strict=True):
system = sys.platform
if system == "win32":
rez_cmd = 'rez-env rez -- echo %REZ_REZ_ROOT%'
else:
rez_cmd = 'rez-env rez -- printenv REZ_REZ_ROOT'
process = subprocess.Popen(rez_cmd, stdout=subprocess.PIPE, shell=True)
rez_path, err = process.communicate()
if err or not rez_path:
if strict:
raise ImportError("Failed to find Rez as a package in the current "
"environment! Try 'rez-bind rez'!")
else:
print >> sys.stderr, ("WARNING: Failed to find a Rez package in the current "
"environment. Unable to request Rez packages.")
rez_path = ""
else:
rez_path = rez_path.strip()
print "Found Rez:", rez_path
print "Adding Rez to system path..."
sys.path.append(rez_path)
return rez_path | [
"def",
"check_rez",
"(",
"self",
",",
"strict",
"=",
"True",
")",
":",
"system",
"=",
"sys",
".",
"platform",
"if",
"system",
"==",
"\"win32\"",
":",
"rez_cmd",
"=",
"'rez-env rez -- echo %REZ_REZ_ROOT%'",
"else",
":",
"rez_cmd",
"=",
"'rez-env rez -- printenv R... | 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.
This will prevent the app from being launched.
:returns: A path to the Rez package. | [
"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"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/support/shotgun_toolkit/rez_app_launch.py#L119-L155 |
246,523 | nerdvegas/rez | src/rezplugins/release_vcs/svn.py | get_last_changed_revision | 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:
raise ReleaseVCSError("svn.info2() returned no results on url %s" % url)
return svn_entries[0][1].last_changed_rev
except pysvn.ClientError, ce:
raise ReleaseVCSError("svn.info2() raised ClientError: %s" % ce) | python | def get_last_changed_revision(client, url):
try:
svn_entries = client.info2(url,
pysvn.Revision(pysvn.opt_revision_kind.head),
recurse=False)
if not svn_entries:
raise ReleaseVCSError("svn.info2() returned no results on url %s" % url)
return svn_entries[0][1].last_changed_rev
except pysvn.ClientError, ce:
raise ReleaseVCSError("svn.info2() raised ClientError: %s" % ce) | [
"def",
"get_last_changed_revision",
"(",
"client",
",",
"url",
")",
":",
"try",
":",
"svn_entries",
"=",
"client",
".",
"info2",
"(",
"url",
",",
"pysvn",
".",
"Revision",
"(",
"pysvn",
".",
"opt_revision_kind",
".",
"head",
")",
",",
"recurse",
"=",
"Fa... | util func, get last revision of url | [
"util",
"func",
"get",
"last",
"revision",
"of",
"url"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/svn.py#L26-L38 |
246,524 | nerdvegas/rez | src/rezplugins/release_vcs/svn.py | get_svn_login | 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 = getpass.getpass("--> ")
return True, username, pwd, False | python | def get_svn_login(realm, username, may_save):
import getpass
print "svn requires a password for the user %s:" % username
pwd = ''
while not pwd.strip():
pwd = getpass.getpass("--> ")
return True, username, pwd, False | [
"def",
"get_svn_login",
"(",
"realm",
",",
"username",
",",
"may_save",
")",
":",
"import",
"getpass",
"print",
"\"svn requires a password for the user %s:\"",
"%",
"username",
"pwd",
"=",
"''",
"while",
"not",
"pwd",
".",
"strip",
"(",
")",
":",
"pwd",
"=",
... | provide svn with permissions. @TODO this will have to be updated to take
into account automated releases etc. | [
"provide",
"svn",
"with",
"permissions",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/release_vcs/svn.py#L41-L53 |
246,525 | nerdvegas/rez | src/rez/vendor/pygraph/readwrite/markup.py | read | 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 = parseString(string)
if dom.getElementsByTagName("graph"):
G = graph()
elif dom.getElementsByTagName("digraph"):
G = digraph()
elif dom.getElementsByTagName("hypergraph"):
return read_hypergraph(string)
else:
raise InvalidGraphType
# Read nodes...
for each_node in dom.getElementsByTagName("node"):
G.add_node(each_node.getAttribute('id'))
for each_attr in each_node.getElementsByTagName("attribute"):
G.add_node_attribute(each_node.getAttribute('id'),
(each_attr.getAttribute('attr'),
each_attr.getAttribute('value')))
# Read edges...
for each_edge in dom.getElementsByTagName("edge"):
if (not G.has_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')))):
G.add_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')), \
wt = float(each_edge.getAttribute('wt')), label = each_edge.getAttribute('label'))
for each_attr in each_edge.getElementsByTagName("attribute"):
attr_tuple = (each_attr.getAttribute('attr'), each_attr.getAttribute('value'))
if (attr_tuple not in G.edge_attributes((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')))):
G.add_edge_attribute((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')), attr_tuple)
return G | python | def read(string):
dom = parseString(string)
if dom.getElementsByTagName("graph"):
G = graph()
elif dom.getElementsByTagName("digraph"):
G = digraph()
elif dom.getElementsByTagName("hypergraph"):
return read_hypergraph(string)
else:
raise InvalidGraphType
# Read nodes...
for each_node in dom.getElementsByTagName("node"):
G.add_node(each_node.getAttribute('id'))
for each_attr in each_node.getElementsByTagName("attribute"):
G.add_node_attribute(each_node.getAttribute('id'),
(each_attr.getAttribute('attr'),
each_attr.getAttribute('value')))
# Read edges...
for each_edge in dom.getElementsByTagName("edge"):
if (not G.has_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')))):
G.add_edge((each_edge.getAttribute('from'), each_edge.getAttribute('to')), \
wt = float(each_edge.getAttribute('wt')), label = each_edge.getAttribute('label'))
for each_attr in each_edge.getElementsByTagName("attribute"):
attr_tuple = (each_attr.getAttribute('attr'), each_attr.getAttribute('value'))
if (attr_tuple not in G.edge_attributes((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')))):
G.add_edge_attribute((each_edge.getAttribute('from'), \
each_edge.getAttribute('to')), attr_tuple)
return G | [
"def",
"read",
"(",
"string",
")",
":",
"dom",
"=",
"parseString",
"(",
"string",
")",
"if",
"dom",
".",
"getElementsByTagName",
"(",
"\"graph\"",
")",
":",
"G",
"=",
"graph",
"(",
")",
"elif",
"dom",
".",
"getElementsByTagName",
"(",
"\"digraph\"",
")",... | 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 | [
"Read",
"a",
"graph",
"from",
"a",
"XML",
"document",
"and",
"return",
"it",
".",
"Nodes",
"and",
"edges",
"specified",
"in",
"the",
"input",
"will",
"be",
"added",
"to",
"the",
"current",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/readwrite/markup.py#L91-L132 |
246,526 | nerdvegas/rez | src/rez/vendor/pygraph/readwrite/markup.py | read_hypergraph | 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
"""
hgr = hypergraph()
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
hgr.add_node(each_node.getAttribute('id'))
for each_node in dom.getElementsByTagName("hyperedge"):
hgr.add_hyperedge(each_node.getAttribute('id'))
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
for each_edge in each_node.getElementsByTagName("link"):
hgr.link(str(each_node.getAttribute('id')), str(each_edge.getAttribute('to')))
return hgr | python | def read_hypergraph(string):
hgr = hypergraph()
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
hgr.add_node(each_node.getAttribute('id'))
for each_node in dom.getElementsByTagName("hyperedge"):
hgr.add_hyperedge(each_node.getAttribute('id'))
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
for each_edge in each_node.getElementsByTagName("link"):
hgr.link(str(each_node.getAttribute('id')), str(each_edge.getAttribute('to')))
return hgr | [
"def",
"read_hypergraph",
"(",
"string",
")",
":",
"hgr",
"=",
"hypergraph",
"(",
")",
"dom",
"=",
"parseString",
"(",
"string",
")",
"for",
"each_node",
"in",
"dom",
".",
"getElementsByTagName",
"(",
"\"node\"",
")",
":",
"hgr",
".",
"add_node",
"(",
"e... | 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 | [
"Read",
"a",
"graph",
"from",
"a",
"XML",
"document",
".",
"Nodes",
"and",
"hyperedges",
"specified",
"in",
"the",
"input",
"will",
"be",
"added",
"to",
"the",
"current",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/readwrite/markup.py#L172-L195 |
246,527 | nerdvegas/rez | src/rez/utils/diff_packages.py | diff_packages | 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 is None:
it = iter_packages(pkg1.name)
pkgs = [x for x in it if x.version < pkg1.version]
if not pkgs:
raise RezError("No package to diff with - %s is the earliest "
"package version" % pkg1.qualified_name)
pkgs = sorted(pkgs, key=lambda x: x.version)
pkg2 = pkgs[-1]
def _check_pkg(pkg):
if not (pkg.vcs and pkg.revision):
raise RezError("Cannot diff package %s: it is a legacy format "
"package that does not contain enough information"
% pkg.qualified_name)
_check_pkg(pkg1)
_check_pkg(pkg2)
path = mkdtemp(prefix="rez-pkg-diff")
paths = []
for pkg in (pkg1, pkg2):
print "Exporting %s..." % pkg.qualified_name
path_ = os.path.join(path, pkg.qualified_name)
vcs_cls_1 = plugin_manager.get_plugin_class("release_vcs", pkg1.vcs)
vcs_cls_1.export(revision=pkg.revision, path=path_)
paths.append(path_)
difftool = config.difftool
print "Opening diff viewer %s..." % difftool
proc = Popen([difftool] + paths)
proc.wait() | python | def diff_packages(pkg1, pkg2=None):
if pkg2 is None:
it = iter_packages(pkg1.name)
pkgs = [x for x in it if x.version < pkg1.version]
if not pkgs:
raise RezError("No package to diff with - %s is the earliest "
"package version" % pkg1.qualified_name)
pkgs = sorted(pkgs, key=lambda x: x.version)
pkg2 = pkgs[-1]
def _check_pkg(pkg):
if not (pkg.vcs and pkg.revision):
raise RezError("Cannot diff package %s: it is a legacy format "
"package that does not contain enough information"
% pkg.qualified_name)
_check_pkg(pkg1)
_check_pkg(pkg2)
path = mkdtemp(prefix="rez-pkg-diff")
paths = []
for pkg in (pkg1, pkg2):
print "Exporting %s..." % pkg.qualified_name
path_ = os.path.join(path, pkg.qualified_name)
vcs_cls_1 = plugin_manager.get_plugin_class("release_vcs", pkg1.vcs)
vcs_cls_1.export(revision=pkg.revision, path=path_)
paths.append(path_)
difftool = config.difftool
print "Opening diff viewer %s..." % difftool
proc = Popen([difftool] + paths)
proc.wait() | [
"def",
"diff_packages",
"(",
"pkg1",
",",
"pkg2",
"=",
"None",
")",
":",
"if",
"pkg2",
"is",
"None",
":",
"it",
"=",
"iter_packages",
"(",
"pkg1",
".",
"name",
")",
"pkgs",
"=",
"[",
"x",
"for",
"x",
"in",
"it",
"if",
"x",
".",
"version",
"<",
... | 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. | [
"Invoke",
"a",
"diff",
"editor",
"to",
"show",
"the",
"difference",
"between",
"the",
"source",
"of",
"two",
"packages",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/diff_packages.py#L10-L49 |
246,528 | nerdvegas/rez | src/rez/cli/_util.py | sigint_handler | 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 | def sigint_handler(signum, frame):
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) | [
"def",
"sigint_handler",
"(",
"signum",
",",
"frame",
")",
":",
"global",
"_handled_int",
"if",
"not",
"_handled_int",
":",
"_handled_int",
"=",
"True",
"if",
"not",
"_env_var_true",
"(",
"\"_REZ_QUIET_ON_SIG\"",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
... | Exit gracefully on ctrl-C. | [
"Exit",
"gracefully",
"on",
"ctrl",
"-",
"C",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/_util.py#L141-L148 |
246,529 | nerdvegas/rez | src/rez/cli/_util.py | sigterm_handler | 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 | def sigterm_handler(signum, frame):
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) | [
"def",
"sigterm_handler",
"(",
"signum",
",",
"frame",
")",
":",
"global",
"_handled_term",
"if",
"not",
"_handled_term",
":",
"_handled_term",
"=",
"True",
"if",
"not",
"_env_var_true",
"(",
"\"_REZ_QUIET_ON_SIG\"",
")",
":",
"print",
">>",
"sys",
".",
"stder... | Exit gracefully on terminate. | [
"Exit",
"gracefully",
"on",
"terminate",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/_util.py#L151-L158 |
246,530 | nerdvegas/rez | src/rez/cli/_util.py | LazyArgumentParser.format_help | 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():
action._setup_subparser(parser_name, parser)
return super(LazyArgumentParser, self).format_help() | python | def format_help(self):
if self._subparsers:
for action in self._subparsers._actions:
if isinstance(action, LazySubParsersAction):
for parser_name, parser in action._name_parser_map.iteritems():
action._setup_subparser(parser_name, parser)
return super(LazyArgumentParser, self).format_help() | [
"def",
"format_help",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subparsers",
":",
"for",
"action",
"in",
"self",
".",
"_subparsers",
".",
"_actions",
":",
"if",
"isinstance",
"(",
"action",
",",
"LazySubParsersAction",
")",
":",
"for",
"parser_name",
","... | Sets up all sub-parsers when help is requested. | [
"Sets",
"up",
"all",
"sub",
"-",
"parsers",
"when",
"help",
"is",
"requested",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/_util.py#L110-L117 |
246,531 | nerdvegas/rez | src/rez/utils/formatting.py | is_valid_package_name | 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 not is_valid:
raise PackageRequestError("Not a valid package name: %r" % name)
return is_valid | python | def is_valid_package_name(name, raise_error=False):
is_valid = PACKAGE_NAME_REGEX.match(name)
if raise_error and not is_valid:
raise PackageRequestError("Not a valid package name: %r" % name)
return is_valid | [
"def",
"is_valid_package_name",
"(",
"name",
",",
"raise_error",
"=",
"False",
")",
":",
"is_valid",
"=",
"PACKAGE_NAME_REGEX",
".",
"match",
"(",
"name",
")",
"if",
"raise_error",
"and",
"not",
"is_valid",
":",
"raise",
"PackageRequestError",
"(",
"\"Not a vali... | 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. | [
"Test",
"the",
"validity",
"of",
"a",
"package",
"name",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L27-L40 |
246,532 | nerdvegas/rez | src/rez/utils/formatting.py | expand_abbreviations | 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 dude'
Args:
txt (str): Format string.
fields (list of str): Fields to expand to.
Returns:
Expanded string.
"""
def _expand(matchobj):
s = matchobj.group("var")
if s not in fields:
matches = [x for x in fields if x.startswith(s)]
if len(matches) == 1:
s = matches[0]
return "{%s}" % s
return re.sub(FORMAT_VAR_REGEX, _expand, txt) | python | def expand_abbreviations(txt, fields):
def _expand(matchobj):
s = matchobj.group("var")
if s not in fields:
matches = [x for x in fields if x.startswith(s)]
if len(matches) == 1:
s = matches[0]
return "{%s}" % s
return re.sub(FORMAT_VAR_REGEX, _expand, txt) | [
"def",
"expand_abbreviations",
"(",
"txt",
",",
"fields",
")",
":",
"def",
"_expand",
"(",
"matchobj",
")",
":",
"s",
"=",
"matchobj",
".",
"group",
"(",
"\"var\"",
")",
"if",
"s",
"not",
"in",
"fields",
":",
"matches",
"=",
"[",
"x",
"for",
"x",
"... | 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 dude'
Args:
txt (str): Format string.
fields (list of str): Fields to expand to.
Returns:
Expanded string. | [
"Expand",
"abbreviations",
"in",
"a",
"format",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L174-L200 |
246,533 | nerdvegas/rez | src/rez/utils/formatting.py | dict_to_attributes_code | 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.
"""
lines = []
for key, value in dict_.iteritems():
if isinstance(value, dict):
txt = dict_to_attributes_code(value)
lines_ = txt.split('\n')
for line in lines_:
if not line.startswith(' '):
line = "%s.%s" % (key, line)
lines.append(line)
else:
value_txt = pformat(value)
if '\n' in value_txt:
lines.append("%s = \\" % key)
value_txt = indent(value_txt)
lines.extend(value_txt.split('\n'))
else:
line = "%s = %s" % (key, value_txt)
lines.append(line)
return '\n'.join(lines) | python | def dict_to_attributes_code(dict_):
lines = []
for key, value in dict_.iteritems():
if isinstance(value, dict):
txt = dict_to_attributes_code(value)
lines_ = txt.split('\n')
for line in lines_:
if not line.startswith(' '):
line = "%s.%s" % (key, line)
lines.append(line)
else:
value_txt = pformat(value)
if '\n' in value_txt:
lines.append("%s = \\" % key)
value_txt = indent(value_txt)
lines.extend(value_txt.split('\n'))
else:
line = "%s = %s" % (key, value_txt)
lines.append(line)
return '\n'.join(lines) | [
"def",
"dict_to_attributes_code",
"(",
"dict_",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"dict_",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"txt",
"=",
"dict_to_attributes_code",
... | 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. | [
"Given",
"a",
"nested",
"dict",
"generate",
"a",
"python",
"code",
"equivalent",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L247-L279 |
246,534 | nerdvegas/rez | src/rez/utils/formatting.py | columnise | 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
for row in rows:
s = ''
for i, e in enumerate(row):
se = str(e)
if i < len(row) - 1:
n = maxwidths[i] + padding - len(se)
se += ' ' * n
s += se
strs.append(s)
return strs | python | def columnise(rows, padding=2):
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
for row in rows:
s = ''
for i, e in enumerate(row):
se = str(e)
if i < len(row) - 1:
n = maxwidths[i] + padding - len(se)
se += ' ' * n
s += se
strs.append(s)
return strs | [
"def",
"columnise",
"(",
"rows",
",",
"padding",
"=",
"2",
")",
":",
"strs",
"=",
"[",
"]",
"maxwidths",
"=",
"{",
"}",
"for",
"row",
"in",
"rows",
":",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"row",
")",
":",
"se",
"=",
"str",
"(",
"e"... | Print rows of entries in aligned columns. | [
"Print",
"rows",
"of",
"entries",
"in",
"aligned",
"columns",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L282-L304 |
246,535 | nerdvegas/rez | src/rez/utils/formatting.py | print_colored_columns | 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] for x in rows]
for col, line in zip(colors, columnise(rows_, padding=padding)):
printer(line, col) | python | def print_colored_columns(printer, rows, padding=2):
rows_ = [x[:-1] for x in rows]
colors = [x[-1] for x in rows]
for col, line in zip(colors, columnise(rows_, padding=padding)):
printer(line, col) | [
"def",
"print_colored_columns",
"(",
"printer",
",",
"rows",
",",
"padding",
"=",
"2",
")",
":",
"rows_",
"=",
"[",
"x",
"[",
":",
"-",
"1",
"]",
"for",
"x",
"in",
"rows",
"]",
"colors",
"=",
"[",
"x",
"[",
"-",
"1",
"]",
"for",
"x",
"in",
"r... | 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. | [
"Like",
"columnise",
"but",
"with",
"colored",
"rows",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L307-L319 |
246,536 | nerdvegas/rez | src/rez/utils/formatting.py | expanduser | 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' may inadvertently convert to a homedir, if a package
happens to match a username.
"""
if '~' not in path:
return path
if os.name == "nt":
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif 'HOMEPATH' in os.environ:
drive = os.environ.get('HOMEDRIVE', '')
userhome = os.path.join(drive, os.environ['HOMEPATH'])
else:
return path
else:
userhome = os.path.expanduser('~')
def _expanduser(path):
return EXPANDUSER_RE.sub(
lambda m: m.groups()[0] + userhome + m.groups()[1],
path)
# only replace '~' if it's at start of string or is preceeded by pathsep or
# ';' or whitespace; AND, is followed either by sep, pathsep, ';', ' ' or
# end-of-string.
#
return os.path.normpath(_expanduser(path)) | python | def expanduser(path):
if '~' not in path:
return path
if os.name == "nt":
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif 'HOMEPATH' in os.environ:
drive = os.environ.get('HOMEDRIVE', '')
userhome = os.path.join(drive, os.environ['HOMEPATH'])
else:
return path
else:
userhome = os.path.expanduser('~')
def _expanduser(path):
return EXPANDUSER_RE.sub(
lambda m: m.groups()[0] + userhome + m.groups()[1],
path)
# only replace '~' if it's at start of string or is preceeded by pathsep or
# ';' or whitespace; AND, is followed either by sep, pathsep, ';', ' ' or
# end-of-string.
#
return os.path.normpath(_expanduser(path)) | [
"def",
"expanduser",
"(",
"path",
")",
":",
"if",
"'~'",
"not",
"in",
"path",
":",
"return",
"path",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
":",
"userhome",
"=",
"os",
".",
"environ",
"[",
"'HOME'"... | 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' may inadvertently convert to a homedir, if a package
happens to match a username. | [
"Expand",
"~",
"to",
"home",
"directory",
"in",
"the",
"given",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L439-L473 |
246,537 | nerdvegas/rez | src/rez/utils/formatting.py | as_block_string | 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].rstrip() # drop double quotes
lines.append(line_)
return '"""\n%s\n"""' % '\n'.join(lines) | python | def as_block_string(txt):
import json
lines = []
for line in txt.split('\n'):
line_ = json.dumps(line)
line_ = line_[1:-1].rstrip() # drop double quotes
lines.append(line_)
return '"""\n%s\n"""' % '\n'.join(lines) | [
"def",
"as_block_string",
"(",
"txt",
")",
":",
"import",
"json",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"txt",
".",
"split",
"(",
"'\\n'",
")",
":",
"line_",
"=",
"json",
".",
"dumps",
"(",
"line",
")",
"line_",
"=",
"line_",
"[",
"1",
":"... | Return a string formatted as a python block comment string, like the one
you're currently reading. Special characters are escaped if necessary. | [
"Return",
"a",
"string",
"formatted",
"as",
"a",
"python",
"block",
"comment",
"string",
"like",
"the",
"one",
"you",
"re",
"currently",
"reading",
".",
"Special",
"characters",
"are",
"escaped",
"if",
"necessary",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L476-L488 |
246,538 | nerdvegas/rez | src/rez/utils/formatting.py | StringFormatMixin.format | 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
brackets and parenthesis removed. If None, defaults to the
object's 'format_pretty' attribute.
expand (`StringFormatType`): Expansion mode. If None, will default
to the object's 'format_expand' attribute.
Returns:
The formatting string.
"""
if pretty is None:
pretty = self.format_pretty
if expand is None:
expand = self.format_expand
formatter = ObjectStringFormatter(self, pretty=pretty, expand=expand)
return formatter.format(s) | python | def format(self, s, pretty=None, expand=None):
if pretty is None:
pretty = self.format_pretty
if expand is None:
expand = self.format_expand
formatter = ObjectStringFormatter(self, pretty=pretty, expand=expand)
return formatter.format(s) | [
"def",
"format",
"(",
"self",
",",
"s",
",",
"pretty",
"=",
"None",
",",
"expand",
"=",
"None",
")",
":",
"if",
"pretty",
"is",
"None",
":",
"pretty",
"=",
"self",
".",
"format_pretty",
"if",
"expand",
"is",
"None",
":",
"expand",
"=",
"self",
".",... | 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
brackets and parenthesis removed. If None, defaults to the
object's 'format_pretty' attribute.
expand (`StringFormatType`): Expansion mode. If None, will default
to the object's 'format_expand' attribute.
Returns:
The formatting string. | [
"Format",
"a",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L150-L171 |
246,539 | nerdvegas/rez | src/rez/vendor/version/version.py | Version.copy | def copy(self):
"""Returns a copy of the version."""
other = Version(None)
other.tokens = self.tokens[:]
other.seps = self.seps[:]
return other | python | def copy(self):
other = Version(None)
other.tokens = self.tokens[:]
other.seps = self.seps[:]
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"other",
"=",
"Version",
"(",
"None",
")",
"other",
".",
"tokens",
"=",
"self",
".",
"tokens",
"[",
":",
"]",
"other",
".",
"seps",
"=",
"self",
".",
"seps",
"[",
":",
"]",
"return",
"other"
] | Returns a copy of the version. | [
"Returns",
"a",
"copy",
"of",
"the",
"version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L297-L302 |
246,540 | nerdvegas/rez | src/rez/vendor/version/version.py | Version.trim | 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_]
other.seps = self.seps[:len_ - 1]
return other | python | def trim(self, len_):
other = Version(None)
other.tokens = self.tokens[:len_]
other.seps = self.seps[:len_ - 1]
return other | [
"def",
"trim",
"(",
"self",
",",
"len_",
")",
":",
"other",
"=",
"Version",
"(",
"None",
")",
"other",
".",
"tokens",
"=",
"self",
".",
"tokens",
"[",
":",
"len_",
"]",
"other",
".",
"seps",
"=",
"self",
".",
"seps",
"[",
":",
"len_",
"-",
"1",... | 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. | [
"Return",
"a",
"copy",
"of",
"the",
"version",
"possibly",
"with",
"less",
"tokens",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L304-L314 |
246,541 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.union | 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 not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds[:]
for range in other:
bounds += range.bounds
bounds = self._union(bounds)
range = VersionRange(None)
range.bounds = bounds
return range | python | def union(self, other):
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds[:]
for range in other:
bounds += range.bounds
bounds = self._union(bounds)
range = VersionRange(None)
range.bounds = bounds
return range | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"hasattr",
"(",
"other",
",",
"\"__iter__\"",
")",
":",
"other",
"=",
"[",
"other",
"]",
"bounds",
"=",
"self",
".",
"bounds",
"[",
":",
"]",
"for",
"range",
"in",
"other",
":",
"b... | 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. | [
"OR",
"together",
"version",
"ranges",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L814-L834 |
246,542 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.intersection | 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 None if
no ranges intersect.
"""
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds
for range in other:
bounds = self._intersection(bounds, range.bounds)
if not bounds:
return None
range = VersionRange(None)
range.bounds = bounds
return range | python | def intersection(self, other):
if not hasattr(other, "__iter__"):
other = [other]
bounds = self.bounds
for range in other:
bounds = self._intersection(bounds, range.bounds)
if not bounds:
return None
range = VersionRange(None)
range.bounds = bounds
return range | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"hasattr",
"(",
"other",
",",
"\"__iter__\"",
")",
":",
"other",
"=",
"[",
"other",
"]",
"bounds",
"=",
"self",
".",
"bounds",
"for",
"range",
"in",
"other",
":",
"bounds",
"=",... | 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 None if
no ranges intersect. | [
"AND",
"together",
"version",
"ranges",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L836-L859 |
246,543 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.inverse | 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:
bounds = self._inverse(self.bounds)
range = VersionRange(None)
range.bounds = bounds
return range | python | def inverse(self):
if self.is_any():
return None
else:
bounds = self._inverse(self.bounds)
range = VersionRange(None)
range.bounds = bounds
return range | [
"def",
"inverse",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_any",
"(",
")",
":",
"return",
"None",
"else",
":",
"bounds",
"=",
"self",
".",
"_inverse",
"(",
"self",
".",
"bounds",
")",
"range",
"=",
"VersionRange",
"(",
"None",
")",
"range",
".... | 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). | [
"Calculate",
"the",
"inverse",
"of",
"the",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L861-L874 |
246,544 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.split | 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)
range.bounds = [bound]
ranges.append(range)
return ranges | python | def split(self):
ranges = []
for bound in self.bounds:
range = VersionRange(None)
range.bounds = [bound]
ranges.append(range)
return ranges | [
"def",
"split",
"(",
"self",
")",
":",
"ranges",
"=",
"[",
"]",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"range",
"=",
"VersionRange",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"[",
"bound",
"]",
"ranges",
".",
"append",
"(",
"range",... | Split into separate contiguous ranges.
Returns:
A list of VersionRange objects. For example, the range "3|5+" will
be split into ["3", "5+"]. | [
"Split",
"into",
"separate",
"contiguous",
"ranges",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L887-L899 |
246,545 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.as_span | 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 representing upper bound of the range.
Returns:
`VersionRange` object.
"""
lower = (None if lower_version is None
else _LowerBound(lower_version, lower_inclusive))
upper = (None if upper_version is None
else _UpperBound(upper_version, upper_inclusive))
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | python | def as_span(cls, lower_version=None, upper_version=None,
lower_inclusive=True, upper_inclusive=True):
lower = (None if lower_version is None
else _LowerBound(lower_version, lower_inclusive))
upper = (None if upper_version is None
else _UpperBound(upper_version, upper_inclusive))
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | [
"def",
"as_span",
"(",
"cls",
",",
"lower_version",
"=",
"None",
",",
"upper_version",
"=",
"None",
",",
"lower_inclusive",
"=",
"True",
",",
"upper_inclusive",
"=",
"True",
")",
":",
"lower",
"=",
"(",
"None",
"if",
"lower_version",
"is",
"None",
"else",
... | Create a range from lower_version..upper_version.
Args:
lower_version: Version object representing lower bound of the range.
upper_version: Version object representing upper bound of the range.
Returns:
`VersionRange` object. | [
"Create",
"a",
"range",
"from",
"lower_version",
"..",
"upper_version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L902-L921 |
246,546 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.from_version | 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'/'=='. If None, a bounded range will be created
that contains the version superset.
Returns:
`VersionRange` object.
"""
lower = None
upper = None
if op is None:
lower = _LowerBound(version, True)
upper = _UpperBound(version.next(), False)
elif op in ("eq", "=="):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
elif op in ("gt", ">"):
lower = _LowerBound(version, False)
elif op in ("gte", ">="):
lower = _LowerBound(version, True)
elif op in ("lt", "<"):
upper = _UpperBound(version, False)
elif op in ("lte", "<="):
upper = _UpperBound(version, True)
else:
raise VersionError("Unknown bound operation '%s'" % op)
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | python | def from_version(cls, version, op=None):
lower = None
upper = None
if op is None:
lower = _LowerBound(version, True)
upper = _UpperBound(version.next(), False)
elif op in ("eq", "=="):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
elif op in ("gt", ">"):
lower = _LowerBound(version, False)
elif op in ("gte", ">="):
lower = _LowerBound(version, True)
elif op in ("lt", "<"):
upper = _UpperBound(version, False)
elif op in ("lte", "<="):
upper = _UpperBound(version, True)
else:
raise VersionError("Unknown bound operation '%s'" % op)
bound = _Bound(lower, upper)
range = cls(None)
range.bounds = [bound]
return range | [
"def",
"from_version",
"(",
"cls",
",",
"version",
",",
"op",
"=",
"None",
")",
":",
"lower",
"=",
"None",
"upper",
"=",
"None",
"if",
"op",
"is",
"None",
":",
"lower",
"=",
"_LowerBound",
"(",
"version",
",",
"True",
")",
"upper",
"=",
"_UpperBound"... | 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'/'=='. If None, a bounded range will be created
that contains the version superset.
Returns:
`VersionRange` object. | [
"Create",
"a",
"range",
"from",
"a",
"version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L924-L960 |
246,547 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.from_versions | 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:
`VersionRange` object.
"""
range = cls(None)
range.bounds = []
for version in dedup(sorted(versions)):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
bound = _Bound(lower, upper)
range.bounds.append(bound)
return range | python | def from_versions(cls, versions):
range = cls(None)
range.bounds = []
for version in dedup(sorted(versions)):
lower = _LowerBound(version, True)
upper = _UpperBound(version, True)
bound = _Bound(lower, upper)
range.bounds.append(bound)
return range | [
"def",
"from_versions",
"(",
"cls",
",",
"versions",
")",
":",
"range",
"=",
"cls",
"(",
"None",
")",
"range",
".",
"bounds",
"=",
"[",
"]",
"for",
"version",
"in",
"dedup",
"(",
"sorted",
"(",
"versions",
")",
")",
":",
"lower",
"=",
"_LowerBound",
... | 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:
`VersionRange` object. | [
"Create",
"a",
"range",
"from",
"a",
"list",
"of",
"versions",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L963-L982 |
246,548 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.to_versions | 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.version == bound.upper.version):
versions.append(bound.lower.version)
return versions or None | python | def to_versions(self):
versions = []
for bound in self.bounds:
if bound.lower.inclusive and bound.upper.inclusive \
and (bound.lower.version == bound.upper.version):
versions.append(bound.lower.version)
return versions or None | [
"def",
"to_versions",
"(",
"self",
")",
":",
"versions",
"=",
"[",
"]",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"if",
"bound",
".",
"lower",
".",
"inclusive",
"and",
"bound",
".",
"upper",
".",
"inclusive",
"and",
"(",
"bound",
".",
"lower"... | Returns exact version ranges as Version objects, or None if there
are no exact version ranges present. | [
"Returns",
"exact",
"version",
"ranges",
"as",
"Version",
"objects",
"or",
"None",
"if",
"there",
"are",
"no",
"exact",
"version",
"ranges",
"present",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L984-L994 |
246,549 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.contains_version | 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:
return True
if i == -1:
return False
else:
_, contains = self._contains_version(version)
return contains
return False | python | def contains_version(self, version):
if len(self.bounds) < 5:
# not worth overhead of binary search
for bound in self.bounds:
i = bound.version_containment(version)
if i == 0:
return True
if i == -1:
return False
else:
_, contains = self._contains_version(version)
return contains
return False | [
"def",
"contains_version",
"(",
"self",
",",
"version",
")",
":",
"if",
"len",
"(",
"self",
".",
"bounds",
")",
"<",
"5",
":",
"# not worth overhead of binary search",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"i",
"=",
"bound",
".",
"version_conta... | Returns True if version is contained in this range. | [
"Returns",
"True",
"if",
"version",
"is",
"contained",
"in",
"this",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L996-L1010 |
246,550 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.iter_intersecting | 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,
mode=_ContainsVersionIterator.MODE_INTERSECTING) | python | def iter_intersecting(self, iterable, key=None, descending=False):
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_INTERSECTING) | [
"def",
"iter_intersecting",
"(",
"self",
",",
"iterable",
",",
"key",
"=",
"None",
",",
"descending",
"=",
"False",
")",
":",
"return",
"_ContainsVersionIterator",
"(",
"self",
",",
"iterable",
",",
"key",
",",
"descending",
",",
"mode",
"=",
"_ContainsVersi... | Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect. | [
"Like",
"iter_intersect_test",
"but",
"returns",
"intersections",
"only",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1033-L1040 |
246,551 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.iter_non_intersecting | 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, descending,
mode=_ContainsVersionIterator.MODE_NON_INTERSECTING) | python | def iter_non_intersecting(self, iterable, key=None, descending=False):
return _ContainsVersionIterator(self, iterable, key, descending,
mode=_ContainsVersionIterator.MODE_NON_INTERSECTING) | [
"def",
"iter_non_intersecting",
"(",
"self",
",",
"iterable",
",",
"key",
"=",
"None",
",",
"descending",
"=",
"False",
")",
":",
"return",
"_ContainsVersionIterator",
"(",
"self",
",",
"iterable",
",",
"key",
",",
"descending",
",",
"mode",
"=",
"_ContainsV... | Like `iter_intersect_test`, but returns non-intersections only.
Returns:
An iterator that returns items from `iterable` that don't intersect. | [
"Like",
"iter_intersect_test",
"but",
"returns",
"non",
"-",
"intersections",
"only",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1042-L1049 |
246,552 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.span | 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.bounds[0].lower, self.bounds[-1].upper)
other.bounds = [bound]
return other | python | def span(self):
other = VersionRange(None)
bound = _Bound(self.bounds[0].lower, self.bounds[-1].upper)
other.bounds = [bound]
return other | [
"def",
"span",
"(",
"self",
")",
":",
"other",
"=",
"VersionRange",
"(",
"None",
")",
"bound",
"=",
"_Bound",
"(",
"self",
".",
"bounds",
"[",
"0",
"]",
".",
"lower",
",",
"self",
".",
"bounds",
"[",
"-",
"1",
"]",
".",
"upper",
")",
"other",
"... | 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". | [
"Return",
"a",
"contiguous",
"range",
"that",
"is",
"a",
"superset",
"of",
"this",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1051-L1061 |
246,553 | nerdvegas/rez | src/rez/vendor/version/version.py | VersionRange.visit_versions | 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
example setting an upper bound to a smaller version than the lower bound.
Use at your own risk.
Args:
func (callable): Takes a `Version` instance arg, and is applied to
every version in the range. If `func` returns a `Version`, it
will replace the existing version, updating this `VersionRange`
instance in place.
"""
for bound in self.bounds:
if bound.lower is not _LowerBound.min:
result = func(bound.lower.version)
if isinstance(result, Version):
bound.lower.version = result
if bound.upper is not _UpperBound.inf:
result = func(bound.upper.version)
if isinstance(result, Version):
bound.upper.version = result | python | def visit_versions(self, func):
for bound in self.bounds:
if bound.lower is not _LowerBound.min:
result = func(bound.lower.version)
if isinstance(result, Version):
bound.lower.version = result
if bound.upper is not _UpperBound.inf:
result = func(bound.upper.version)
if isinstance(result, Version):
bound.upper.version = result | [
"def",
"visit_versions",
"(",
"self",
",",
"func",
")",
":",
"for",
"bound",
"in",
"self",
".",
"bounds",
":",
"if",
"bound",
".",
"lower",
"is",
"not",
"_LowerBound",
".",
"min",
":",
"result",
"=",
"func",
"(",
"bound",
".",
"lower",
".",
"version"... | 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
example setting an upper bound to a smaller version than the lower bound.
Use at your own risk.
Args:
func (callable): Takes a `Version` instance arg, and is applied to
every version in the range. If `func` returns a `Version`, it
will replace the existing version, updating this `VersionRange`
instance in place. | [
"Visit",
"each",
"version",
"in",
"the",
"range",
"and",
"apply",
"a",
"function",
"to",
"each",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L1065-L1092 |
246,554 | getsentry/raven-python | raven/transport/http.py | HTTPTransport.send | 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,
verify_ssl=self.verify_ssl,
ca_certs=self.ca_certs,
)
except urllib2.HTTPError as exc:
msg = exc.headers.get('x-sentry-error')
code = exc.getcode()
if code == 429:
try:
retry_after = int(exc.headers.get('retry-after'))
except (ValueError, TypeError):
retry_after = 0
raise RateLimited(msg, retry_after)
elif msg:
raise APIError(msg, code)
else:
raise
return response | python | def send(self, url, data, headers):
req = urllib2.Request(url, headers=headers)
try:
response = urlopen(
url=req,
data=data,
timeout=self.timeout,
verify_ssl=self.verify_ssl,
ca_certs=self.ca_certs,
)
except urllib2.HTTPError as exc:
msg = exc.headers.get('x-sentry-error')
code = exc.getcode()
if code == 429:
try:
retry_after = int(exc.headers.get('retry-after'))
except (ValueError, TypeError):
retry_after = 0
raise RateLimited(msg, retry_after)
elif msg:
raise APIError(msg, code)
else:
raise
return response | [
"def",
"send",
"(",
"self",
",",
"url",
",",
"data",
",",
"headers",
")",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"try",
":",
"response",
"=",
"urlopen",
"(",
"url",
"=",
"req",
",",
"data",
"=... | Sends a request to a remote webserver using HTTP POST. | [
"Sends",
"a",
"request",
"to",
"a",
"remote",
"webserver",
"using",
"HTTP",
"POST",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/transport/http.py#L31-L58 |
246,555 | getsentry/raven-python | raven/contrib/django/views.py | extract_auth_vars | 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_AUTHORIZATION', '').startswith('Sentry'):
return request.META['HTTP_AUTHORIZATION']
else:
# Try to construct from GET request
args = [
'%s=%s' % i
for i in request.GET.items()
if i[0].startswith('sentry_') and i[0] != 'sentry_data'
]
if args:
return 'Sentry %s' % ', '.join(args)
return None | python | def extract_auth_vars(request):
if request.META.get('HTTP_X_SENTRY_AUTH', '').startswith('Sentry'):
return request.META['HTTP_X_SENTRY_AUTH']
elif request.META.get('HTTP_AUTHORIZATION', '').startswith('Sentry'):
return request.META['HTTP_AUTHORIZATION']
else:
# Try to construct from GET request
args = [
'%s=%s' % i
for i in request.GET.items()
if i[0].startswith('sentry_') and i[0] != 'sentry_data'
]
if args:
return 'Sentry %s' % ', '.join(args)
return None | [
"def",
"extract_auth_vars",
"(",
"request",
")",
":",
"if",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_X_SENTRY_AUTH'",
",",
"''",
")",
".",
"startswith",
"(",
"'Sentry'",
")",
":",
"return",
"request",
".",
"META",
"[",
"'HTTP_X_SENTRY_AUTH'",
"]",
"... | raven-js will pass both Authorization and X-Sentry-Auth depending on the browser
and server configurations. | [
"raven",
"-",
"js",
"will",
"pass",
"both",
"Authorization",
"and",
"X",
"-",
"Sentry",
"-",
"Auth",
"depending",
"on",
"the",
"browser",
"and",
"server",
"configurations",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/views.py#L61-L79 |
246,556 | getsentry/raven-python | raven/events.py | Exception._get_value | 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_locals,
)
exc_module = getattr(exc_type, '__module__', None)
if exc_module:
exc_module = str(exc_module)
exc_type = getattr(exc_type, '__name__', '<unknown>')
return {
'value': to_unicode(exc_value),
'type': str(exc_type),
'module': to_unicode(exc_module),
'stacktrace': stack_info,
} | python | def _get_value(self, exc_type, exc_value, exc_traceback):
stack_info = get_stack_info(
iter_traceback_frames(exc_traceback),
transformer=self.transform,
capture_locals=self.client.capture_locals,
)
exc_module = getattr(exc_type, '__module__', None)
if exc_module:
exc_module = str(exc_module)
exc_type = getattr(exc_type, '__name__', '<unknown>')
return {
'value': to_unicode(exc_value),
'type': str(exc_type),
'module': to_unicode(exc_module),
'stacktrace': stack_info,
} | [
"def",
"_get_value",
"(",
"self",
",",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
")",
":",
"stack_info",
"=",
"get_stack_info",
"(",
"iter_traceback_frames",
"(",
"exc_traceback",
")",
",",
"transformer",
"=",
"self",
".",
"transform",
",",
"capture_lo... | Convert exception info to a value for the values list. | [
"Convert",
"exception",
"info",
"to",
"a",
"value",
"for",
"the",
"values",
"list",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/events.py#L90-L110 |
246,557 | getsentry/raven-python | raven/breadcrumbs.py | record | 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 is None:
timestamp = time()
for ctx in raven.context.get_active_contexts():
ctx.breadcrumbs.record(timestamp, level, message, category,
data, type, processor) | python | def record(message=None, timestamp=None, level=None, category=None,
data=None, type=None, processor=None):
if timestamp is None:
timestamp = time()
for ctx in raven.context.get_active_contexts():
ctx.breadcrumbs.record(timestamp, level, message, category,
data, type, processor) | [
"def",
"record",
"(",
"message",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"level",
"=",
"None",
",",
"category",
"=",
"None",
",",
"data",
"=",
"None",
",",
"type",
"=",
"None",
",",
"processor",
"=",
"None",
")",
":",
"if",
"timestamp",
"i... | Records a breadcrumb for all active clients. This is what integration
code should use rather than invoking the `captureBreadcrumb` method
on a specific client. | [
"Records",
"a",
"breadcrumb",
"for",
"all",
"active",
"clients",
".",
"This",
"is",
"what",
"integration",
"code",
"should",
"use",
"rather",
"than",
"invoking",
"the",
"captureBreadcrumb",
"method",
"on",
"a",
"specific",
"client",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/breadcrumbs.py#L116-L126 |
246,558 | getsentry/raven-python | raven/breadcrumbs.py | ignore_logger | 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(name_or_logger, handler) | python | def ignore_logger(name_or_logger, allow_level=None):
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(name_or_logger, handler) | [
"def",
"ignore_logger",
"(",
"name_or_logger",
",",
"allow_level",
"=",
"None",
")",
":",
"def",
"handler",
"(",
"logger",
",",
"level",
",",
"msg",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"allow_level",
"is",
"not",
"None",
"and",
"level",
">=",
"... | Ignores a logger during breadcrumb recording. | [
"Ignores",
"a",
"logger",
"during",
"breadcrumb",
"recording",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/breadcrumbs.py#L275-L283 |
246,559 | getsentry/raven-python | raven/utils/serializer/manager.py | Serializer.transform | 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.context.add(objid)
try:
for serializer in self.serializers:
try:
if serializer.can(value):
return serializer.serialize(value, **kwargs)
except Exception as e:
logger.exception(e)
return text_type(type(value))
# if all else fails, lets use the repr of the object
try:
return repr(value)
except Exception as e:
logger.exception(e)
# It's common case that a model's __unicode__ definition
# may try to query the database which if it was not
# cleaned up correctly, would hit a transaction aborted
# exception
return text_type(type(value))
finally:
self.context.remove(objid) | python | def transform(self, value, **kwargs):
if value is None:
return None
objid = id(value)
if objid in self.context:
return '<...>'
self.context.add(objid)
try:
for serializer in self.serializers:
try:
if serializer.can(value):
return serializer.serialize(value, **kwargs)
except Exception as e:
logger.exception(e)
return text_type(type(value))
# if all else fails, lets use the repr of the object
try:
return repr(value)
except Exception as e:
logger.exception(e)
# It's common case that a model's __unicode__ definition
# may try to query the database which if it was not
# cleaned up correctly, would hit a transaction aborted
# exception
return text_type(type(value))
finally:
self.context.remove(objid) | [
"def",
"transform",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"objid",
"=",
"id",
"(",
"value",
")",
"if",
"objid",
"in",
"self",
".",
"context",
":",
"return",
"'<...>'",
"sel... | Primary function which handles recursively transforming
values via their serializers | [
"Primary",
"function",
"which",
"handles",
"recursively",
"transforming",
"values",
"via",
"their",
"serializers"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/serializer/manager.py#L52-L85 |
246,560 | getsentry/raven-python | raven/contrib/tornado/__init__.py | AsyncSentryClient.send | 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 | def send(self, auth_header=None, callback=None, **data):
message = self.encode(data)
return self.send_encoded(message, auth_header=auth_header, callback=callback) | [
"def",
"send",
"(",
"self",
",",
"auth_header",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"data",
")",
":",
"message",
"=",
"self",
".",
"encode",
"(",
"data",
")",
"return",
"self",
".",
"send_encoded",
"(",
"message",
",",
"auth_hea... | Serializes the message and passes the payload onto ``send_encoded``. | [
"Serializes",
"the",
"message",
"and",
"passes",
"the",
"payload",
"onto",
"send_encoded",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L47-L53 |
246,561 | getsentry/raven-python | raven/contrib/tornado/__init__.py | AsyncSentryClient._send_remote | 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 = {}
return AsyncHTTPClient().fetch(
url, callback, method="POST", body=data, headers=headers,
validate_cert=self.validate_cert
) | python | def _send_remote(self, url, data, headers=None, callback=None):
if headers is None:
headers = {}
return AsyncHTTPClient().fetch(
url, callback, method="POST", body=data, headers=headers,
validate_cert=self.validate_cert
) | [
"def",
"_send_remote",
"(",
"self",
",",
"url",
",",
"data",
",",
"headers",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"}",
"return",
"AsyncHTTPClient",
"(",
")",
".",
"fetch",
"(",
... | 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. | [
"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",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L82-L94 |
246,562 | getsentry/raven-python | raven/contrib/tornado/__init__.py | SentryMixin.get_sentry_data_from_request | 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_url(),
'method': self.request.method,
'data': self.request.body,
'query_string': self.request.query,
'cookies': self.request.headers.get('Cookie', None),
'headers': dict(self.request.headers),
}
} | python | def get_sentry_data_from_request(self):
return {
'request': {
'url': self.request.full_url(),
'method': self.request.method,
'data': self.request.body,
'query_string': self.request.query,
'cookies': self.request.headers.get('Cookie', None),
'headers': dict(self.request.headers),
}
} | [
"def",
"get_sentry_data_from_request",
"(",
"self",
")",
":",
"return",
"{",
"'request'",
":",
"{",
"'url'",
":",
"self",
".",
"request",
".",
"full_url",
"(",
")",
",",
"'method'",
":",
"self",
".",
"request",
".",
"method",
",",
"'data'",
":",
"self",
... | Extracts the data required for 'sentry.interfaces.Http' from the
current request being handled by the request handler
:param return: A dictionary. | [
"Extracts",
"the",
"data",
"required",
"for",
"sentry",
".",
"interfaces",
".",
"Http",
"from",
"the",
"current",
"request",
"being",
"handled",
"by",
"the",
"request",
"handler"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L147-L163 |
246,563 | getsentry/raven-python | raven/base.py | Client.get_public_dsn | 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 self.is_enabled():
url = self.remote.get_public_dsn()
if scheme:
return '%s:%s' % (scheme, url)
return url | python | def get_public_dsn(self, scheme=None):
if self.is_enabled():
url = self.remote.get_public_dsn()
if scheme:
return '%s:%s' % (scheme, url)
return url | [
"def",
"get_public_dsn",
"(",
"self",
",",
"scheme",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_enabled",
"(",
")",
":",
"url",
"=",
"self",
".",
"remote",
".",
"get_public_dsn",
"(",
")",
"if",
"scheme",
":",
"return",
"'%s:%s'",
"%",
"(",
"schem... | 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') | [
"Returns",
"a",
"public",
"DSN",
"which",
"is",
"consumable",
"by",
"raven",
"-",
"js"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L330-L345 |
246,564 | getsentry/raven-python | raven/base.py | Client.capture | 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:
>>> capture('raven.events.Message', message='foo', data={
>>> 'request': {
>>> 'url': '...',
>>> 'data': {},
>>> 'query_string': '...',
>>> 'method': 'POST',
>>> },
>>> 'logger': 'logger.name',
>>> }, extra={
>>> 'key': 'value',
>>> })
The finalized ``data`` structure contains the following (some optional)
builtin values:
>>> {
>>> # the culprit and version information
>>> 'culprit': 'full.module.name', # or /arbitrary/path
>>>
>>> # all detectable installed modules
>>> 'modules': {
>>> 'full.module.name': 'version string',
>>> },
>>>
>>> # arbitrary data provided by user
>>> 'extra': {
>>> 'key': 'value',
>>> }
>>> }
:param event_type: the module path to the Event class. Builtins can use
shorthand class notation and exclude the full module
path.
:param data: the data base, useful for specifying structured data
interfaces. Any key which contains a '.' will be
assumed to be a data interface.
:param date: the datetime of this event
:param time_spent: a integer value representing the duration of the
event (in milliseconds)
:param extra: a dictionary of additional standard metadata
:param stack: a stacktrace for the event
:param tags: dict of extra tags
:param sample_rate: a float in the range [0, 1] to sample this message
:return: a 32-length string identifying this event
"""
if not self.is_enabled():
return
exc_info = kwargs.get('exc_info')
if exc_info is not None:
if self.skip_error_for_logging(exc_info):
return
elif not self.should_capture(exc_info):
self.logger.info(
'Not capturing exception due to filters: %s', exc_info[0],
exc_info=sys.exc_info())
return
self.record_exception_seen(exc_info)
data = self.build_msg(
event_type, data, date, time_spent, extra, stack, tags=tags,
**kwargs)
# should this event be sampled?
if sample_rate is None:
sample_rate = self.sample_rate
if self._random.random() < sample_rate:
self.send(**data)
self._local_state.last_event_id = data['event_id']
return data['event_id'] | python | def capture(self, event_type, data=None, date=None, time_spent=None,
extra=None, stack=None, tags=None, sample_rate=None,
**kwargs):
if not self.is_enabled():
return
exc_info = kwargs.get('exc_info')
if exc_info is not None:
if self.skip_error_for_logging(exc_info):
return
elif not self.should_capture(exc_info):
self.logger.info(
'Not capturing exception due to filters: %s', exc_info[0],
exc_info=sys.exc_info())
return
self.record_exception_seen(exc_info)
data = self.build_msg(
event_type, data, date, time_spent, extra, stack, tags=tags,
**kwargs)
# should this event be sampled?
if sample_rate is None:
sample_rate = self.sample_rate
if self._random.random() < sample_rate:
self.send(**data)
self._local_state.last_event_id = data['event_id']
return data['event_id'] | [
"def",
"capture",
"(",
"self",
",",
"event_type",
",",
"data",
"=",
"None",
",",
"date",
"=",
"None",
",",
"time_spent",
"=",
"None",
",",
"extra",
"=",
"None",
",",
"stack",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"sample_rate",
"=",
"None",
"... | Captures and processes an event and pipes it off to SentryClient.send.
To use structured data (interfaces) with capture:
>>> capture('raven.events.Message', message='foo', data={
>>> 'request': {
>>> 'url': '...',
>>> 'data': {},
>>> 'query_string': '...',
>>> 'method': 'POST',
>>> },
>>> 'logger': 'logger.name',
>>> }, extra={
>>> 'key': 'value',
>>> })
The finalized ``data`` structure contains the following (some optional)
builtin values:
>>> {
>>> # the culprit and version information
>>> 'culprit': 'full.module.name', # or /arbitrary/path
>>>
>>> # all detectable installed modules
>>> 'modules': {
>>> 'full.module.name': 'version string',
>>> },
>>>
>>> # arbitrary data provided by user
>>> 'extra': {
>>> 'key': 'value',
>>> }
>>> }
:param event_type: the module path to the Event class. Builtins can use
shorthand class notation and exclude the full module
path.
:param data: the data base, useful for specifying structured data
interfaces. Any key which contains a '.' will be
assumed to be a data interface.
:param date: the datetime of this event
:param time_spent: a integer value representing the duration of the
event (in milliseconds)
:param extra: a dictionary of additional standard metadata
:param stack: a stacktrace for the event
:param tags: dict of extra tags
:param sample_rate: a float in the range [0, 1] to sample this message
:return: a 32-length string identifying this event | [
"Captures",
"and",
"processes",
"an",
"event",
"and",
"pipes",
"it",
"off",
"to",
"SentryClient",
".",
"send",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L577-L657 |
246,565 | getsentry/raven-python | raven/base.py | Client._log_failed_submission | 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']['values'][-1]:
# try to reconstruct a reasonable version of the exception
for frame in data['exception']['values'][-1]['stacktrace'].get('frames', []):
output.append(' File "%(fn)s", line %(lineno)s, in %(func)s' % {
'fn': frame.get('filename', 'unknown_filename'),
'lineno': frame.get('lineno', -1),
'func': frame.get('function', 'unknown_function'),
})
self.uncaught_logger.error(output) | python | def _log_failed_submission(self, data):
message = data.pop('message', '<no message value>')
output = [message]
if 'exception' in data and 'stacktrace' in data['exception']['values'][-1]:
# try to reconstruct a reasonable version of the exception
for frame in data['exception']['values'][-1]['stacktrace'].get('frames', []):
output.append(' File "%(fn)s", line %(lineno)s, in %(func)s' % {
'fn': frame.get('filename', 'unknown_filename'),
'lineno': frame.get('lineno', -1),
'func': frame.get('function', 'unknown_function'),
})
self.uncaught_logger.error(output) | [
"def",
"_log_failed_submission",
"(",
"self",
",",
"data",
")",
":",
"message",
"=",
"data",
".",
"pop",
"(",
"'message'",
",",
"'<no message value>'",
")",
"output",
"=",
"[",
"message",
"]",
"if",
"'exception'",
"in",
"data",
"and",
"'stacktrace'",
"in",
... | Log a reasonable representation of an event that should have been sent
to Sentry | [
"Log",
"a",
"reasonable",
"representation",
"of",
"an",
"event",
"that",
"should",
"have",
"been",
"sent",
"to",
"Sentry"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L696-L712 |
246,566 | getsentry/raven-python | raven/base.py | Client.send_encoded | 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 = time.time()
auth_header = get_auth_header(
protocol=self.protocol_version,
timestamp=timestamp,
client=client_string,
api_key=self.remote.public_key,
api_secret=self.remote.secret_key,
)
headers = {
'User-Agent': client_string,
'X-Sentry-Auth': auth_header,
'Content-Encoding': self.get_content_encoding(),
'Content-Type': 'application/octet-stream',
}
return self.send_remote(
url=self.remote.store_endpoint,
data=message,
headers=headers,
**kwargs
) | python | def send_encoded(self, message, auth_header=None, **kwargs):
client_string = 'raven-python/%s' % (raven.VERSION,)
if not auth_header:
timestamp = time.time()
auth_header = get_auth_header(
protocol=self.protocol_version,
timestamp=timestamp,
client=client_string,
api_key=self.remote.public_key,
api_secret=self.remote.secret_key,
)
headers = {
'User-Agent': client_string,
'X-Sentry-Auth': auth_header,
'Content-Encoding': self.get_content_encoding(),
'Content-Type': 'application/octet-stream',
}
return self.send_remote(
url=self.remote.store_endpoint,
data=message,
headers=headers,
**kwargs
) | [
"def",
"send_encoded",
"(",
"self",
",",
"message",
",",
"auth_header",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client_string",
"=",
"'raven-python/%s'",
"%",
"(",
"raven",
".",
"VERSION",
",",
")",
"if",
"not",
"auth_header",
":",
"timestamp",
... | Given an already serialized message, signs the message and passes the
payload off to ``send_remote``. | [
"Given",
"an",
"already",
"serialized",
"message",
"signs",
"the",
"message",
"and",
"passes",
"the",
"payload",
"off",
"to",
"send_remote",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L752-L781 |
246,567 | getsentry/raven-python | raven/base.py | Client.captureQuery | 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 | def captureQuery(self, query, params=(), engine=None, **kwargs):
return self.capture(
'raven.events.Query', query=query, params=params, engine=engine,
**kwargs) | [
"def",
"captureQuery",
"(",
"self",
",",
"query",
",",
"params",
"=",
"(",
")",
",",
"engine",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"capture",
"(",
"'raven.events.Query'",
",",
"query",
"=",
"query",
",",
"params",
"... | Creates an event for a SQL query.
>>> client.captureQuery('SELECT * FROM foo') | [
"Creates",
"an",
"event",
"for",
"a",
"SQL",
"query",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L892-L900 |
246,568 | getsentry/raven-python | raven/base.py | Client.captureBreadcrumb | 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
# which will record to the correct client automatically.
self.context.breadcrumbs.record(*args, **kwargs) | python | def captureBreadcrumb(self, *args, **kwargs):
# Note: framework integration should not call this method but
# instead use the raven.breadcrumbs.record_breadcrumb function
# which will record to the correct client automatically.
self.context.breadcrumbs.record(*args, **kwargs) | [
"def",
"captureBreadcrumb",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Note: framework integration should not call this method but",
"# instead use the raven.breadcrumbs.record_breadcrumb function",
"# which will record to the correct client automatically.",
... | Records a breadcrumb with the current context. They will be
sent with the next event. | [
"Records",
"a",
"breadcrumb",
"with",
"the",
"current",
"context",
".",
"They",
"will",
"be",
"sent",
"with",
"the",
"next",
"event",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L908-L916 |
246,569 | getsentry/raven-python | raven/transport/registry.py | TransportRegistry.register_scheme | 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[scheme] = cls | python | def register_scheme(self, scheme, cls):
if scheme in self._schemes:
raise DuplicateScheme()
urlparse.register_scheme(scheme)
# TODO (vng): verify the interface of the new class
self._schemes[scheme] = cls | [
"def",
"register_scheme",
"(",
"self",
",",
"scheme",
",",
"cls",
")",
":",
"if",
"scheme",
"in",
"self",
".",
"_schemes",
":",
"raise",
"DuplicateScheme",
"(",
")",
"urlparse",
".",
"register_scheme",
"(",
"scheme",
")",
"# TODO (vng): verify the interface of t... | It is possible to inject new schemes at runtime | [
"It",
"is",
"possible",
"to",
"inject",
"new",
"schemes",
"at",
"runtime"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/transport/registry.py#L40-L49 |
246,570 | getsentry/raven-python | raven/contrib/flask.py | Sentry.get_http_info | 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_retriever(request, retriever) | python | def get_http_info(self, request):
if self.is_json_type(request.mimetype):
retriever = self.get_json_data
else:
retriever = self.get_form_data
return self.get_http_info_with_retriever(request, retriever) | [
"def",
"get_http_info",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"is_json_type",
"(",
"request",
".",
"mimetype",
")",
":",
"retriever",
"=",
"self",
".",
"get_json_data",
"else",
":",
"retriever",
"=",
"self",
".",
"get_form_data",
"retur... | Determine how to retrieve actual data by using request.mimetype. | [
"Determine",
"how",
"to",
"retrieve",
"actual",
"data",
"by",
"using",
"request",
".",
"mimetype",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/flask.py#L194-L202 |
246,571 | getsentry/raven-python | raven/conf/__init__.py | setup_logging | 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_logging(SentryHandler(client))
Within Django:
>>> from raven.contrib.django.handlers import SentryHandler
>>> setup_logging(SentryHandler())
Returns a boolean based on if logging was configured or not.
"""
logger = logging.getLogger()
if handler.__class__ in map(type, logger.handlers):
return False
logger.addHandler(handler)
# Add StreamHandler to sentry's default so you can catch missed exceptions
for logger_name in exclude:
logger = logging.getLogger(logger_name)
logger.propagate = False
logger.addHandler(logging.StreamHandler())
return True | python | def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS):
logger = logging.getLogger()
if handler.__class__ in map(type, logger.handlers):
return False
logger.addHandler(handler)
# Add StreamHandler to sentry's default so you can catch missed exceptions
for logger_name in exclude:
logger = logging.getLogger(logger_name)
logger.propagate = False
logger.addHandler(logging.StreamHandler())
return True | [
"def",
"setup_logging",
"(",
"handler",
",",
"exclude",
"=",
"EXCLUDE_LOGGER_DEFAULTS",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"if",
"handler",
".",
"__class__",
"in",
"map",
"(",
"type",
",",
"logger",
".",
"handlers",
")",
":",
... | 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_logging(SentryHandler(client))
Within Django:
>>> from raven.contrib.django.handlers import SentryHandler
>>> setup_logging(SentryHandler())
Returns a boolean based on if logging was configured or not. | [
"Configures",
"logging",
"to",
"pipe",
"to",
"Sentry",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/conf/__init__.py#L26-L57 |
246,572 | getsentry/raven-python | raven/utils/stacks.py | to_dict | 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)
return dict((k, dictish[k]) for k in m()) | python | def to_dict(dictish):
if hasattr(dictish, 'iterkeys'):
m = dictish.iterkeys
elif hasattr(dictish, 'keys'):
m = dictish.keys
else:
raise ValueError(dictish)
return dict((k, dictish[k]) for k in m()) | [
"def",
"to_dict",
"(",
"dictish",
")",
":",
"if",
"hasattr",
"(",
"dictish",
",",
"'iterkeys'",
")",
":",
"m",
"=",
"dictish",
".",
"iterkeys",
"elif",
"hasattr",
"(",
"dictish",
",",
"'keys'",
")",
":",
"m",
"=",
"dictish",
".",
"keys",
"else",
":",... | Given something that closely resembles a dictionary, we attempt
to coerce it into a propery dictionary. | [
"Given",
"something",
"that",
"closely",
"resembles",
"a",
"dictionary",
"we",
"attempt",
"to",
"coerce",
"it",
"into",
"a",
"propery",
"dictionary",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/stacks.py#L96-L108 |
246,573 | getsentry/raven-python | raven/utils/stacks.py | slim_frame_data | 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('in_app'):
app_frames.append(frame)
else:
system_frames.append(frame)
if frames_len <= frame_allowance:
return frames
remaining = frames_len - frame_allowance
app_count = len(app_frames)
system_allowance = max(frame_allowance - app_count, 0)
if system_allowance:
half_max = int(system_allowance / 2)
# prioritize trimming system frames
for frame in system_frames[half_max:-half_max]:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
remaining -= 1
else:
for frame in system_frames:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
remaining -= 1
if remaining:
app_allowance = app_count - remaining
half_max = int(app_allowance / 2)
for frame in app_frames[half_max:-half_max]:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
return frames | python | def slim_frame_data(frames, frame_allowance=25):
frames_len = 0
app_frames = []
system_frames = []
for frame in frames:
frames_len += 1
if frame.get('in_app'):
app_frames.append(frame)
else:
system_frames.append(frame)
if frames_len <= frame_allowance:
return frames
remaining = frames_len - frame_allowance
app_count = len(app_frames)
system_allowance = max(frame_allowance - app_count, 0)
if system_allowance:
half_max = int(system_allowance / 2)
# prioritize trimming system frames
for frame in system_frames[half_max:-half_max]:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
remaining -= 1
else:
for frame in system_frames:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
remaining -= 1
if remaining:
app_allowance = app_count - remaining
half_max = int(app_allowance / 2)
for frame in app_frames[half_max:-half_max]:
frame.pop('vars', None)
frame.pop('pre_context', None)
frame.pop('post_context', None)
return frames | [
"def",
"slim_frame_data",
"(",
"frames",
",",
"frame_allowance",
"=",
"25",
")",
":",
"frames_len",
"=",
"0",
"app_frames",
"=",
"[",
"]",
"system_frames",
"=",
"[",
"]",
"for",
"frame",
"in",
"frames",
":",
"frames_len",
"+=",
"1",
"if",
"frame",
".",
... | Removes various excess metadata from middle frames which go beyond
``frame_allowance``.
Returns ``frames``. | [
"Removes",
"various",
"excess",
"metadata",
"from",
"middle",
"frames",
"which",
"go",
"beyond",
"frame_allowance",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/stacks.py#L167-L215 |
246,574 | getsentry/raven-python | raven/contrib/webpy/utils.py | get_data_from_request | 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(),
'headers': dict(get_headers(web.ctx.environ)),
'env': dict(get_environ(web.ctx.environ)),
}
} | python | def get_data_from_request():
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(),
'headers': dict(get_headers(web.ctx.environ)),
'env': dict(get_environ(web.ctx.environ)),
}
} | [
"def",
"get_data_from_request",
"(",
")",
":",
"return",
"{",
"'request'",
":",
"{",
"'url'",
":",
"'%s://%s%s'",
"%",
"(",
"web",
".",
"ctx",
"[",
"'protocol'",
"]",
",",
"web",
".",
"ctx",
"[",
"'host'",
"]",
",",
"web",
".",
"ctx",
"[",
"'path'",
... | Returns request data extracted from web.ctx. | [
"Returns",
"request",
"data",
"extracted",
"from",
"web",
".",
"ctx",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/webpy/utils.py#L15-L26 |
246,575 | getsentry/raven-python | raven/contrib/django/resolver.py | get_regex | 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 | def get_regex(resolver_or_pattern):
try:
regex = resolver_or_pattern.regex
except AttributeError:
regex = resolver_or_pattern.pattern.regex
return regex | [
"def",
"get_regex",
"(",
"resolver_or_pattern",
")",
":",
"try",
":",
"regex",
"=",
"resolver_or_pattern",
".",
"regex",
"except",
"AttributeError",
":",
"regex",
"=",
"resolver_or_pattern",
".",
"pattern",
".",
"regex",
"return",
"regex"
] | Utility method for django's deprecated resolver.regex | [
"Utility",
"method",
"for",
"django",
"s",
"deprecated",
"resolver",
".",
"regex"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/resolver.py#L11-L17 |
246,576 | getsentry/raven-python | raven/utils/basic.py | once | def once(func):
"""Runs a thing once and once only."""
lock = threading.Lock()
def new_func(*args, **kwargs):
if new_func.called:
return
with lock:
if new_func.called:
return
rv = func(*args, **kwargs)
new_func.called = True
return rv
new_func = update_wrapper(new_func, func)
new_func.called = False
return new_func | python | def once(func):
lock = threading.Lock()
def new_func(*args, **kwargs):
if new_func.called:
return
with lock:
if new_func.called:
return
rv = func(*args, **kwargs)
new_func.called = True
return rv
new_func = update_wrapper(new_func, func)
new_func.called = False
return new_func | [
"def",
"once",
"(",
"func",
")",
":",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"new_func",
".",
"called",
":",
"return",
"with",
"lock",
":",
"if",
"new_func",
... | Runs a thing once and once only. | [
"Runs",
"a",
"thing",
"once",
"and",
"once",
"only",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/basic.py#L75-L91 |
246,577 | getsentry/raven-python | raven/contrib/django/utils.py | get_host | def get_host(request):
"""
A reimplementation of Django's get_host, without the
SuspiciousOperation check.
"""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in request.META):
host = request.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in request.META:
host = request.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = request.META['SERVER_NAME']
server_port = str(request.META['SERVER_PORT'])
if server_port != (request.is_secure() and '443' or '80'):
host = '%s:%s' % (host, server_port)
return host | python | def get_host(request):
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in request.META):
host = request.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in request.META:
host = request.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = request.META['SERVER_NAME']
server_port = str(request.META['SERVER_PORT'])
if server_port != (request.is_secure() and '443' or '80'):
host = '%s:%s' % (host, server_port)
return host | [
"def",
"get_host",
"(",
"request",
")",
":",
"# We try three options, in order of decreasing preference.",
"if",
"settings",
".",
"USE_X_FORWARDED_HOST",
"and",
"(",
"'HTTP_X_FORWARDED_HOST'",
"in",
"request",
".",
"META",
")",
":",
"host",
"=",
"request",
".",
"META"... | A reimplementation of Django's get_host, without the
SuspiciousOperation check. | [
"A",
"reimplementation",
"of",
"Django",
"s",
"get_host",
"without",
"the",
"SuspiciousOperation",
"check",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/utils.py#L84-L101 |
246,578 | getsentry/raven-python | raven/contrib/django/models.py | install_middleware | def install_middleware(middleware_name, lookup_names=None):
"""
Install specified middleware
"""
if lookup_names is None:
lookup_names = (middleware_name,)
# default settings.MIDDLEWARE is None
middleware_attr = 'MIDDLEWARE' if getattr(settings,
'MIDDLEWARE',
None) is not None \
else 'MIDDLEWARE_CLASSES'
# make sure to get an empty tuple when attr is None
middleware = getattr(settings, middleware_attr, ()) or ()
if set(lookup_names).isdisjoint(set(middleware)):
setattr(settings,
middleware_attr,
type(middleware)((middleware_name,)) + middleware) | python | def install_middleware(middleware_name, lookup_names=None):
if lookup_names is None:
lookup_names = (middleware_name,)
# default settings.MIDDLEWARE is None
middleware_attr = 'MIDDLEWARE' if getattr(settings,
'MIDDLEWARE',
None) is not None \
else 'MIDDLEWARE_CLASSES'
# make sure to get an empty tuple when attr is None
middleware = getattr(settings, middleware_attr, ()) or ()
if set(lookup_names).isdisjoint(set(middleware)):
setattr(settings,
middleware_attr,
type(middleware)((middleware_name,)) + middleware) | [
"def",
"install_middleware",
"(",
"middleware_name",
",",
"lookup_names",
"=",
"None",
")",
":",
"if",
"lookup_names",
"is",
"None",
":",
"lookup_names",
"=",
"(",
"middleware_name",
",",
")",
"# default settings.MIDDLEWARE is None",
"middleware_attr",
"=",
"'MIDDLEWA... | Install specified middleware | [
"Install",
"specified",
"middleware"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/models.py#L222-L238 |
246,579 | sebp/scikit-survival | sksurv/meta/base.py | _fit_and_score | def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params):
"""Train survival model on given data and return its score on test data"""
X_train, y_train = _safe_split(est, x, y, train_index)
train_params = fit_params.copy()
# Training
est.set_params(**parameters)
est.fit(X_train, y_train, **train_params)
# Testing
test_predict_params = predict_params.copy()
X_test, y_test = _safe_split(est, x, y, test_index, train_index)
score = scorer(est, X_test, y_test, **test_predict_params)
if not isinstance(score, numbers.Number):
raise ValueError("scoring must return a number, got %s (%s) instead."
% (str(score), type(score)))
return score | python | def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params):
X_train, y_train = _safe_split(est, x, y, train_index)
train_params = fit_params.copy()
# Training
est.set_params(**parameters)
est.fit(X_train, y_train, **train_params)
# Testing
test_predict_params = predict_params.copy()
X_test, y_test = _safe_split(est, x, y, test_index, train_index)
score = scorer(est, X_test, y_test, **test_predict_params)
if not isinstance(score, numbers.Number):
raise ValueError("scoring must return a number, got %s (%s) instead."
% (str(score), type(score)))
return score | [
"def",
"_fit_and_score",
"(",
"est",
",",
"x",
",",
"y",
",",
"scorer",
",",
"train_index",
",",
"test_index",
",",
"parameters",
",",
"fit_params",
",",
"predict_params",
")",
":",
"X_train",
",",
"y_train",
"=",
"_safe_split",
"(",
"est",
",",
"x",
","... | Train survival model on given data and return its score on test data | [
"Train",
"survival",
"model",
"on",
"given",
"data",
"and",
"return",
"its",
"score",
"on",
"test",
"data"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/base.py#L17-L35 |
246,580 | sebp/scikit-survival | sksurv/linear_model/coxnet.py | CoxnetSurvivalAnalysis._interpolate_coefficients | def _interpolate_coefficients(self, alpha):
"""Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training."""
exact = False
coef_idx = None
for i, val in enumerate(self.alphas_):
if val > alpha:
coef_idx = i
elif alpha - val < numpy.finfo(numpy.float).eps:
coef_idx = i
exact = True
break
if coef_idx is None:
coef = self.coef_[:, 0]
elif exact or coef_idx == len(self.alphas_) - 1:
coef = self.coef_[:, coef_idx]
else:
# interpolate between coefficients
a1 = self.alphas_[coef_idx + 1]
a2 = self.alphas_[coef_idx]
frac = (alpha - a1) / (a2 - a1)
coef = frac * self.coef_[:, coef_idx] + (1.0 - frac) * self.coef_[:, coef_idx + 1]
return coef | python | def _interpolate_coefficients(self, alpha):
exact = False
coef_idx = None
for i, val in enumerate(self.alphas_):
if val > alpha:
coef_idx = i
elif alpha - val < numpy.finfo(numpy.float).eps:
coef_idx = i
exact = True
break
if coef_idx is None:
coef = self.coef_[:, 0]
elif exact or coef_idx == len(self.alphas_) - 1:
coef = self.coef_[:, coef_idx]
else:
# interpolate between coefficients
a1 = self.alphas_[coef_idx + 1]
a2 = self.alphas_[coef_idx]
frac = (alpha - a1) / (a2 - a1)
coef = frac * self.coef_[:, coef_idx] + (1.0 - frac) * self.coef_[:, coef_idx + 1]
return coef | [
"def",
"_interpolate_coefficients",
"(",
"self",
",",
"alpha",
")",
":",
"exact",
"=",
"False",
"coef_idx",
"=",
"None",
"for",
"i",
",",
"val",
"in",
"enumerate",
"(",
"self",
".",
"alphas_",
")",
":",
"if",
"val",
">",
"alpha",
":",
"coef_idx",
"=",
... | Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training. | [
"Interpolate",
"coefficients",
"by",
"calculating",
"the",
"weighted",
"average",
"of",
"coefficient",
"vectors",
"corresponding",
"to",
"neighbors",
"of",
"alpha",
"in",
"the",
"list",
"of",
"alphas",
"constructed",
"during",
"training",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxnet.py#L239-L263 |
246,581 | sebp/scikit-survival | sksurv/linear_model/coxnet.py | CoxnetSurvivalAnalysis.predict | def predict(self, X, alpha=None):
"""The linear predictor of the model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test data of which to calculate log-likelihood from
alpha : float, optional
Constant that multiplies the penalty terms. If the same alpha was used during training, exact
coefficients are used, otherwise coefficients are interpolated from the closest alpha values that
were used during training. If set to ``None``, the last alpha in the solution path is used.
Returns
-------
T : array, shape = (n_samples,)
The predicted decision function
"""
X = check_array(X)
coef = self._get_coef(alpha)
return numpy.dot(X, coef) | python | def predict(self, X, alpha=None):
X = check_array(X)
coef = self._get_coef(alpha)
return numpy.dot(X, coef) | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"alpha",
"=",
"None",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
")",
"coef",
"=",
"self",
".",
"_get_coef",
"(",
"alpha",
")",
"return",
"numpy",
".",
"dot",
"(",
"X",
",",
"coef",
")"
] | The linear predictor of the model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test data of which to calculate log-likelihood from
alpha : float, optional
Constant that multiplies the penalty terms. If the same alpha was used during training, exact
coefficients are used, otherwise coefficients are interpolated from the closest alpha values that
were used during training. If set to ``None``, the last alpha in the solution path is used.
Returns
-------
T : array, shape = (n_samples,)
The predicted decision function | [
"The",
"linear",
"predictor",
"of",
"the",
"model",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxnet.py#L265-L285 |
246,582 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._create_base_ensemble | def _create_base_ensemble(self, out, n_estimators, n_folds):
"""For each base estimator collect models trained on each fold"""
ensemble_scores = numpy.empty((n_estimators, n_folds))
base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object)
for model, fold, score, est in out:
ensemble_scores[model, fold] = score
base_ensemble[model, fold] = est
return ensemble_scores, base_ensemble | python | def _create_base_ensemble(self, out, n_estimators, n_folds):
ensemble_scores = numpy.empty((n_estimators, n_folds))
base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object)
for model, fold, score, est in out:
ensemble_scores[model, fold] = score
base_ensemble[model, fold] = est
return ensemble_scores, base_ensemble | [
"def",
"_create_base_ensemble",
"(",
"self",
",",
"out",
",",
"n_estimators",
",",
"n_folds",
")",
":",
"ensemble_scores",
"=",
"numpy",
".",
"empty",
"(",
"(",
"n_estimators",
",",
"n_folds",
")",
")",
"base_ensemble",
"=",
"numpy",
".",
"empty_like",
"(",
... | For each base estimator collect models trained on each fold | [
"For",
"each",
"base",
"estimator",
"collect",
"models",
"trained",
"on",
"each",
"fold"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L152-L160 |
246,583 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._create_cv_ensemble | def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None):
"""For each selected base estimator, average models trained on each fold"""
fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object)
for i, idx in enumerate(idx_models_included):
model_name = self.base_estimators[idx][0] if model_names is None else model_names[idx]
avg_model = EnsembleAverage(base_ensemble[idx, :], name=model_name)
fitted_models[i] = avg_model
return fitted_models | python | def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None):
fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object)
for i, idx in enumerate(idx_models_included):
model_name = self.base_estimators[idx][0] if model_names is None else model_names[idx]
avg_model = EnsembleAverage(base_ensemble[idx, :], name=model_name)
fitted_models[i] = avg_model
return fitted_models | [
"def",
"_create_cv_ensemble",
"(",
"self",
",",
"base_ensemble",
",",
"idx_models_included",
",",
"model_names",
"=",
"None",
")",
":",
"fitted_models",
"=",
"numpy",
".",
"empty",
"(",
"len",
"(",
"idx_models_included",
")",
",",
"dtype",
"=",
"numpy",
".",
... | For each selected base estimator, average models trained on each fold | [
"For",
"each",
"selected",
"base",
"estimator",
"average",
"models",
"trained",
"on",
"each",
"fold"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L162-L170 |
246,584 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._get_base_estimators | def _get_base_estimators(self, X):
"""Takes special care of estimators using custom kernel function
Parameters
----------
X : array, shape = (n_samples, n_features)
Samples to pre-compute kernel matrix from.
Returns
-------
base_estimators : list
Same as `self.base_estimators`, expect that estimators with custom kernel function
use ``kernel='precomputed'``.
kernel_cache : dict
Maps estimator name to kernel matrix. Use this for cross-validation instead of `X`.
"""
base_estimators = []
kernel_cache = {}
kernel_fns = {}
for i, (name, estimator) in enumerate(self.base_estimators):
if hasattr(estimator, 'kernel') and callable(estimator.kernel):
if not hasattr(estimator, '_get_kernel'):
raise ValueError(
'estimator %s uses a custom kernel function, but does not have a _get_kernel method' % name)
kernel_mat = kernel_fns.get(estimator.kernel, None)
if kernel_mat is None:
kernel_mat = estimator._get_kernel(X)
kernel_cache[i] = kernel_mat
kernel_fns[estimator.kernel] = kernel_mat
kernel_cache[i] = kernel_mat
# We precompute kernel, but only for training, for testing use original custom kernel function
kernel_estimator = clone(estimator)
kernel_estimator.set_params(kernel='precomputed')
base_estimators.append((name, kernel_estimator))
else:
base_estimators.append((name, estimator))
return base_estimators, kernel_cache | python | def _get_base_estimators(self, X):
base_estimators = []
kernel_cache = {}
kernel_fns = {}
for i, (name, estimator) in enumerate(self.base_estimators):
if hasattr(estimator, 'kernel') and callable(estimator.kernel):
if not hasattr(estimator, '_get_kernel'):
raise ValueError(
'estimator %s uses a custom kernel function, but does not have a _get_kernel method' % name)
kernel_mat = kernel_fns.get(estimator.kernel, None)
if kernel_mat is None:
kernel_mat = estimator._get_kernel(X)
kernel_cache[i] = kernel_mat
kernel_fns[estimator.kernel] = kernel_mat
kernel_cache[i] = kernel_mat
# We precompute kernel, but only for training, for testing use original custom kernel function
kernel_estimator = clone(estimator)
kernel_estimator.set_params(kernel='precomputed')
base_estimators.append((name, kernel_estimator))
else:
base_estimators.append((name, estimator))
return base_estimators, kernel_cache | [
"def",
"_get_base_estimators",
"(",
"self",
",",
"X",
")",
":",
"base_estimators",
"=",
"[",
"]",
"kernel_cache",
"=",
"{",
"}",
"kernel_fns",
"=",
"{",
"}",
"for",
"i",
",",
"(",
"name",
",",
"estimator",
")",
"in",
"enumerate",
"(",
"self",
".",
"b... | Takes special care of estimators using custom kernel function
Parameters
----------
X : array, shape = (n_samples, n_features)
Samples to pre-compute kernel matrix from.
Returns
-------
base_estimators : list
Same as `self.base_estimators`, expect that estimators with custom kernel function
use ``kernel='precomputed'``.
kernel_cache : dict
Maps estimator name to kernel matrix. Use this for cross-validation instead of `X`. | [
"Takes",
"special",
"care",
"of",
"estimators",
"using",
"custom",
"kernel",
"function"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L172-L214 |
246,585 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._restore_base_estimators | def _restore_base_estimators(self, kernel_cache, out, X, cv):
"""Restore custom kernel functions of estimators for predictions"""
train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)}
for idx, fold, _, est in out:
if idx in kernel_cache:
if not hasattr(est, 'fit_X_'):
raise ValueError(
'estimator %s uses a custom kernel function, '
'but does not have the attribute `fit_X_` after training' % self.base_estimators[idx][0])
est.set_params(kernel=self.base_estimators[idx][1].kernel)
est.fit_X_ = X[train_folds[fold]]
return out | python | def _restore_base_estimators(self, kernel_cache, out, X, cv):
train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)}
for idx, fold, _, est in out:
if idx in kernel_cache:
if not hasattr(est, 'fit_X_'):
raise ValueError(
'estimator %s uses a custom kernel function, '
'but does not have the attribute `fit_X_` after training' % self.base_estimators[idx][0])
est.set_params(kernel=self.base_estimators[idx][1].kernel)
est.fit_X_ = X[train_folds[fold]]
return out | [
"def",
"_restore_base_estimators",
"(",
"self",
",",
"kernel_cache",
",",
"out",
",",
"X",
",",
"cv",
")",
":",
"train_folds",
"=",
"{",
"fold",
":",
"train_index",
"for",
"fold",
",",
"(",
"train_index",
",",
"_",
")",
"in",
"enumerate",
"(",
"cv",
")... | Restore custom kernel functions of estimators for predictions | [
"Restore",
"custom",
"kernel",
"functions",
"of",
"estimators",
"for",
"predictions"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L216-L230 |
246,586 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._fit_and_score_ensemble | def _fit_and_score_ensemble(self, X, y, cv, **fit_params):
"""Create a cross-validated model by training a model for each fold with the same model parameters"""
fit_params_steps = self._split_fit_params(fit_params)
folds = list(cv.split(X, y))
# Take care of custom kernel functions
base_estimators, kernel_cache = self._get_base_estimators(X)
out = Parallel(
n_jobs=self.n_jobs, verbose=self.verbose
)(
delayed(_fit_and_score_fold)(clone(estimator),
X if i not in kernel_cache else kernel_cache[i],
y,
self.scorer,
train_index, test_index,
fit_params_steps[name],
i, fold)
for i, (name, estimator) in enumerate(base_estimators)
for fold, (train_index, test_index) in enumerate(folds))
if len(kernel_cache) > 0:
out = self._restore_base_estimators(kernel_cache, out, X, folds)
return self._create_base_ensemble(out, len(base_estimators), len(folds)) | python | def _fit_and_score_ensemble(self, X, y, cv, **fit_params):
fit_params_steps = self._split_fit_params(fit_params)
folds = list(cv.split(X, y))
# Take care of custom kernel functions
base_estimators, kernel_cache = self._get_base_estimators(X)
out = Parallel(
n_jobs=self.n_jobs, verbose=self.verbose
)(
delayed(_fit_and_score_fold)(clone(estimator),
X if i not in kernel_cache else kernel_cache[i],
y,
self.scorer,
train_index, test_index,
fit_params_steps[name],
i, fold)
for i, (name, estimator) in enumerate(base_estimators)
for fold, (train_index, test_index) in enumerate(folds))
if len(kernel_cache) > 0:
out = self._restore_base_estimators(kernel_cache, out, X, folds)
return self._create_base_ensemble(out, len(base_estimators), len(folds)) | [
"def",
"_fit_and_score_ensemble",
"(",
"self",
",",
"X",
",",
"y",
",",
"cv",
",",
"*",
"*",
"fit_params",
")",
":",
"fit_params_steps",
"=",
"self",
".",
"_split_fit_params",
"(",
"fit_params",
")",
"folds",
"=",
"list",
"(",
"cv",
".",
"split",
"(",
... | Create a cross-validated model by training a model for each fold with the same model parameters | [
"Create",
"a",
"cross",
"-",
"validated",
"model",
"by",
"training",
"a",
"model",
"for",
"each",
"fold",
"with",
"the",
"same",
"model",
"parameters"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L232-L257 |
246,587 | sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection.fit | def fit(self, X, y=None, **fit_params):
"""Fit ensemble of models
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self
"""
self._check_params()
cv = check_cv(self.cv, X)
self._fit(X, y, cv, **fit_params)
return self | python | def fit(self, X, y=None, **fit_params):
self._check_params()
cv = check_cv(self.cv, X)
self._fit(X, y, cv, **fit_params)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"fit_params",
")",
":",
"self",
".",
"_check_params",
"(",
")",
"cv",
"=",
"check_cv",
"(",
"self",
".",
"cv",
",",
"X",
")",
"self",
".",
"_fit",
"(",
"X",
",",
"y",
... | Fit ensemble of models
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self | [
"Fit",
"ensemble",
"of",
"models"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L277-L297 |
246,588 | sebp/scikit-survival | sksurv/io/arffwrite.py | writearff | def writearff(data, filename, relation_name=None, index=True):
"""Write ARFF file
Parameters
----------
data : :class:`pandas.DataFrame`
DataFrame containing data
filename : string or file-like object
Path to ARFF file or file-like object. In the latter case,
the handle is closed by calling this function.
relation_name : string, optional, default: "pandas"
Name of relation in ARFF file.
index : boolean, optional, default: True
Write row names (index)
"""
if isinstance(filename, str):
fp = open(filename, 'w')
if relation_name is None:
relation_name = os.path.basename(filename)
else:
fp = filename
if relation_name is None:
relation_name = "pandas"
try:
data = _write_header(data, fp, relation_name, index)
fp.write("\n")
_write_data(data, fp)
finally:
fp.close() | python | def writearff(data, filename, relation_name=None, index=True):
if isinstance(filename, str):
fp = open(filename, 'w')
if relation_name is None:
relation_name = os.path.basename(filename)
else:
fp = filename
if relation_name is None:
relation_name = "pandas"
try:
data = _write_header(data, fp, relation_name, index)
fp.write("\n")
_write_data(data, fp)
finally:
fp.close() | [
"def",
"writearff",
"(",
"data",
",",
"filename",
",",
"relation_name",
"=",
"None",
",",
"index",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"fp",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"if",
"relation_... | Write ARFF file
Parameters
----------
data : :class:`pandas.DataFrame`
DataFrame containing data
filename : string or file-like object
Path to ARFF file or file-like object. In the latter case,
the handle is closed by calling this function.
relation_name : string, optional, default: "pandas"
Name of relation in ARFF file.
index : boolean, optional, default: True
Write row names (index) | [
"Write",
"ARFF",
"file"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L23-L57 |
246,589 | sebp/scikit-survival | sksurv/io/arffwrite.py | _write_header | def _write_header(data, fp, relation_name, index):
"""Write header containing attribute names and types"""
fp.write("@relation {0}\n\n".format(relation_name))
if index:
data = data.reset_index()
attribute_names = _sanitize_column_names(data)
for column, series in data.iteritems():
name = attribute_names[column]
fp.write("@attribute {0}\t".format(name))
if is_categorical_dtype(series) or is_object_dtype(series):
_write_attribute_categorical(series, fp)
elif numpy.issubdtype(series.dtype, numpy.floating):
fp.write("real")
elif numpy.issubdtype(series.dtype, numpy.integer):
fp.write("integer")
elif numpy.issubdtype(series.dtype, numpy.datetime64):
fp.write("date 'yyyy-MM-dd HH:mm:ss'")
else:
raise TypeError('unsupported type %s' % series.dtype)
fp.write("\n")
return data | python | def _write_header(data, fp, relation_name, index):
fp.write("@relation {0}\n\n".format(relation_name))
if index:
data = data.reset_index()
attribute_names = _sanitize_column_names(data)
for column, series in data.iteritems():
name = attribute_names[column]
fp.write("@attribute {0}\t".format(name))
if is_categorical_dtype(series) or is_object_dtype(series):
_write_attribute_categorical(series, fp)
elif numpy.issubdtype(series.dtype, numpy.floating):
fp.write("real")
elif numpy.issubdtype(series.dtype, numpy.integer):
fp.write("integer")
elif numpy.issubdtype(series.dtype, numpy.datetime64):
fp.write("date 'yyyy-MM-dd HH:mm:ss'")
else:
raise TypeError('unsupported type %s' % series.dtype)
fp.write("\n")
return data | [
"def",
"_write_header",
"(",
"data",
",",
"fp",
",",
"relation_name",
",",
"index",
")",
":",
"fp",
".",
"write",
"(",
"\"@relation {0}\\n\\n\"",
".",
"format",
"(",
"relation_name",
")",
")",
"if",
"index",
":",
"data",
"=",
"data",
".",
"reset_index",
... | Write header containing attribute names and types | [
"Write",
"header",
"containing",
"attribute",
"names",
"and",
"types"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L60-L85 |
246,590 | sebp/scikit-survival | sksurv/io/arffwrite.py | _sanitize_column_names | def _sanitize_column_names(data):
"""Replace illegal characters with underscore"""
new_names = {}
for name in data.columns:
new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name)
return new_names | python | def _sanitize_column_names(data):
new_names = {}
for name in data.columns:
new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name)
return new_names | [
"def",
"_sanitize_column_names",
"(",
"data",
")",
":",
"new_names",
"=",
"{",
"}",
"for",
"name",
"in",
"data",
".",
"columns",
":",
"new_names",
"[",
"name",
"]",
"=",
"_ILLEGAL_CHARACTER_PAT",
".",
"sub",
"(",
"\"_\"",
",",
"name",
")",
"return",
"new... | Replace illegal characters with underscore | [
"Replace",
"illegal",
"characters",
"with",
"underscore"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L88-L93 |
246,591 | sebp/scikit-survival | sksurv/io/arffwrite.py | _write_data | def _write_data(data, fp):
"""Write the data section"""
fp.write("@data\n")
def to_str(x):
if pandas.isnull(x):
return '?'
else:
return str(x)
data = data.applymap(to_str)
n_rows = data.shape[0]
for i in range(n_rows):
str_values = list(data.iloc[i, :].apply(_check_str_array))
line = ",".join(str_values)
fp.write(line)
fp.write("\n") | python | def _write_data(data, fp):
fp.write("@data\n")
def to_str(x):
if pandas.isnull(x):
return '?'
else:
return str(x)
data = data.applymap(to_str)
n_rows = data.shape[0]
for i in range(n_rows):
str_values = list(data.iloc[i, :].apply(_check_str_array))
line = ",".join(str_values)
fp.write(line)
fp.write("\n") | [
"def",
"_write_data",
"(",
"data",
",",
"fp",
")",
":",
"fp",
".",
"write",
"(",
"\"@data\\n\"",
")",
"def",
"to_str",
"(",
"x",
")",
":",
"if",
"pandas",
".",
"isnull",
"(",
"x",
")",
":",
"return",
"'?'",
"else",
":",
"return",
"str",
"(",
"x",... | Write the data section | [
"Write",
"the",
"data",
"section"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L130-L146 |
246,592 | sebp/scikit-survival | sksurv/meta/stacking.py | Stacking.fit | def fit(self, X, y=None, **fit_params):
"""Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self
"""
X = numpy.asarray(X)
self._fit_estimators(X, y, **fit_params)
Xt = self._predict_estimators(X)
self.meta_estimator.fit(Xt, y)
return self | python | def fit(self, X, y=None, **fit_params):
X = numpy.asarray(X)
self._fit_estimators(X, y, **fit_params)
Xt = self._predict_estimators(X)
self.meta_estimator.fit(Xt, y)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"fit_params",
")",
":",
"X",
"=",
"numpy",
".",
"asarray",
"(",
"X",
")",
"self",
".",
"_fit_estimators",
"(",
"X",
",",
"y",
",",
"*",
"*",
"fit_params",
")",
"Xt",
"... | Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self | [
"Fit",
"base",
"estimators",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/stacking.py#L115-L135 |
246,593 | sebp/scikit-survival | sksurv/column.py | standardize | def standardize(table, with_std=True):
"""
Perform Z-Normalization on each numeric column of the given table.
Parameters
----------
table : pandas.DataFrame or numpy.ndarray
Data to standardize.
with_std : bool, optional, default: True
If ``False`` data is only centered and not converted to unit variance.
Returns
-------
normalized : pandas.DataFrame
Table with numeric columns normalized.
Categorical columns in the input table remain unchanged.
"""
if isinstance(table, pandas.DataFrame):
cat_columns = table.select_dtypes(include=['category']).columns
else:
cat_columns = []
new_frame = _apply_along_column(table, standardize_column, with_std=with_std)
# work around for apply converting category dtype to object
# https://github.com/pydata/pandas/issues/9573
for col in cat_columns:
new_frame[col] = table[col].copy()
return new_frame | python | def standardize(table, with_std=True):
if isinstance(table, pandas.DataFrame):
cat_columns = table.select_dtypes(include=['category']).columns
else:
cat_columns = []
new_frame = _apply_along_column(table, standardize_column, with_std=with_std)
# work around for apply converting category dtype to object
# https://github.com/pydata/pandas/issues/9573
for col in cat_columns:
new_frame[col] = table[col].copy()
return new_frame | [
"def",
"standardize",
"(",
"table",
",",
"with_std",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"pandas",
".",
"DataFrame",
")",
":",
"cat_columns",
"=",
"table",
".",
"select_dtypes",
"(",
"include",
"=",
"[",
"'category'",
"]",
")",
... | Perform Z-Normalization on each numeric column of the given table.
Parameters
----------
table : pandas.DataFrame or numpy.ndarray
Data to standardize.
with_std : bool, optional, default: True
If ``False`` data is only centered and not converted to unit variance.
Returns
-------
normalized : pandas.DataFrame
Table with numeric columns normalized.
Categorical columns in the input table remain unchanged. | [
"Perform",
"Z",
"-",
"Normalization",
"on",
"each",
"numeric",
"column",
"of",
"the",
"given",
"table",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L47-L77 |
246,594 | sebp/scikit-survival | sksurv/column.py | encode_categorical | def encode_categorical(table, columns=None, **kwargs):
"""
Encode categorical columns with `M` categories into `M-1` columns according
to the one-hot scheme.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
columns : list-like, optional, default: None
Column names in the DataFrame to be encoded.
If `columns` is None then all the columns with
`object` or `category` dtype will be converted.
allow_drop : boolean, optional, default: True
Whether to allow dropping categorical columns that only consist
of a single category.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged.
"""
if isinstance(table, pandas.Series):
if not is_categorical_dtype(table.dtype) and not table.dtype.char == "O":
raise TypeError("series must be of categorical dtype, but was {}".format(table.dtype))
return _encode_categorical_series(table, **kwargs)
def _is_categorical_or_object(series):
return is_categorical_dtype(series.dtype) or series.dtype.char == "O"
if columns is None:
# for columns containing categories
columns_to_encode = {nam for nam, s in table.iteritems() if _is_categorical_or_object(s)}
else:
columns_to_encode = set(columns)
items = []
for name, series in table.iteritems():
if name in columns_to_encode:
series = _encode_categorical_series(series, **kwargs)
if series is None:
continue
items.append(series)
# concat columns of tables
new_table = pandas.concat(items, axis=1, copy=False)
return new_table | python | def encode_categorical(table, columns=None, **kwargs):
if isinstance(table, pandas.Series):
if not is_categorical_dtype(table.dtype) and not table.dtype.char == "O":
raise TypeError("series must be of categorical dtype, but was {}".format(table.dtype))
return _encode_categorical_series(table, **kwargs)
def _is_categorical_or_object(series):
return is_categorical_dtype(series.dtype) or series.dtype.char == "O"
if columns is None:
# for columns containing categories
columns_to_encode = {nam for nam, s in table.iteritems() if _is_categorical_or_object(s)}
else:
columns_to_encode = set(columns)
items = []
for name, series in table.iteritems():
if name in columns_to_encode:
series = _encode_categorical_series(series, **kwargs)
if series is None:
continue
items.append(series)
# concat columns of tables
new_table = pandas.concat(items, axis=1, copy=False)
return new_table | [
"def",
"encode_categorical",
"(",
"table",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"pandas",
".",
"Series",
")",
":",
"if",
"not",
"is_categorical_dtype",
"(",
"table",
".",
"dtype",
")",
"... | Encode categorical columns with `M` categories into `M-1` columns according
to the one-hot scheme.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
columns : list-like, optional, default: None
Column names in the DataFrame to be encoded.
If `columns` is None then all the columns with
`object` or `category` dtype will be converted.
allow_drop : boolean, optional, default: True
Whether to allow dropping categorical columns that only consist
of a single category.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged. | [
"Encode",
"categorical",
"columns",
"with",
"M",
"categories",
"into",
"M",
"-",
"1",
"columns",
"according",
"to",
"the",
"one",
"-",
"hot",
"scheme",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L97-L146 |
246,595 | sebp/scikit-survival | sksurv/column.py | categorical_to_numeric | def categorical_to_numeric(table):
"""Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged.
"""
def transform(column):
if is_categorical_dtype(column.dtype):
return column.cat.codes
if column.dtype.char == "O":
try:
nc = column.astype(numpy.int64)
except ValueError:
classes = column.dropna().unique()
classes.sort(kind="mergesort")
nc = column.replace(classes, numpy.arange(classes.shape[0]))
return nc
elif column.dtype == bool:
return column.astype(numpy.int64)
return column
if isinstance(table, pandas.Series):
return pandas.Series(transform(table), name=table.name, index=table.index)
else:
if _pandas_version_under0p23:
return table.apply(transform, axis=0, reduce=False)
else:
return table.apply(transform, axis=0, result_type='reduce') | python | def categorical_to_numeric(table):
def transform(column):
if is_categorical_dtype(column.dtype):
return column.cat.codes
if column.dtype.char == "O":
try:
nc = column.astype(numpy.int64)
except ValueError:
classes = column.dropna().unique()
classes.sort(kind="mergesort")
nc = column.replace(classes, numpy.arange(classes.shape[0]))
return nc
elif column.dtype == bool:
return column.astype(numpy.int64)
return column
if isinstance(table, pandas.Series):
return pandas.Series(transform(table), name=table.name, index=table.index)
else:
if _pandas_version_under0p23:
return table.apply(transform, axis=0, reduce=False)
else:
return table.apply(transform, axis=0, result_type='reduce') | [
"def",
"categorical_to_numeric",
"(",
"table",
")",
":",
"def",
"transform",
"(",
"column",
")",
":",
"if",
"is_categorical_dtype",
"(",
"column",
".",
"dtype",
")",
":",
"return",
"column",
".",
"cat",
".",
"codes",
"if",
"column",
".",
"dtype",
".",
"c... | Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
Numeric columns in the input table remain unchanged. | [
"Encode",
"categorical",
"columns",
"to",
"numeric",
"by",
"converting",
"each",
"category",
"to",
"an",
"integer",
"value",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L171-L208 |
246,596 | sebp/scikit-survival | sksurv/util.py | check_y_survival | def check_y_survival(y_or_event, *args, allow_all_censored=False):
"""Check that array correctly represents an outcome for survival analysis.
Parameters
----------
y_or_event : structured array with two fields, or boolean array
If a structured array, it must contain the binary event indicator
as first field, and time of event or time of censoring as
second field. Otherwise, it is assumed that a boolean array
representing the event indicator is passed.
*args : list of array-likes
Any number of array-like objects representing time information.
Elements that are `None` are passed along in the return value.
allow_all_censored : bool, optional, default: False
Whether to allow all events to be censored.
Returns
-------
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring.
"""
if len(args) == 0:
y = y_or_event
if not isinstance(y, numpy.ndarray) or y.dtype.fields is None or len(y.dtype.fields) != 2:
raise ValueError('y must be a structured array with the first field'
' being a binary class event indicator and the second field'
' the time of the event/censoring')
event_field, time_field = y.dtype.names
y_event = y[event_field]
time_args = (y[time_field],)
else:
y_event = numpy.asanyarray(y_or_event)
time_args = args
event = check_array(y_event, ensure_2d=False)
if not numpy.issubdtype(event.dtype, numpy.bool_):
raise ValueError('elements of event indicator must be boolean, but found {0}'.format(event.dtype))
if not (allow_all_censored or numpy.any(event)):
raise ValueError('all samples are censored')
return_val = [event]
for i, yt in enumerate(time_args):
if yt is None:
return_val.append(yt)
continue
yt = check_array(yt, ensure_2d=False)
if not numpy.issubdtype(yt.dtype, numpy.number):
raise ValueError('time must be numeric, but found {} for argument {}'.format(yt.dtype, i + 2))
return_val.append(yt)
return tuple(return_val) | python | def check_y_survival(y_or_event, *args, allow_all_censored=False):
if len(args) == 0:
y = y_or_event
if not isinstance(y, numpy.ndarray) or y.dtype.fields is None or len(y.dtype.fields) != 2:
raise ValueError('y must be a structured array with the first field'
' being a binary class event indicator and the second field'
' the time of the event/censoring')
event_field, time_field = y.dtype.names
y_event = y[event_field]
time_args = (y[time_field],)
else:
y_event = numpy.asanyarray(y_or_event)
time_args = args
event = check_array(y_event, ensure_2d=False)
if not numpy.issubdtype(event.dtype, numpy.bool_):
raise ValueError('elements of event indicator must be boolean, but found {0}'.format(event.dtype))
if not (allow_all_censored or numpy.any(event)):
raise ValueError('all samples are censored')
return_val = [event]
for i, yt in enumerate(time_args):
if yt is None:
return_val.append(yt)
continue
yt = check_array(yt, ensure_2d=False)
if not numpy.issubdtype(yt.dtype, numpy.number):
raise ValueError('time must be numeric, but found {} for argument {}'.format(yt.dtype, i + 2))
return_val.append(yt)
return tuple(return_val) | [
"def",
"check_y_survival",
"(",
"y_or_event",
",",
"*",
"args",
",",
"allow_all_censored",
"=",
"False",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"y",
"=",
"y_or_event",
"if",
"not",
"isinstance",
"(",
"y",
",",
"numpy",
".",
"ndarray",... | Check that array correctly represents an outcome for survival analysis.
Parameters
----------
y_or_event : structured array with two fields, or boolean array
If a structured array, it must contain the binary event indicator
as first field, and time of event or time of censoring as
second field. Otherwise, it is assumed that a boolean array
representing the event indicator is passed.
*args : list of array-likes
Any number of array-like objects representing time information.
Elements that are `None` are passed along in the return value.
allow_all_censored : bool, optional, default: False
Whether to allow all events to be censored.
Returns
-------
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring. | [
"Check",
"that",
"array",
"correctly",
"represents",
"an",
"outcome",
"for",
"survival",
"analysis",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L104-L164 |
246,597 | sebp/scikit-survival | sksurv/util.py | check_arrays_survival | def check_arrays_survival(X, y, **kwargs):
"""Check that all arrays have consistent first dimensions.
Parameters
----------
X : array-like
Data matrix containing feature vectors.
y : structured array with two fields
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
kwargs : dict
Additional arguments passed to :func:`sklearn.utils.check_array`.
Returns
-------
X : array, shape=[n_samples, n_features]
Feature vectors.
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring.
"""
event, time = check_y_survival(y)
kwargs.setdefault("dtype", numpy.float64)
X = check_array(X, ensure_min_samples=2, **kwargs)
check_consistent_length(X, event, time)
return X, event, time | python | def check_arrays_survival(X, y, **kwargs):
event, time = check_y_survival(y)
kwargs.setdefault("dtype", numpy.float64)
X = check_array(X, ensure_min_samples=2, **kwargs)
check_consistent_length(X, event, time)
return X, event, time | [
"def",
"check_arrays_survival",
"(",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"y",
")",
"kwargs",
".",
"setdefault",
"(",
"\"dtype\"",
",",
"numpy",
".",
"float64",
")",
"X",
"=",
"check_arra... | Check that all arrays have consistent first dimensions.
Parameters
----------
X : array-like
Data matrix containing feature vectors.
y : structured array with two fields
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
kwargs : dict
Additional arguments passed to :func:`sklearn.utils.check_array`.
Returns
-------
X : array, shape=[n_samples, n_features]
Feature vectors.
event : array, shape=[n_samples,], dtype=bool
Binary event indicator.
time : array, shape=[n_samples,], dtype=float
Time of event or censoring. | [
"Check",
"that",
"all",
"arrays",
"have",
"consistent",
"first",
"dimensions",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L167-L198 |
246,598 | sebp/scikit-survival | sksurv/util.py | Surv.from_arrays | def from_arrays(event, time, name_event=None, name_time=None):
"""Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
Name of event, optional, default: 'event'
name_time : str|None
Name of observed time, optional, default: 'time'
Returns
-------
y : np.array
Structured array with two fields.
"""
name_event = name_event or 'event'
name_time = name_time or 'time'
if name_time == name_event:
raise ValueError('name_time must be different from name_event')
time = numpy.asanyarray(time, dtype=numpy.float_)
y = numpy.empty(time.shape[0],
dtype=[(name_event, numpy.bool_), (name_time, numpy.float_)])
y[name_time] = time
event = numpy.asanyarray(event)
check_consistent_length(time, event)
if numpy.issubdtype(event.dtype, numpy.bool_):
y[name_event] = event
else:
events = numpy.unique(event)
events.sort()
if len(events) != 2:
raise ValueError('event indicator must be binary')
if numpy.all(events == numpy.array([0, 1], dtype=events.dtype)):
y[name_event] = event.astype(numpy.bool_)
else:
raise ValueError('non-boolean event indicator must contain 0 and 1 only')
return y | python | def from_arrays(event, time, name_event=None, name_time=None):
name_event = name_event or 'event'
name_time = name_time or 'time'
if name_time == name_event:
raise ValueError('name_time must be different from name_event')
time = numpy.asanyarray(time, dtype=numpy.float_)
y = numpy.empty(time.shape[0],
dtype=[(name_event, numpy.bool_), (name_time, numpy.float_)])
y[name_time] = time
event = numpy.asanyarray(event)
check_consistent_length(time, event)
if numpy.issubdtype(event.dtype, numpy.bool_):
y[name_event] = event
else:
events = numpy.unique(event)
events.sort()
if len(events) != 2:
raise ValueError('event indicator must be binary')
if numpy.all(events == numpy.array([0, 1], dtype=events.dtype)):
y[name_event] = event.astype(numpy.bool_)
else:
raise ValueError('non-boolean event indicator must contain 0 and 1 only')
return y | [
"def",
"from_arrays",
"(",
"event",
",",
"time",
",",
"name_event",
"=",
"None",
",",
"name_time",
"=",
"None",
")",
":",
"name_event",
"=",
"name_event",
"or",
"'event'",
"name_time",
"=",
"name_time",
"or",
"'time'",
"if",
"name_time",
"==",
"name_event",
... | Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
Name of event, optional, default: 'event'
name_time : str|None
Name of observed time, optional, default: 'time'
Returns
-------
y : np.array
Structured array with two fields. | [
"Create",
"structured",
"array",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L28-L73 |
246,599 | sebp/scikit-survival | sksurv/util.py | Surv.from_dataframe | def from_dataframe(event, time, data):
"""Create structured array from data frame.
Parameters
----------
event : object
Identifier of column containing event indicator.
time : object
Identifier of column containing time.
data : pandas.DataFrame
Dataset.
Returns
-------
y : np.array
Structured array with two fields.
"""
if not isinstance(data, pandas.DataFrame):
raise TypeError(
"exepected pandas.DataFrame, but got {!r}".format(type(data)))
return Surv.from_arrays(
data.loc[:, event].values,
data.loc[:, time].values,
name_event=str(event),
name_time=str(time)) | python | def from_dataframe(event, time, data):
if not isinstance(data, pandas.DataFrame):
raise TypeError(
"exepected pandas.DataFrame, but got {!r}".format(type(data)))
return Surv.from_arrays(
data.loc[:, event].values,
data.loc[:, time].values,
name_event=str(event),
name_time=str(time)) | [
"def",
"from_dataframe",
"(",
"event",
",",
"time",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"pandas",
".",
"DataFrame",
")",
":",
"raise",
"TypeError",
"(",
"\"exepected pandas.DataFrame, but got {!r}\"",
".",
"format",
"(",
"type",... | Create structured array from data frame.
Parameters
----------
event : object
Identifier of column containing event indicator.
time : object
Identifier of column containing time.
data : pandas.DataFrame
Dataset.
Returns
-------
y : np.array
Structured array with two fields. | [
"Create",
"structured",
"array",
"from",
"data",
"frame",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L76-L101 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.