Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def create_branches(self, branches):
if not isinstance(branches, TreeBuffer):
branches = TreeBuffer(branches)
self.set_buffer(branches, create_branches=True) | [
"\n Create branches from a TreeBuffer or dict mapping names to type names\n\n Parameters\n ----------\n branches : TreeBuffer or dict\n "
] |
Please provide a description of the function:def update_buffer(self, treebuffer, transfer_objects=False):
self._buffer.update(treebuffer)
if transfer_objects:
self._buffer.set_objects(treebuffer) | [
"\n Merge items from a TreeBuffer into this Tree's TreeBuffer\n\n Parameters\n ----------\n buffer : rootpy.tree.buffer.TreeBuffer\n The TreeBuffer to merge into this Tree's buffer\n\n transfer_objects : bool, optional (default=False)\n If True then all objec... |
Please provide a description of the function:def set_buffer(self, treebuffer,
branches=None,
ignore_branches=None,
create_branches=False,
visible=True,
ignore_missing=False,
ignore_duplicates=False,
... | [
"\n Set the Tree buffer\n\n Parameters\n ----------\n treebuffer : rootpy.tree.buffer.TreeBuffer\n a TreeBuffer\n\n branches : list, optional (default=None)\n only include these branches from the TreeBuffer\n\n ignore_branches : list, optional (default... |
Please provide a description of the function:def glob(self, patterns, exclude=None):
if isinstance(patterns, string_types):
patterns = [patterns]
if isinstance(exclude, string_types):
exclude = [exclude]
matches = []
for pattern in patterns:
m... | [
"\n Return a list of branch names that match ``pattern``.\n Exclude all matched branch names which also match a pattern in\n ``exclude``. ``exclude`` may be a string or list of strings.\n\n Parameters\n ----------\n patterns: str or list\n branches are matched ag... |
Please provide a description of the function:def GetEntry(self, entry):
if not (0 <= entry < self.GetEntries()):
raise IndexError("entry index out of range: {0:d}".format(entry))
self._buffer.reset_collections()
return super(BaseTree, self).GetEntry(entry) | [
"\n Get an entry. Tree collections are reset\n (see ``rootpy.tree.treeobject``)\n\n Parameters\n ----------\n entry : int\n entry index\n\n Returns\n -------\n ROOT.TTree.GetEntry : int\n The number of bytes read\n "
] |
Please provide a description of the function:def csv(self, sep=',', branches=None,
include_labels=True, limit=None,
stream=None):
supported_types = (Scalar, Array, stl.string)
if stream is None:
stream = sys.stdout
if not self._buffer:
sel... | [
"\n Print csv representation of tree only including branches\n of basic types (no objects, vectors, etc..)\n\n Parameters\n ----------\n sep : str, optional (default=',')\n The delimiter used to separate columns\n\n branches : list, optional (default=None)\n ... |
Please provide a description of the function:def GetEntries(self, cut=None, weighted_cut=None, weighted=False):
if weighted_cut:
hist = Hist(1, -1, 2)
branch = self.GetListOfBranches()[0].GetName()
weight = self.GetWeight()
self.SetWeight(1)
s... | [
"\n Get the number of (weighted) entries in the Tree\n\n Parameters\n ----------\n cut : str or rootpy.tree.cut.Cut, optional (default=None)\n Only entries passing this cut will be included in the count\n\n weighted_cut : str or rootpy.tree.cut.Cut, optional (default=No... |
Please provide a description of the function:def GetMaximum(self, expression, cut=None):
if cut:
self.Draw(expression, cut, 'goff')
else:
self.Draw(expression, '', 'goff')
vals = self.GetV1()
n = self.GetSelectedRows()
vals = [vals[i] for i in ran... | [
"\n TODO: we need a better way of determining the maximum value of an\n expression.\n "
] |
Please provide a description of the function:def GetMinimum(self, expression, cut=None):
if cut:
self.Draw(expression, cut, "goff")
else:
self.Draw(expression, "", "goff")
vals = self.GetV1()
n = self.GetSelectedRows()
vals = [vals[i] for i in ran... | [
"\n TODO: we need a better way of determining the minimum value of an\n expression.\n "
] |
Please provide a description of the function:def CopyTree(self, selection, *args, **kwargs):
return super(BaseTree, self).CopyTree(str(selection), *args, **kwargs) | [
"\n Copy the tree while supporting a rootpy.tree.cut.Cut selection in\n addition to a simple string.\n "
] |
Please provide a description of the function:def Draw(self,
expression,
selection="",
options="",
hist=None,
create_hist=False,
**kwargs):
if isinstance(expression, string_types):
# Check that we have a valid draw... | [
"\n Draw a TTree with a selection as usual, but return the created\n histogram.\n\n Parameters\n ----------\n expression : str\n The expression to draw. Multidimensional expressions are separated\n by \":\". rootpy reverses the expressions along each dimensio... |
Please provide a description of the function:def to_array(self, *args, **kwargs):
from root_numpy import tree2array
return tree2array(self, *args, **kwargs) | [
"\n Convert this tree into a NumPy structured array\n "
] |
Please provide a description of the function:def color_key(tkey):
name = tkey.GetName()
classname = tkey.GetClassName()
for class_regex, color in _COLOR_MATCHER:
if class_regex.match(classname):
return colored(name, color=color)
return name | [
"\n Function which returns a colorized TKey name given its type\n "
] |
Please provide a description of the function:def plot_corrcoef_matrix(matrix, names=None,
cmap=None, cmap_text=None,
fontsize=12, grid=False,
axes=None):
import numpy as np
from matplotlib import pyplot as plt
from matplotlib im... | [
"\n This function will draw a lower-triangular correlation matrix\n\n Parameters\n ----------\n\n matrix : 2-dimensional numpy array/matrix\n A correlation coefficient matrix\n\n names : list of strings, optional (default=None)\n List of the parameter names corresponding to the rows in ... |
Please provide a description of the function:def cov(m, y=None, rowvar=1, bias=0, ddof=None, weights=None, repeat_weights=0):
import numpy as np
# Check inputs
if ddof is not None and ddof != int(ddof):
raise ValueError(
"ddof must be integer")
X = np.array(m, ndmin=2, dtype=fl... | [
"\n Estimate a covariance matrix, given data.\n\n Covariance indicates the level to which two variables vary together.\n If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,\n then the covariance matrix element :math:`C_{ij}` is the covariance of\n :math:`x_i` and :math:`x_j`. The ... |
Please provide a description of the function:def corrcoef(x, y=None, rowvar=1, bias=0, ddof=None, weights=None,
repeat_weights=0):
import numpy as np
c = cov(x, y, rowvar, bias, ddof, weights, repeat_weights)
if c.size == 0:
# handle empty arrays
return c
try:
d... | [
"\n Return correlation coefficients.\n\n Please refer to the documentation for `cov` for more detail. The\n relationship between the correlation coefficient matrix, `P`, and the\n covariance matrix, `C`, is\n\n .. math:: P_{ij} = \\\\frac{ C_{ij} } { \\\\sqrt{ C_{ii} * C_{jj} } }\n\n The values o... |
Please provide a description of the function:def safe(self, parentheses=True):
if not self:
return ""
string = str(self)
string = string.replace("**", "_pow_")
string = string.replace("*", "_mul_")
string = string.replace("/", "_div_")
string = string... | [
"\n Returns a string representation with special characters\n replaced by safer characters for use in file names.\n "
] |
Please provide a description of the function:def latex(self):
if not self:
return ""
s = str(self)
s = s.replace("==", " = ")
s = s.replace("<=", " \leq ")
s = s.replace(">=", " \geq ")
s = s.replace("&&", r" \text{ and } ")
s = s.replace("||"... | [
"\n Returns a string representation for use in LaTeX\n "
] |
Please provide a description of the function:def replace(self, name, newname):
if not re.match("[a-zA-Z]\w*", name):
return None
if not re.match("[a-zA-Z]\w*", newname):
return None
def _replace(match):
return match.group(0).replace(match.group('name... | [
"\n Replace all occurrences of name with newname\n "
] |
Please provide a description of the function:def _findlinestarts(code):
lineno = code.co_firstlineno
addr = 0
for byte_incr, line_incr in zip(code.co_lnotab[0::2], code.co_lnotab[1::2]):
if byte_incr:
yield addr, lineno
addr += byte_incr
... | [
"Find the offsets in a byte code which are start of lines in the source\n Generate pairs offset,lineno as described in Python/compile.c\n This is a modified version of dis.findlinestarts, which allows multiplelinestarts\n with the same line number"
] |
Please provide a description of the function:def from_code(cls, co):
free_cell_isection = set(co.co_cellvars) & set(co.co_freevars)
if free_cell_isection:
print(co.co_name + ': has non-empty co.co_cellvars & co.co_freevars', free_cell_isection)
return None
co_co... | [
"Disassemble a Python code object into a Code object"
] |
Please provide a description of the function:def save_image(self, image_file):
self.ensure_pyplot()
command = 'plt.gcf().savefig("%s")'%image_file
#print 'SAVEFIG', command # dbg
self.process_input_line('bookmark ipy_thisdir', store_history=False)
self.process_input_lin... | [
"\n Saves the image file to disk.\n "
] |
Please provide a description of the function:def process_pure_python(self, content):
output = []
savefig = False # keep up with this to clear figure
multiline = False # to handle line continuation
multiline_start = None
fmtin = self.promptin
ct = 0
for ... | [
"\n content is a list of strings. it is unedited directive conent\n\n This runs it line by line in the InteractiveShell, prepends\n prompts as needed capturing stderr and stdout, then returns\n the content as a list as if it were ipython code\n "
] |
Please provide a description of the function:def convert_markerstyle(inputstyle, mode, inputmode=None):
mode = mode.lower()
if mode not in ('mpl', 'root'):
raise ValueError("`{0}` is not valid `mode`".format(mode))
if inputmode is None:
if inputstyle in markerstyles_root2mpl:
... | [
"\n Convert *inputstyle* to ROOT or matplotlib format.\n\n Output format is determined by *mode* ('root' or 'mpl'). The *inputstyle*\n may be a ROOT marker style, a matplotlib marker style, or a description\n such as 'star' or 'square'.\n "
] |
Please provide a description of the function:def convert_linestyle(inputstyle, mode, inputmode=None):
mode = mode.lower()
if mode not in ('mpl', 'root'):
raise ValueError(
"`{0}` is not a valid `mode`".format(mode))
try:
inputstyle = int(inputstyle)
if inputstyle < 1... | [
"\n Convert *inputstyle* to ROOT or matplotlib format.\n\n Output format is determined by *mode* ('root' or 'mpl'). The *inputstyle*\n may be a ROOT line style, a matplotlib line style, or a description\n such as 'solid' or 'dotted'.\n "
] |
Please provide a description of the function:def convert_fillstyle(inputstyle, mode, inputmode=None):
mode = mode.lower()
if mode not in ('mpl', 'root'):
raise ValueError("`{0}` is not a valid `mode`".format(mode))
if inputmode is None:
try:
# inputstyle is a ROOT linestyle
... | [
"\n Convert *inputstyle* to ROOT or matplotlib format.\n\n Output format is determined by *mode* ('root' or 'mpl'). The *inputstyle*\n may be a ROOT fill style, a matplotlib hatch style, None, 'none', 'hollow',\n or 'solid'.\n "
] |
Please provide a description of the function:def convert_color(color, mode):
mode = mode.lower()
if mode not in ('mpl', 'root'):
raise ValueError(
"`{0}` is not a valid `mode`".format(mode))
try:
# color is an r,g,b tuple
color = tuple([float(x) for x in color[:3]])
... | [
"\n Convert *color* to a TColor if *mode='root'* or to (r,g,b) if 'mpl'.\n\n The *color* argument can be a ROOT TColor or color index, an *RGB*\n or *RGBA* sequence or a string in any of several forms:\n\n 1) a letter from the set 'rgbcmykw'\n 2) a hex color string, like '#00FFFF'\n 3)... |
Please provide a description of the function:def _clone_post_init(self, obj=None, **kwargs):
# Initialize the extra attributes
if obj is None or obj is self:
# We must be asrootpy-ing a ROOT object
# or freshly init-ing a rootpy object
for attr, value in Plot... | [
"\n obj must be another Plottable instance. obj is used by Clone to properly\n transfer all attributes onto this object.\n "
] |
Please provide a description of the function:def decorate(self, other=None, **kwargs):
if 'color' in kwargs:
incompatible = []
for othercolor in ('linecolor', 'fillcolor', 'markercolor'):
if othercolor in kwargs:
incompatible.append(othercolor... | [
"\n Apply style options to a Plottable object.\n\n Returns a reference to self.\n "
] |
Please provide a description of the function:def SetLineColor(self, color):
self._linecolor = Color(color)
if isinstance(self, ROOT.TAttLine):
ROOT.TAttLine.SetLineColor(self, self._linecolor('root')) | [
"\n *color* may be any color understood by ROOT or matplotlib.\n\n For full documentation of accepted *color* arguments, see\n :class:`rootpy.plotting.style.Color`.\n "
] |
Please provide a description of the function:def SetLineStyle(self, style):
self._linestyle = LineStyle(style)
if isinstance(self, ROOT.TAttLine):
ROOT.TAttLine.SetLineStyle(self, self._linestyle('root')) | [
"\n *style* may be any line style understood by ROOT or matplotlib.\n\n For full documentation of accepted *style* arguments, see\n :class:`rootpy.plotting.style.LineStyle`.\n "
] |
Please provide a description of the function:def SetFillColor(self, color):
self._fillcolor = Color(color)
if isinstance(self, ROOT.TAttFill):
ROOT.TAttFill.SetFillColor(self, self._fillcolor('root')) | [
"\n *color* may be any color understood by ROOT or matplotlib.\n\n For full documentation of accepted *color* arguments, see\n :class:`rootpy.plotting.style.Color`.\n "
] |
Please provide a description of the function:def SetFillStyle(self, style):
self._fillstyle = FillStyle(style)
if isinstance(self, ROOT.TAttFill):
ROOT.TAttFill.SetFillStyle(self, self._fillstyle('root')) | [
"\n *style* may be any fill style understood by ROOT or matplotlib.\n\n For full documentation of accepted *style* arguments, see\n :class:`rootpy.plotting.style.FillStyle`.\n "
] |
Please provide a description of the function:def SetMarkerColor(self, color):
self._markercolor = Color(color)
if isinstance(self, ROOT.TAttMarker):
ROOT.TAttMarker.SetMarkerColor(self, self._markercolor('root')) | [
"\n *color* may be any color understood by ROOT or matplotlib.\n\n For full documentation of accepted *color* arguments, see\n :class:`rootpy.plotting.style.Color`.\n "
] |
Please provide a description of the function:def SetMarkerStyle(self, style):
self._markerstyle = MarkerStyle(style)
if isinstance(self, ROOT.TAttMarker):
ROOT.TAttMarker.SetMarkerStyle(self, self._markerstyle('root')) | [
"\n *style* may be any marker style understood by ROOT or matplotlib.\n\n For full documentation of accepted *style* arguments, see\n :class:`rootpy.plotting.style.MarkerStyle`.\n "
] |
Please provide a description of the function:def SetColor(self, color):
self.SetFillColor(color)
self.SetLineColor(color)
self.SetMarkerColor(color) | [
"\n *color* may be any color understood by ROOT or matplotlib.\n\n Set all color attributes with one method call.\n\n For full documentation of accepted *color* arguments, see\n :class:`rootpy.plotting.style.Color`.\n "
] |
Please provide a description of the function:def Draw(self, *args, **kwargs):
if kwargs:
return self.DrawCopy(*args, **kwargs)
pad = ROOT.gPad
own_pad = False
if not pad:
# avoid circular import by delaying import until needed here
from .canv... | [
"\n Parameters\n ----------\n args : positional arguments\n Positional arguments are passed directly to ROOT's Draw\n kwargs : keyword arguments\n If keyword arguments are present, then a clone is drawn instead\n with DrawCopy, where the name, title, and ... |
Please provide a description of the function:def DrawCopy(self, *args, **kwargs):
copy = self.Clone(**kwargs)
copy.Draw(*args)
return copy | [
"\n Parameters\n ----------\n args : positional arguments\n Positional arguments are passed directly to ROOT's Draw\n kwargs : keyword arguments\n The name, title, and style attributes of the clone are\n taken from ``kwargs``.\n\n Returns\n ... |
Please provide a description of the function:def getitem(self, index):
if index >= getattr(self.tree, self.size):
raise IndexError(index)
if self.__cache_objects and index in self.__cache:
return self.__cache[index]
obj = self.tree_object_cls(self.tree, self.name... | [
"\n direct access without going through self.selection\n "
] |
Please provide a description of the function:def configure_defaults():
log.debug("configure_defaults()")
global initialized
initialized = True
if use_rootpy_handler:
# Need to do it again here, since it is overridden by ROOT.
set_error_handler(python_logging_error_handler)
if... | [
"\n This function is executed immediately after ROOT's finalSetup\n "
] |
Please provide a description of the function:def rp_module_level_in_stack():
from traceback import extract_stack
from rootpy import _ROOTPY_SOURCE_PATH
modlevel_files = [filename for filename, _, func, _ in extract_stack()
if func == "<module>"]
return any(path.startswith(_RO... | [
"\n Returns true if we're during a rootpy import\n "
] |
Please provide a description of the function:def monitor_deletion():
monitors = {}
def set_deleted(x):
def _(weakref):
del monitors[x]
return _
def monitor(item, name):
monitors[name] = ref(item, set_deleted(name))
def is_alive(name):
return monitors.g... | [
"\n Function for checking for correct deletion of weakref-able objects.\n\n Example usage::\n\n monitor, is_alive = monitor_deletion()\n obj = set()\n monitor(obj, \"obj\")\n assert is_alive(\"obj\") # True because there is a ref to `obj` is_alive\n del obj\n assert n... |
Please provide a description of the function:def draw(plottables, pad=None, same=False,
xaxis=None, yaxis=None,
xtitle=None, ytitle=None,
xlimits=None, ylimits=None,
xdivisions=None, ydivisions=None,
logx=False, logy=False,
**kwargs):
context = preserve_cur... | [
"\n Draw a list of histograms, stacks, and/or graphs.\n\n Parameters\n ----------\n plottables : Hist, Graph, HistStack, or list of such objects\n List of objects to draw.\n\n pad : Pad or Canvas, optional (default=None)\n The pad to draw onto. If None then use the current global pad.\n... |
Please provide a description of the function:def _limits_helper(x1, x2, a, b, snap=False):
if x2 < x1:
raise ValueError("x2 < x1")
if a + b >= 1:
raise ValueError("a + b >= 1")
if a < 0:
raise ValueError("a < 0")
if b < 0:
raise ValueError("b < 0")
if snap:
... | [
"\n Given x1, x2, a, b, where:\n\n x1 - x0 x3 - x2\n a = ------- , b = -------\n x3 - x0 x3 - x0\n\n determine the points x0 and x3:\n\n x0 x1 x2 x3\n |----------|-----------------|--------|\n\n "
] |
Please provide a description of the function:def get_limits(plottables,
xpadding=0,
ypadding=0.1,
xerror_in_padding=True,
yerror_in_padding=True,
snap=True,
logx=False,
logy=False,
logx_crop_value=1E-... | [
"\n Get the axes limits that should be used for a 1D histogram, graph, or stack\n of histograms.\n\n Parameters\n ----------\n\n plottables : Hist, Graph, HistStack, or list of such objects\n The object(s) for which visually pleasing plot boundaries are\n requested.\n\n xpadding : fl... |
Please provide a description of the function:def get_band(low_hist, high_hist, middle_hist=None):
npoints = low_hist.nbins(0)
band = Graph(npoints)
for i in range(npoints):
center = low_hist.x(i + 1)
width = low_hist.xwidth(i + 1)
low, high = low_hist.y(i + 1), high_hist.y(i + 1... | [
"\n Convert the low and high histograms into a TGraphAsymmErrors centered at\n the middle histogram if not None otherwise the middle between the low and\n high points, to be used to draw a (possibly asymmetric) error band.\n "
] |
Please provide a description of the function:def canvases_with(drawable):
return [c for c in ROOT.gROOT.GetListOfCanvases()
if drawable in find_all_primitives(c)] | [
"\n Return a list of all canvases where `drawable` has been painted.\n\n Note: This function is inefficient because it inspects all objects on all\n canvases, recursively. Avoid calling it if you have a large number of\n canvases and primitives.\n "
] |
Please provide a description of the function:def find_all_primitives(pad):
result = []
for primitive in pad.GetListOfPrimitives():
result.append(primitive)
if hasattr(primitive, "GetListOfFunctions"):
result.extend(primitive.GetListOfFunctions())
if hasattr(primitive, "G... | [
"\n Recursively find all primities on a pad, even those hiding behind a\n GetListOfFunctions() of a primitive\n "
] |
Please provide a description of the function:def tick_length_pixels(pad, xaxis, yaxis, xlength, ylength=None):
if ylength is None:
ylength = xlength
xaxis.SetTickLength(xlength / float(pad.height_pixels))
yaxis.SetTickLength(ylength / float(pad.width_pixels)) | [
"\n Set the axes tick lengths in pixels\n "
] |
Please provide a description of the function:def convert(origin, target, type):
_origin = origin.upper()
if _origin == 'ROOTCODE':
_origin = root_type_codes
elif _origin == 'ROOTNAME':
_origin = root_type_names
elif _origin == 'ARRAY':
_origin = python_codes
elif _origin... | [
"\n convert type from origin to target\n origin/target must be ROOTCODE, ROOTNAME, ARRAY, or NUMPY\n "
] |
Please provide a description of the function:def set(self, value):
if isinstance(value, BaseScalar):
self[0] = self.convert(value.value)
else:
self[0] = self.convert(value) | [
"Set the value"
] |
Please provide a description of the function:def reset(self):
if self.resetable:
for i in range(len(self)):
self[i] = self.default | [
"Reset the value to the default"
] |
Please provide a description of the function:def LHCb_label(side="L", status="final", text="", pad=None):
if pad is None:
pad = ROOT.gPad
with preserve_current_canvas():
pad.cd()
if side == "L":
l = ROOT.TPaveText(pad.GetLeftMargin() + 0.05,
... | [
"Add an 'LHCb (Preliminary|Unofficial)' label to the current pad."
] |
Please provide a description of the function:def minimize(func,
minimizer_type=None,
minimizer_algo=None,
strategy=None,
retry=0,
scan=False,
print_level=None):
llog = log['minimize']
min_opts = ROOT.Math.MinimizerOptions
if... | [
"\n Minimize a RooAbsReal function\n\n Parameters\n ----------\n\n func : RooAbsReal\n The function to minimize\n\n minimizer_type : string, optional (default=None)\n The minimizer type: \"Minuit\" or \"Minuit2\".\n If None (the default) then use the current global default value.... |
Please provide a description of the function:def to_code(self, from_function=False):
num_fastnames = sum(1 for op, arg in self.code if isopcode(op) and op in haslocal)
is_function = self.newlocals or num_fastnames > 0 or len(self.args) > 0
nested = is_function and from_function
... | [
"Assemble a Python code object from a Code object"
] |
Please provide a description of the function:def make_string(obj):
if inspect.isclass(obj):
if issubclass(obj, Object):
return obj._ROOT.__name__
if issubclass(obj, string_types):
return 'string'
return obj.__name__
if not isinstance(obj, string_types):
... | [
"\n If ``obj`` is a string, return that, otherwise attempt to figure out the\n name of a type.\n "
] |
Please provide a description of the function:def generate(declaration, headers=None, has_iterators=False):
global NEW_DICTS
# FIXME: _rootpy_dictionary_already_exists returns false positives
# if a third-party module provides "incomplete" dictionaries.
#if compiled._rootpy_dictionary_already_exists... | [
"Compile and load the reflection dictionary for a type.\n\n If the requested dictionary has already been cached, then load that instead.\n\n Parameters\n ----------\n declaration : str\n A type declaration (for example \"vector<int>\")\n headers : str or list of str\n A header file or l... |
Please provide a description of the function:def ensure_built(self, headers=None):
if not self.params:
return
else:
for child in self.params:
child.ensure_built(headers=headers)
if headers is None:
headers = self.guess_headers
... | [
"\n Make sure that a dictionary exists for this type.\n "
] |
Please provide a description of the function:def guess_headers(self):
name = self.name.replace("*", "")
headers = []
if name in KNOWN_TYPES:
headers.append(KNOWN_TYPES[name])
elif name in STL:
headers.append('<{0}>'.format(name))
elif hasattr(ROOT... | [
"\n Attempt to guess what headers may be required in order to use this\n type. Returns `guess_headers` of all children recursively.\n\n * If the typename is in the :const:`KNOWN_TYPES` dictionary, use the\n header specified there\n * If it's an STL type, include <{type}>\n ... |
Please provide a description of the function:def cls(self):
# TODO: register the resulting type?
return SmartTemplate(self.name)(", ".join(map(str, self.params))) | [
"\n Return the class definition for this type\n "
] |
Please provide a description of the function:def from_string(cls, string):
cls.TYPE.setParseAction(cls.make)
try:
return cls.TYPE.parseString(string, parseAll=True)[0]
except ParseException:
log.error("Failed to parse '{0}'".format(string))
raise | [
"\n Parse ``string`` into a CPPType instance\n "
] |
Please provide a description of the function:def to_numpy(self):
import numpy as np
cols, rows = self.GetNcols(), self.GetNrows()
return np.matrix([[self(i, j)
for j in range(cols)]
for i in range(rows)]) | [
"\n Convert this matrix into a\n `numpy.matrix <http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html>`_.\n "
] |
Please provide a description of the function:def callback(cfunc):
# Note:
# ROOT wants a c_voidp whose addressof() == the call site of the target
# function. This hackery is necessary to achieve that.
return C.c_voidp.from_address(C.cast(cfunc, C.c_voidp).value) | [
"\n Turn a ctypes CFUNCTYPE instance into a value which can be passed into PyROOT\n "
] |
Please provide a description of the function:def objectproxy_realaddress(obj):
voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj)
return C.addressof(C.c_char.from_buffer(voidp)) | [
"\n Obtain a real address as an integer from an objectproxy.\n "
] |
Please provide a description of the function:def as_list_with_options(self):
it = ROOT.TIter(self)
elem = it.Next()
result = []
while elem:
if it.GetOption():
result.append(TListItemWithOption(elem, it.GetOption()))
else:
r... | [
"\n Similar to list(self) except elements which have an option associated\n with them are returned as a ``TListItemWithOption``\n "
] |
Please provide a description of the function:def Add(self, value, *optional):
if isinstance(value, TListItemWithOption):
if optional:
raise RuntimeError(
"option specified along with "
"TListItemWithOption. Specify one or the "
... | [
"\n Overload ROOT's basic TList::Add to support supplying\n TListItemWithOption\n "
] |
Please provide a description of the function:def set_style(style, mpl=False, **kwargs):
if mpl:
import matplotlib as mpl
style_dictionary = {}
if isinstance(style, string_types):
style_dictionary = get_style(style, mpl=True, **kwargs)
log.info("using matplotlib ... | [
"\n If mpl is False accept either style name or a TStyle instance.\n If mpl is True accept either style name or a matplotlib.rcParams-like\n dictionary\n "
] |
Please provide a description of the function:def root_open(filename, mode=''):
mode_map = {'a': 'UPDATE',
'a+': 'UPDATE',
'r': 'READ',
'r+': 'UPDATE',
'w': 'RECREATE',
'w+': 'RECREATE'}
if mode in mode_map:
mode = mode... | [
"\n Open a ROOT file via ROOT's static ROOT.TFile.Open [1] function and return\n an asrootpy'd File.\n\n Parameters\n ----------\n\n filename : string\n The absolute or relative path to the ROOT file.\n\n mode : string, optional (default='')\n Mode indicating how the file is to be op... |
Please provide a description of the function:def cd_previous(self):
if self._prev_dir is None or isinstance(self._prev_dir, ROOT.TROOT):
return False
if isinstance(self._prev_dir, ROOT.TFile):
if self._prev_dir.IsOpen() and self._prev_dir.IsWritable():
se... | [
"\n cd to the gDirectory before this file was open.\n "
] |
Please provide a description of the function:def Close(self, *args):
super(_DirectoryBase, self).Close(*args)
return self.cd_previous() | [
"\n Like ROOT's Close but reverts to the gDirectory before this file was\n opened.\n "
] |
Please provide a description of the function:def keys(self, latest=False):
if latest:
keys = {}
for key in self.keys():
name = key.GetName()
if name in keys:
if key.GetCycle() > keys[name].GetCycle():
ke... | [
"\n Return a list of the keys in this directory.\n\n Parameters\n ----------\n\n latest : bool, optional (default=False)\n If True then return a list of keys with unique names where only the\n key with the highest cycle number is included where multiple keys\n ... |
Please provide a description of the function:def Get(self, path, rootpy=True, **kwargs):
thing = super(_DirectoryBase, self).Get(path)
if not thing:
raise DoesNotExist
# Ensure that the file we took the object from is alive at least as
# long as the object being tak... | [
"\n Return the requested object cast as its corresponding subclass in\n rootpy if one exists and ``rootpy=True``, otherwise return the\n unadulterated TObject.\n "
] |
Please provide a description of the function:def GetKey(self, path, cycle=9999, rootpy=True, **kwargs):
key = super(_DirectoryBase, self).GetKey(path, cycle)
if not key:
raise DoesNotExist
if rootpy:
return asrootpy(key, **kwargs)
return key | [
"\n Override TDirectory's GetKey and also handle accessing keys nested\n arbitrarily deep in subdirectories.\n "
] |
Please provide a description of the function:def mkdir(self, path, title="", recurse=False):
head, tail = os.path.split(os.path.normpath(path))
if tail == "":
raise ValueError("invalid directory name: {0}".format(path))
with preserve_current_directory():
dest = s... | [
"\n Make a new directory. If recurse is True, create parent directories\n as required. Return the newly created TDirectory.\n "
] |
Please provide a description of the function:def rm(self, path, cycle=';*'):
rdir = self
with preserve_current_directory():
dirname, objname = os.path.split(os.path.normpath(path))
if dirname:
rdir = rdir.Get(dirname)
rdir.Delete(objname + cyc... | [
"\n Delete an object at `path` relative to this directory\n "
] |
Please provide a description of the function:def copytree(self, dest_dir, src=None, newname=None,
exclude=None, overwrite=False):
def copy_object(obj, dest, name=None):
if name is None:
name = obj.GetName()
if not overwrite and name in dest:
... | [
"\n Copy this directory or just one contained object into another\n directory.\n\n Parameters\n ----------\n\n dest_dir : string or Directory\n The destination directory.\n\n src : string, optional (default=None)\n If ``src`` is None then this entire d... |
Please provide a description of the function:def walk(self,
top=None,
path=None,
depth=0,
maxdepth=-1,
class_ref=None,
class_pattern=None,
return_classname=False,
treat_dirs_as_objs=False):
dirnames,... | [
"\n Walk the directory structure and content in and below a directory.\n For each directory in the directory tree rooted at ``top`` (including\n ``top`` itself, but excluding '.' and '..'), yield a 3-tuple\n ``dirpath, dirnames, filenames``.\n\n Parameters\n ----------\n\n ... |
Please provide a description of the function:def _populate_cache(self):
self.cache = autovivitree()
for path, dirs, objects in self.walk(return_classname=True,
treat_dirs_as_objs=True):
b = self.cache
for d in ['']+path.split... | [
"\n Walk through the whole file and populate the cache\n all objects below the current path are added, i.e.\n for the contents with ina, inb and inab TH1F histograms::\n\n /a/ina\n /b/inb\n /a/b/inab\n\n the cache is (omitting the directories)::\n\n ... |
Please provide a description of the function:def find(self,
regexp, negate_regexp=False,
class_pattern=None,
find_fnc=re.search,
refresh_cache=False):
if refresh_cache or not hasattr(self, 'cache'):
self._populate_cache()
b = self... | [
"\n yield the full path of the matching regular expression and the\n match itself\n "
] |
Please provide a description of the function:def uses_super(func):
if isinstance(func, property):
return any(uses_super(f) for f in (func.fget, func.fset, func.fdel) if f)
elif isinstance(func, (staticmethod, classmethod)):
if sys.version_info >= (2, 7):
func = func.__func__
... | [
"\n Check if the function/property/classmethod/staticmethod uses the `super` builtin\n "
] |
Please provide a description of the function:def start_new_gui_thread():
PyGUIThread = getattr(ROOT, 'PyGUIThread', None)
if PyGUIThread is not None:
assert not PyGUIThread.isAlive(), "GUI thread already running!"
assert _processRootEvents, (
"GUI thread wasn't started when rootwait w... | [
"\n Attempt to start a new GUI thread, if possible.\n\n It is only possible to start one if there was one running on module import.\n "
] |
Please provide a description of the function:def stop_gui_thread():
PyGUIThread = getattr(ROOT, 'PyGUIThread', None)
if PyGUIThread is None or not PyGUIThread.isAlive():
log.debug("no existing GUI thread is runnng")
return False
ROOT.keeppolling = 0
try:
PyGUIThread.finish... | [
"\n Try to stop the GUI thread. If it was running returns True,\n otherwise False.\n "
] |
Please provide a description of the function:def wait_for_zero_canvases(middle_mouse_close=False):
if not __ACTIVE:
wait_failover(wait_for_zero_canvases)
return
@dispatcher
def count_canvases():
if not get_visible_canvases():
try:
ROOT.gSyst... | [
"\n Wait for all canvases to be closed, or CTRL-c.\n\n If `middle_mouse_close`, middle click will shut the canvas.\n\n incpy.ignore\n ",
"\n Count the number of active canvases and finish gApplication.Run()\n if there are none remaining.\n\n incpy.ignore\n ",
"\n S... |
Please provide a description of the function:def wait_for_frame(frame):
if not frame:
# It's already closed or maybe we're in batch mode
return
@dispatcher
def close():
ROOT.gSystem.ExitLoop()
if not getattr(frame, "_py_close_dispatcher_attached", False):
frame._py... | [
"\n wait until a TGMainFrame is closed or ctrl-c\n ",
"\n Signal handler for CTRL-c to cause gApplication.Run() to finish.\n\n incpy.ignore\n "
] |
Please provide a description of the function:def wait_for_browser_close(b):
if b:
if not __ACTIVE:
wait_failover(wait_for_browser_close)
return
wait_for_frame(b.GetBrowserImp().GetMainFrame()) | [
"\n Can be used to wait until a TBrowser is closed\n "
] |
Please provide a description of the function:def log_trace(logger, level=logging.DEBUG, show_enter=True, show_exit=True):
def wrap(function):
l = logger.getChild(function.__name__).log
@wraps(function)
def thunk(*args, **kwargs):
global trace_depth
trace_depth.va... | [
"\n log a statement on function entry and exit\n "
] |
Please provide a description of the function:def update(self, pbar):
'Updates the widget to show the ETA or total time when finished.'
if pbar.currval == 0:
return 'ETA: --:--:--'
elif pbar.finished:
return 'Time: %s' % self.format_time(pbar.seconds_elapsed)
els... | [] |
Please provide a description of the function:def update(self, pbar):
'Updates the widget with the current SI prefixed speed.'
if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6: # =~ 0
scaled = power = 0
else:
scaled, power = self._speed(pbar)
return self.fo... | [] |
Please provide a description of the function:def log_stack(logger, level=logging.INFO, limit=None, frame=None):
if showing_stack.inside:
return
showing_stack.inside = True
try:
if frame is None:
frame = sys._getframe(1)
stack = "".join(traceback.format_stack(frame, l... | [
"\n Display the current stack on ``logger``.\n\n This function is designed to be used during emission of log messages, so it\n won't call itself.\n "
] |
Please provide a description of the function:def showdeletion(self, *objects):
from ..memory import showdeletion as S
for o in objects:
S.monitor_object_cleanup(o) | [
"\n Record a stack trace at the point when an ROOT TObject is deleted\n "
] |
Please provide a description of the function:def trace(self, level=logging.DEBUG, show_enter=True, show_exit=True):
from . import log_trace
return log_trace(self, level, show_enter, show_exit) | [
"\n Functions decorated with this function show function entry and exit with\n values, defaults to debug log level.\n\n :param level: log severity to use for function tracing\n :param show_enter: log function entry\n :param show_enter: log function exit\n\n Example use:\n\n... |
Please provide a description of the function:def show_stack(self, message_regex="^.*$", min_level=logging.DEBUG,
limit=4096, once=True):
value = re.compile(message_regex), limit, once, min_level
self.show_stack_regexes.append(value) | [
"\n Enable showing the origin of log messages by dumping a stack trace into\n the ``stack`` logger at the :const:``logging.INFO`` severity.\n\n :param message_regex: is a full-line regex which the message must\n satisfy in order to trigger stack dump\n :param min_level: the mi... |
Please provide a description of the function:def frame_unique(f):
return f.f_code.co_filename, f.f_code.co_name, f.f_lineno | [
"\n A tuple representing a value which is unique to a given frame's line of\n execution\n "
] |
Please provide a description of the function:def show_stack_depth(self, record, frame):
logger = self
depths = [-1]
msg = record.getMessage()
# For each logger in the hierarchy
while logger:
to_match = getattr(logger, "show_stack_regexes", ())
f... | [
"\n Compute the maximum stack depth to show requested by any hooks,\n returning -1 if there are none matching, or if we've already emitted\n one for the line of code referred to.\n "
] |
Please provide a description of the function:def getChild(self, suffix):
if suffix is None:
return self
if self.root is not self:
if suffix.startswith(self.name + "."):
# Remove duplicate prefix
suffix = suffix[len(self.name + "."):]
... | [
"\n Taken from CPython 2.7, modified to remove duplicate prefix and suffixes\n "
] |
Please provide a description of the function:def requires_ROOT(version, exception=False):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
if ROOT_VERSION < version:
msg = ("{0} requires at least ROOT {1} "
"but you are using {2}".format(... | [
"\n A decorator for functions or methods that require a minimum ROOT version.\n If `exception` is False (the default) a warning is issued and None is\n returned, otherwise a `NotImplementedError` exception is raised.\n `exception` may also be an `Exception` in which case it will be raised\n instead o... |
Please provide a description of the function:def method_file_check(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
curr_dir = ROOT.gDirectory
if isinstance(curr_dir, ROOT.TROOT) or not curr_dir:
raise RuntimeError(
"You must first create a File before calling {... | [
"\n A decorator to check that a TFile as been created before f is called.\n This function can decorate methods.\n\n This requires special treatment since in Python 3 unbound methods are\n just functions: http://stackoverflow.com/a/3589335/1002176 but to get\n consistent access to the class in both 2.... |
Please provide a description of the function:def method_file_cd(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
with preserve_current_directory():
self.GetDirectory().cd()
return f(self, *args, **kwargs)
return wrapper | [
"\n A decorator to cd back to the original directory where this object was\n created (useful for any calls to TObject.Write).\n This function can decorate methods.\n "
] |
Please provide a description of the function:def chainable(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
# perform action
f(self, *args, **kwargs)
# return reference to class.
return self
return wrapper | [
"\n Decorator which causes a 'void' function to return self\n\n Allows chaining of multiple modifier class methods.\n "
] |
Please provide a description of the function:def camel_to_snake(name):
s1 = FIRST_CAP_RE.sub(r'\1_\2', name)
return ALL_CAP_RE.sub(r'\1_\2', s1).lower() | [
"\n http://stackoverflow.com/questions/1175208/\n elegant-python-function-to-convert-camelcase-to-camel-case\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.