Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def snake_case_methods(cls, debug=False):
if not CONVERT_SNAKE_CASE:
return cls
# get the ROOT base class
root_base = cls._ROOT
members = inspect.getmembers(root_base)
# filter out any methods that already exist in lower and uppercase forms
... | [
"\n A class decorator adding snake_case methods\n that alias capitalized ROOT methods. cls must subclass\n a ROOT class and define the _ROOT class variable.\n "
] |
Please provide a description of the function:def sync(lock):
def sync(f):
@wraps(f)
def new_function(*args, **kwargs):
lock.acquire()
try:
return f(*args, **kwargs)
finally:
lock.release()
return new_function
return... | [
"\n A synchronization decorator\n "
] |
Please provide a description of the function:def as_ufloat(roorealvar):
if isinstance(roorealvar, (U.AffineScalarFunc, U.Variable)):
return roorealvar
return U.ufloat((roorealvar.getVal(), roorealvar.getError())) | [
"\n Cast a `RooRealVar` to an `uncertainties.ufloat`\n "
] |
Please provide a description of the function:def correlated_values(param_names, roofitresult):
pars = roofitresult.floatParsFinal()
#pars.Print()
pars = [pars[i] for i in range(pars.getSize())]
parnames = [p.GetName() for p in pars]
values = [(p.getVal(), p.getError()) for p in pars]
#valu... | [
"\n Return symbolic values from a `RooFitResult` taking into account covariance\n\n This is useful for numerically computing the uncertainties for expressions\n using correlated values arising from a fit.\n\n Parameters\n ----------\n\n param_names: list of strings\n A list of parameters to... |
Please provide a description of the function:def checkattr(metacls, attr, value):
if not isinstance(value, (
types.MethodType,
types.FunctionType,
classmethod,
staticmethod,
property)):
if attr in dir(type('dumm... | [
"\n Only allow class attributes that are instances of\n rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy\n "
] |
Please provide a description of the function:def prefix(cls, name):
attrs = dict([(name + attr, value) for attr, value in cls.get_attrs()])
return TreeModelMeta(
'_'.join([name, cls.__name__]),
(TreeModel,), attrs) | [
"\n Create a new TreeModel where class attribute\n names are prefixed with ``name``\n "
] |
Please provide a description of the function:def get_attrs(cls):
ignore = dir(type('dummy', (object,), {})) + ['__metaclass__']
attrs = [
item for item in inspect.getmembers(cls) if item[0] not in ignore
and not isinstance(
item[1], (
... | [
"\n Get all class attributes ordered by definition\n "
] |
Please provide a description of the function:def to_struct(cls, name=None):
if name is None:
name = cls.__name__
basic_attrs = dict([(attr_name, value)
for attr_name, value in cls.get_attrs()
if isinstance(value, Column)])
... | [
"\n Convert the TreeModel into a compiled C struct\n "
] |
Please provide a description of the function:def id_to_name(id):
name = pdgid_names.get(id)
if not name:
name = repr(id)
return name | [
"\n Convert a PDG ID to a printable string.\n "
] |
Please provide a description of the function:def id_to_root_name(id):
name = root_names.get(id)
if not name:
name = repr(id)
return name | [
"\n Convert a PDG ID to a string with root markup.\n "
] |
Please provide a description of the function:def new_closure(vals):
args = ','.join('x%i' % i for i in range(len(vals)))
f = eval("lambda %s:lambda:(%s)" % (args, args))
if sys.version_info[0] >= 3:
return f(*vals).__closure__
return f(*vals).func_closure | [
"\n Build a new closure\n "
] |
Please provide a description of the function:def _inject_closure_values_fix_closures(c, injected, **kwargs):
code = c.code
orig_len = len(code)
for iback, (opcode, value) in enumerate(reversed(code)):
i = orig_len - iback - 1
if opcode != MAKE_CLOSURE:
continue
cod... | [
"\n Recursively fix closures\n\n Python bytecode for a closure looks like::\n\n LOAD_CLOSURE var1\n BUILD_TUPLE <n_of_vars_closed_over>\n LOAD_CONST <code_object_containing_closure>\n MAKE_CLOSURE\n\n or this in 3.6 (MAKE_CLOSURE is no longer an opcode)::\n\n LOAD_... |
Please provide a description of the function:def _inject_closure_values_fix_code(c, injected, **kwargs):
# Add more closure variables
c.freevars += injected
# Replace LOAD_GLOBAL with LOAD_DEREF (fetch from closure cells)
# for named variables
for i, (opcode, value) in enumerate(c.code):
... | [
"\n Fix code objects, recursively fixing any closures\n "
] |
Please provide a description of the function:def inject_closure_values(func, **kwargs):
wrapped_by = None
if isinstance(func, property):
fget, fset, fdel = func.fget, func.fset, func.fdel
if fget: fget = fix_func(fget, **kwargs)
if fset: fset = fix_func(fset, **kwargs)
if f... | [
"\n Returns a new function identical to the previous one except that it acts as\n though global variables named in `kwargs` have been closed over with the\n values specified in the `kwargs` dictionary.\n\n Works on properties, class/static methods and functions.\n\n This can be useful for mocking and... |
Please provide a description of the function:def axes(self, ndim=1,
xlimits=None, ylimits=None, zlimits=None,
xbins=1, ybins=1, zbins=1):
if xlimits is None:
xlimits = (0, 1)
if ylimits is None:
ylimits = (0, 1)
if zlimits is None:
... | [
"\n Create and return axes on this pad\n "
] |
Please provide a description of the function:def tree2hdf5(tree, hfile, group=None,
entries=-1, show_progress=False, **kwargs):
show_progress = show_progress and check_tty(sys.stdout)
if show_progress:
widgets = [Percentage(), ' ', Bar(), ' ', ETA()]
own_h5file = False
if isi... | [
"\n Convert a TTree into a HDF5 table.\n\n Parameters\n ----------\n\n tree : ROOT.TTree\n A ROOT TTree.\n\n hfile : string or PyTables HDF5 File\n A PyTables HDF5 File handle or string path to an existing HDF5 file.\n\n group : string or PyTables Group instance, optional (default=No... |
Please provide a description of the function:def root2hdf5(rfile, hfile, rpath='',
entries=-1, userfunc=None,
show_progress=False,
ignore_exception=False,
**kwargs):
own_rootfile = False
if isinstance(rfile, string_types):
rfile = root_open(rf... | [
"\n Convert all trees in a ROOT file into tables in an HDF5 file.\n\n Parameters\n ----------\n\n rfile : string or asrootpy'd ROOT File\n A ROOT File handle or string path to an existing ROOT file.\n\n hfile : string or PyTables HDF5 File\n A PyTables HDF5 File handle or string path to... |
Please provide a description of the function:def Crop(self, x1, x2, copy=False):
numPoints = self.GetN()
if copy:
cropGraph = self.Clone()
copyGraph = self
else:
cropGraph = self
copyGraph = self.Clone()
cropGraph.Set(0)
X ... | [
"\n Remove points which lie outside of [x1, x2].\n If x1 and/or x2 is below/above the current lowest/highest\n x-coordinates, additional points are added to the graph using a\n linear interpolation\n "
] |
Please provide a description of the function:def Reverse(self, copy=False):
numPoints = self.GetN()
if copy:
revGraph = self.Clone()
else:
revGraph = self
X = self.GetX()
EXlow = self.GetEXlow()
EXhigh = self.GetEXhigh()
Y = self.G... | [
"\n Reverse the order of the points\n "
] |
Please provide a description of the function:def Shift(self, value, copy=False):
numPoints = self.GetN()
if copy:
shiftGraph = self.Clone()
else:
shiftGraph = self
X = self.GetX()
EXlow = self.GetEXlow()
EXhigh = self.GetEXhigh()
Y... | [
"\n Shift the graph left or right by value\n "
] |
Please provide a description of the function:def Append(self, other):
orig_len = len(self)
self.Set(orig_len + len(other))
ipoint = orig_len
if hasattr(self, 'SetPointError'):
for point in other:
self.SetPoint(ipoint, point.x.value, point.y.value)
... | [
"\n Append points from another graph\n "
] |
Please provide a description of the function:def keepalive(nurse, *patients):
if DISABLED:
return
if hashable(nurse):
hashable_patients = []
for p in patients:
if hashable(p):
log.debug("Keeping {0} alive for lifetime of {1}".format(p, nurse))
... | [
"\n Keep ``patients`` alive at least as long as ``nurse`` is around using a\n ``WeakKeyDictionary``.\n "
] |
Please provide a description of the function:def canonify_slice(s, n):
if isinstance(s, (int, long)):
return canonify_slice(slice(s, s + 1, None), n)
start = s.start % n if s.start is not None else 0
stop = s.stop % n if s.stop is not None else n
step = s.step if s.step is not None else 1
... | [
"\n Convert a slice object into a canonical form\n to simplify treatment in histogram bin content\n and edge slicing.\n "
] |
Please provide a description of the function:def bin_to_edge_slice(s, n):
s = canonify_slice(s, n)
start = s.start
stop = s.stop
if start > stop:
_stop = start + 1
start = stop + 1
stop = _stop
start = max(start - 1, 0)
step = abs(s.step)
if stop <= 1 or start >=... | [
"\n Convert a bin slice into a bin edge slice.\n "
] |
Please provide a description of the function:def histogram(data, *args, **kwargs):
from .autobinning import autobinning
dim = kwargs.pop('dim', 1)
if dim != 1:
raise NotImplementedError
if 'binning' in kwargs:
args = autobinning(data, kwargs['binning'])
del kwargs['binning']... | [
"\n Create and fill a one-dimensional histogram.\n\n The same arguments as the ``Hist`` class are expected.\n If the number of bins and the ranges are not specified they are\n automatically deduced with the ``autobinning`` function using the method\n specified by the ``binning`` argument. Only one-di... |
Please provide a description of the function:def overflow(self):
indices = self.hist.xyz(self.idx)
for i in range(self.hist.GetDimension()):
if indices[i] == 0 or indices[i] == self.hist.nbins(i) + 1:
return True
return False | [
"\n Returns true if this BinProxy is for an overflow bin\n "
] |
Please provide a description of the function:def effective_entries(self):
sum_w2 = self.sum_w2
if sum_w2 == 0:
return abs(self.value)
return (self.value ** 2) / sum_w2 | [
"\n Number of effective entries in this bin.\n The number of unweighted entries this bin would need to\n contain in order to have the same statistical power as this\n bin with possibly weighted entries, estimated by:\n\n (sum of weights) ** 2 / (sum of squares of weights)\n\n ... |
Please provide a description of the function:def xyz(self, idx):
# Not implemented for Python 3:
# GetBinXYZ(i, x, y, z)
nx = self.GetNbinsX() + 2
ny = self.GetNbinsY() + 2
ndim = self.GetDimension()
if ndim < 2:
binx = idx % nx
biny = 0... | [
"\n return binx, biny, binz corresponding to the global bin number\n "
] |
Please provide a description of the function:def nbins(self, axis=0, overflow=False):
if axis == 0:
nbins = self.GetNbinsX()
elif axis == 1:
nbins = self.GetNbinsY()
elif axis == 2:
nbins = self.GetNbinsZ()
else:
raise ValueError("... | [
"\n Get the number of bins along an axis\n "
] |
Please provide a description of the function:def bins_range(self, axis=0, overflow=False):
nbins = self.nbins(axis=axis, overflow=False)
if overflow:
start = 0
end_offset = 2
else:
start = 1
end_offset = 1
return range(start, nbins... | [
"\n Return a range of bin indices for iterating along an axis\n\n Parameters\n ----------\n\n axis : int, optional (default=1)\n The axis (0, 1 or 2).\n\n overflow : bool, optional (default=False)\n If True then include the underflow and overflow bins\n ... |
Please provide a description of the function:def uniform(self, axis=None, precision=1E-7):
if axis is None:
for axis in range(self.GetDimension()):
widths = list(self._width(axis=axis))
if not all(abs(x - widths[0]) < precision for x in widths):
... | [
"\n Return True if the binning is uniform along the specified axis.\n If axis is None (the default), then return True if the binning is\n uniform along all axes. Otherwise return False.\n\n Parameters\n ----------\n\n axis : int (default=None)\n Axis along which ... |
Please provide a description of the function:def uniform_binned(self, name=None):
if self.GetDimension() == 1:
new_hist = Hist(
self.GetNbinsX(), 0, self.GetNbinsX(),
name=name, type=self.TYPE)
elif self.GetDimension() == 2:
new_hist = His... | [
"\n Return a new histogram with constant width bins along all axes by\n using the bin indices as the bin edges of the new histogram.\n "
] |
Please provide a description of the function:def underflow(self, axis=0):
if axis not in range(3):
raise ValueError("axis must be 0, 1, or 2")
if self.DIM == 1:
return self.GetBinContent(0)
elif self.DIM == 2:
def idx(i):
arg = [i]
... | [
"\n Return the underflow for the given axis.\n\n Depending on the dimension of the histogram, may return an array.\n "
] |
Please provide a description of the function:def lowerbound(self, axis=0):
if not 0 <= axis < self.GetDimension():
raise ValueError(
"axis must be a non-negative integer less than "
"the dimensionality of the histogram")
if axis == 0:
retu... | [
"\n Get the lower bound of the binning along an axis\n "
] |
Please provide a description of the function:def bounds(self, axis=0):
if not 0 <= axis < self.GetDimension():
raise ValueError(
"axis must be a non-negative integer less than "
"the dimensionality of the histogram")
if axis == 0:
return s... | [
"\n Get the lower and upper bounds of the binning along an axis\n "
] |
Please provide a description of the function:def check_compatibility(self, other, check_edges=False, precision=1E-7):
if self.GetDimension() != other.GetDimension():
raise TypeError("histogram dimensionalities do not match")
if len(self) != len(other):
raise ValueError("... | [
"\n Test whether two histograms are considered compatible by the number of\n dimensions, number of bins along each axis, and optionally the bin\n edges.\n\n Parameters\n ----------\n\n other : histogram\n A rootpy histogram\n\n check_edges : bool, optional... |
Please provide a description of the function:def fill_array(self, array, weights=None):
try:
try:
from root_numpy import fill_hist as fill_func
except ImportError:
from root_numpy import fill_array as fill_func
except ImportError:
... | [
"\n Fill this histogram with a NumPy array\n "
] |
Please provide a description of the function:def fill_view(self, view):
other = view.hist
_other_x_center = other.axis(0).GetBinCenter
_other_y_center = other.axis(1).GetBinCenter
_other_z_center = other.axis(2).GetBinCenter
_other_get = other.GetBinContent
_othe... | [
"\n Fill this histogram from a view of another histogram\n "
] |
Please provide a description of the function:def get_sum_w2(self, ix, iy=0, iz=0):
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = self.nbins(axis=0, overflow=True)
... | [
"\n Obtain the true number of entries in the bin weighted by w^2\n "
] |
Please provide a description of the function:def set_sum_w2(self, w, ix, iy=0, iz=0):
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = self.nbins(axis=0, overflow=True)
... | [
"\n Sets the true number of entries in the bin weighted by w^2\n "
] |
Please provide a description of the function:def merge_bins(self, bin_ranges, axis=0):
ndim = self.GetDimension()
if axis > ndim - 1:
raise ValueError(
"axis is out of range")
axis_bins = self.nbins(axis=axis, overflow=True)
# collect the indices alo... | [
"\n Merge bins in bin ranges\n\n Parameters\n ----------\n\n bin_ranges : list of tuples\n A list of tuples of bin indices for each bin range to be merged\n into one bin.\n\n axis : int (default=1)\n The integer identifying the axis to merge bins a... |
Please provide a description of the function:def rebinned(self, bins, axis=0):
ndim = self.GetDimension()
if axis >= ndim:
raise ValueError(
"axis must be less than the dimensionality of the histogram")
if isinstance(bins, int):
_bins = [1] * ndi... | [
"\n Return a new rebinned histogram\n\n Parameters\n ----------\n\n bins : int, tuple, or iterable\n If ``bins`` is an int, then return a histogram that is rebinned by\n grouping N=``bins`` bins together along the axis ``axis``.\n If ``bins`` is a tuple, ... |
Please provide a description of the function:def smoothed(self, iterations=1):
copy = self.Clone(shallow=True)
copy.Smooth(iterations)
return copy | [
"\n Return a smoothed copy of this histogram\n\n Parameters\n ----------\n\n iterations : int, optional (default=1)\n The number of smoothing iterations\n\n Returns\n -------\n\n hist : asrootpy'd histogram\n The smoothed histogram\n\n "
... |
Please provide a description of the function:def empty_clone(self, binning=None, axis=0, type=None, **kwargs):
ndim = self.GetDimension()
if binning is False and ndim == 1:
raise ValueError(
"cannot remove the x-axis of a 1D histogram")
args = []
for ... | [
"\n Return a new empty histogram. The binning may be modified\n along one axis by specifying the binning and axis arguments.\n If binning is False, then the corresponding axis is dropped\n from the returned histogram.\n "
] |
Please provide a description of the function:def quantiles(self, quantiles,
axis=0, strict=False,
recompute_integral=False):
if axis >= self.GetDimension():
raise ValueError(
"axis must be less than the dimensionality of the histogram")
... | [
"\n Calculate the quantiles of this histogram.\n\n Parameters\n ----------\n\n quantiles : list or int\n A list of cumulative probabilities or an integer used to determine\n equally spaced values between 0 and 1 (inclusive).\n\n axis : int, optional (default=... |
Please provide a description of the function:def integral(self, xbin1=None, xbin2=None,
width=False, error=False, overflow=False):
if xbin1 is None:
xbin1 = 0 if overflow else 1
if xbin2 is None:
xbin2 = -1 if overflow else -2
nbinsx = self.nbins... | [
"\n Compute the integral and error over a range of bins\n "
] |
Please provide a description of the function:def poisson_errors(self):
graph = Graph(self.nbins(axis=0), type='asymm')
graph.SetLineWidth(self.GetLineWidth())
graph.SetMarkerSize(self.GetMarkerSize())
chisqr = ROOT.TMath.ChisquareQuantile
npoints = 0
for bin in s... | [
"\n Return a TGraphAsymmErrors representation of this histogram where the\n point y errors are Poisson.\n "
] |
Please provide a description of the function:def ravel(self, name=None):
nbinsx = self.nbins(0)
nbinsy = self.nbins(1)
left_edge = self.xedgesl(1)
right_edge = self.xedgesh(nbinsx)
out = Hist(nbinsx * nbinsy,
left_edge, nbinsy * (right_edge - left_edge... | [
"\n Convert 2D histogram into 1D histogram with the y-axis repeated along\n the x-axis, similar to NumPy's ravel().\n "
] |
Please provide a description of the function:def integral(self,
xbin1=1, xbin2=-2,
ybin1=1, ybin2=-2,
zbin1=1, zbin2=-2,
width=False,
error=False,
overflow=False):
if xbin1 is None:
xbin1 =... | [
"\n Compute the integral and error over a range of bins\n "
] |
Please provide a description of the function:def matchPreviousExpr(expr):
rep = Forward()
e2 = expr.copy()
rep <<= e2
def copyTokenToRepeater(s,l,t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s,l,t):
theseTokens = _flatten(t.asList())
... | [
"Helper to define an expression that is indirectly defined from\r\n the tokens matched in a previous expression, that is, it looks\r\n for a 'repeat' of a previous expression. For example::\r\n first = Word(nums)\r\n second = matchPreviousExpr(first)\r\n matchExpr = first ... |
Please provide a description of the function:def oneOf( strs, caseless=False, useRegex=True ):
if caseless:
isequal = ( lambda a,b: a.upper() == b.upper() )
masks = ( lambda a,b: b.upper().startswith(a.upper()) )
parseElementClass = CaselessLiteral
else:
isequal = ( l... | [
"Helper to quickly define a set of alternative Literals, and makes sure to do\r\n longest-first testing when there is a conflict, regardless of the input order,\r\n but returns a C{L{MatchFirst}} for best performance.\r\n\r\n Parameters:\r\n - strs - a string of space-delimited literals, or... |
Please provide a description of the function:def close_on_esc_or_middlemouse(event, x, y, obj):
#print "Event handler called:", args
if (event == ROOT.kButton2Down
# User pressed middle mouse
or (event == ROOT.kMouseMotion and
x == y == 0 and
# User pressed esca... | [
"\n Closes canvases when escape is pressed or the canvas area is clicked with\n the middle mouse button. (ROOT requires that the mouse is over the canvas\n area itself before sending signals of any kind.)\n "
] |
Please provide a description of the function:def attach_event_handler(canvas, handler=close_on_esc_or_middlemouse):
if getattr(canvas, "_py_event_dispatcher_attached", None):
return
event_dispatcher = C.TPyDispatcherProcessedEvent(handler)
canvas.Connect("ProcessedEvent(int,int,int,TObject*)",... | [
"\n Attach a handler function to the ProcessedEvent slot, defaulting to\n closing when middle mouse is clicked or escape is pressed\n\n Note that escape only works if the pad has focus, which in ROOT-land means\n the mouse has to be over the canvas area.\n "
] |
Please provide a description of the function:def plot_contour_matrix(arrays,
fields,
filename,
weights=None,
sample_names=None,
sample_lines=None,
sample_colors=None,
... | [
"\n Create a matrix of contour plots showing all possible 2D projections of a\n multivariate dataset. You may optionally animate the contours as a cut on\n one of the fields is increased. ImageMagick must be installed to produce\n animations.\n\n Parameters\n ----------\n\n arrays : list of arr... |
Please provide a description of the function:def _num_to_string(self, number, pad_to_length=None):
output = ""
while number:
number, digit = divmod(number, self._alpha_len)
output += self._alphabet[digit]
if pad_to_length:
remainder = max(pad_to_lengt... | [
"\n Convert a number to a string, using the given alphabet.\n "
] |
Please provide a description of the function:def _string_to_int(self, string):
number = 0
for char in string[::-1]:
number = number * self._alpha_len + self._alphabet.index(char)
return number | [
"\n Convert a string to a number, using the given alphabet..\n "
] |
Please provide a description of the function:def encode(self, uuid, pad_length=22):
return self._num_to_string(uuid.int, pad_to_length=pad_length) | [
"\n Encodes a UUID into a string (LSB first) according to the alphabet\n If leftmost (MSB) bits 0, string might be shorter\n "
] |
Please provide a description of the function:def uuid(self, name=None, pad_length=22):
# If no name is given, generate a random UUID.
if name is None:
uuid = _uu.uuid4()
elif "http" not in name.lower():
uuid = _uu.uuid5(_uu.NAMESPACE_DNS, name)
else:
... | [
"\n Generate and return a UUID.\n\n If the name parameter is provided, set the namespace to the provided\n name and generate a UUID.\n "
] |
Please provide a description of the function:def random(self, length=22):
random_num = int(binascii.b2a_hex(os.urandom(length)), 16)
return self._num_to_string(random_num, pad_to_length=length)[:length] | [
"\n Generate and return a cryptographically-secure short random string\n of the specified length.\n "
] |
Please provide a description of the function:def fit(self,
data='obsData',
model_config='ModelConfig',
param_const=None,
param_values=None,
param_ranges=None,
poi_const=False,
poi_value=None,
poi_range=None,
exte... | [
"\n Fit a pdf to data in a workspace\n\n Parameters\n ----------\n\n workspace : RooWorkspace\n The workspace\n\n data : str or RooAbsData, optional (default='obsData')\n The name of the data or a RooAbsData instance.\n\n model_config : str or ModelCon... |
Please provide a description of the function:def ensure_trafaret(trafaret):
if isinstance(trafaret, Trafaret):
return trafaret
elif isinstance(trafaret, type):
if issubclass(trafaret, Trafaret):
return trafaret()
# str, int, float are classes, but its appropriate to use ... | [
"\n Helper for complex trafarets, takes trafaret instance or class\n and returns trafaret instance\n "
] |
Please provide a description of the function:def DictKeys(keys):
req = [(Key(key), Any) for key in keys]
return Dict(dict(req)) | [
"\n Checks if dict has all given keys\n\n :param keys:\n :type keys:\n\n >>> _dd(DictKeys(['a','b']).check({'a':1,'b':2,}))\n \"{'a': 1, 'b': 2}\"\n >>> extract_error(DictKeys(['a','b']), {'a':1,'b':2,'c':3,})\n {'c': 'c is not allowed key'}\n >>> extract_error(DictKeys(['key','key2']), {'ke... |
Please provide a description of the function:def guard(trafaret=None, **kwargs):
if (
trafaret
and not isinstance(trafaret, Dict)
and not isinstance(trafaret, Forward)
):
raise RuntimeError("trafaret should be instance of Dict or Forward")
elif trafaret and kwargs:
... | [
"\n Decorator for protecting function with trafarets\n\n >>> @guard(a=String, b=Int, c=String)\n ... def fn(a, b, c=\"default\"):\n ... '''docstring'''\n ... return (a, b, c)\n ...\n >>> fn.__module__ = None\n >>> help(fn)\n Help on function fn:\n <BLANKLINE>\n fn(*args, **k... |
Please provide a description of the function:def catch(checker, *a, **kw):
try:
return checker(*a, **kw)
except DataError as error:
return error | [
"\n Helper for tests - catch error and return it as dict\n "
] |
Please provide a description of the function:def extract_error(checker, *a, **kw):
res = catch_error(checker, *a, **kw)
if isinstance(res, DataError):
return res.as_dict()
return res | [
"\n Helper for tests - catch error and return it as dict\n "
] |
Please provide a description of the function:def _clone_args(self):
keys = list(self.keys)
kw = {}
if self.allow_any or self.extras:
kw['allow_extra'] = list(self.extras)
if self.allow_any:
kw['allow_extra'].append('*')
kw['allow_extra... | [
" return args to create new Dict clone\n "
] |
Please provide a description of the function:def make_optional(self, *args):
deprecated('This method is deprecated. You can not change keys instances.')
for key in self.keys:
if key.name in args or '*' in args:
key.make_optional()
return self | [
" Deprecated. will change in-place keys for given args\n or all keys if `*` in args.\n "
] |
Please provide a description of the function:def merge(self, other):
ignore = self.ignore
extra = self.extras
if isinstance(other, Dict):
other_keys = other.keys
ignore += other.ignore
extra += other.extras
elif isinstance(other, (list, tuple)... | [
"\n Extends one Dict with other Dict Key`s or Key`s list,\n or dict instance supposed for Dict\n "
] |
Please provide a description of the function:def fold(data, prefix='', delimeter='__'):
if not isinstance(delimeter, (tuple, list)):
delimeter = (delimeter, )
def deep(data):
if len(data) == 1 and len(data[0][0]) < 2:
if data[0][0]:
return {data[0][0][0]: data[0... | [
"\n >>> _dd(fold({'a__a': 4}))\n \"{'a': {'a': 4}}\"\n >>> _dd(fold({'a__a': 4, 'a__b': 5}))\n \"{'a': {'a': 4, 'b': 5}}\"\n >>> _dd(fold({'a__1': 2, 'a__0': 1, 'a__2': 3}))\n \"{'a': [1, 2, 3]}\"\n >>> _dd(fold({'form__a__b': 5, 'form__a__a': 4}, 'form'))\n \"{'a': {'a': 4, 'b': 5}}\"\n ... |
Please provide a description of the function:def get_deep_attr(obj, keys):
cur = obj
for k in keys:
if isinstance(cur, Mapping) and k in cur:
cur = cur[k]
continue
else:
try:
cur = getattr(cur, k)
continue
excep... | [
" Helper for DeepKey"
] |
Please provide a description of the function:def construct(arg):
'''
Shortcut syntax to define trafarets.
- int, str, float and bool will return t.Int, t.String, t.Float and t.Bool
- one element list will return t.List
- tuple or list with several args will return t.Tuple
- dict will return t.D... | [] |
Please provide a description of the function:def subdict(name, *keys, **kw):
trafaret = kw.pop('trafaret') # coz py2k
def inner(data, context=None):
errors = False
preserve_output = []
touched = set()
collect = {}
for key in keys:
for k, v, names in key... | [
"\n Subdict key.\n\n Takes a `name`, any number of keys as args and keyword argument `trafaret`.\n Use it like:\n\n def check_passwords_equal(data):\n if data['password'] != data['password_confirm']:\n return t.DataError('Passwords are not equal')\n return data['... |
Please provide a description of the function:def confirm_key(name, confirm_name, trafaret):
def check_(value):
first, second = None, None
if name in value:
first = value[name]
else:
yield name, t.DataError('is required'), (name,)
if confirm_name in value:... | [
"\n confirm_key - takes `name`, `confirm_name` and `trafaret`.\n\n Checks if data['name'] equals data['confirm_name'] and both\n are valid against `trafaret`.\n "
] |
Please provide a description of the function:def get_capacity(self, legacy=None):
params = None
if legacy:
params = {'legacy': legacy}
return self.call_api('/capacity', params=params)['capacity'] | [
"Get capacity of all facilities.\n\n :param legacy: Indicate set of server types to include in response\n\n Validation of `legacy` is left to the packet api to avoid going out of date if any new value is introduced.\n The currently known values are:\n - only (current default, will be s... |
Please provide a description of the function:def supported_currencies(self, project='moneywagon', level="full"):
ret = []
if project == 'multiexplorer-wallet':
for currency, data in self.sorted_crypto_data:
if not data.get("bip44_coin_type"):
cont... | [
"\n Returns a list of all currencies that are supported by the passed in project.\n and support level. Support level can be: \"block\", \"transaction\", \"address\"\n or \"full\".\n "
] |
Please provide a description of the function:def not_supported_currencies(self, project='moneywagon', level="full"):
supported = self.supported_currencies(project, level)
ret = []
for symbol, data in self.sorted_crypto_data:
if symbol == '': # template
contin... | [
"\n Returns a list of all currencies that are defined in moneywagon, by not\n supported by the passed in project and support level. Support level can\n be: \"block\", \"transaction\", \"address\" or \"full\".\n "
] |
Please provide a description of the function:def altcore_data(self):
ret = []
for symbol in self.supported_currencies(project='altcore', level="address"):
data = crypto_data[symbol]
priv = data.get('private_key_prefix')
pub = data.get('address_version_byte')
... | [
"\n Returns the crypto_data for all currencies defined in moneywagon that also\n meet the minimum support for altcore. Data is keyed according to the\n bitcore specification.\n "
] |
Please provide a description of the function:def modify_mempool(mempool, remove=0, add=0, verbose=False):
for i in range(remove):
popped = mempool.pop()
if verbose: print("removed:", popped)
for i in range(add):
new_txid = _make_txid()
mempool.append(new_txid)
if ve... | [
"\n Given a list of txids (mempool), add and remove some items to simulate\n an out of sync mempool.\n "
] |
Please provide a description of the function:def from_unit_to_satoshi(self, value, unit='satoshi'):
if not unit or unit == 'satoshi':
return value
if unit == 'bitcoin' or unit == 'btc':
return value * 1e8
# assume fiat currency that we can convert
conver... | [
"\n Convert a value to satoshis. units can be any fiat currency.\n By default the unit is satoshi.\n "
] |
Please provide a description of the function:def add_raw_inputs(self, inputs, private_key=None):
for i in inputs:
self.ins.append(dict(input=i, private_key=private_key))
self.change_address = i['address'] | [
"\n Add a set of utxo's to this transaction. This method is better to use if you\n want more fine control of which inputs get added to a transaction.\n `inputs` is a list of \"unspent outputs\" (they were 'outputs' to previous transactions,\n and 'inputs' to subsiquent transactions).\n... |
Please provide a description of the function:def _get_utxos(self, address, services, **modes):
return get_unspent_outputs(
self.crypto, address, services=services,
**modes
) | [
"\n Using the service fallback engine, get utxos from remote service.\n "
] |
Please provide a description of the function:def private_key_to_address(self, pk):
pub = privtopub(pk)
pub_byte, priv_byte = get_magic_bytes(self.crypto)
if priv_byte >= 128:
priv_byte -= 128 #pybitcointools bug
return pubtoaddr(pub, pub_byte) | [
"\n Convert a private key (in hex format) into an address.\n "
] |
Please provide a description of the function:def add_inputs(self, private_key=None, address=None, amount='all', max_ins=None, password=None, services=None, **modes):
if private_key:
if private_key.startswith('6P'):
if not password:
raise Exception("Passwo... | [
"\n Make call to external service to get inputs from an address and/or private_key.\n `amount` is the amount of [currency] worth of inputs (in satoshis) to add from\n this address. Pass in 'all' (the default) to use *all* inputs found for this address.\n Returned is the number of units ... |
Please provide a description of the function:def total_input_satoshis(self):
just_inputs = [x['input'] for x in self.ins]
return sum([x['amount'] for x in just_inputs]) | [
"\n Add up all the satoshis coming from all input tx's.\n "
] |
Please provide a description of the function:def add_output(self, address, value, unit='satoshi'):
value_satoshi = self.from_unit_to_satoshi(value, unit)
if self.verbose:
print("Adding output of: %s satoshi (%.8f)" % (
value_satoshi, (value_satoshi / 1e8)
... | [
"\n Add an output (a person who will receive funds via this tx).\n If no unit is specified, satoshi is implied.\n "
] |
Please provide a description of the function:def onchain_exchange(self, withdraw_crypto, withdraw_address, value, unit='satoshi'):
self.onchain_rate = get_onchain_exchange_rates(
self.crypto, withdraw_crypto, best=True, verbose=self.verbose
)
exchange_rate = float(self.oncha... | [
"\n This method is like `add_output` but it sends to another\n "
] |
Please provide a description of the function:def fee(self, value=None, unit='satoshi'):
convert = None
if not value:
# no fee was specified, use $0.02 as default.
convert = get_current_price(self.crypto, "usd")
self.fee_satoshi = int(0.02 / convert * 1e8)
... | [
"\n Set the miner fee, if unit is not set, assumes value is satoshi.\n If using 'optimal', make sure you have already added all outputs.\n "
] |
Please provide a description of the function:def estimate_size(self):
# if there are no outs use 1 (because the change will be an out)
outs = len(self.outs) or 1
return outs * 34 + 148 * len(self.ins) + 10 | [
"\n Estimate how many bytes this transaction will be by countng inputs\n and outputs.\n Formula taken from: http://bitcoin.stackexchange.com/a/3011/18150\n "
] |
Please provide a description of the function:def get_hex(self, signed=True):
total_ins_satoshi = self.total_input_satoshis()
if total_ins_satoshi == 0:
raise ValueError("Can't make transaction, there are zero inputs")
# Note: there can be zero outs (sweep or coalesc transac... | [
"\n Given all the data the user has given so far, make the hex using pybitcointools\n "
] |
Please provide a description of the function:def gen_primes():
D = {}
q = 2
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1 | [
" Generate an infinite sequence of prime numbers.\n "
] |
Please provide a description of the function:def get_current_price(crypto, fiat, services=None, convert_to=None, helper_prices=None, **modes):
fiat = fiat.lower()
args = {'crypto': crypto, 'fiat': fiat, 'convert_to': convert_to}
if not services:
services = get_optimal_services(crypto, 'current... | [
"\n High level function for getting current exchange rate for a cryptocurrency.\n If the fiat value is not explicitly defined, it will try the wildcard service.\n if that does not work, it tries converting to an intermediate cryptocurrency\n if available.\n "
] |
Please provide a description of the function:def get_optimal_fee(crypto, tx_bytes, **modes):
try:
services = get_optimal_services(crypto, 'get_optimal_fee')
except NoServicesDefined:
convert = get_current_price(crypto, 'usd')
fee = int(0.02 / convert * 1e8)
if modes.get('re... | [
"\n Get the optimal fee based on how big the transaction is. Currently this\n is only provided for BTC. Other currencies will return $0.02 in satoshi.\n "
] |
Please provide a description of the function:def get_onchain_exchange_rates(deposit_crypto=None, withdraw_crypto=None, **modes):
from moneywagon.onchain_exchange import ALL_SERVICES
rates = []
for Service in ALL_SERVICES:
srv = Service(verbose=modes.get('verbose', False))
rates.extend(... | [
"\n Gets exchange rates for all defined on-chain exchange services.\n "
] |
Please provide a description of the function:def generate_keypair(crypto, seed, password=None):
if crypto in ['eth', 'etc']:
raise CurrencyNotSupported("Ethereums not yet supported")
pub_byte, priv_byte = get_magic_bytes(crypto)
priv = sha256(seed)
pub = privtopub(priv)
priv_wif = enc... | [
"\n Generate a private key and publickey for any currency, given a seed.\n That seed can be random, or a brainwallet phrase.\n "
] |
Please provide a description of the function:def sweep(crypto, private_key, to_address, fee=None, password=None, **modes):
from moneywagon.tx import Transaction
tx = Transaction(crypto, verbose=modes.get('verbose', False))
tx.add_inputs(private_key=private_key, password=password, **modes)
tx.change... | [
"\n Move all funds by private key to another address.\n "
] |
Please provide a description of the function:def guess_currency_from_address(address):
if is_py2:
fixer = lambda x: int(x.encode('hex'), 16)
else:
fixer = lambda x: x # does nothing
first_byte = fixer(b58decode_check(address)[0])
double_first_byte = fixer(b58decode_check(address)[:... | [
"\n Given a crypto address, find which currency it likely belongs to.\n Raises an exception if it can't find a match. Raises exception if address\n is invalid.\n "
] |
Please provide a description of the function:def change_version_byte(address, new_version=None, new_crypto=None):
if not new_version and new_crypto:
try:
new_version = crypto_data[new_crypto]['address_version_byte']
except KeyError:
raise CurrencyNotSupported("Unknown cu... | [
"\n Convert the passed in address (or any base58 encoded string), and change the\n version byte to `new_version`.\n "
] |
Please provide a description of the function:def service_table(format='simple', authenticated=False):
if authenticated:
all_services = ExchangeUniverse.get_authenticated_services()
else:
all_services = ALL_SERVICES
if format == 'html':
linkify = lambda x: "<a href='{0}' target=... | [
"\n Returns a string depicting all services currently installed.\n "
] |
Please provide a description of the function:def find_pair(self, crypto="", fiat="", verbose=False):
self.fetch_pairs()
if not crypto and not fiat:
raise Exception("Fiat or Crypto required")
def is_matched(crypto, fiat, pair):
if crypto and not fiat:
... | [
"\n This utility is used to find an exchange that supports a given exchange pair.\n "
] |
Please provide a description of the function:def all_balances(currency, services=None, verbose=False, timeout=None):
balances = {}
if not services:
services = [
x(verbose=verbose, timeout=timeout)
for x in ExchangeUniverse.get_authenticated_services()
]
for e in... | [
"\n Get balances for passed in currency for all exchanges.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.