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 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
14,100
|
rootpy/rootpy
|
rootpy/decorators.py
|
method_file_check
|
def method_file_check(f):
"""
A decorator to check that a TFile as been created before f is called.
This function can decorate methods.
This requires special treatment since in Python 3 unbound methods are
just functions: http://stackoverflow.com/a/3589335/1002176 but to get
consistent access to the class in both 2.x and 3.x, we need self.
"""
@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 {0}.{1}".format(
self.__class__.__name__, _get_qualified_name(f)))
if not curr_dir.IsWritable():
raise RuntimeError(
"Calling {0}.{1} requires that the "
"current File is writable".format(
self.__class__.__name__, _get_qualified_name(f)))
return f(self, *args, **kwargs)
return wrapper
|
python
|
def method_file_check(f):
"""
A decorator to check that a TFile as been created before f is called.
This function can decorate methods.
This requires special treatment since in Python 3 unbound methods are
just functions: http://stackoverflow.com/a/3589335/1002176 but to get
consistent access to the class in both 2.x and 3.x, we need self.
"""
@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 {0}.{1}".format(
self.__class__.__name__, _get_qualified_name(f)))
if not curr_dir.IsWritable():
raise RuntimeError(
"Calling {0}.{1} requires that the "
"current File is writable".format(
self.__class__.__name__, _get_qualified_name(f)))
return f(self, *args, **kwargs)
return wrapper
|
[
"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 {0}.{1}\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"_get_qualified_name",
"(",
"f",
")",
")",
")",
"if",
"not",
"curr_dir",
".",
"IsWritable",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Calling {0}.{1} requires that the \"",
"\"current File is writable\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"_get_qualified_name",
"(",
"f",
")",
")",
")",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
A decorator to check that a TFile as been created before f is called.
This function can decorate methods.
This requires special treatment since in Python 3 unbound methods are
just functions: http://stackoverflow.com/a/3589335/1002176 but to get
consistent access to the class in both 2.x and 3.x, we need self.
|
[
"A",
"decorator",
"to",
"check",
"that",
"a",
"TFile",
"as",
"been",
"created",
"before",
"f",
"is",
"called",
".",
"This",
"function",
"can",
"decorate",
"methods",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/decorators.py#L64-L86
|
14,101
|
rootpy/rootpy
|
rootpy/decorators.py
|
chainable
|
def chainable(f):
"""
Decorator which causes a 'void' function to return self
Allows chaining of multiple modifier class methods.
"""
@wraps(f)
def wrapper(self, *args, **kwargs):
# perform action
f(self, *args, **kwargs)
# return reference to class.
return self
return wrapper
|
python
|
def chainable(f):
"""
Decorator which causes a 'void' function to return self
Allows chaining of multiple modifier class methods.
"""
@wraps(f)
def wrapper(self, *args, **kwargs):
# perform action
f(self, *args, **kwargs)
# return reference to class.
return self
return wrapper
|
[
"def",
"chainable",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# perform action",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# return reference to class.",
"return",
"self",
"return",
"wrapper"
] |
Decorator which causes a 'void' function to return self
Allows chaining of multiple modifier class methods.
|
[
"Decorator",
"which",
"causes",
"a",
"void",
"function",
"to",
"return",
"self"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/decorators.py#L103-L115
|
14,102
|
rootpy/rootpy
|
rootpy/decorators.py
|
snake_case_methods
|
def snake_case_methods(cls, debug=False):
"""
A class decorator adding snake_case methods
that alias capitalized ROOT methods. cls must subclass
a ROOT class and define the _ROOT class variable.
"""
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
# i.e. TDirectory::cd and Cd...
names = {}
for name, member in members:
lower_name = name.lower()
if lower_name in names:
del names[lower_name]
else:
names[lower_name] = None
for name, member in members:
if name.lower() not in names:
continue
# Don't touch special methods or methods without cap letters
if name[0] == '_' or name.islower():
continue
# Is this a method of the ROOT base class?
if not inspect.ismethod(member) and not inspect.isfunction(member):
continue
# convert CamelCase to snake_case
new_name = camel_to_snake(name)
# Use a __dict__ lookup rather than getattr because we _want_ to
# obtain the _descriptor_, and not what the descriptor gives us
# when it is `getattr`'d.
value = None
skip = False
for c in cls.mro():
# skip methods that are already overridden
if new_name in c.__dict__:
skip = True
break
if name in c.__dict__:
value = c.__dict__[name]
break
# <neo>Woah, a use for for-else</neo>
else:
# Weird. Maybe the item lives somewhere else, such as on the
# metaclass?
value = getattr(cls, name)
if skip:
continue
setattr(cls, new_name, value)
return cls
|
python
|
def snake_case_methods(cls, debug=False):
"""
A class decorator adding snake_case methods
that alias capitalized ROOT methods. cls must subclass
a ROOT class and define the _ROOT class variable.
"""
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
# i.e. TDirectory::cd and Cd...
names = {}
for name, member in members:
lower_name = name.lower()
if lower_name in names:
del names[lower_name]
else:
names[lower_name] = None
for name, member in members:
if name.lower() not in names:
continue
# Don't touch special methods or methods without cap letters
if name[0] == '_' or name.islower():
continue
# Is this a method of the ROOT base class?
if not inspect.ismethod(member) and not inspect.isfunction(member):
continue
# convert CamelCase to snake_case
new_name = camel_to_snake(name)
# Use a __dict__ lookup rather than getattr because we _want_ to
# obtain the _descriptor_, and not what the descriptor gives us
# when it is `getattr`'d.
value = None
skip = False
for c in cls.mro():
# skip methods that are already overridden
if new_name in c.__dict__:
skip = True
break
if name in c.__dict__:
value = c.__dict__[name]
break
# <neo>Woah, a use for for-else</neo>
else:
# Weird. Maybe the item lives somewhere else, such as on the
# metaclass?
value = getattr(cls, name)
if skip:
continue
setattr(cls, new_name, value)
return cls
|
[
"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",
"# i.e. TDirectory::cd and Cd...",
"names",
"=",
"{",
"}",
"for",
"name",
",",
"member",
"in",
"members",
":",
"lower_name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"lower_name",
"in",
"names",
":",
"del",
"names",
"[",
"lower_name",
"]",
"else",
":",
"names",
"[",
"lower_name",
"]",
"=",
"None",
"for",
"name",
",",
"member",
"in",
"members",
":",
"if",
"name",
".",
"lower",
"(",
")",
"not",
"in",
"names",
":",
"continue",
"# Don't touch special methods or methods without cap letters",
"if",
"name",
"[",
"0",
"]",
"==",
"'_'",
"or",
"name",
".",
"islower",
"(",
")",
":",
"continue",
"# Is this a method of the ROOT base class?",
"if",
"not",
"inspect",
".",
"ismethod",
"(",
"member",
")",
"and",
"not",
"inspect",
".",
"isfunction",
"(",
"member",
")",
":",
"continue",
"# convert CamelCase to snake_case",
"new_name",
"=",
"camel_to_snake",
"(",
"name",
")",
"# Use a __dict__ lookup rather than getattr because we _want_ to",
"# obtain the _descriptor_, and not what the descriptor gives us",
"# when it is `getattr`'d.",
"value",
"=",
"None",
"skip",
"=",
"False",
"for",
"c",
"in",
"cls",
".",
"mro",
"(",
")",
":",
"# skip methods that are already overridden",
"if",
"new_name",
"in",
"c",
".",
"__dict__",
":",
"skip",
"=",
"True",
"break",
"if",
"name",
"in",
"c",
".",
"__dict__",
":",
"value",
"=",
"c",
".",
"__dict__",
"[",
"name",
"]",
"break",
"# <neo>Woah, a use for for-else</neo>",
"else",
":",
"# Weird. Maybe the item lives somewhere else, such as on the",
"# metaclass?",
"value",
"=",
"getattr",
"(",
"cls",
",",
"name",
")",
"if",
"skip",
":",
"continue",
"setattr",
"(",
"cls",
",",
"new_name",
",",
"value",
")",
"return",
"cls"
] |
A class decorator adding snake_case methods
that alias capitalized ROOT methods. cls must subclass
a ROOT class and define the _ROOT class variable.
|
[
"A",
"class",
"decorator",
"adding",
"snake_case",
"methods",
"that",
"alias",
"capitalized",
"ROOT",
"methods",
".",
"cls",
"must",
"subclass",
"a",
"ROOT",
"class",
"and",
"define",
"the",
"_ROOT",
"class",
"variable",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/decorators.py#L131-L184
|
14,103
|
rootpy/rootpy
|
rootpy/decorators.py
|
sync
|
def sync(lock):
"""
A synchronization decorator
"""
def sync(f):
@wraps(f)
def new_function(*args, **kwargs):
lock.acquire()
try:
return f(*args, **kwargs)
finally:
lock.release()
return new_function
return sync
|
python
|
def sync(lock):
"""
A synchronization decorator
"""
def sync(f):
@wraps(f)
def new_function(*args, **kwargs):
lock.acquire()
try:
return f(*args, **kwargs)
finally:
lock.release()
return new_function
return sync
|
[
"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",
"sync"
] |
A synchronization decorator
|
[
"A",
"synchronization",
"decorator"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/decorators.py#L187-L200
|
14,104
|
rootpy/rootpy
|
rootpy/stats/correlated_values.py
|
as_ufloat
|
def as_ufloat(roorealvar):
"""
Cast a `RooRealVar` to an `uncertainties.ufloat`
"""
if isinstance(roorealvar, (U.AffineScalarFunc, U.Variable)):
return roorealvar
return U.ufloat((roorealvar.getVal(), roorealvar.getError()))
|
python
|
def as_ufloat(roorealvar):
"""
Cast a `RooRealVar` to an `uncertainties.ufloat`
"""
if isinstance(roorealvar, (U.AffineScalarFunc, U.Variable)):
return roorealvar
return U.ufloat((roorealvar.getVal(), roorealvar.getError()))
|
[
"def",
"as_ufloat",
"(",
"roorealvar",
")",
":",
"if",
"isinstance",
"(",
"roorealvar",
",",
"(",
"U",
".",
"AffineScalarFunc",
",",
"U",
".",
"Variable",
")",
")",
":",
"return",
"roorealvar",
"return",
"U",
".",
"ufloat",
"(",
"(",
"roorealvar",
".",
"getVal",
"(",
")",
",",
"roorealvar",
".",
"getError",
"(",
")",
")",
")"
] |
Cast a `RooRealVar` to an `uncertainties.ufloat`
|
[
"Cast",
"a",
"RooRealVar",
"to",
"an",
"uncertainties",
".",
"ufloat"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/stats/correlated_values.py#L13-L19
|
14,105
|
rootpy/rootpy
|
rootpy/stats/correlated_values.py
|
correlated_values
|
def correlated_values(param_names, roofitresult):
"""
Return symbolic values from a `RooFitResult` taking into account covariance
This is useful for numerically computing the uncertainties for expressions
using correlated values arising from a fit.
Parameters
----------
param_names: list of strings
A list of parameters to extract from the result. The order of the names
is the order of the return value.
roofitresult : RooFitResult
A RooFitResult from a fit.
Returns
-------
list of correlated values from the uncertainties package.
Examples
--------
.. sourcecode:: python
# Fit a pdf to a histogram
pdf = some_roofit_pdf_with_variables("f(x, a, b, c)")
fitresult = pdf.fitTo(histogram, ROOT.RooFit.Save())
a, b, c = correlated_values(["a", "b", "c"], fitresult)
# Arbitrary math expression according to what the `uncertainties`
# package supports, automatically computes correct error propagation
sum_value = a + b + c
value, error = sum_value.nominal_value, sum_value.std_dev()
"""
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]
#values = [as_ufloat(p) for p in pars]
matrix = asrootpy(roofitresult.correlationMatrix()).to_numpy()
uvalues = U.correlated_values_norm(values, matrix.tolist())
uvalues = dict((n, v) for n, v in zip(parnames, uvalues))
assert all(n in uvalues for n in parnames), (
"name {0} isn't in parameter list {1}".format(n, parnames))
# Return a tuple in the order it was asked for
return tuple(uvalues[n] for n in param_names)
|
python
|
def correlated_values(param_names, roofitresult):
"""
Return symbolic values from a `RooFitResult` taking into account covariance
This is useful for numerically computing the uncertainties for expressions
using correlated values arising from a fit.
Parameters
----------
param_names: list of strings
A list of parameters to extract from the result. The order of the names
is the order of the return value.
roofitresult : RooFitResult
A RooFitResult from a fit.
Returns
-------
list of correlated values from the uncertainties package.
Examples
--------
.. sourcecode:: python
# Fit a pdf to a histogram
pdf = some_roofit_pdf_with_variables("f(x, a, b, c)")
fitresult = pdf.fitTo(histogram, ROOT.RooFit.Save())
a, b, c = correlated_values(["a", "b", "c"], fitresult)
# Arbitrary math expression according to what the `uncertainties`
# package supports, automatically computes correct error propagation
sum_value = a + b + c
value, error = sum_value.nominal_value, sum_value.std_dev()
"""
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]
#values = [as_ufloat(p) for p in pars]
matrix = asrootpy(roofitresult.correlationMatrix()).to_numpy()
uvalues = U.correlated_values_norm(values, matrix.tolist())
uvalues = dict((n, v) for n, v in zip(parnames, uvalues))
assert all(n in uvalues for n in parnames), (
"name {0} isn't in parameter list {1}".format(n, parnames))
# Return a tuple in the order it was asked for
return tuple(uvalues[n] for n in param_names)
|
[
"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",
"]",
"#values = [as_ufloat(p) for p in pars]",
"matrix",
"=",
"asrootpy",
"(",
"roofitresult",
".",
"correlationMatrix",
"(",
")",
")",
".",
"to_numpy",
"(",
")",
"uvalues",
"=",
"U",
".",
"correlated_values_norm",
"(",
"values",
",",
"matrix",
".",
"tolist",
"(",
")",
")",
"uvalues",
"=",
"dict",
"(",
"(",
"n",
",",
"v",
")",
"for",
"n",
",",
"v",
"in",
"zip",
"(",
"parnames",
",",
"uvalues",
")",
")",
"assert",
"all",
"(",
"n",
"in",
"uvalues",
"for",
"n",
"in",
"parnames",
")",
",",
"(",
"\"name {0} isn't in parameter list {1}\"",
".",
"format",
"(",
"n",
",",
"parnames",
")",
")",
"# Return a tuple in the order it was asked for",
"return",
"tuple",
"(",
"uvalues",
"[",
"n",
"]",
"for",
"n",
"in",
"param_names",
")"
] |
Return symbolic values from a `RooFitResult` taking into account covariance
This is useful for numerically computing the uncertainties for expressions
using correlated values arising from a fit.
Parameters
----------
param_names: list of strings
A list of parameters to extract from the result. The order of the names
is the order of the return value.
roofitresult : RooFitResult
A RooFitResult from a fit.
Returns
-------
list of correlated values from the uncertainties package.
Examples
--------
.. sourcecode:: python
# Fit a pdf to a histogram
pdf = some_roofit_pdf_with_variables("f(x, a, b, c)")
fitresult = pdf.fitTo(histogram, ROOT.RooFit.Save())
a, b, c = correlated_values(["a", "b", "c"], fitresult)
# Arbitrary math expression according to what the `uncertainties`
# package supports, automatically computes correct error propagation
sum_value = a + b + c
value, error = sum_value.nominal_value, sum_value.std_dev()
|
[
"Return",
"symbolic",
"values",
"from",
"a",
"RooFitResult",
"taking",
"into",
"account",
"covariance"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/stats/correlated_values.py#L22-L75
|
14,106
|
rootpy/rootpy
|
rootpy/tree/treemodel.py
|
TreeModelMeta.checkattr
|
def checkattr(metacls, attr, value):
"""
Only allow class attributes that are instances of
rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy
"""
if not isinstance(value, (
types.MethodType,
types.FunctionType,
classmethod,
staticmethod,
property)):
if attr in dir(type('dummy', (object,), {})) + \
['__metaclass__', '__qualname__']:
return
if attr.startswith('_'):
raise SyntaxError(
"TreeModel attribute `{0}` "
"must not start with `_`".format(attr))
if not inspect.isclass(value):
if not isinstance(value, Column):
raise TypeError(
"TreeModel attribute `{0}` "
"must be an instance of "
"`rootpy.tree.treetypes.Column`".format(attr))
return
if not issubclass(value, (ROOT.TObject, ROOT.ObjectProxy)):
raise TypeError(
"TreeModel attribute `{0}` must inherit "
"from `ROOT.TObject` or `ROOT.ObjectProxy`".format(
attr))
|
python
|
def checkattr(metacls, attr, value):
"""
Only allow class attributes that are instances of
rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy
"""
if not isinstance(value, (
types.MethodType,
types.FunctionType,
classmethod,
staticmethod,
property)):
if attr in dir(type('dummy', (object,), {})) + \
['__metaclass__', '__qualname__']:
return
if attr.startswith('_'):
raise SyntaxError(
"TreeModel attribute `{0}` "
"must not start with `_`".format(attr))
if not inspect.isclass(value):
if not isinstance(value, Column):
raise TypeError(
"TreeModel attribute `{0}` "
"must be an instance of "
"`rootpy.tree.treetypes.Column`".format(attr))
return
if not issubclass(value, (ROOT.TObject, ROOT.ObjectProxy)):
raise TypeError(
"TreeModel attribute `{0}` must inherit "
"from `ROOT.TObject` or `ROOT.ObjectProxy`".format(
attr))
|
[
"def",
"checkattr",
"(",
"metacls",
",",
"attr",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"types",
".",
"MethodType",
",",
"types",
".",
"FunctionType",
",",
"classmethod",
",",
"staticmethod",
",",
"property",
")",
")",
":",
"if",
"attr",
"in",
"dir",
"(",
"type",
"(",
"'dummy'",
",",
"(",
"object",
",",
")",
",",
"{",
"}",
")",
")",
"+",
"[",
"'__metaclass__'",
",",
"'__qualname__'",
"]",
":",
"return",
"if",
"attr",
".",
"startswith",
"(",
"'_'",
")",
":",
"raise",
"SyntaxError",
"(",
"\"TreeModel attribute `{0}` \"",
"\"must not start with `_`\"",
".",
"format",
"(",
"attr",
")",
")",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Column",
")",
":",
"raise",
"TypeError",
"(",
"\"TreeModel attribute `{0}` \"",
"\"must be an instance of \"",
"\"`rootpy.tree.treetypes.Column`\"",
".",
"format",
"(",
"attr",
")",
")",
"return",
"if",
"not",
"issubclass",
"(",
"value",
",",
"(",
"ROOT",
".",
"TObject",
",",
"ROOT",
".",
"ObjectProxy",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"TreeModel attribute `{0}` must inherit \"",
"\"from `ROOT.TObject` or `ROOT.ObjectProxy`\"",
".",
"format",
"(",
"attr",
")",
")"
] |
Only allow class attributes that are instances of
rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy
|
[
"Only",
"allow",
"class",
"attributes",
"that",
"are",
"instances",
"of",
"rootpy",
".",
"types",
".",
"Column",
"ROOT",
".",
"TObject",
"or",
"ROOT",
".",
"ObjectProxy"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/tree/treemodel.py#L53-L82
|
14,107
|
rootpy/rootpy
|
rootpy/tree/treemodel.py
|
TreeModelMeta.prefix
|
def prefix(cls, name):
"""
Create a new TreeModel where class attribute
names are prefixed with ``name``
"""
attrs = dict([(name + attr, value) for attr, value in cls.get_attrs()])
return TreeModelMeta(
'_'.join([name, cls.__name__]),
(TreeModel,), attrs)
|
python
|
def prefix(cls, name):
"""
Create a new TreeModel where class attribute
names are prefixed with ``name``
"""
attrs = dict([(name + attr, value) for attr, value in cls.get_attrs()])
return TreeModelMeta(
'_'.join([name, cls.__name__]),
(TreeModel,), attrs)
|
[
"def",
"prefix",
"(",
"cls",
",",
"name",
")",
":",
"attrs",
"=",
"dict",
"(",
"[",
"(",
"name",
"+",
"attr",
",",
"value",
")",
"for",
"attr",
",",
"value",
"in",
"cls",
".",
"get_attrs",
"(",
")",
"]",
")",
"return",
"TreeModelMeta",
"(",
"'_'",
".",
"join",
"(",
"[",
"name",
",",
"cls",
".",
"__name__",
"]",
")",
",",
"(",
"TreeModel",
",",
")",
",",
"attrs",
")"
] |
Create a new TreeModel where class attribute
names are prefixed with ``name``
|
[
"Create",
"a",
"new",
"TreeModel",
"where",
"class",
"attribute",
"names",
"are",
"prefixed",
"with",
"name"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/tree/treemodel.py#L84-L92
|
14,108
|
rootpy/rootpy
|
rootpy/tree/treemodel.py
|
TreeModelMeta.get_attrs
|
def get_attrs(cls):
"""
Get all class attributes ordered by definition
"""
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], (
types.FunctionType,
types.MethodType,
classmethod,
staticmethod,
property))]
# sort by idx and use attribute name to break ties
attrs.sort(key=lambda attr: (getattr(attr[1], 'idx', -1), attr[0]))
return attrs
|
python
|
def get_attrs(cls):
"""
Get all class attributes ordered by definition
"""
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], (
types.FunctionType,
types.MethodType,
classmethod,
staticmethod,
property))]
# sort by idx and use attribute name to break ties
attrs.sort(key=lambda attr: (getattr(attr[1], 'idx', -1), attr[0]))
return attrs
|
[
"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",
"]",
",",
"(",
"types",
".",
"FunctionType",
",",
"types",
".",
"MethodType",
",",
"classmethod",
",",
"staticmethod",
",",
"property",
")",
")",
"]",
"# sort by idx and use attribute name to break ties",
"attrs",
".",
"sort",
"(",
"key",
"=",
"lambda",
"attr",
":",
"(",
"getattr",
"(",
"attr",
"[",
"1",
"]",
",",
"'idx'",
",",
"-",
"1",
")",
",",
"attr",
"[",
"0",
"]",
")",
")",
"return",
"attrs"
] |
Get all class attributes ordered by definition
|
[
"Get",
"all",
"class",
"attributes",
"ordered",
"by",
"definition"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/tree/treemodel.py#L104-L120
|
14,109
|
rootpy/rootpy
|
rootpy/tree/treemodel.py
|
TreeModelMeta.to_struct
|
def to_struct(cls, name=None):
"""
Convert the TreeModel into a compiled C struct
"""
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)])
if not basic_attrs:
return None
src = 'struct {0} {{'.format(name)
for attr_name, value in basic_attrs.items():
src += '{0} {1};'.format(value.type.typename, attr_name)
src += '};'
if ROOT.gROOT.ProcessLine(src) != 0:
return None
return getattr(ROOT, name, None)
|
python
|
def to_struct(cls, name=None):
"""
Convert the TreeModel into a compiled C struct
"""
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)])
if not basic_attrs:
return None
src = 'struct {0} {{'.format(name)
for attr_name, value in basic_attrs.items():
src += '{0} {1};'.format(value.type.typename, attr_name)
src += '};'
if ROOT.gROOT.ProcessLine(src) != 0:
return None
return getattr(ROOT, name, None)
|
[
"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",
")",
"]",
")",
"if",
"not",
"basic_attrs",
":",
"return",
"None",
"src",
"=",
"'struct {0} {{'",
".",
"format",
"(",
"name",
")",
"for",
"attr_name",
",",
"value",
"in",
"basic_attrs",
".",
"items",
"(",
")",
":",
"src",
"+=",
"'{0} {1};'",
".",
"format",
"(",
"value",
".",
"type",
".",
"typename",
",",
"attr_name",
")",
"src",
"+=",
"'};'",
"if",
"ROOT",
".",
"gROOT",
".",
"ProcessLine",
"(",
"src",
")",
"!=",
"0",
":",
"return",
"None",
"return",
"getattr",
"(",
"ROOT",
",",
"name",
",",
"None",
")"
] |
Convert the TreeModel into a compiled C struct
|
[
"Convert",
"the",
"TreeModel",
"into",
"a",
"compiled",
"C",
"struct"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/tree/treemodel.py#L122-L139
|
14,110
|
rootpy/rootpy
|
rootpy/extern/hep/pdg.py
|
id_to_name
|
def id_to_name(id):
"""
Convert a PDG ID to a printable string.
"""
name = pdgid_names.get(id)
if not name:
name = repr(id)
return name
|
python
|
def id_to_name(id):
"""
Convert a PDG ID to a printable string.
"""
name = pdgid_names.get(id)
if not name:
name = repr(id)
return name
|
[
"def",
"id_to_name",
"(",
"id",
")",
":",
"name",
"=",
"pdgid_names",
".",
"get",
"(",
"id",
")",
"if",
"not",
"name",
":",
"name",
"=",
"repr",
"(",
"id",
")",
"return",
"name"
] |
Convert a PDG ID to a printable string.
|
[
"Convert",
"a",
"PDG",
"ID",
"to",
"a",
"printable",
"string",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/hep/pdg.py#L36-L43
|
14,111
|
rootpy/rootpy
|
rootpy/extern/hep/pdg.py
|
id_to_root_name
|
def id_to_root_name(id):
"""
Convert a PDG ID to a string with root markup.
"""
name = root_names.get(id)
if not name:
name = repr(id)
return name
|
python
|
def id_to_root_name(id):
"""
Convert a PDG ID to a string with root markup.
"""
name = root_names.get(id)
if not name:
name = repr(id)
return name
|
[
"def",
"id_to_root_name",
"(",
"id",
")",
":",
"name",
"=",
"root_names",
".",
"get",
"(",
"id",
")",
"if",
"not",
"name",
":",
"name",
"=",
"repr",
"(",
"id",
")",
"return",
"name"
] |
Convert a PDG ID to a string with root markup.
|
[
"Convert",
"a",
"PDG",
"ID",
"to",
"a",
"string",
"with",
"root",
"markup",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/hep/pdg.py#L46-L53
|
14,112
|
rootpy/rootpy
|
rootpy/utils/inject_closure.py
|
new_closure
|
def new_closure(vals):
"""
Build a new closure
"""
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
|
python
|
def new_closure(vals):
"""
Build a new closure
"""
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
|
[
"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"
] |
Build a new closure
|
[
"Build",
"a",
"new",
"closure"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/utils/inject_closure.py#L19-L27
|
14,113
|
rootpy/rootpy
|
rootpy/utils/inject_closure.py
|
_inject_closure_values_fix_closures
|
def _inject_closure_values_fix_closures(c, injected, **kwargs):
"""
Recursively fix closures
Python bytecode for a closure looks like::
LOAD_CLOSURE var1
BUILD_TUPLE <n_of_vars_closed_over>
LOAD_CONST <code_object_containing_closure>
MAKE_CLOSURE
or this in 3.6 (MAKE_CLOSURE is no longer an opcode)::
LOAD_CLOSURE var1
BUILD_TUPLE <n_of_vars_closed_over>
LOAD_CONST <code_object_containing_closure>
LOAD_CONST <locals>
MAKE_FUNCTION
This function finds closures and adds the injected closed variables in the
right place.
"""
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
codeobj = code[i-1-OPCODE_OFFSET]
assert codeobj[0] == byteplay.LOAD_CONST
build_tuple = code[i-2-OPCODE_OFFSET]
assert build_tuple[0] == byteplay.BUILD_TUPLE
n_closed = build_tuple[1]
load_closures = code[i-2-OPCODE_OFFSET-n_closed:i-2-OPCODE_OFFSET]
assert all(o == byteplay.LOAD_CLOSURE for o, _ in load_closures)
newlcs = [(byteplay.LOAD_CLOSURE, inj) for inj in injected]
code[i-2-OPCODE_OFFSET] = byteplay.BUILD_TUPLE, n_closed + len(injected)
code[i-2-OPCODE_OFFSET:i-2-OPCODE_OFFSET] = newlcs
_inject_closure_values_fix_code(codeobj[1], injected, **kwargs)
|
python
|
def _inject_closure_values_fix_closures(c, injected, **kwargs):
"""
Recursively fix closures
Python bytecode for a closure looks like::
LOAD_CLOSURE var1
BUILD_TUPLE <n_of_vars_closed_over>
LOAD_CONST <code_object_containing_closure>
MAKE_CLOSURE
or this in 3.6 (MAKE_CLOSURE is no longer an opcode)::
LOAD_CLOSURE var1
BUILD_TUPLE <n_of_vars_closed_over>
LOAD_CONST <code_object_containing_closure>
LOAD_CONST <locals>
MAKE_FUNCTION
This function finds closures and adds the injected closed variables in the
right place.
"""
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
codeobj = code[i-1-OPCODE_OFFSET]
assert codeobj[0] == byteplay.LOAD_CONST
build_tuple = code[i-2-OPCODE_OFFSET]
assert build_tuple[0] == byteplay.BUILD_TUPLE
n_closed = build_tuple[1]
load_closures = code[i-2-OPCODE_OFFSET-n_closed:i-2-OPCODE_OFFSET]
assert all(o == byteplay.LOAD_CLOSURE for o, _ in load_closures)
newlcs = [(byteplay.LOAD_CLOSURE, inj) for inj in injected]
code[i-2-OPCODE_OFFSET] = byteplay.BUILD_TUPLE, n_closed + len(injected)
code[i-2-OPCODE_OFFSET:i-2-OPCODE_OFFSET] = newlcs
_inject_closure_values_fix_code(codeobj[1], injected, **kwargs)
|
[
"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",
"codeobj",
"=",
"code",
"[",
"i",
"-",
"1",
"-",
"OPCODE_OFFSET",
"]",
"assert",
"codeobj",
"[",
"0",
"]",
"==",
"byteplay",
".",
"LOAD_CONST",
"build_tuple",
"=",
"code",
"[",
"i",
"-",
"2",
"-",
"OPCODE_OFFSET",
"]",
"assert",
"build_tuple",
"[",
"0",
"]",
"==",
"byteplay",
".",
"BUILD_TUPLE",
"n_closed",
"=",
"build_tuple",
"[",
"1",
"]",
"load_closures",
"=",
"code",
"[",
"i",
"-",
"2",
"-",
"OPCODE_OFFSET",
"-",
"n_closed",
":",
"i",
"-",
"2",
"-",
"OPCODE_OFFSET",
"]",
"assert",
"all",
"(",
"o",
"==",
"byteplay",
".",
"LOAD_CLOSURE",
"for",
"o",
",",
"_",
"in",
"load_closures",
")",
"newlcs",
"=",
"[",
"(",
"byteplay",
".",
"LOAD_CLOSURE",
",",
"inj",
")",
"for",
"inj",
"in",
"injected",
"]",
"code",
"[",
"i",
"-",
"2",
"-",
"OPCODE_OFFSET",
"]",
"=",
"byteplay",
".",
"BUILD_TUPLE",
",",
"n_closed",
"+",
"len",
"(",
"injected",
")",
"code",
"[",
"i",
"-",
"2",
"-",
"OPCODE_OFFSET",
":",
"i",
"-",
"2",
"-",
"OPCODE_OFFSET",
"]",
"=",
"newlcs",
"_inject_closure_values_fix_code",
"(",
"codeobj",
"[",
"1",
"]",
",",
"injected",
",",
"*",
"*",
"kwargs",
")"
] |
Recursively fix closures
Python bytecode for a closure looks like::
LOAD_CLOSURE var1
BUILD_TUPLE <n_of_vars_closed_over>
LOAD_CONST <code_object_containing_closure>
MAKE_CLOSURE
or this in 3.6 (MAKE_CLOSURE is no longer an opcode)::
LOAD_CLOSURE var1
BUILD_TUPLE <n_of_vars_closed_over>
LOAD_CONST <code_object_containing_closure>
LOAD_CONST <locals>
MAKE_FUNCTION
This function finds closures and adds the injected closed variables in the
right place.
|
[
"Recursively",
"fix",
"closures"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/utils/inject_closure.py#L30-L75
|
14,114
|
rootpy/rootpy
|
rootpy/utils/inject_closure.py
|
_inject_closure_values_fix_code
|
def _inject_closure_values_fix_code(c, injected, **kwargs):
"""
Fix code objects, recursively fixing any closures
"""
# 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):
if opcode == byteplay.LOAD_GLOBAL and value in kwargs:
c.code[i] = byteplay.LOAD_DEREF, value
_inject_closure_values_fix_closures(c, injected, **kwargs)
return c
|
python
|
def _inject_closure_values_fix_code(c, injected, **kwargs):
"""
Fix code objects, recursively fixing any closures
"""
# 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):
if opcode == byteplay.LOAD_GLOBAL and value in kwargs:
c.code[i] = byteplay.LOAD_DEREF, value
_inject_closure_values_fix_closures(c, injected, **kwargs)
return c
|
[
"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",
")",
":",
"if",
"opcode",
"==",
"byteplay",
".",
"LOAD_GLOBAL",
"and",
"value",
"in",
"kwargs",
":",
"c",
".",
"code",
"[",
"i",
"]",
"=",
"byteplay",
".",
"LOAD_DEREF",
",",
"value",
"_inject_closure_values_fix_closures",
"(",
"c",
",",
"injected",
",",
"*",
"*",
"kwargs",
")",
"return",
"c"
] |
Fix code objects, recursively fixing any closures
|
[
"Fix",
"code",
"objects",
"recursively",
"fixing",
"any",
"closures"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/utils/inject_closure.py#L78-L93
|
14,115
|
rootpy/rootpy
|
rootpy/utils/inject_closure.py
|
inject_closure_values
|
def inject_closure_values(func, **kwargs):
"""
Returns a new function identical to the previous one except that it acts as
though global variables named in `kwargs` have been closed over with the
values specified in the `kwargs` dictionary.
Works on properties, class/static methods and functions.
This can be useful for mocking and other nefarious activities.
"""
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 fdel: fdel = fix_func(fdel, **kwargs)
wrapped_by = type(func)
return wrapped_by(fget, fset, fdel)
elif isinstance(func, (staticmethod, classmethod)):
func = func.__func__
wrapped_by = type(func)
newfunc = _inject_closure_values(func, **kwargs)
if wrapped_by:
newfunc = wrapped_by(newfunc)
return newfunc
|
python
|
def inject_closure_values(func, **kwargs):
"""
Returns a new function identical to the previous one except that it acts as
though global variables named in `kwargs` have been closed over with the
values specified in the `kwargs` dictionary.
Works on properties, class/static methods and functions.
This can be useful for mocking and other nefarious activities.
"""
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 fdel: fdel = fix_func(fdel, **kwargs)
wrapped_by = type(func)
return wrapped_by(fget, fset, fdel)
elif isinstance(func, (staticmethod, classmethod)):
func = func.__func__
wrapped_by = type(func)
newfunc = _inject_closure_values(func, **kwargs)
if wrapped_by:
newfunc = wrapped_by(newfunc)
return newfunc
|
[
"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",
"fdel",
":",
"fdel",
"=",
"fix_func",
"(",
"fdel",
",",
"*",
"*",
"kwargs",
")",
"wrapped_by",
"=",
"type",
"(",
"func",
")",
"return",
"wrapped_by",
"(",
"fget",
",",
"fset",
",",
"fdel",
")",
"elif",
"isinstance",
"(",
"func",
",",
"(",
"staticmethod",
",",
"classmethod",
")",
")",
":",
"func",
"=",
"func",
".",
"__func__",
"wrapped_by",
"=",
"type",
"(",
"func",
")",
"newfunc",
"=",
"_inject_closure_values",
"(",
"func",
",",
"*",
"*",
"kwargs",
")",
"if",
"wrapped_by",
":",
"newfunc",
"=",
"wrapped_by",
"(",
"newfunc",
")",
"return",
"newfunc"
] |
Returns a new function identical to the previous one except that it acts as
though global variables named in `kwargs` have been closed over with the
values specified in the `kwargs` dictionary.
Works on properties, class/static methods and functions.
This can be useful for mocking and other nefarious activities.
|
[
"Returns",
"a",
"new",
"function",
"identical",
"to",
"the",
"previous",
"one",
"except",
"that",
"it",
"acts",
"as",
"though",
"global",
"variables",
"named",
"in",
"kwargs",
"have",
"been",
"closed",
"over",
"with",
"the",
"values",
"specified",
"in",
"the",
"kwargs",
"dictionary",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/utils/inject_closure.py#L137-L165
|
14,116
|
rootpy/rootpy
|
rootpy/plotting/canvas.py
|
_PadBase.axes
|
def axes(self, ndim=1,
xlimits=None, ylimits=None, zlimits=None,
xbins=1, ybins=1, zbins=1):
"""
Create and return axes on this pad
"""
if xlimits is None:
xlimits = (0, 1)
if ylimits is None:
ylimits = (0, 1)
if zlimits is None:
zlimits = (0, 1)
if ndim == 1:
from .hist import Hist
hist = Hist(1, xlimits[0], xlimits[1])
elif ndim == 2:
from .hist import Hist2D
hist = Hist2D(1, xlimits[0], xlimits[1],
1, ylimits[0], ylimits[1])
elif ndim == 3:
from .hist import Hist3D
hist = Hist3D(1, xlimits[0], xlimits[1],
1, ylimits[0], ylimits[1],
1, zlimits[0], zlimits[1])
else:
raise ValueError("ndim must be 1, 2, or 3")
with self:
hist.Draw('AXIS')
xaxis = hist.xaxis
yaxis = hist.yaxis
if isinstance(xbins, (list, tuple)):
xbins = array('d', xbins)
if hasattr(xbins, '__iter__'):
xaxis.Set(len(xbins) - 1, xbins)
else:
xaxis.Set(xbins, *xlimits)
if ndim > 1:
if isinstance(ybins, (list, tuple)):
ybins = array('d', ybins)
if hasattr(ybins, '__iter__'):
yaxis.Set(len(ybins) - 1, ybins)
else:
yaxis.Set(ybins, *ylimits)
else:
yaxis.limits = ylimits
yaxis.range_user = ylimits
if ndim > 1:
zaxis = hist.zaxis
if ndim == 3:
if isinstance(zbins, (list, tuple)):
zbins = array('d', zbins)
if hasattr(zbins, '__iter__'):
zaxis.Set(len(zbins) - 1, zbins)
else:
zaxis.Set(zbins, *zlimits)
else:
zaxis.limits = zlimits
zaxis.range_user = zlimits
return xaxis, yaxis, zaxis
return xaxis, yaxis
|
python
|
def axes(self, ndim=1,
xlimits=None, ylimits=None, zlimits=None,
xbins=1, ybins=1, zbins=1):
"""
Create and return axes on this pad
"""
if xlimits is None:
xlimits = (0, 1)
if ylimits is None:
ylimits = (0, 1)
if zlimits is None:
zlimits = (0, 1)
if ndim == 1:
from .hist import Hist
hist = Hist(1, xlimits[0], xlimits[1])
elif ndim == 2:
from .hist import Hist2D
hist = Hist2D(1, xlimits[0], xlimits[1],
1, ylimits[0], ylimits[1])
elif ndim == 3:
from .hist import Hist3D
hist = Hist3D(1, xlimits[0], xlimits[1],
1, ylimits[0], ylimits[1],
1, zlimits[0], zlimits[1])
else:
raise ValueError("ndim must be 1, 2, or 3")
with self:
hist.Draw('AXIS')
xaxis = hist.xaxis
yaxis = hist.yaxis
if isinstance(xbins, (list, tuple)):
xbins = array('d', xbins)
if hasattr(xbins, '__iter__'):
xaxis.Set(len(xbins) - 1, xbins)
else:
xaxis.Set(xbins, *xlimits)
if ndim > 1:
if isinstance(ybins, (list, tuple)):
ybins = array('d', ybins)
if hasattr(ybins, '__iter__'):
yaxis.Set(len(ybins) - 1, ybins)
else:
yaxis.Set(ybins, *ylimits)
else:
yaxis.limits = ylimits
yaxis.range_user = ylimits
if ndim > 1:
zaxis = hist.zaxis
if ndim == 3:
if isinstance(zbins, (list, tuple)):
zbins = array('d', zbins)
if hasattr(zbins, '__iter__'):
zaxis.Set(len(zbins) - 1, zbins)
else:
zaxis.Set(zbins, *zlimits)
else:
zaxis.limits = zlimits
zaxis.range_user = zlimits
return xaxis, yaxis, zaxis
return xaxis, yaxis
|
[
"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",
":",
"zlimits",
"=",
"(",
"0",
",",
"1",
")",
"if",
"ndim",
"==",
"1",
":",
"from",
".",
"hist",
"import",
"Hist",
"hist",
"=",
"Hist",
"(",
"1",
",",
"xlimits",
"[",
"0",
"]",
",",
"xlimits",
"[",
"1",
"]",
")",
"elif",
"ndim",
"==",
"2",
":",
"from",
".",
"hist",
"import",
"Hist2D",
"hist",
"=",
"Hist2D",
"(",
"1",
",",
"xlimits",
"[",
"0",
"]",
",",
"xlimits",
"[",
"1",
"]",
",",
"1",
",",
"ylimits",
"[",
"0",
"]",
",",
"ylimits",
"[",
"1",
"]",
")",
"elif",
"ndim",
"==",
"3",
":",
"from",
".",
"hist",
"import",
"Hist3D",
"hist",
"=",
"Hist3D",
"(",
"1",
",",
"xlimits",
"[",
"0",
"]",
",",
"xlimits",
"[",
"1",
"]",
",",
"1",
",",
"ylimits",
"[",
"0",
"]",
",",
"ylimits",
"[",
"1",
"]",
",",
"1",
",",
"zlimits",
"[",
"0",
"]",
",",
"zlimits",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"ndim must be 1, 2, or 3\"",
")",
"with",
"self",
":",
"hist",
".",
"Draw",
"(",
"'AXIS'",
")",
"xaxis",
"=",
"hist",
".",
"xaxis",
"yaxis",
"=",
"hist",
".",
"yaxis",
"if",
"isinstance",
"(",
"xbins",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"xbins",
"=",
"array",
"(",
"'d'",
",",
"xbins",
")",
"if",
"hasattr",
"(",
"xbins",
",",
"'__iter__'",
")",
":",
"xaxis",
".",
"Set",
"(",
"len",
"(",
"xbins",
")",
"-",
"1",
",",
"xbins",
")",
"else",
":",
"xaxis",
".",
"Set",
"(",
"xbins",
",",
"*",
"xlimits",
")",
"if",
"ndim",
">",
"1",
":",
"if",
"isinstance",
"(",
"ybins",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"ybins",
"=",
"array",
"(",
"'d'",
",",
"ybins",
")",
"if",
"hasattr",
"(",
"ybins",
",",
"'__iter__'",
")",
":",
"yaxis",
".",
"Set",
"(",
"len",
"(",
"ybins",
")",
"-",
"1",
",",
"ybins",
")",
"else",
":",
"yaxis",
".",
"Set",
"(",
"ybins",
",",
"*",
"ylimits",
")",
"else",
":",
"yaxis",
".",
"limits",
"=",
"ylimits",
"yaxis",
".",
"range_user",
"=",
"ylimits",
"if",
"ndim",
">",
"1",
":",
"zaxis",
"=",
"hist",
".",
"zaxis",
"if",
"ndim",
"==",
"3",
":",
"if",
"isinstance",
"(",
"zbins",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"zbins",
"=",
"array",
"(",
"'d'",
",",
"zbins",
")",
"if",
"hasattr",
"(",
"zbins",
",",
"'__iter__'",
")",
":",
"zaxis",
".",
"Set",
"(",
"len",
"(",
"zbins",
")",
"-",
"1",
",",
"zbins",
")",
"else",
":",
"zaxis",
".",
"Set",
"(",
"zbins",
",",
"*",
"zlimits",
")",
"else",
":",
"zaxis",
".",
"limits",
"=",
"zlimits",
"zaxis",
".",
"range_user",
"=",
"zlimits",
"return",
"xaxis",
",",
"yaxis",
",",
"zaxis",
"return",
"xaxis",
",",
"yaxis"
] |
Create and return axes on this pad
|
[
"Create",
"and",
"return",
"axes",
"on",
"this",
"pad"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/canvas.py#L34-L93
|
14,117
|
rootpy/rootpy
|
rootpy/root2hdf5.py
|
root2hdf5
|
def root2hdf5(rfile, hfile, rpath='',
entries=-1, userfunc=None,
show_progress=False,
ignore_exception=False,
**kwargs):
"""
Convert all trees in a ROOT file into tables in an HDF5 file.
Parameters
----------
rfile : string or asrootpy'd ROOT File
A ROOT File handle or string path to an existing ROOT file.
hfile : string or PyTables HDF5 File
A PyTables HDF5 File handle or string path to an existing HDF5 file.
rpath : string, optional (default='')
Top level path to begin traversal through the ROOT file. By default
convert everything in and below the root directory.
entries : int, optional (default=-1)
The number of entries to read at once while converting a ROOT TTree
into an HDF5 table. By default read the entire TTree into memory (this
may not be desired if your TTrees are large).
userfunc : callable, optional (default=None)
A function that will be called on every tree and that must return a
tree or list of trees that will be converted instead of the original
tree.
show_progress : bool, optional (default=False)
If True, then display and update a progress bar on stdout as each tree
is converted.
ignore_exception : bool, optional (default=False)
If True, then ignore exceptions raised in converting trees and instead
skip such trees.
kwargs : dict, optional
Additional keyword arguments for the tree2array function.
"""
own_rootfile = False
if isinstance(rfile, string_types):
rfile = root_open(rfile)
own_rootfile = True
own_h5file = False
if isinstance(hfile, string_types):
hfile = tables_open(filename=hfile, mode="w", title="Data")
own_h5file = True
for dirpath, dirnames, treenames in rfile.walk(
rpath, class_ref=QROOT.TTree):
# skip directories w/o trees
if not treenames:
continue
treenames.sort()
group_where = '/' + os.path.dirname(dirpath)
group_name = os.path.basename(dirpath)
if not group_name:
group = hfile.root
elif TABLES_NEW_API:
group = hfile.create_group(group_where, group_name,
createparents=True)
else:
group = hfile.createGroup(group_where, group_name)
ntrees = len(treenames)
log.info(
"Will convert {0:d} tree{1} in {2}".format(
ntrees, 's' if ntrees != 1 else '',
os.path.join(group_where, group_name)))
for treename in treenames:
input_tree = rfile.Get(os.path.join(dirpath, treename))
if userfunc is not None:
tmp_file = TemporaryFile()
# call user-defined function on tree and get output trees
log.info("Calling user function on tree '{0}'".format(
input_tree.GetName()))
trees = userfunc(input_tree)
if not isinstance(trees, list):
trees = [trees]
else:
trees = [input_tree]
tmp_file = None
for tree in trees:
try:
tree2hdf5(tree, hfile, group=group,
entries=entries,
show_progress=show_progress,
**kwargs)
except Exception as e:
if ignore_exception:
log.error("Failed to convert tree '{0}': {1}".format(
tree.GetName(), str(e)))
else:
raise
input_tree.Delete()
if userfunc is not None:
for tree in trees:
tree.Delete()
tmp_file.Close()
if own_h5file:
hfile.close()
if own_rootfile:
rfile.Close()
|
python
|
def root2hdf5(rfile, hfile, rpath='',
entries=-1, userfunc=None,
show_progress=False,
ignore_exception=False,
**kwargs):
"""
Convert all trees in a ROOT file into tables in an HDF5 file.
Parameters
----------
rfile : string or asrootpy'd ROOT File
A ROOT File handle or string path to an existing ROOT file.
hfile : string or PyTables HDF5 File
A PyTables HDF5 File handle or string path to an existing HDF5 file.
rpath : string, optional (default='')
Top level path to begin traversal through the ROOT file. By default
convert everything in and below the root directory.
entries : int, optional (default=-1)
The number of entries to read at once while converting a ROOT TTree
into an HDF5 table. By default read the entire TTree into memory (this
may not be desired if your TTrees are large).
userfunc : callable, optional (default=None)
A function that will be called on every tree and that must return a
tree or list of trees that will be converted instead of the original
tree.
show_progress : bool, optional (default=False)
If True, then display and update a progress bar on stdout as each tree
is converted.
ignore_exception : bool, optional (default=False)
If True, then ignore exceptions raised in converting trees and instead
skip such trees.
kwargs : dict, optional
Additional keyword arguments for the tree2array function.
"""
own_rootfile = False
if isinstance(rfile, string_types):
rfile = root_open(rfile)
own_rootfile = True
own_h5file = False
if isinstance(hfile, string_types):
hfile = tables_open(filename=hfile, mode="w", title="Data")
own_h5file = True
for dirpath, dirnames, treenames in rfile.walk(
rpath, class_ref=QROOT.TTree):
# skip directories w/o trees
if not treenames:
continue
treenames.sort()
group_where = '/' + os.path.dirname(dirpath)
group_name = os.path.basename(dirpath)
if not group_name:
group = hfile.root
elif TABLES_NEW_API:
group = hfile.create_group(group_where, group_name,
createparents=True)
else:
group = hfile.createGroup(group_where, group_name)
ntrees = len(treenames)
log.info(
"Will convert {0:d} tree{1} in {2}".format(
ntrees, 's' if ntrees != 1 else '',
os.path.join(group_where, group_name)))
for treename in treenames:
input_tree = rfile.Get(os.path.join(dirpath, treename))
if userfunc is not None:
tmp_file = TemporaryFile()
# call user-defined function on tree and get output trees
log.info("Calling user function on tree '{0}'".format(
input_tree.GetName()))
trees = userfunc(input_tree)
if not isinstance(trees, list):
trees = [trees]
else:
trees = [input_tree]
tmp_file = None
for tree in trees:
try:
tree2hdf5(tree, hfile, group=group,
entries=entries,
show_progress=show_progress,
**kwargs)
except Exception as e:
if ignore_exception:
log.error("Failed to convert tree '{0}': {1}".format(
tree.GetName(), str(e)))
else:
raise
input_tree.Delete()
if userfunc is not None:
for tree in trees:
tree.Delete()
tmp_file.Close()
if own_h5file:
hfile.close()
if own_rootfile:
rfile.Close()
|
[
"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",
"(",
"rfile",
")",
"own_rootfile",
"=",
"True",
"own_h5file",
"=",
"False",
"if",
"isinstance",
"(",
"hfile",
",",
"string_types",
")",
":",
"hfile",
"=",
"tables_open",
"(",
"filename",
"=",
"hfile",
",",
"mode",
"=",
"\"w\"",
",",
"title",
"=",
"\"Data\"",
")",
"own_h5file",
"=",
"True",
"for",
"dirpath",
",",
"dirnames",
",",
"treenames",
"in",
"rfile",
".",
"walk",
"(",
"rpath",
",",
"class_ref",
"=",
"QROOT",
".",
"TTree",
")",
":",
"# skip directories w/o trees",
"if",
"not",
"treenames",
":",
"continue",
"treenames",
".",
"sort",
"(",
")",
"group_where",
"=",
"'/'",
"+",
"os",
".",
"path",
".",
"dirname",
"(",
"dirpath",
")",
"group_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"dirpath",
")",
"if",
"not",
"group_name",
":",
"group",
"=",
"hfile",
".",
"root",
"elif",
"TABLES_NEW_API",
":",
"group",
"=",
"hfile",
".",
"create_group",
"(",
"group_where",
",",
"group_name",
",",
"createparents",
"=",
"True",
")",
"else",
":",
"group",
"=",
"hfile",
".",
"createGroup",
"(",
"group_where",
",",
"group_name",
")",
"ntrees",
"=",
"len",
"(",
"treenames",
")",
"log",
".",
"info",
"(",
"\"Will convert {0:d} tree{1} in {2}\"",
".",
"format",
"(",
"ntrees",
",",
"'s'",
"if",
"ntrees",
"!=",
"1",
"else",
"''",
",",
"os",
".",
"path",
".",
"join",
"(",
"group_where",
",",
"group_name",
")",
")",
")",
"for",
"treename",
"in",
"treenames",
":",
"input_tree",
"=",
"rfile",
".",
"Get",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"treename",
")",
")",
"if",
"userfunc",
"is",
"not",
"None",
":",
"tmp_file",
"=",
"TemporaryFile",
"(",
")",
"# call user-defined function on tree and get output trees",
"log",
".",
"info",
"(",
"\"Calling user function on tree '{0}'\"",
".",
"format",
"(",
"input_tree",
".",
"GetName",
"(",
")",
")",
")",
"trees",
"=",
"userfunc",
"(",
"input_tree",
")",
"if",
"not",
"isinstance",
"(",
"trees",
",",
"list",
")",
":",
"trees",
"=",
"[",
"trees",
"]",
"else",
":",
"trees",
"=",
"[",
"input_tree",
"]",
"tmp_file",
"=",
"None",
"for",
"tree",
"in",
"trees",
":",
"try",
":",
"tree2hdf5",
"(",
"tree",
",",
"hfile",
",",
"group",
"=",
"group",
",",
"entries",
"=",
"entries",
",",
"show_progress",
"=",
"show_progress",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"ignore_exception",
":",
"log",
".",
"error",
"(",
"\"Failed to convert tree '{0}': {1}\"",
".",
"format",
"(",
"tree",
".",
"GetName",
"(",
")",
",",
"str",
"(",
"e",
")",
")",
")",
"else",
":",
"raise",
"input_tree",
".",
"Delete",
"(",
")",
"if",
"userfunc",
"is",
"not",
"None",
":",
"for",
"tree",
"in",
"trees",
":",
"tree",
".",
"Delete",
"(",
")",
"tmp_file",
".",
"Close",
"(",
")",
"if",
"own_h5file",
":",
"hfile",
".",
"close",
"(",
")",
"if",
"own_rootfile",
":",
"rfile",
".",
"Close",
"(",
")"
] |
Convert all trees in a ROOT file into tables in an HDF5 file.
Parameters
----------
rfile : string or asrootpy'd ROOT File
A ROOT File handle or string path to an existing ROOT file.
hfile : string or PyTables HDF5 File
A PyTables HDF5 File handle or string path to an existing HDF5 file.
rpath : string, optional (default='')
Top level path to begin traversal through the ROOT file. By default
convert everything in and below the root directory.
entries : int, optional (default=-1)
The number of entries to read at once while converting a ROOT TTree
into an HDF5 table. By default read the entire TTree into memory (this
may not be desired if your TTrees are large).
userfunc : callable, optional (default=None)
A function that will be called on every tree and that must return a
tree or list of trees that will be converted instead of the original
tree.
show_progress : bool, optional (default=False)
If True, then display and update a progress bar on stdout as each tree
is converted.
ignore_exception : bool, optional (default=False)
If True, then ignore exceptions raised in converting trees and instead
skip such trees.
kwargs : dict, optional
Additional keyword arguments for the tree2array function.
|
[
"Convert",
"all",
"trees",
"in",
"a",
"ROOT",
"file",
"into",
"tables",
"in",
"an",
"HDF5",
"file",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/root2hdf5.py#L190-L310
|
14,118
|
rootpy/rootpy
|
rootpy/plotting/graph.py
|
_Graph1DBase.Reverse
|
def Reverse(self, copy=False):
"""
Reverse the order of the points
"""
numPoints = self.GetN()
if copy:
revGraph = self.Clone()
else:
revGraph = self
X = self.GetX()
EXlow = self.GetEXlow()
EXhigh = self.GetEXhigh()
Y = self.GetY()
EYlow = self.GetEYlow()
EYhigh = self.GetEYhigh()
for i in range(numPoints):
index = numPoints - 1 - i
revGraph.SetPoint(i, X[index], Y[index])
revGraph.SetPointError(
i,
EXlow[index], EXhigh[index],
EYlow[index], EYhigh[index])
return revGraph
|
python
|
def Reverse(self, copy=False):
"""
Reverse the order of the points
"""
numPoints = self.GetN()
if copy:
revGraph = self.Clone()
else:
revGraph = self
X = self.GetX()
EXlow = self.GetEXlow()
EXhigh = self.GetEXhigh()
Y = self.GetY()
EYlow = self.GetEYlow()
EYhigh = self.GetEYhigh()
for i in range(numPoints):
index = numPoints - 1 - i
revGraph.SetPoint(i, X[index], Y[index])
revGraph.SetPointError(
i,
EXlow[index], EXhigh[index],
EYlow[index], EYhigh[index])
return revGraph
|
[
"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",
".",
"GetY",
"(",
")",
"EYlow",
"=",
"self",
".",
"GetEYlow",
"(",
")",
"EYhigh",
"=",
"self",
".",
"GetEYhigh",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"numPoints",
")",
":",
"index",
"=",
"numPoints",
"-",
"1",
"-",
"i",
"revGraph",
".",
"SetPoint",
"(",
"i",
",",
"X",
"[",
"index",
"]",
",",
"Y",
"[",
"index",
"]",
")",
"revGraph",
".",
"SetPointError",
"(",
"i",
",",
"EXlow",
"[",
"index",
"]",
",",
"EXhigh",
"[",
"index",
"]",
",",
"EYlow",
"[",
"index",
"]",
",",
"EYhigh",
"[",
"index",
"]",
")",
"return",
"revGraph"
] |
Reverse the order of the points
|
[
"Reverse",
"the",
"order",
"of",
"the",
"points"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/graph.py#L493-L515
|
14,119
|
rootpy/rootpy
|
rootpy/plotting/graph.py
|
_Graph1DBase.Shift
|
def Shift(self, value, copy=False):
"""
Shift the graph left or right by value
"""
numPoints = self.GetN()
if copy:
shiftGraph = self.Clone()
else:
shiftGraph = self
X = self.GetX()
EXlow = self.GetEXlow()
EXhigh = self.GetEXhigh()
Y = self.GetY()
EYlow = self.GetEYlow()
EYhigh = self.GetEYhigh()
for i in range(numPoints):
shiftGraph.SetPoint(i, X[i] + value, Y[i])
shiftGraph.SetPointError(
i,
EXlow[i], EXhigh[i],
EYlow[i], EYhigh[i])
return shiftGraph
|
python
|
def Shift(self, value, copy=False):
"""
Shift the graph left or right by value
"""
numPoints = self.GetN()
if copy:
shiftGraph = self.Clone()
else:
shiftGraph = self
X = self.GetX()
EXlow = self.GetEXlow()
EXhigh = self.GetEXhigh()
Y = self.GetY()
EYlow = self.GetEYlow()
EYhigh = self.GetEYhigh()
for i in range(numPoints):
shiftGraph.SetPoint(i, X[i] + value, Y[i])
shiftGraph.SetPointError(
i,
EXlow[i], EXhigh[i],
EYlow[i], EYhigh[i])
return shiftGraph
|
[
"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",
"=",
"self",
".",
"GetY",
"(",
")",
"EYlow",
"=",
"self",
".",
"GetEYlow",
"(",
")",
"EYhigh",
"=",
"self",
".",
"GetEYhigh",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"numPoints",
")",
":",
"shiftGraph",
".",
"SetPoint",
"(",
"i",
",",
"X",
"[",
"i",
"]",
"+",
"value",
",",
"Y",
"[",
"i",
"]",
")",
"shiftGraph",
".",
"SetPointError",
"(",
"i",
",",
"EXlow",
"[",
"i",
"]",
",",
"EXhigh",
"[",
"i",
"]",
",",
"EYlow",
"[",
"i",
"]",
",",
"EYhigh",
"[",
"i",
"]",
")",
"return",
"shiftGraph"
] |
Shift the graph left or right by value
|
[
"Shift",
"the",
"graph",
"left",
"or",
"right",
"by",
"value"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/graph.py#L586-L607
|
14,120
|
rootpy/rootpy
|
rootpy/plotting/graph.py
|
_Graph1DBase.Integrate
|
def Integrate(self):
"""
Integrate using the trapazoidal method
"""
area = 0.
X = self.GetX()
Y = self.GetY()
for i in range(self.GetN() - 1):
area += (X[i + 1] - X[i]) * (Y[i] + Y[i + 1]) / 2.
return area
|
python
|
def Integrate(self):
"""
Integrate using the trapazoidal method
"""
area = 0.
X = self.GetX()
Y = self.GetY()
for i in range(self.GetN() - 1):
area += (X[i + 1] - X[i]) * (Y[i] + Y[i + 1]) / 2.
return area
|
[
"def",
"Integrate",
"(",
"self",
")",
":",
"area",
"=",
"0.",
"X",
"=",
"self",
".",
"GetX",
"(",
")",
"Y",
"=",
"self",
".",
"GetY",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"GetN",
"(",
")",
"-",
"1",
")",
":",
"area",
"+=",
"(",
"X",
"[",
"i",
"+",
"1",
"]",
"-",
"X",
"[",
"i",
"]",
")",
"*",
"(",
"Y",
"[",
"i",
"]",
"+",
"Y",
"[",
"i",
"+",
"1",
"]",
")",
"/",
"2.",
"return",
"area"
] |
Integrate using the trapazoidal method
|
[
"Integrate",
"using",
"the",
"trapazoidal",
"method"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/graph.py#L609-L618
|
14,121
|
rootpy/rootpy
|
rootpy/plotting/graph.py
|
_Graph1DBase.Append
|
def Append(self, other):
"""
Append points from another graph
"""
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)
self.SetPointError(
ipoint,
point.x.error_low, point.x.error_hi,
point.y.error_low, point.y.error_hi)
ipoint += 1
else:
for point in other:
self.SetPoint(ipoint, point.x.value, point.y.value)
ipoint += 1
|
python
|
def Append(self, other):
"""
Append points from another graph
"""
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)
self.SetPointError(
ipoint,
point.x.error_low, point.x.error_hi,
point.y.error_low, point.y.error_hi)
ipoint += 1
else:
for point in other:
self.SetPoint(ipoint, point.x.value, point.y.value)
ipoint += 1
|
[
"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",
")",
"self",
".",
"SetPointError",
"(",
"ipoint",
",",
"point",
".",
"x",
".",
"error_low",
",",
"point",
".",
"x",
".",
"error_hi",
",",
"point",
".",
"y",
".",
"error_low",
",",
"point",
".",
"y",
".",
"error_hi",
")",
"ipoint",
"+=",
"1",
"else",
":",
"for",
"point",
"in",
"other",
":",
"self",
".",
"SetPoint",
"(",
"ipoint",
",",
"point",
".",
"x",
".",
"value",
",",
"point",
".",
"y",
".",
"value",
")",
"ipoint",
"+=",
"1"
] |
Append points from another graph
|
[
"Append",
"points",
"from",
"another",
"graph"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/graph.py#L620-L638
|
14,122
|
rootpy/rootpy
|
rootpy/memory/keepalive.py
|
keepalive
|
def keepalive(nurse, *patients):
"""
Keep ``patients`` alive at least as long as ``nurse`` is around using a
``WeakKeyDictionary``.
"""
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))
hashable_patients.append(p)
else:
log.warning("Unable to keep unhashable object {0} "
"alive for lifetime of {1}".format(p, nurse))
KEEPALIVE.setdefault(nurse, set()).update(hashable_patients)
else:
log.warning("Unable to keep objects alive for lifetime of "
"unhashable object {0}".format(nurse))
|
python
|
def keepalive(nurse, *patients):
"""
Keep ``patients`` alive at least as long as ``nurse`` is around using a
``WeakKeyDictionary``.
"""
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))
hashable_patients.append(p)
else:
log.warning("Unable to keep unhashable object {0} "
"alive for lifetime of {1}".format(p, nurse))
KEEPALIVE.setdefault(nurse, set()).update(hashable_patients)
else:
log.warning("Unable to keep objects alive for lifetime of "
"unhashable object {0}".format(nurse))
|
[
"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",
")",
")",
"hashable_patients",
".",
"append",
"(",
"p",
")",
"else",
":",
"log",
".",
"warning",
"(",
"\"Unable to keep unhashable object {0} \"",
"\"alive for lifetime of {1}\"",
".",
"format",
"(",
"p",
",",
"nurse",
")",
")",
"KEEPALIVE",
".",
"setdefault",
"(",
"nurse",
",",
"set",
"(",
")",
")",
".",
"update",
"(",
"hashable_patients",
")",
"else",
":",
"log",
".",
"warning",
"(",
"\"Unable to keep objects alive for lifetime of \"",
"\"unhashable object {0}\"",
".",
"format",
"(",
"nurse",
")",
")"
] |
Keep ``patients`` alive at least as long as ``nurse`` is around using a
``WeakKeyDictionary``.
|
[
"Keep",
"patients",
"alive",
"at",
"least",
"as",
"long",
"as",
"nurse",
"is",
"around",
"using",
"a",
"WeakKeyDictionary",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/memory/keepalive.py#L26-L45
|
14,123
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
canonify_slice
|
def canonify_slice(s, n):
"""
Convert a slice object into a canonical form
to simplify treatment in histogram bin content
and edge slicing.
"""
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
return slice(start, stop, step)
|
python
|
def canonify_slice(s, n):
"""
Convert a slice object into a canonical form
to simplify treatment in histogram bin content
and edge slicing.
"""
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
return slice(start, stop, step)
|
[
"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",
"return",
"slice",
"(",
"start",
",",
"stop",
",",
"step",
")"
] |
Convert a slice object into a canonical form
to simplify treatment in histogram bin content
and edge slicing.
|
[
"Convert",
"a",
"slice",
"object",
"into",
"a",
"canonical",
"form",
"to",
"simplify",
"treatment",
"in",
"histogram",
"bin",
"content",
"and",
"edge",
"slicing",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L37-L48
|
14,124
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
bin_to_edge_slice
|
def bin_to_edge_slice(s, n):
"""
Convert a bin slice into a bin edge slice.
"""
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 - 1 or stop == start + 1:
return slice(0, None, min(step, n - 2))
s = slice(start, stop, abs(s.step))
if len(range(*s.indices(n - 1))) < 2:
return slice(start, stop, stop - start - 1)
return s
|
python
|
def bin_to_edge_slice(s, n):
"""
Convert a bin slice into a bin edge slice.
"""
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 - 1 or stop == start + 1:
return slice(0, None, min(step, n - 2))
s = slice(start, stop, abs(s.step))
if len(range(*s.indices(n - 1))) < 2:
return slice(start, stop, stop - start - 1)
return s
|
[
"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",
"-",
"1",
"or",
"stop",
"==",
"start",
"+",
"1",
":",
"return",
"slice",
"(",
"0",
",",
"None",
",",
"min",
"(",
"step",
",",
"n",
"-",
"2",
")",
")",
"s",
"=",
"slice",
"(",
"start",
",",
"stop",
",",
"abs",
"(",
"s",
".",
"step",
")",
")",
"if",
"len",
"(",
"range",
"(",
"*",
"s",
".",
"indices",
"(",
"n",
"-",
"1",
")",
")",
")",
"<",
"2",
":",
"return",
"slice",
"(",
"start",
",",
"stop",
",",
"stop",
"-",
"start",
"-",
"1",
")",
"return",
"s"
] |
Convert a bin slice into a bin edge slice.
|
[
"Convert",
"a",
"bin",
"slice",
"into",
"a",
"bin",
"edge",
"slice",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L51-L69
|
14,125
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
histogram
|
def histogram(data, *args, **kwargs):
"""
Create and fill a one-dimensional histogram.
The same arguments as the ``Hist`` class are expected.
If the number of bins and the ranges are not specified they are
automatically deduced with the ``autobinning`` function using the method
specified by the ``binning`` argument. Only one-dimensional histogramming
is supported.
"""
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']
histo = Hist(*args, **kwargs)
for d in data:
histo.Fill(d)
return list(histo.xedgesl()), histo
|
python
|
def histogram(data, *args, **kwargs):
"""
Create and fill a one-dimensional histogram.
The same arguments as the ``Hist`` class are expected.
If the number of bins and the ranges are not specified they are
automatically deduced with the ``autobinning`` function using the method
specified by the ``binning`` argument. Only one-dimensional histogramming
is supported.
"""
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']
histo = Hist(*args, **kwargs)
for d in data:
histo.Fill(d)
return list(histo.xedgesl()), histo
|
[
"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'",
"]",
"histo",
"=",
"Hist",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"d",
"in",
"data",
":",
"histo",
".",
"Fill",
"(",
"d",
")",
"return",
"list",
"(",
"histo",
".",
"xedgesl",
"(",
")",
")",
",",
"histo"
] |
Create and fill a one-dimensional histogram.
The same arguments as the ``Hist`` class are expected.
If the number of bins and the ranges are not specified they are
automatically deduced with the ``autobinning`` function using the method
specified by the ``binning`` argument. Only one-dimensional histogramming
is supported.
|
[
"Create",
"and",
"fill",
"a",
"one",
"-",
"dimensional",
"histogram",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L2649-L2669
|
14,126
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
BinProxy.overflow
|
def overflow(self):
"""
Returns true if this BinProxy is for an overflow bin
"""
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
|
python
|
def overflow(self):
"""
Returns true if this BinProxy is for an overflow bin
"""
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
|
[
"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"
] |
Returns true if this BinProxy is for an overflow bin
|
[
"Returns",
"true",
"if",
"this",
"BinProxy",
"is",
"for",
"an",
"overflow",
"bin"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L217-L225
|
14,127
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.xyz
|
def xyz(self, idx):
"""
return binx, biny, binz corresponding to the global bin number
"""
# 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
binz = 0
elif ndim < 3:
binx = idx % nx
biny = ((idx - binx) // nx) % ny
binz = 0
elif ndim < 4:
binx = idx % nx
biny = ((idx - binx) // nx) % ny
binz = ((idx - binx) // nx - biny) // ny
else:
raise NotImplementedError
return binx, biny, binz
|
python
|
def xyz(self, idx):
"""
return binx, biny, binz corresponding to the global bin number
"""
# 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
binz = 0
elif ndim < 3:
binx = idx % nx
biny = ((idx - binx) // nx) % ny
binz = 0
elif ndim < 4:
binx = idx % nx
biny = ((idx - binx) // nx) % ny
binz = ((idx - binx) // nx - biny) // ny
else:
raise NotImplementedError
return binx, biny, binz
|
[
"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",
"binz",
"=",
"0",
"elif",
"ndim",
"<",
"3",
":",
"binx",
"=",
"idx",
"%",
"nx",
"biny",
"=",
"(",
"(",
"idx",
"-",
"binx",
")",
"//",
"nx",
")",
"%",
"ny",
"binz",
"=",
"0",
"elif",
"ndim",
"<",
"4",
":",
"binx",
"=",
"idx",
"%",
"nx",
"biny",
"=",
"(",
"(",
"idx",
"-",
"binx",
")",
"//",
"nx",
")",
"%",
"ny",
"binz",
"=",
"(",
"(",
"idx",
"-",
"binx",
")",
"//",
"nx",
"-",
"biny",
")",
"//",
"ny",
"else",
":",
"raise",
"NotImplementedError",
"return",
"binx",
",",
"biny",
",",
"binz"
] |
return binx, biny, binz corresponding to the global bin number
|
[
"return",
"binx",
"biny",
"binz",
"corresponding",
"to",
"the",
"global",
"bin",
"number"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L377-L400
|
14,128
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.nbins
|
def nbins(self, axis=0, overflow=False):
"""
Get the number of bins along an axis
"""
if axis == 0:
nbins = self.GetNbinsX()
elif axis == 1:
nbins = self.GetNbinsY()
elif axis == 2:
nbins = self.GetNbinsZ()
else:
raise ValueError("axis must be 0, 1, or 2")
if overflow:
nbins += 2
return nbins
|
python
|
def nbins(self, axis=0, overflow=False):
"""
Get the number of bins along an axis
"""
if axis == 0:
nbins = self.GetNbinsX()
elif axis == 1:
nbins = self.GetNbinsY()
elif axis == 2:
nbins = self.GetNbinsZ()
else:
raise ValueError("axis must be 0, 1, or 2")
if overflow:
nbins += 2
return nbins
|
[
"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",
"(",
"\"axis must be 0, 1, or 2\"",
")",
"if",
"overflow",
":",
"nbins",
"+=",
"2",
"return",
"nbins"
] |
Get the number of bins along an axis
|
[
"Get",
"the",
"number",
"of",
"bins",
"along",
"an",
"axis"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L463-L477
|
14,129
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.bins_range
|
def bins_range(self, axis=0, overflow=False):
"""
Return a range of bin indices for iterating along an axis
Parameters
----------
axis : int, optional (default=1)
The axis (0, 1 or 2).
overflow : bool, optional (default=False)
If True then include the underflow and overflow bins
otherwise only include the visible bins.
Returns
-------
an range object of bin indices
"""
nbins = self.nbins(axis=axis, overflow=False)
if overflow:
start = 0
end_offset = 2
else:
start = 1
end_offset = 1
return range(start, nbins + end_offset)
|
python
|
def bins_range(self, axis=0, overflow=False):
"""
Return a range of bin indices for iterating along an axis
Parameters
----------
axis : int, optional (default=1)
The axis (0, 1 or 2).
overflow : bool, optional (default=False)
If True then include the underflow and overflow bins
otherwise only include the visible bins.
Returns
-------
an range object of bin indices
"""
nbins = self.nbins(axis=axis, overflow=False)
if overflow:
start = 0
end_offset = 2
else:
start = 1
end_offset = 1
return range(start, nbins + end_offset)
|
[
"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",
"+",
"end_offset",
")"
] |
Return a range of bin indices for iterating along an axis
Parameters
----------
axis : int, optional (default=1)
The axis (0, 1 or 2).
overflow : bool, optional (default=False)
If True then include the underflow and overflow bins
otherwise only include the visible bins.
Returns
-------
an range object of bin indices
|
[
"Return",
"a",
"range",
"of",
"bin",
"indices",
"for",
"iterating",
"along",
"an",
"axis"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L479-L506
|
14,130
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.uniform_binned
|
def uniform_binned(self, name=None):
"""
Return a new histogram with constant width bins along all axes by
using the bin indices as the bin edges of the new histogram.
"""
if self.GetDimension() == 1:
new_hist = Hist(
self.GetNbinsX(), 0, self.GetNbinsX(),
name=name, type=self.TYPE)
elif self.GetDimension() == 2:
new_hist = Hist2D(
self.GetNbinsX(), 0, self.GetNbinsX(),
self.GetNbinsY(), 0, self.GetNbinsY(),
name=name, type=self.TYPE)
else:
new_hist = Hist3D(
self.GetNbinsX(), 0, self.GetNbinsX(),
self.GetNbinsY(), 0, self.GetNbinsY(),
self.GetNbinsZ(), 0, self.GetNbinsZ(),
name=name, type=self.TYPE)
# copy over the bin contents and errors
for outbin, inbin in zip(new_hist.bins(), self.bins()):
outbin.value = inbin.value
outbin.error = inbin.error
new_hist.decorate(self)
new_hist.entries = self.entries
return new_hist
|
python
|
def uniform_binned(self, name=None):
"""
Return a new histogram with constant width bins along all axes by
using the bin indices as the bin edges of the new histogram.
"""
if self.GetDimension() == 1:
new_hist = Hist(
self.GetNbinsX(), 0, self.GetNbinsX(),
name=name, type=self.TYPE)
elif self.GetDimension() == 2:
new_hist = Hist2D(
self.GetNbinsX(), 0, self.GetNbinsX(),
self.GetNbinsY(), 0, self.GetNbinsY(),
name=name, type=self.TYPE)
else:
new_hist = Hist3D(
self.GetNbinsX(), 0, self.GetNbinsX(),
self.GetNbinsY(), 0, self.GetNbinsY(),
self.GetNbinsZ(), 0, self.GetNbinsZ(),
name=name, type=self.TYPE)
# copy over the bin contents and errors
for outbin, inbin in zip(new_hist.bins(), self.bins()):
outbin.value = inbin.value
outbin.error = inbin.error
new_hist.decorate(self)
new_hist.entries = self.entries
return new_hist
|
[
"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",
"=",
"Hist2D",
"(",
"self",
".",
"GetNbinsX",
"(",
")",
",",
"0",
",",
"self",
".",
"GetNbinsX",
"(",
")",
",",
"self",
".",
"GetNbinsY",
"(",
")",
",",
"0",
",",
"self",
".",
"GetNbinsY",
"(",
")",
",",
"name",
"=",
"name",
",",
"type",
"=",
"self",
".",
"TYPE",
")",
"else",
":",
"new_hist",
"=",
"Hist3D",
"(",
"self",
".",
"GetNbinsX",
"(",
")",
",",
"0",
",",
"self",
".",
"GetNbinsX",
"(",
")",
",",
"self",
".",
"GetNbinsY",
"(",
")",
",",
"0",
",",
"self",
".",
"GetNbinsY",
"(",
")",
",",
"self",
".",
"GetNbinsZ",
"(",
")",
",",
"0",
",",
"self",
".",
"GetNbinsZ",
"(",
")",
",",
"name",
"=",
"name",
",",
"type",
"=",
"self",
".",
"TYPE",
")",
"# copy over the bin contents and errors",
"for",
"outbin",
",",
"inbin",
"in",
"zip",
"(",
"new_hist",
".",
"bins",
"(",
")",
",",
"self",
".",
"bins",
"(",
")",
")",
":",
"outbin",
".",
"value",
"=",
"inbin",
".",
"value",
"outbin",
".",
"error",
"=",
"inbin",
".",
"error",
"new_hist",
".",
"decorate",
"(",
"self",
")",
"new_hist",
".",
"entries",
"=",
"self",
".",
"entries",
"return",
"new_hist"
] |
Return a new histogram with constant width bins along all axes by
using the bin indices as the bin edges of the new histogram.
|
[
"Return",
"a",
"new",
"histogram",
"with",
"constant",
"width",
"bins",
"along",
"all",
"axes",
"by",
"using",
"the",
"bin",
"indices",
"as",
"the",
"bin",
"edges",
"of",
"the",
"new",
"histogram",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L749-L775
|
14,131
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.underflow
|
def underflow(self, axis=0):
"""
Return the underflow for the given axis.
Depending on the dimension of the histogram, may return an array.
"""
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]
arg.insert(axis, 0)
return arg
return [
self.GetBinContent(*idx(i))
for i in self.bins_range(axis=(axis + 1) % 2, overflow=True)]
elif self.DIM == 3:
axes = [0, 1, 2]
axes.remove(axis)
axis2, axis3 = axes
def idx(i, j):
arg = [i, j]
arg.insert(axis, 0)
return arg
return [[
self.GetBinContent(*idx(i, j))
for i in self.bins_range(axis=axis2, overflow=True)]
for j in self.bins_range(axis=axis3, overflow=True)]
|
python
|
def underflow(self, axis=0):
"""
Return the underflow for the given axis.
Depending on the dimension of the histogram, may return an array.
"""
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]
arg.insert(axis, 0)
return arg
return [
self.GetBinContent(*idx(i))
for i in self.bins_range(axis=(axis + 1) % 2, overflow=True)]
elif self.DIM == 3:
axes = [0, 1, 2]
axes.remove(axis)
axis2, axis3 = axes
def idx(i, j):
arg = [i, j]
arg.insert(axis, 0)
return arg
return [[
self.GetBinContent(*idx(i, j))
for i in self.bins_range(axis=axis2, overflow=True)]
for j in self.bins_range(axis=axis3, overflow=True)]
|
[
"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",
"]",
"arg",
".",
"insert",
"(",
"axis",
",",
"0",
")",
"return",
"arg",
"return",
"[",
"self",
".",
"GetBinContent",
"(",
"*",
"idx",
"(",
"i",
")",
")",
"for",
"i",
"in",
"self",
".",
"bins_range",
"(",
"axis",
"=",
"(",
"axis",
"+",
"1",
")",
"%",
"2",
",",
"overflow",
"=",
"True",
")",
"]",
"elif",
"self",
".",
"DIM",
"==",
"3",
":",
"axes",
"=",
"[",
"0",
",",
"1",
",",
"2",
"]",
"axes",
".",
"remove",
"(",
"axis",
")",
"axis2",
",",
"axis3",
"=",
"axes",
"def",
"idx",
"(",
"i",
",",
"j",
")",
":",
"arg",
"=",
"[",
"i",
",",
"j",
"]",
"arg",
".",
"insert",
"(",
"axis",
",",
"0",
")",
"return",
"arg",
"return",
"[",
"[",
"self",
".",
"GetBinContent",
"(",
"*",
"idx",
"(",
"i",
",",
"j",
")",
")",
"for",
"i",
"in",
"self",
".",
"bins_range",
"(",
"axis",
"=",
"axis2",
",",
"overflow",
"=",
"True",
")",
"]",
"for",
"j",
"in",
"self",
".",
"bins_range",
"(",
"axis",
"=",
"axis3",
",",
"overflow",
"=",
"True",
")",
"]"
] |
Return the underflow for the given axis.
Depending on the dimension of the histogram, may return an array.
|
[
"Return",
"the",
"underflow",
"for",
"the",
"given",
"axis",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L777-L806
|
14,132
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.lowerbound
|
def lowerbound(self, axis=0):
"""
Get the lower bound of the binning along an axis
"""
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 self.xedges(1)
if axis == 1:
return self.yedges(1)
if axis == 2:
return self.zedges(1)
raise TypeError("axis must be an integer")
|
python
|
def lowerbound(self, axis=0):
"""
Get the lower bound of the binning along an axis
"""
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 self.xedges(1)
if axis == 1:
return self.yedges(1)
if axis == 2:
return self.zedges(1)
raise TypeError("axis must be an integer")
|
[
"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",
":",
"return",
"self",
".",
"xedges",
"(",
"1",
")",
"if",
"axis",
"==",
"1",
":",
"return",
"self",
".",
"yedges",
"(",
"1",
")",
"if",
"axis",
"==",
"2",
":",
"return",
"self",
".",
"zedges",
"(",
"1",
")",
"raise",
"TypeError",
"(",
"\"axis must be an integer\"",
")"
] |
Get the lower bound of the binning along an axis
|
[
"Get",
"the",
"lower",
"bound",
"of",
"the",
"binning",
"along",
"an",
"axis"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L844-L858
|
14,133
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.bounds
|
def bounds(self, axis=0):
"""
Get the lower and upper bounds of the binning along an axis
"""
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 self.xedges(1), self.xedges(-2)
if axis == 1:
return self.yedges(1), self.yedges(-2)
if axis == 2:
return self.zedges(1), self.zedges(-2)
raise TypeError("axis must be an integer")
|
python
|
def bounds(self, axis=0):
"""
Get the lower and upper bounds of the binning along an axis
"""
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 self.xedges(1), self.xedges(-2)
if axis == 1:
return self.yedges(1), self.yedges(-2)
if axis == 2:
return self.zedges(1), self.zedges(-2)
raise TypeError("axis must be an integer")
|
[
"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",
"self",
".",
"xedges",
"(",
"1",
")",
",",
"self",
".",
"xedges",
"(",
"-",
"2",
")",
"if",
"axis",
"==",
"1",
":",
"return",
"self",
".",
"yedges",
"(",
"1",
")",
",",
"self",
".",
"yedges",
"(",
"-",
"2",
")",
"if",
"axis",
"==",
"2",
":",
"return",
"self",
".",
"zedges",
"(",
"1",
")",
",",
"self",
".",
"zedges",
"(",
"-",
"2",
")",
"raise",
"TypeError",
"(",
"\"axis must be an integer\"",
")"
] |
Get the lower and upper bounds of the binning along an axis
|
[
"Get",
"the",
"lower",
"and",
"upper",
"bounds",
"of",
"the",
"binning",
"along",
"an",
"axis"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L876-L890
|
14,134
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.check_compatibility
|
def check_compatibility(self, other, check_edges=False, precision=1E-7):
"""
Test whether two histograms are considered compatible by the number of
dimensions, number of bins along each axis, and optionally the bin
edges.
Parameters
----------
other : histogram
A rootpy histogram
check_edges : bool, optional (default=False)
If True then also check that the bin edges are equal within
the specified precision.
precision : float, optional (default=1E-7)
The value below which differences between floats are treated as
nil when comparing bin edges.
Raises
------
TypeError
If the histogram dimensionalities do not match
ValueError
If the histogram sizes, number of bins along an axis, or
optionally the bin edges do not match
"""
if self.GetDimension() != other.GetDimension():
raise TypeError("histogram dimensionalities do not match")
if len(self) != len(other):
raise ValueError("histogram sizes do not match")
for axis in range(self.GetDimension()):
if self.nbins(axis=axis) != other.nbins(axis=axis):
raise ValueError(
"numbers of bins along axis {0:d} do not match".format(
axis))
if check_edges:
for axis in range(self.GetDimension()):
if not all([abs(l - r) < precision
for l, r in zip(self._edges(axis), other._edges(axis))]):
raise ValueError(
"edges do not match along axis {0:d}".format(axis))
|
python
|
def check_compatibility(self, other, check_edges=False, precision=1E-7):
"""
Test whether two histograms are considered compatible by the number of
dimensions, number of bins along each axis, and optionally the bin
edges.
Parameters
----------
other : histogram
A rootpy histogram
check_edges : bool, optional (default=False)
If True then also check that the bin edges are equal within
the specified precision.
precision : float, optional (default=1E-7)
The value below which differences between floats are treated as
nil when comparing bin edges.
Raises
------
TypeError
If the histogram dimensionalities do not match
ValueError
If the histogram sizes, number of bins along an axis, or
optionally the bin edges do not match
"""
if self.GetDimension() != other.GetDimension():
raise TypeError("histogram dimensionalities do not match")
if len(self) != len(other):
raise ValueError("histogram sizes do not match")
for axis in range(self.GetDimension()):
if self.nbins(axis=axis) != other.nbins(axis=axis):
raise ValueError(
"numbers of bins along axis {0:d} do not match".format(
axis))
if check_edges:
for axis in range(self.GetDimension()):
if not all([abs(l - r) < precision
for l, r in zip(self._edges(axis), other._edges(axis))]):
raise ValueError(
"edges do not match along axis {0:d}".format(axis))
|
[
"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",
"(",
"\"histogram sizes do not match\"",
")",
"for",
"axis",
"in",
"range",
"(",
"self",
".",
"GetDimension",
"(",
")",
")",
":",
"if",
"self",
".",
"nbins",
"(",
"axis",
"=",
"axis",
")",
"!=",
"other",
".",
"nbins",
"(",
"axis",
"=",
"axis",
")",
":",
"raise",
"ValueError",
"(",
"\"numbers of bins along axis {0:d} do not match\"",
".",
"format",
"(",
"axis",
")",
")",
"if",
"check_edges",
":",
"for",
"axis",
"in",
"range",
"(",
"self",
".",
"GetDimension",
"(",
")",
")",
":",
"if",
"not",
"all",
"(",
"[",
"abs",
"(",
"l",
"-",
"r",
")",
"<",
"precision",
"for",
"l",
",",
"r",
"in",
"zip",
"(",
"self",
".",
"_edges",
"(",
"axis",
")",
",",
"other",
".",
"_edges",
"(",
"axis",
")",
")",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"edges do not match along axis {0:d}\"",
".",
"format",
"(",
"axis",
")",
")"
] |
Test whether two histograms are considered compatible by the number of
dimensions, number of bins along each axis, and optionally the bin
edges.
Parameters
----------
other : histogram
A rootpy histogram
check_edges : bool, optional (default=False)
If True then also check that the bin edges are equal within
the specified precision.
precision : float, optional (default=1E-7)
The value below which differences between floats are treated as
nil when comparing bin edges.
Raises
------
TypeError
If the histogram dimensionalities do not match
ValueError
If the histogram sizes, number of bins along an axis, or
optionally the bin edges do not match
|
[
"Test",
"whether",
"two",
"histograms",
"are",
"considered",
"compatible",
"by",
"the",
"number",
"of",
"dimensions",
"number",
"of",
"bins",
"along",
"each",
"axis",
"and",
"optionally",
"the",
"bin",
"edges",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1018-L1063
|
14,135
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.fill_array
|
def fill_array(self, array, weights=None):
"""
Fill this histogram with a NumPy array
"""
try:
try:
from root_numpy import fill_hist as fill_func
except ImportError:
from root_numpy import fill_array as fill_func
except ImportError:
log.critical(
"root_numpy is needed for Hist*.fill_array. "
"Is it installed and importable?")
raise
fill_func(self, array, weights=weights)
|
python
|
def fill_array(self, array, weights=None):
"""
Fill this histogram with a NumPy array
"""
try:
try:
from root_numpy import fill_hist as fill_func
except ImportError:
from root_numpy import fill_array as fill_func
except ImportError:
log.critical(
"root_numpy is needed for Hist*.fill_array. "
"Is it installed and importable?")
raise
fill_func(self, array, weights=weights)
|
[
"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",
":",
"log",
".",
"critical",
"(",
"\"root_numpy is needed for Hist*.fill_array. \"",
"\"Is it installed and importable?\"",
")",
"raise",
"fill_func",
"(",
"self",
",",
"array",
",",
"weights",
"=",
"weights",
")"
] |
Fill this histogram with a NumPy array
|
[
"Fill",
"this",
"histogram",
"with",
"a",
"NumPy",
"array"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1192-L1206
|
14,136
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.fill_view
|
def fill_view(self, view):
"""
Fill this histogram from a view of another histogram
"""
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
_other_get_bin = super(_HistBase, other).GetBin
other_sum_w2 = other.GetSumw2()
_other_sum_w2_at = other_sum_w2.At
_find = self.FindBin
sum_w2 = self.GetSumw2()
_sum_w2_at = sum_w2.At
_sum_w2_setat = sum_w2.SetAt
_set = self.SetBinContent
_get = self.GetBinContent
for x, y, z in view.points:
idx = _find(
_other_x_center(x),
_other_y_center(y),
_other_z_center(z))
other_idx = _other_get_bin(x, y, z)
_set(idx, _get(idx) + _other_get(other_idx))
_sum_w2_setat(
_sum_w2_at(idx) + _other_sum_w2_at(other_idx),
idx)
|
python
|
def fill_view(self, view):
"""
Fill this histogram from a view of another histogram
"""
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
_other_get_bin = super(_HistBase, other).GetBin
other_sum_w2 = other.GetSumw2()
_other_sum_w2_at = other_sum_w2.At
_find = self.FindBin
sum_w2 = self.GetSumw2()
_sum_w2_at = sum_w2.At
_sum_w2_setat = sum_w2.SetAt
_set = self.SetBinContent
_get = self.GetBinContent
for x, y, z in view.points:
idx = _find(
_other_x_center(x),
_other_y_center(y),
_other_z_center(z))
other_idx = _other_get_bin(x, y, z)
_set(idx, _get(idx) + _other_get(other_idx))
_sum_w2_setat(
_sum_w2_at(idx) + _other_sum_w2_at(other_idx),
idx)
|
[
"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",
"_other_get_bin",
"=",
"super",
"(",
"_HistBase",
",",
"other",
")",
".",
"GetBin",
"other_sum_w2",
"=",
"other",
".",
"GetSumw2",
"(",
")",
"_other_sum_w2_at",
"=",
"other_sum_w2",
".",
"At",
"_find",
"=",
"self",
".",
"FindBin",
"sum_w2",
"=",
"self",
".",
"GetSumw2",
"(",
")",
"_sum_w2_at",
"=",
"sum_w2",
".",
"At",
"_sum_w2_setat",
"=",
"sum_w2",
".",
"SetAt",
"_set",
"=",
"self",
".",
"SetBinContent",
"_get",
"=",
"self",
".",
"GetBinContent",
"for",
"x",
",",
"y",
",",
"z",
"in",
"view",
".",
"points",
":",
"idx",
"=",
"_find",
"(",
"_other_x_center",
"(",
"x",
")",
",",
"_other_y_center",
"(",
"y",
")",
",",
"_other_z_center",
"(",
"z",
")",
")",
"other_idx",
"=",
"_other_get_bin",
"(",
"x",
",",
"y",
",",
"z",
")",
"_set",
"(",
"idx",
",",
"_get",
"(",
"idx",
")",
"+",
"_other_get",
"(",
"other_idx",
")",
")",
"_sum_w2_setat",
"(",
"_sum_w2_at",
"(",
"idx",
")",
"+",
"_other_sum_w2_at",
"(",
"other_idx",
")",
",",
"idx",
")"
] |
Fill this histogram from a view of another histogram
|
[
"Fill",
"this",
"histogram",
"from",
"a",
"view",
"of",
"another",
"histogram"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1208-L1237
|
14,137
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.get_sum_w2
|
def get_sum_w2(self, ix, iy=0, iz=0):
"""
Obtain the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = self.nbins(axis=0, overflow=True)
yl = self.nbins(axis=1, overflow=True)
idx = xl * yl * iz + xl * iy + ix
if not 0 <= idx < self.GetSumw2N():
raise IndexError("bin index out of range")
return self.GetSumw2().At(idx)
|
python
|
def get_sum_w2(self, ix, iy=0, iz=0):
"""
Obtain the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = self.nbins(axis=0, overflow=True)
yl = self.nbins(axis=1, overflow=True)
idx = xl * yl * iz + xl * iy + ix
if not 0 <= idx < self.GetSumw2N():
raise IndexError("bin index out of range")
return self.GetSumw2().At(idx)
|
[
"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",
")",
"yl",
"=",
"self",
".",
"nbins",
"(",
"axis",
"=",
"1",
",",
"overflow",
"=",
"True",
")",
"idx",
"=",
"xl",
"*",
"yl",
"*",
"iz",
"+",
"xl",
"*",
"iy",
"+",
"ix",
"if",
"not",
"0",
"<=",
"idx",
"<",
"self",
".",
"GetSumw2N",
"(",
")",
":",
"raise",
"IndexError",
"(",
"\"bin index out of range\"",
")",
"return",
"self",
".",
"GetSumw2",
"(",
")",
".",
"At",
"(",
"idx",
")"
] |
Obtain the true number of entries in the bin weighted by w^2
|
[
"Obtain",
"the",
"true",
"number",
"of",
"entries",
"in",
"the",
"bin",
"weighted",
"by",
"w^2"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1245-L1258
|
14,138
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.set_sum_w2
|
def set_sum_w2(self, w, ix, iy=0, iz=0):
"""
Sets the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = self.nbins(axis=0, overflow=True)
yl = self.nbins(axis=1, overflow=True)
idx = xl * yl * iz + xl * iy + ix
if not 0 <= idx < self.GetSumw2N():
raise IndexError("bin index out of range")
self.GetSumw2().SetAt(w, idx)
|
python
|
def set_sum_w2(self, w, ix, iy=0, iz=0):
"""
Sets the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = self.nbins(axis=0, overflow=True)
yl = self.nbins(axis=1, overflow=True)
idx = xl * yl * iz + xl * iy + ix
if not 0 <= idx < self.GetSumw2N():
raise IndexError("bin index out of range")
self.GetSumw2().SetAt(w, idx)
|
[
"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",
")",
"yl",
"=",
"self",
".",
"nbins",
"(",
"axis",
"=",
"1",
",",
"overflow",
"=",
"True",
")",
"idx",
"=",
"xl",
"*",
"yl",
"*",
"iz",
"+",
"xl",
"*",
"iy",
"+",
"ix",
"if",
"not",
"0",
"<=",
"idx",
"<",
"self",
".",
"GetSumw2N",
"(",
")",
":",
"raise",
"IndexError",
"(",
"\"bin index out of range\"",
")",
"self",
".",
"GetSumw2",
"(",
")",
".",
"SetAt",
"(",
"w",
",",
"idx",
")"
] |
Sets the true number of entries in the bin weighted by w^2
|
[
"Sets",
"the",
"true",
"number",
"of",
"entries",
"in",
"the",
"bin",
"weighted",
"by",
"w^2"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1260-L1273
|
14,139
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.rebinned
|
def rebinned(self, bins, axis=0):
"""
Return a new rebinned histogram
Parameters
----------
bins : int, tuple, or iterable
If ``bins`` is an int, then return a histogram that is rebinned by
grouping N=``bins`` bins together along the axis ``axis``.
If ``bins`` is a tuple, then it must contain the same number of
elements as there are dimensions of this histogram and each element
will be used to rebin along the associated axis.
If ``bins`` is another iterable, then it will define the bin
edges along the axis ``axis`` in the new rebinned histogram.
axis : int, optional (default=0)
The axis to rebin along.
Returns
-------
The rebinned histogram
"""
ndim = self.GetDimension()
if axis >= ndim:
raise ValueError(
"axis must be less than the dimensionality of the histogram")
if isinstance(bins, int):
_bins = [1] * ndim
try:
_bins[axis] = bins
except IndexError:
raise ValueError("axis must be 0, 1, or 2")
bins = tuple(_bins)
if isinstance(bins, tuple):
if len(bins) != ndim:
raise ValueError(
"bins must be a tuple with the same "
"number of elements as histogram axes")
newname = '{0}_{1}'.format(self.__class__.__name__, uuid())
if ndim == 1:
hist = self.Rebin(bins[0], newname)
elif ndim == 2:
hist = self.Rebin2D(bins[0], bins[1], newname)
else:
hist = self.Rebin3D(bins[0], bins[1], bins[2], newname)
hist = asrootpy(hist)
elif hasattr(bins, '__iter__'):
hist = self.empty_clone(bins, axis=axis)
nbinsx = self.nbins(0)
nbinsy = self.nbins(1)
nbinsz = self.nbins(2)
xaxis = self.xaxis
yaxis = self.yaxis
zaxis = self.zaxis
sum_w2 = self.GetSumw2()
_sum_w2_at = sum_w2.At
new_sum_w2 = hist.GetSumw2()
_new_sum_w2_at = new_sum_w2.At
_new_sum_w2_setat = new_sum_w2.SetAt
_x_center = xaxis.GetBinCenter
_y_center = yaxis.GetBinCenter
_z_center = zaxis.GetBinCenter
_find = hist.FindBin
_set = hist.SetBinContent
_get = hist.GetBinContent
_this_get = self.GetBinContent
_get_bin = super(_HistBase, self).GetBin
for z in range(1, nbinsz + 1):
for y in range(1, nbinsy + 1):
for x in range(1, nbinsx + 1):
newbin = _find(
_x_center(x), _y_center(y), _z_center(z))
idx = _get_bin(x, y, z)
_set(newbin, _get(newbin) + _this_get(idx))
_new_sum_w2_setat(
_new_sum_w2_at(newbin) + _sum_w2_at(idx),
newbin)
hist.SetEntries(self.GetEntries())
else:
raise TypeError(
"bins must either be an integer, a tuple, or an iterable")
return hist
|
python
|
def rebinned(self, bins, axis=0):
"""
Return a new rebinned histogram
Parameters
----------
bins : int, tuple, or iterable
If ``bins`` is an int, then return a histogram that is rebinned by
grouping N=``bins`` bins together along the axis ``axis``.
If ``bins`` is a tuple, then it must contain the same number of
elements as there are dimensions of this histogram and each element
will be used to rebin along the associated axis.
If ``bins`` is another iterable, then it will define the bin
edges along the axis ``axis`` in the new rebinned histogram.
axis : int, optional (default=0)
The axis to rebin along.
Returns
-------
The rebinned histogram
"""
ndim = self.GetDimension()
if axis >= ndim:
raise ValueError(
"axis must be less than the dimensionality of the histogram")
if isinstance(bins, int):
_bins = [1] * ndim
try:
_bins[axis] = bins
except IndexError:
raise ValueError("axis must be 0, 1, or 2")
bins = tuple(_bins)
if isinstance(bins, tuple):
if len(bins) != ndim:
raise ValueError(
"bins must be a tuple with the same "
"number of elements as histogram axes")
newname = '{0}_{1}'.format(self.__class__.__name__, uuid())
if ndim == 1:
hist = self.Rebin(bins[0], newname)
elif ndim == 2:
hist = self.Rebin2D(bins[0], bins[1], newname)
else:
hist = self.Rebin3D(bins[0], bins[1], bins[2], newname)
hist = asrootpy(hist)
elif hasattr(bins, '__iter__'):
hist = self.empty_clone(bins, axis=axis)
nbinsx = self.nbins(0)
nbinsy = self.nbins(1)
nbinsz = self.nbins(2)
xaxis = self.xaxis
yaxis = self.yaxis
zaxis = self.zaxis
sum_w2 = self.GetSumw2()
_sum_w2_at = sum_w2.At
new_sum_w2 = hist.GetSumw2()
_new_sum_w2_at = new_sum_w2.At
_new_sum_w2_setat = new_sum_w2.SetAt
_x_center = xaxis.GetBinCenter
_y_center = yaxis.GetBinCenter
_z_center = zaxis.GetBinCenter
_find = hist.FindBin
_set = hist.SetBinContent
_get = hist.GetBinContent
_this_get = self.GetBinContent
_get_bin = super(_HistBase, self).GetBin
for z in range(1, nbinsz + 1):
for y in range(1, nbinsy + 1):
for x in range(1, nbinsx + 1):
newbin = _find(
_x_center(x), _y_center(y), _z_center(z))
idx = _get_bin(x, y, z)
_set(newbin, _get(newbin) + _this_get(idx))
_new_sum_w2_setat(
_new_sum_w2_at(newbin) + _sum_w2_at(idx),
newbin)
hist.SetEntries(self.GetEntries())
else:
raise TypeError(
"bins must either be an integer, a tuple, or an iterable")
return hist
|
[
"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",
"]",
"*",
"ndim",
"try",
":",
"_bins",
"[",
"axis",
"]",
"=",
"bins",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"\"axis must be 0, 1, or 2\"",
")",
"bins",
"=",
"tuple",
"(",
"_bins",
")",
"if",
"isinstance",
"(",
"bins",
",",
"tuple",
")",
":",
"if",
"len",
"(",
"bins",
")",
"!=",
"ndim",
":",
"raise",
"ValueError",
"(",
"\"bins must be a tuple with the same \"",
"\"number of elements as histogram axes\"",
")",
"newname",
"=",
"'{0}_{1}'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"uuid",
"(",
")",
")",
"if",
"ndim",
"==",
"1",
":",
"hist",
"=",
"self",
".",
"Rebin",
"(",
"bins",
"[",
"0",
"]",
",",
"newname",
")",
"elif",
"ndim",
"==",
"2",
":",
"hist",
"=",
"self",
".",
"Rebin2D",
"(",
"bins",
"[",
"0",
"]",
",",
"bins",
"[",
"1",
"]",
",",
"newname",
")",
"else",
":",
"hist",
"=",
"self",
".",
"Rebin3D",
"(",
"bins",
"[",
"0",
"]",
",",
"bins",
"[",
"1",
"]",
",",
"bins",
"[",
"2",
"]",
",",
"newname",
")",
"hist",
"=",
"asrootpy",
"(",
"hist",
")",
"elif",
"hasattr",
"(",
"bins",
",",
"'__iter__'",
")",
":",
"hist",
"=",
"self",
".",
"empty_clone",
"(",
"bins",
",",
"axis",
"=",
"axis",
")",
"nbinsx",
"=",
"self",
".",
"nbins",
"(",
"0",
")",
"nbinsy",
"=",
"self",
".",
"nbins",
"(",
"1",
")",
"nbinsz",
"=",
"self",
".",
"nbins",
"(",
"2",
")",
"xaxis",
"=",
"self",
".",
"xaxis",
"yaxis",
"=",
"self",
".",
"yaxis",
"zaxis",
"=",
"self",
".",
"zaxis",
"sum_w2",
"=",
"self",
".",
"GetSumw2",
"(",
")",
"_sum_w2_at",
"=",
"sum_w2",
".",
"At",
"new_sum_w2",
"=",
"hist",
".",
"GetSumw2",
"(",
")",
"_new_sum_w2_at",
"=",
"new_sum_w2",
".",
"At",
"_new_sum_w2_setat",
"=",
"new_sum_w2",
".",
"SetAt",
"_x_center",
"=",
"xaxis",
".",
"GetBinCenter",
"_y_center",
"=",
"yaxis",
".",
"GetBinCenter",
"_z_center",
"=",
"zaxis",
".",
"GetBinCenter",
"_find",
"=",
"hist",
".",
"FindBin",
"_set",
"=",
"hist",
".",
"SetBinContent",
"_get",
"=",
"hist",
".",
"GetBinContent",
"_this_get",
"=",
"self",
".",
"GetBinContent",
"_get_bin",
"=",
"super",
"(",
"_HistBase",
",",
"self",
")",
".",
"GetBin",
"for",
"z",
"in",
"range",
"(",
"1",
",",
"nbinsz",
"+",
"1",
")",
":",
"for",
"y",
"in",
"range",
"(",
"1",
",",
"nbinsy",
"+",
"1",
")",
":",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"nbinsx",
"+",
"1",
")",
":",
"newbin",
"=",
"_find",
"(",
"_x_center",
"(",
"x",
")",
",",
"_y_center",
"(",
"y",
")",
",",
"_z_center",
"(",
"z",
")",
")",
"idx",
"=",
"_get_bin",
"(",
"x",
",",
"y",
",",
"z",
")",
"_set",
"(",
"newbin",
",",
"_get",
"(",
"newbin",
")",
"+",
"_this_get",
"(",
"idx",
")",
")",
"_new_sum_w2_setat",
"(",
"_new_sum_w2_at",
"(",
"newbin",
")",
"+",
"_sum_w2_at",
"(",
"idx",
")",
",",
"newbin",
")",
"hist",
".",
"SetEntries",
"(",
"self",
".",
"GetEntries",
"(",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"bins must either be an integer, a tuple, or an iterable\"",
")",
"return",
"hist"
] |
Return a new rebinned histogram
Parameters
----------
bins : int, tuple, or iterable
If ``bins`` is an int, then return a histogram that is rebinned by
grouping N=``bins`` bins together along the axis ``axis``.
If ``bins`` is a tuple, then it must contain the same number of
elements as there are dimensions of this histogram and each element
will be used to rebin along the associated axis.
If ``bins`` is another iterable, then it will define the bin
edges along the axis ``axis`` in the new rebinned histogram.
axis : int, optional (default=0)
The axis to rebin along.
Returns
-------
The rebinned histogram
|
[
"Return",
"a",
"new",
"rebinned",
"histogram"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1405-L1491
|
14,140
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.smoothed
|
def smoothed(self, iterations=1):
"""
Return a smoothed copy of this histogram
Parameters
----------
iterations : int, optional (default=1)
The number of smoothing iterations
Returns
-------
hist : asrootpy'd histogram
The smoothed histogram
"""
copy = self.Clone(shallow=True)
copy.Smooth(iterations)
return copy
|
python
|
def smoothed(self, iterations=1):
"""
Return a smoothed copy of this histogram
Parameters
----------
iterations : int, optional (default=1)
The number of smoothing iterations
Returns
-------
hist : asrootpy'd histogram
The smoothed histogram
"""
copy = self.Clone(shallow=True)
copy.Smooth(iterations)
return copy
|
[
"def",
"smoothed",
"(",
"self",
",",
"iterations",
"=",
"1",
")",
":",
"copy",
"=",
"self",
".",
"Clone",
"(",
"shallow",
"=",
"True",
")",
"copy",
".",
"Smooth",
"(",
"iterations",
")",
"return",
"copy"
] |
Return a smoothed copy of this histogram
Parameters
----------
iterations : int, optional (default=1)
The number of smoothing iterations
Returns
-------
hist : asrootpy'd histogram
The smoothed histogram
|
[
"Return",
"a",
"smoothed",
"copy",
"of",
"this",
"histogram"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1493-L1512
|
14,141
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_HistBase.empty_clone
|
def empty_clone(self, binning=None, axis=0, type=None, **kwargs):
"""
Return a new empty histogram. The binning may be modified
along one axis by specifying the binning and axis arguments.
If binning is False, then the corresponding axis is dropped
from the returned histogram.
"""
ndim = self.GetDimension()
if binning is False and ndim == 1:
raise ValueError(
"cannot remove the x-axis of a 1D histogram")
args = []
for iaxis in range(ndim):
if iaxis == axis:
if binning is False:
# skip this axis
continue
elif binning is not None:
if hasattr(binning, '__iter__'):
binning = (binning,)
args.extend(binning)
continue
args.append(list(self._edges(axis=iaxis)))
if type is None:
type = self.TYPE
if binning is False:
ndim -= 1
cls = [Hist, Hist2D, Hist3D][ndim - 1]
return cls(*args, type=type, **kwargs)
|
python
|
def empty_clone(self, binning=None, axis=0, type=None, **kwargs):
"""
Return a new empty histogram. The binning may be modified
along one axis by specifying the binning and axis arguments.
If binning is False, then the corresponding axis is dropped
from the returned histogram.
"""
ndim = self.GetDimension()
if binning is False and ndim == 1:
raise ValueError(
"cannot remove the x-axis of a 1D histogram")
args = []
for iaxis in range(ndim):
if iaxis == axis:
if binning is False:
# skip this axis
continue
elif binning is not None:
if hasattr(binning, '__iter__'):
binning = (binning,)
args.extend(binning)
continue
args.append(list(self._edges(axis=iaxis)))
if type is None:
type = self.TYPE
if binning is False:
ndim -= 1
cls = [Hist, Hist2D, Hist3D][ndim - 1]
return cls(*args, type=type, **kwargs)
|
[
"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",
"iaxis",
"in",
"range",
"(",
"ndim",
")",
":",
"if",
"iaxis",
"==",
"axis",
":",
"if",
"binning",
"is",
"False",
":",
"# skip this axis",
"continue",
"elif",
"binning",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"binning",
",",
"'__iter__'",
")",
":",
"binning",
"=",
"(",
"binning",
",",
")",
"args",
".",
"extend",
"(",
"binning",
")",
"continue",
"args",
".",
"append",
"(",
"list",
"(",
"self",
".",
"_edges",
"(",
"axis",
"=",
"iaxis",
")",
")",
")",
"if",
"type",
"is",
"None",
":",
"type",
"=",
"self",
".",
"TYPE",
"if",
"binning",
"is",
"False",
":",
"ndim",
"-=",
"1",
"cls",
"=",
"[",
"Hist",
",",
"Hist2D",
",",
"Hist3D",
"]",
"[",
"ndim",
"-",
"1",
"]",
"return",
"cls",
"(",
"*",
"args",
",",
"type",
"=",
"type",
",",
"*",
"*",
"kwargs",
")"
] |
Return a new empty histogram. The binning may be modified
along one axis by specifying the binning and axis arguments.
If binning is False, then the corresponding axis is dropped
from the returned histogram.
|
[
"Return",
"a",
"new",
"empty",
"histogram",
".",
"The",
"binning",
"may",
"be",
"modified",
"along",
"one",
"axis",
"by",
"specifying",
"the",
"binning",
"and",
"axis",
"arguments",
".",
"If",
"binning",
"is",
"False",
"then",
"the",
"corresponding",
"axis",
"is",
"dropped",
"from",
"the",
"returned",
"histogram",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1514-L1542
|
14,142
|
rootpy/rootpy
|
rootpy/plotting/hist.py
|
_Hist.poisson_errors
|
def poisson_errors(self):
"""
Return a TGraphAsymmErrors representation of this histogram where the
point y errors are Poisson.
"""
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 self.bins(overflow=False):
entries = bin.effective_entries
if entries <= 0:
continue
ey_low = entries - 0.5 * chisqr(0.1586555, 2. * entries)
ey_high = 0.5 * chisqr(
1. - 0.1586555, 2. * (entries + 1)) - entries
ex = bin.x.width / 2.
graph.SetPoint(npoints, bin.x.center, bin.value)
graph.SetPointEXlow(npoints, ex)
graph.SetPointEXhigh(npoints, ex)
graph.SetPointEYlow(npoints, ey_low)
graph.SetPointEYhigh(npoints, ey_high)
npoints += 1
graph.Set(npoints)
return graph
|
python
|
def poisson_errors(self):
"""
Return a TGraphAsymmErrors representation of this histogram where the
point y errors are Poisson.
"""
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 self.bins(overflow=False):
entries = bin.effective_entries
if entries <= 0:
continue
ey_low = entries - 0.5 * chisqr(0.1586555, 2. * entries)
ey_high = 0.5 * chisqr(
1. - 0.1586555, 2. * (entries + 1)) - entries
ex = bin.x.width / 2.
graph.SetPoint(npoints, bin.x.center, bin.value)
graph.SetPointEXlow(npoints, ex)
graph.SetPointEXhigh(npoints, ex)
graph.SetPointEYlow(npoints, ey_low)
graph.SetPointEYhigh(npoints, ey_high)
npoints += 1
graph.Set(npoints)
return graph
|
[
"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",
"self",
".",
"bins",
"(",
"overflow",
"=",
"False",
")",
":",
"entries",
"=",
"bin",
".",
"effective_entries",
"if",
"entries",
"<=",
"0",
":",
"continue",
"ey_low",
"=",
"entries",
"-",
"0.5",
"*",
"chisqr",
"(",
"0.1586555",
",",
"2.",
"*",
"entries",
")",
"ey_high",
"=",
"0.5",
"*",
"chisqr",
"(",
"1.",
"-",
"0.1586555",
",",
"2.",
"*",
"(",
"entries",
"+",
"1",
")",
")",
"-",
"entries",
"ex",
"=",
"bin",
".",
"x",
".",
"width",
"/",
"2.",
"graph",
".",
"SetPoint",
"(",
"npoints",
",",
"bin",
".",
"x",
".",
"center",
",",
"bin",
".",
"value",
")",
"graph",
".",
"SetPointEXlow",
"(",
"npoints",
",",
"ex",
")",
"graph",
".",
"SetPointEXhigh",
"(",
"npoints",
",",
"ex",
")",
"graph",
".",
"SetPointEYlow",
"(",
"npoints",
",",
"ey_low",
")",
"graph",
".",
"SetPointEYhigh",
"(",
"npoints",
",",
"ey_high",
")",
"npoints",
"+=",
"1",
"graph",
".",
"Set",
"(",
"npoints",
")",
"return",
"graph"
] |
Return a TGraphAsymmErrors representation of this histogram where the
point y errors are Poisson.
|
[
"Return",
"a",
"TGraphAsymmErrors",
"representation",
"of",
"this",
"histogram",
"where",
"the",
"point",
"y",
"errors",
"are",
"Poisson",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1784-L1809
|
14,143
|
rootpy/rootpy
|
rootpy/interactive/canvas_events.py
|
attach_event_handler
|
def attach_event_handler(canvas, handler=close_on_esc_or_middlemouse):
"""
Attach a handler function to the ProcessedEvent slot, defaulting to
closing when middle mouse is clicked or escape is pressed
Note that escape only works if the pad has focus, which in ROOT-land means
the mouse has to be over the canvas area.
"""
if getattr(canvas, "_py_event_dispatcher_attached", None):
return
event_dispatcher = C.TPyDispatcherProcessedEvent(handler)
canvas.Connect("ProcessedEvent(int,int,int,TObject*)",
"TPyDispatcherProcessedEvent", event_dispatcher,
"Dispatch(int,int,int,TObject*)")
# Attach a handler only once to each canvas, and keep the dispatcher alive
canvas._py_event_dispatcher_attached = event_dispatcher
|
python
|
def attach_event_handler(canvas, handler=close_on_esc_or_middlemouse):
"""
Attach a handler function to the ProcessedEvent slot, defaulting to
closing when middle mouse is clicked or escape is pressed
Note that escape only works if the pad has focus, which in ROOT-land means
the mouse has to be over the canvas area.
"""
if getattr(canvas, "_py_event_dispatcher_attached", None):
return
event_dispatcher = C.TPyDispatcherProcessedEvent(handler)
canvas.Connect("ProcessedEvent(int,int,int,TObject*)",
"TPyDispatcherProcessedEvent", event_dispatcher,
"Dispatch(int,int,int,TObject*)")
# Attach a handler only once to each canvas, and keep the dispatcher alive
canvas._py_event_dispatcher_attached = event_dispatcher
|
[
"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*)\"",
",",
"\"TPyDispatcherProcessedEvent\"",
",",
"event_dispatcher",
",",
"\"Dispatch(int,int,int,TObject*)\"",
")",
"# Attach a handler only once to each canvas, and keep the dispatcher alive",
"canvas",
".",
"_py_event_dispatcher_attached",
"=",
"event_dispatcher"
] |
Attach a handler function to the ProcessedEvent slot, defaulting to
closing when middle mouse is clicked or escape is pressed
Note that escape only works if the pad has focus, which in ROOT-land means
the mouse has to be over the canvas area.
|
[
"Attach",
"a",
"handler",
"function",
"to",
"the",
"ProcessedEvent",
"slot",
"defaulting",
"to",
"closing",
"when",
"middle",
"mouse",
"is",
"clicked",
"or",
"escape",
"is",
"pressed"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/interactive/canvas_events.py#L58-L75
|
14,144
|
rootpy/rootpy
|
rootpy/extern/shortuuid/__init__.py
|
ShortUUID._num_to_string
|
def _num_to_string(self, number, pad_to_length=None):
"""
Convert a number to a string, using the given alphabet.
"""
output = ""
while number:
number, digit = divmod(number, self._alpha_len)
output += self._alphabet[digit]
if pad_to_length:
remainder = max(pad_to_length - len(output), 0)
output = output + self._alphabet[0] * remainder
return output
|
python
|
def _num_to_string(self, number, pad_to_length=None):
"""
Convert a number to a string, using the given alphabet.
"""
output = ""
while number:
number, digit = divmod(number, self._alpha_len)
output += self._alphabet[digit]
if pad_to_length:
remainder = max(pad_to_length - len(output), 0)
output = output + self._alphabet[0] * remainder
return output
|
[
"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_length",
"-",
"len",
"(",
"output",
")",
",",
"0",
")",
"output",
"=",
"output",
"+",
"self",
".",
"_alphabet",
"[",
"0",
"]",
"*",
"remainder",
"return",
"output"
] |
Convert a number to a string, using the given alphabet.
|
[
"Convert",
"a",
"number",
"to",
"a",
"string",
"using",
"the",
"given",
"alphabet",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/shortuuid/__init__.py#L17-L28
|
14,145
|
rootpy/rootpy
|
rootpy/extern/shortuuid/__init__.py
|
ShortUUID._string_to_int
|
def _string_to_int(self, string):
"""
Convert a string to a number, using the given alphabet..
"""
number = 0
for char in string[::-1]:
number = number * self._alpha_len + self._alphabet.index(char)
return number
|
python
|
def _string_to_int(self, string):
"""
Convert a string to a number, using the given alphabet..
"""
number = 0
for char in string[::-1]:
number = number * self._alpha_len + self._alphabet.index(char)
return number
|
[
"def",
"_string_to_int",
"(",
"self",
",",
"string",
")",
":",
"number",
"=",
"0",
"for",
"char",
"in",
"string",
"[",
":",
":",
"-",
"1",
"]",
":",
"number",
"=",
"number",
"*",
"self",
".",
"_alpha_len",
"+",
"self",
".",
"_alphabet",
".",
"index",
"(",
"char",
")",
"return",
"number"
] |
Convert a string to a number, using the given alphabet..
|
[
"Convert",
"a",
"string",
"to",
"a",
"number",
"using",
"the",
"given",
"alphabet",
".."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/shortuuid/__init__.py#L30-L37
|
14,146
|
rootpy/rootpy
|
rootpy/extern/shortuuid/__init__.py
|
ShortUUID.uuid
|
def uuid(self, name=None, pad_length=22):
"""
Generate and return a UUID.
If the name parameter is provided, set the namespace to the provided
name and generate a UUID.
"""
# 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:
uuid = _uu.uuid5(_uu.NAMESPACE_URL, name)
return self.encode(uuid, pad_length)
|
python
|
def uuid(self, name=None, pad_length=22):
"""
Generate and return a UUID.
If the name parameter is provided, set the namespace to the provided
name and generate a UUID.
"""
# 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:
uuid = _uu.uuid5(_uu.NAMESPACE_URL, name)
return self.encode(uuid, pad_length)
|
[
"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",
":",
"uuid",
"=",
"_uu",
".",
"uuid5",
"(",
"_uu",
".",
"NAMESPACE_URL",
",",
"name",
")",
"return",
"self",
".",
"encode",
"(",
"uuid",
",",
"pad_length",
")"
] |
Generate and return a UUID.
If the name parameter is provided, set the namespace to the provided
name and generate a UUID.
|
[
"Generate",
"and",
"return",
"a",
"UUID",
"."
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/shortuuid/__init__.py#L55-L69
|
14,147
|
rootpy/rootpy
|
rootpy/stats/workspace.py
|
Workspace.fit
|
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,
extended=False,
num_cpu=1,
process_strategy=0,
offset=False,
print_level=None,
return_nll=False,
**kwargs):
"""
Fit a pdf to data in a workspace
Parameters
----------
workspace : RooWorkspace
The workspace
data : str or RooAbsData, optional (default='obsData')
The name of the data or a RooAbsData instance.
model_config : str or ModelConfig, optional (default='ModelConfig')
The name of the ModelConfig in the workspace or a
ModelConfig instance.
param_const : dict, optional (default=None)
A dict mapping parameter names to booleans setting
the const state of the parameter
param_values : dict, optional (default=None)
A dict mapping parameter names to values
param_ranges : dict, optional (default=None)
A dict mapping parameter names to 2-tuples defining the ranges
poi_const : bool, optional (default=False)
If True, then make the parameter of interest (POI) constant
poi_value : float, optional (default=None)
If not None, then set the POI to this value
poi_range : tuple, optional (default=None)
If not None, then set the range of the POI with this 2-tuple
extended : bool, optional (default=False)
If True, add extended likelihood term (False by default)
num_cpu : int, optional (default=1)
Parallelize NLL calculation on multiple CPU cores.
If negative then use all CPU cores.
By default use only one CPU core.
process_strategy : int, optional (default=0)
**Strategy 0:** Divide events into N equal chunks.
**Strategy 1:** Process event i%N in process N. Recommended for
binned data with a substantial number of zero-bins, which will be
distributed across processes more equitably in this strategy.
**Strategy 2:** Process each component likelihood of a
RooSimultaneous fully in a single process and distribute components
over processes. This approach can be benificial if normalization
calculation time dominates the total computation time of a
component (since the normalization calculation must be performed
in each process in strategies 0 and 1. However beware that if the
RooSimultaneous components do not share many parameters this
strategy is inefficient: as most minuit-induced likelihood
calculations involve changing a single parameter, only 1 of the N
processes will be active most of the time if RooSimultaneous
components do not share many parameters.
**Strategy 3:** Follow strategy 0 for all RooSimultaneous
components, except those with less than 30 dataset entries,
for which strategy 2 is followed.
offset : bool, optional (default=False)
Offset likelihood by initial value (so that starting value of FCN
in minuit is zero). This can improve numeric stability in
simultaneously fits with components with large likelihood values.
print_level : int, optional (default=None)
The verbosity level for the minimizer algorithm.
If None (the default) then use the global default print level.
If negative then all non-fatal messages will be suppressed.
return_nll : bool, optional (default=False)
If True then also return the RooAbsReal NLL function that was
minimized.
kwargs : dict, optional
Remaining keyword arguments are passed to the minimize function
Returns
-------
result : RooFitResult
The fit result.
func : RooAbsReal
If return_nll is True, the NLL function is also returned.
See Also
--------
minimize
"""
if isinstance(model_config, string_types):
model_config = self.obj(
model_config, cls=ROOT.RooStats.ModelConfig)
if isinstance(data, string_types):
data = self.data(data)
pdf = model_config.GetPdf()
pois = model_config.GetParametersOfInterest()
if pois.getSize() > 0:
poi = pois.first()
poi.setConstant(poi_const)
if poi_value is not None:
poi.setVal(poi_value)
if poi_range is not None:
poi.setRange(*poi_range)
if param_const is not None:
for param_name, const in param_const.items():
var = self.var(param_name)
var.setConstant(const)
if param_values is not None:
for param_name, param_value in param_values.items():
var = self.var(param_name)
var.setVal(param_value)
if param_ranges is not None:
for param_name, param_range in param_ranges.items():
var = self.var(param_name)
var.setRange(*param_range)
if print_level < 0:
msg_service = ROOT.RooMsgService.instance()
msg_level = msg_service.globalKillBelow()
msg_service.setGlobalKillBelow(ROOT.RooFit.FATAL)
args = [
ROOT.RooFit.Constrain(model_config.GetNuisanceParameters()),
ROOT.RooFit.GlobalObservables(model_config.GetGlobalObservables())]
if extended:
args.append(ROOT.RooFit.Extended(True))
if offset:
args.append(ROOT.RooFit.Offset(True))
if num_cpu != 1:
if num_cpu == 0:
raise ValueError("num_cpu must be non-zero")
if num_cpu < 0:
num_cpu = NCPU
args.append(ROOT.RooFit.NumCPU(num_cpu, process_strategy))
func = pdf.createNLL(data, *args)
if print_level < 0:
msg_service.setGlobalKillBelow(msg_level)
result = minimize(func, print_level=print_level, **kwargs)
if return_nll:
return result, func
return result
|
python
|
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,
extended=False,
num_cpu=1,
process_strategy=0,
offset=False,
print_level=None,
return_nll=False,
**kwargs):
"""
Fit a pdf to data in a workspace
Parameters
----------
workspace : RooWorkspace
The workspace
data : str or RooAbsData, optional (default='obsData')
The name of the data or a RooAbsData instance.
model_config : str or ModelConfig, optional (default='ModelConfig')
The name of the ModelConfig in the workspace or a
ModelConfig instance.
param_const : dict, optional (default=None)
A dict mapping parameter names to booleans setting
the const state of the parameter
param_values : dict, optional (default=None)
A dict mapping parameter names to values
param_ranges : dict, optional (default=None)
A dict mapping parameter names to 2-tuples defining the ranges
poi_const : bool, optional (default=False)
If True, then make the parameter of interest (POI) constant
poi_value : float, optional (default=None)
If not None, then set the POI to this value
poi_range : tuple, optional (default=None)
If not None, then set the range of the POI with this 2-tuple
extended : bool, optional (default=False)
If True, add extended likelihood term (False by default)
num_cpu : int, optional (default=1)
Parallelize NLL calculation on multiple CPU cores.
If negative then use all CPU cores.
By default use only one CPU core.
process_strategy : int, optional (default=0)
**Strategy 0:** Divide events into N equal chunks.
**Strategy 1:** Process event i%N in process N. Recommended for
binned data with a substantial number of zero-bins, which will be
distributed across processes more equitably in this strategy.
**Strategy 2:** Process each component likelihood of a
RooSimultaneous fully in a single process and distribute components
over processes. This approach can be benificial if normalization
calculation time dominates the total computation time of a
component (since the normalization calculation must be performed
in each process in strategies 0 and 1. However beware that if the
RooSimultaneous components do not share many parameters this
strategy is inefficient: as most minuit-induced likelihood
calculations involve changing a single parameter, only 1 of the N
processes will be active most of the time if RooSimultaneous
components do not share many parameters.
**Strategy 3:** Follow strategy 0 for all RooSimultaneous
components, except those with less than 30 dataset entries,
for which strategy 2 is followed.
offset : bool, optional (default=False)
Offset likelihood by initial value (so that starting value of FCN
in minuit is zero). This can improve numeric stability in
simultaneously fits with components with large likelihood values.
print_level : int, optional (default=None)
The verbosity level for the minimizer algorithm.
If None (the default) then use the global default print level.
If negative then all non-fatal messages will be suppressed.
return_nll : bool, optional (default=False)
If True then also return the RooAbsReal NLL function that was
minimized.
kwargs : dict, optional
Remaining keyword arguments are passed to the minimize function
Returns
-------
result : RooFitResult
The fit result.
func : RooAbsReal
If return_nll is True, the NLL function is also returned.
See Also
--------
minimize
"""
if isinstance(model_config, string_types):
model_config = self.obj(
model_config, cls=ROOT.RooStats.ModelConfig)
if isinstance(data, string_types):
data = self.data(data)
pdf = model_config.GetPdf()
pois = model_config.GetParametersOfInterest()
if pois.getSize() > 0:
poi = pois.first()
poi.setConstant(poi_const)
if poi_value is not None:
poi.setVal(poi_value)
if poi_range is not None:
poi.setRange(*poi_range)
if param_const is not None:
for param_name, const in param_const.items():
var = self.var(param_name)
var.setConstant(const)
if param_values is not None:
for param_name, param_value in param_values.items():
var = self.var(param_name)
var.setVal(param_value)
if param_ranges is not None:
for param_name, param_range in param_ranges.items():
var = self.var(param_name)
var.setRange(*param_range)
if print_level < 0:
msg_service = ROOT.RooMsgService.instance()
msg_level = msg_service.globalKillBelow()
msg_service.setGlobalKillBelow(ROOT.RooFit.FATAL)
args = [
ROOT.RooFit.Constrain(model_config.GetNuisanceParameters()),
ROOT.RooFit.GlobalObservables(model_config.GetGlobalObservables())]
if extended:
args.append(ROOT.RooFit.Extended(True))
if offset:
args.append(ROOT.RooFit.Offset(True))
if num_cpu != 1:
if num_cpu == 0:
raise ValueError("num_cpu must be non-zero")
if num_cpu < 0:
num_cpu = NCPU
args.append(ROOT.RooFit.NumCPU(num_cpu, process_strategy))
func = pdf.createNLL(data, *args)
if print_level < 0:
msg_service.setGlobalKillBelow(msg_level)
result = minimize(func, print_level=print_level, **kwargs)
if return_nll:
return result, func
return result
|
[
"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",
",",
"extended",
"=",
"False",
",",
"num_cpu",
"=",
"1",
",",
"process_strategy",
"=",
"0",
",",
"offset",
"=",
"False",
",",
"print_level",
"=",
"None",
",",
"return_nll",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"model_config",
",",
"string_types",
")",
":",
"model_config",
"=",
"self",
".",
"obj",
"(",
"model_config",
",",
"cls",
"=",
"ROOT",
".",
"RooStats",
".",
"ModelConfig",
")",
"if",
"isinstance",
"(",
"data",
",",
"string_types",
")",
":",
"data",
"=",
"self",
".",
"data",
"(",
"data",
")",
"pdf",
"=",
"model_config",
".",
"GetPdf",
"(",
")",
"pois",
"=",
"model_config",
".",
"GetParametersOfInterest",
"(",
")",
"if",
"pois",
".",
"getSize",
"(",
")",
">",
"0",
":",
"poi",
"=",
"pois",
".",
"first",
"(",
")",
"poi",
".",
"setConstant",
"(",
"poi_const",
")",
"if",
"poi_value",
"is",
"not",
"None",
":",
"poi",
".",
"setVal",
"(",
"poi_value",
")",
"if",
"poi_range",
"is",
"not",
"None",
":",
"poi",
".",
"setRange",
"(",
"*",
"poi_range",
")",
"if",
"param_const",
"is",
"not",
"None",
":",
"for",
"param_name",
",",
"const",
"in",
"param_const",
".",
"items",
"(",
")",
":",
"var",
"=",
"self",
".",
"var",
"(",
"param_name",
")",
"var",
".",
"setConstant",
"(",
"const",
")",
"if",
"param_values",
"is",
"not",
"None",
":",
"for",
"param_name",
",",
"param_value",
"in",
"param_values",
".",
"items",
"(",
")",
":",
"var",
"=",
"self",
".",
"var",
"(",
"param_name",
")",
"var",
".",
"setVal",
"(",
"param_value",
")",
"if",
"param_ranges",
"is",
"not",
"None",
":",
"for",
"param_name",
",",
"param_range",
"in",
"param_ranges",
".",
"items",
"(",
")",
":",
"var",
"=",
"self",
".",
"var",
"(",
"param_name",
")",
"var",
".",
"setRange",
"(",
"*",
"param_range",
")",
"if",
"print_level",
"<",
"0",
":",
"msg_service",
"=",
"ROOT",
".",
"RooMsgService",
".",
"instance",
"(",
")",
"msg_level",
"=",
"msg_service",
".",
"globalKillBelow",
"(",
")",
"msg_service",
".",
"setGlobalKillBelow",
"(",
"ROOT",
".",
"RooFit",
".",
"FATAL",
")",
"args",
"=",
"[",
"ROOT",
".",
"RooFit",
".",
"Constrain",
"(",
"model_config",
".",
"GetNuisanceParameters",
"(",
")",
")",
",",
"ROOT",
".",
"RooFit",
".",
"GlobalObservables",
"(",
"model_config",
".",
"GetGlobalObservables",
"(",
")",
")",
"]",
"if",
"extended",
":",
"args",
".",
"append",
"(",
"ROOT",
".",
"RooFit",
".",
"Extended",
"(",
"True",
")",
")",
"if",
"offset",
":",
"args",
".",
"append",
"(",
"ROOT",
".",
"RooFit",
".",
"Offset",
"(",
"True",
")",
")",
"if",
"num_cpu",
"!=",
"1",
":",
"if",
"num_cpu",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"num_cpu must be non-zero\"",
")",
"if",
"num_cpu",
"<",
"0",
":",
"num_cpu",
"=",
"NCPU",
"args",
".",
"append",
"(",
"ROOT",
".",
"RooFit",
".",
"NumCPU",
"(",
"num_cpu",
",",
"process_strategy",
")",
")",
"func",
"=",
"pdf",
".",
"createNLL",
"(",
"data",
",",
"*",
"args",
")",
"if",
"print_level",
"<",
"0",
":",
"msg_service",
".",
"setGlobalKillBelow",
"(",
"msg_level",
")",
"result",
"=",
"minimize",
"(",
"func",
",",
"print_level",
"=",
"print_level",
",",
"*",
"*",
"kwargs",
")",
"if",
"return_nll",
":",
"return",
"result",
",",
"func",
"return",
"result"
] |
Fit a pdf to data in a workspace
Parameters
----------
workspace : RooWorkspace
The workspace
data : str or RooAbsData, optional (default='obsData')
The name of the data or a RooAbsData instance.
model_config : str or ModelConfig, optional (default='ModelConfig')
The name of the ModelConfig in the workspace or a
ModelConfig instance.
param_const : dict, optional (default=None)
A dict mapping parameter names to booleans setting
the const state of the parameter
param_values : dict, optional (default=None)
A dict mapping parameter names to values
param_ranges : dict, optional (default=None)
A dict mapping parameter names to 2-tuples defining the ranges
poi_const : bool, optional (default=False)
If True, then make the parameter of interest (POI) constant
poi_value : float, optional (default=None)
If not None, then set the POI to this value
poi_range : tuple, optional (default=None)
If not None, then set the range of the POI with this 2-tuple
extended : bool, optional (default=False)
If True, add extended likelihood term (False by default)
num_cpu : int, optional (default=1)
Parallelize NLL calculation on multiple CPU cores.
If negative then use all CPU cores.
By default use only one CPU core.
process_strategy : int, optional (default=0)
**Strategy 0:** Divide events into N equal chunks.
**Strategy 1:** Process event i%N in process N. Recommended for
binned data with a substantial number of zero-bins, which will be
distributed across processes more equitably in this strategy.
**Strategy 2:** Process each component likelihood of a
RooSimultaneous fully in a single process and distribute components
over processes. This approach can be benificial if normalization
calculation time dominates the total computation time of a
component (since the normalization calculation must be performed
in each process in strategies 0 and 1. However beware that if the
RooSimultaneous components do not share many parameters this
strategy is inefficient: as most minuit-induced likelihood
calculations involve changing a single parameter, only 1 of the N
processes will be active most of the time if RooSimultaneous
components do not share many parameters.
**Strategy 3:** Follow strategy 0 for all RooSimultaneous
components, except those with less than 30 dataset entries,
for which strategy 2 is followed.
offset : bool, optional (default=False)
Offset likelihood by initial value (so that starting value of FCN
in minuit is zero). This can improve numeric stability in
simultaneously fits with components with large likelihood values.
print_level : int, optional (default=None)
The verbosity level for the minimizer algorithm.
If None (the default) then use the global default print level.
If negative then all non-fatal messages will be suppressed.
return_nll : bool, optional (default=False)
If True then also return the RooAbsReal NLL function that was
minimized.
kwargs : dict, optional
Remaining keyword arguments are passed to the minimize function
Returns
-------
result : RooFitResult
The fit result.
func : RooAbsReal
If return_nll is True, the NLL function is also returned.
See Also
--------
minimize
|
[
"Fit",
"a",
"pdf",
"to",
"data",
"in",
"a",
"workspace"
] |
3926935e1f2100d8ba68070c2ab44055d4800f73
|
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/stats/workspace.py#L162-L333
|
14,148
|
Deepwalker/trafaret
|
trafaret/base.py
|
ensure_trafaret
|
def ensure_trafaret(trafaret):
"""
Helper for complex trafarets, takes trafaret instance or class
and returns trafaret instance
"""
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 them
# as trafaret functions
return Call(lambda val: trafaret(val))
elif callable(trafaret):
return Call(trafaret)
else:
raise RuntimeError("%r should be instance or subclass"
" of Trafaret" % trafaret)
|
python
|
def ensure_trafaret(trafaret):
"""
Helper for complex trafarets, takes trafaret instance or class
and returns trafaret instance
"""
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 them
# as trafaret functions
return Call(lambda val: trafaret(val))
elif callable(trafaret):
return Call(trafaret)
else:
raise RuntimeError("%r should be instance or subclass"
" of Trafaret" % trafaret)
|
[
"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 them",
"# as trafaret functions",
"return",
"Call",
"(",
"lambda",
"val",
":",
"trafaret",
"(",
"val",
")",
")",
"elif",
"callable",
"(",
"trafaret",
")",
":",
"return",
"Call",
"(",
"trafaret",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"%r should be instance or subclass\"",
"\" of Trafaret\"",
"%",
"trafaret",
")"
] |
Helper for complex trafarets, takes trafaret instance or class
and returns trafaret instance
|
[
"Helper",
"for",
"complex",
"trafarets",
"takes",
"trafaret",
"instance",
"or",
"class",
"and",
"returns",
"trafaret",
"instance"
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/base.py#L171-L188
|
14,149
|
Deepwalker/trafaret
|
trafaret/base.py
|
DictKeys
|
def DictKeys(keys):
"""
Checks if dict has all given keys
:param keys:
:type keys:
>>> _dd(DictKeys(['a','b']).check({'a':1,'b':2,}))
"{'a': 1, 'b': 2}"
>>> extract_error(DictKeys(['a','b']), {'a':1,'b':2,'c':3,})
{'c': 'c is not allowed key'}
>>> extract_error(DictKeys(['key','key2']), {'key':'val'})
{'key2': 'is required'}
"""
req = [(Key(key), Any) for key in keys]
return Dict(dict(req))
|
python
|
def DictKeys(keys):
"""
Checks if dict has all given keys
:param keys:
:type keys:
>>> _dd(DictKeys(['a','b']).check({'a':1,'b':2,}))
"{'a': 1, 'b': 2}"
>>> extract_error(DictKeys(['a','b']), {'a':1,'b':2,'c':3,})
{'c': 'c is not allowed key'}
>>> extract_error(DictKeys(['key','key2']), {'key':'val'})
{'key2': 'is required'}
"""
req = [(Key(key), Any) for key in keys]
return Dict(dict(req))
|
[
"def",
"DictKeys",
"(",
"keys",
")",
":",
"req",
"=",
"[",
"(",
"Key",
"(",
"key",
")",
",",
"Any",
")",
"for",
"key",
"in",
"keys",
"]",
"return",
"Dict",
"(",
"dict",
"(",
"req",
")",
")"
] |
Checks if dict has all given keys
:param keys:
:type keys:
>>> _dd(DictKeys(['a','b']).check({'a':1,'b':2,}))
"{'a': 1, 'b': 2}"
>>> extract_error(DictKeys(['a','b']), {'a':1,'b':2,'c':3,})
{'c': 'c is not allowed key'}
>>> extract_error(DictKeys(['key','key2']), {'key':'val'})
{'key2': 'is required'}
|
[
"Checks",
"if",
"dict",
"has",
"all",
"given",
"keys"
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/base.py#L1064-L1079
|
14,150
|
Deepwalker/trafaret
|
trafaret/base.py
|
guard
|
def guard(trafaret=None, **kwargs):
"""
Decorator for protecting function with trafarets
>>> @guard(a=String, b=Int, c=String)
... def fn(a, b, c="default"):
... '''docstring'''
... return (a, b, c)
...
>>> fn.__module__ = None
>>> help(fn)
Help on function fn:
<BLANKLINE>
fn(*args, **kwargs)
guarded with <Dict(a=<String>, b=<Int>, c=<String>)>
<BLANKLINE>
docstring
<BLANKLINE>
>>> fn("foo", 1)
('foo', 1, 'default')
>>> extract_error(fn, "foo", 1, 2)
{'c': 'value is not a string'}
>>> extract_error(fn, "foo")
{'b': 'is required'}
>>> g = guard(Dict())
>>> c = Forward()
>>> c << Dict(name=str, children=List[c])
>>> g = guard(c)
>>> g = guard(Int())
Traceback (most recent call last):
...
RuntimeError: trafaret should be instance of Dict or Forward
"""
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:
raise RuntimeError("choose one way of initialization,"
" trafaret or kwargs")
if not trafaret:
trafaret = Dict(**kwargs)
def wrapper(fn):
argspec = getargspec(fn)
@functools.wraps(fn)
def decor(*args, **kwargs):
fnargs = argspec.args
if fnargs and fnargs[0] in ['self', 'cls']:
obj = args[0]
fnargs = fnargs[1:]
checkargs = args[1:]
else:
obj = None
checkargs = args
try:
call_args = dict(
itertools.chain(zip(fnargs, checkargs), kwargs.items())
)
for name, default in zip(reversed(fnargs),
reversed(argspec.defaults or ())):
if name not in call_args:
call_args[name] = default
converted = trafaret(call_args)
except DataError as err:
raise GuardError(error=err.error)
return fn(obj, **converted) if obj else fn(**converted)
decor.__doc__ = "guarded with %r\n\n" % trafaret + (decor.__doc__ or "")
return decor
return wrapper
|
python
|
def guard(trafaret=None, **kwargs):
"""
Decorator for protecting function with trafarets
>>> @guard(a=String, b=Int, c=String)
... def fn(a, b, c="default"):
... '''docstring'''
... return (a, b, c)
...
>>> fn.__module__ = None
>>> help(fn)
Help on function fn:
<BLANKLINE>
fn(*args, **kwargs)
guarded with <Dict(a=<String>, b=<Int>, c=<String>)>
<BLANKLINE>
docstring
<BLANKLINE>
>>> fn("foo", 1)
('foo', 1, 'default')
>>> extract_error(fn, "foo", 1, 2)
{'c': 'value is not a string'}
>>> extract_error(fn, "foo")
{'b': 'is required'}
>>> g = guard(Dict())
>>> c = Forward()
>>> c << Dict(name=str, children=List[c])
>>> g = guard(c)
>>> g = guard(Int())
Traceback (most recent call last):
...
RuntimeError: trafaret should be instance of Dict or Forward
"""
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:
raise RuntimeError("choose one way of initialization,"
" trafaret or kwargs")
if not trafaret:
trafaret = Dict(**kwargs)
def wrapper(fn):
argspec = getargspec(fn)
@functools.wraps(fn)
def decor(*args, **kwargs):
fnargs = argspec.args
if fnargs and fnargs[0] in ['self', 'cls']:
obj = args[0]
fnargs = fnargs[1:]
checkargs = args[1:]
else:
obj = None
checkargs = args
try:
call_args = dict(
itertools.chain(zip(fnargs, checkargs), kwargs.items())
)
for name, default in zip(reversed(fnargs),
reversed(argspec.defaults or ())):
if name not in call_args:
call_args[name] = default
converted = trafaret(call_args)
except DataError as err:
raise GuardError(error=err.error)
return fn(obj, **converted) if obj else fn(**converted)
decor.__doc__ = "guarded with %r\n\n" % trafaret + (decor.__doc__ or "")
return decor
return wrapper
|
[
"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",
":",
"raise",
"RuntimeError",
"(",
"\"choose one way of initialization,\"",
"\" trafaret or kwargs\"",
")",
"if",
"not",
"trafaret",
":",
"trafaret",
"=",
"Dict",
"(",
"*",
"*",
"kwargs",
")",
"def",
"wrapper",
"(",
"fn",
")",
":",
"argspec",
"=",
"getargspec",
"(",
"fn",
")",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"decor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fnargs",
"=",
"argspec",
".",
"args",
"if",
"fnargs",
"and",
"fnargs",
"[",
"0",
"]",
"in",
"[",
"'self'",
",",
"'cls'",
"]",
":",
"obj",
"=",
"args",
"[",
"0",
"]",
"fnargs",
"=",
"fnargs",
"[",
"1",
":",
"]",
"checkargs",
"=",
"args",
"[",
"1",
":",
"]",
"else",
":",
"obj",
"=",
"None",
"checkargs",
"=",
"args",
"try",
":",
"call_args",
"=",
"dict",
"(",
"itertools",
".",
"chain",
"(",
"zip",
"(",
"fnargs",
",",
"checkargs",
")",
",",
"kwargs",
".",
"items",
"(",
")",
")",
")",
"for",
"name",
",",
"default",
"in",
"zip",
"(",
"reversed",
"(",
"fnargs",
")",
",",
"reversed",
"(",
"argspec",
".",
"defaults",
"or",
"(",
")",
")",
")",
":",
"if",
"name",
"not",
"in",
"call_args",
":",
"call_args",
"[",
"name",
"]",
"=",
"default",
"converted",
"=",
"trafaret",
"(",
"call_args",
")",
"except",
"DataError",
"as",
"err",
":",
"raise",
"GuardError",
"(",
"error",
"=",
"err",
".",
"error",
")",
"return",
"fn",
"(",
"obj",
",",
"*",
"*",
"converted",
")",
"if",
"obj",
"else",
"fn",
"(",
"*",
"*",
"converted",
")",
"decor",
".",
"__doc__",
"=",
"\"guarded with %r\\n\\n\"",
"%",
"trafaret",
"+",
"(",
"decor",
".",
"__doc__",
"or",
"\"\"",
")",
"return",
"decor",
"return",
"wrapper"
] |
Decorator for protecting function with trafarets
>>> @guard(a=String, b=Int, c=String)
... def fn(a, b, c="default"):
... '''docstring'''
... return (a, b, c)
...
>>> fn.__module__ = None
>>> help(fn)
Help on function fn:
<BLANKLINE>
fn(*args, **kwargs)
guarded with <Dict(a=<String>, b=<Int>, c=<String>)>
<BLANKLINE>
docstring
<BLANKLINE>
>>> fn("foo", 1)
('foo', 1, 'default')
>>> extract_error(fn, "foo", 1, 2)
{'c': 'value is not a string'}
>>> extract_error(fn, "foo")
{'b': 'is required'}
>>> g = guard(Dict())
>>> c = Forward()
>>> c << Dict(name=str, children=List[c])
>>> g = guard(c)
>>> g = guard(Int())
Traceback (most recent call last):
...
RuntimeError: trafaret should be instance of Dict or Forward
|
[
"Decorator",
"for",
"protecting",
"function",
"with",
"trafarets"
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/base.py#L1265-L1338
|
14,151
|
Deepwalker/trafaret
|
trafaret/base.py
|
Dict._clone_args
|
def _clone_args(self):
""" return args to create new Dict clone
"""
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_trafaret'] = self.extras_trafaret
if self.ignore_any or self.ignore:
kw['ignore_extra'] = list(self.ignore)
if self.ignore_any:
kw['ignore_any'].append('*')
return keys, kw
|
python
|
def _clone_args(self):
""" return args to create new Dict clone
"""
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_trafaret'] = self.extras_trafaret
if self.ignore_any or self.ignore:
kw['ignore_extra'] = list(self.ignore)
if self.ignore_any:
kw['ignore_any'].append('*')
return keys, kw
|
[
"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_trafaret'",
"]",
"=",
"self",
".",
"extras_trafaret",
"if",
"self",
".",
"ignore_any",
"or",
"self",
".",
"ignore",
":",
"kw",
"[",
"'ignore_extra'",
"]",
"=",
"list",
"(",
"self",
".",
"ignore",
")",
"if",
"self",
".",
"ignore_any",
":",
"kw",
"[",
"'ignore_any'",
"]",
".",
"append",
"(",
"'*'",
")",
"return",
"keys",
",",
"kw"
] |
return args to create new Dict clone
|
[
"return",
"args",
"to",
"create",
"new",
"Dict",
"clone"
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/base.py#L942-L956
|
14,152
|
Deepwalker/trafaret
|
trafaret/base.py
|
Dict.merge
|
def merge(self, other):
"""
Extends one Dict with other Dict Key`s or Key`s list,
or dict instance supposed for Dict
"""
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)):
other_keys = list(other)
elif isinstance(other, dict):
return self.__class__(other, *self.keys)
else:
raise TypeError('You must merge Dict only with Dict'
' or list of Keys')
return self.__class__(*(self.keys + other_keys), ignore_extra=ignore,
allow_extra=extra)
|
python
|
def merge(self, other):
"""
Extends one Dict with other Dict Key`s or Key`s list,
or dict instance supposed for Dict
"""
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)):
other_keys = list(other)
elif isinstance(other, dict):
return self.__class__(other, *self.keys)
else:
raise TypeError('You must merge Dict only with Dict'
' or list of Keys')
return self.__class__(*(self.keys + other_keys), ignore_extra=ignore,
allow_extra=extra)
|
[
"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",
")",
")",
":",
"other_keys",
"=",
"list",
"(",
"other",
")",
"elif",
"isinstance",
"(",
"other",
",",
"dict",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"other",
",",
"*",
"self",
".",
"keys",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'You must merge Dict only with Dict'",
"' or list of Keys'",
")",
"return",
"self",
".",
"__class__",
"(",
"*",
"(",
"self",
".",
"keys",
"+",
"other_keys",
")",
",",
"ignore_extra",
"=",
"ignore",
",",
"allow_extra",
"=",
"extra",
")"
] |
Extends one Dict with other Dict Key`s or Key`s list,
or dict instance supposed for Dict
|
[
"Extends",
"one",
"Dict",
"with",
"other",
"Dict",
"Key",
"s",
"or",
"Key",
"s",
"list",
"or",
"dict",
"instance",
"supposed",
"for",
"Dict"
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/base.py#L1040-L1059
|
14,153
|
Deepwalker/trafaret
|
trafaret/visitor.py
|
get_deep_attr
|
def get_deep_attr(obj, keys):
""" Helper for DeepKey"""
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
except AttributeError:
pass
raise DataError(error='Unexistent key')
return cur
|
python
|
def get_deep_attr(obj, keys):
""" Helper for DeepKey"""
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
except AttributeError:
pass
raise DataError(error='Unexistent key')
return cur
|
[
"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",
"except",
"AttributeError",
":",
"pass",
"raise",
"DataError",
"(",
"error",
"=",
"'Unexistent key'",
")",
"return",
"cur"
] |
Helper for DeepKey
|
[
"Helper",
"for",
"DeepKey"
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/visitor.py#L10-L24
|
14,154
|
Deepwalker/trafaret
|
trafaret/constructor.py
|
construct
|
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.Dict. If key has '?' at the and it will be optional and '?' will be removed
- any callable will be t.Call
- otherwise it will be returned as is
construct is recursive and will try construct all lists, tuples and dicts args
'''
if isinstance(arg, t.Trafaret):
return arg
elif isinstance(arg, tuple) or (isinstance(arg, list) and len(arg) > 1):
return t.Tuple(*(construct(a) for a in arg))
elif isinstance(arg, list):
# if len(arg) == 1
return t.List(construct(arg[0]))
elif isinstance(arg, dict):
return t.Dict({construct_key(key): construct(value) for key, value in arg.items()})
elif isinstance(arg, str):
return t.Atom(arg)
elif isinstance(arg, type):
if arg is int:
return t.Int()
elif arg is float:
return t.Float()
elif arg is str:
return t.String()
elif arg is bool:
return t.Bool()
else:
return t.Type(arg)
elif callable(arg):
return t.Call(arg)
else:
return arg
|
python
|
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.Dict. If key has '?' at the and it will be optional and '?' will be removed
- any callable will be t.Call
- otherwise it will be returned as is
construct is recursive and will try construct all lists, tuples and dicts args
'''
if isinstance(arg, t.Trafaret):
return arg
elif isinstance(arg, tuple) or (isinstance(arg, list) and len(arg) > 1):
return t.Tuple(*(construct(a) for a in arg))
elif isinstance(arg, list):
# if len(arg) == 1
return t.List(construct(arg[0]))
elif isinstance(arg, dict):
return t.Dict({construct_key(key): construct(value) for key, value in arg.items()})
elif isinstance(arg, str):
return t.Atom(arg)
elif isinstance(arg, type):
if arg is int:
return t.Int()
elif arg is float:
return t.Float()
elif arg is str:
return t.String()
elif arg is bool:
return t.Bool()
else:
return t.Type(arg)
elif callable(arg):
return t.Call(arg)
else:
return arg
|
[
"def",
"construct",
"(",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"t",
".",
"Trafaret",
")",
":",
"return",
"arg",
"elif",
"isinstance",
"(",
"arg",
",",
"tuple",
")",
"or",
"(",
"isinstance",
"(",
"arg",
",",
"list",
")",
"and",
"len",
"(",
"arg",
")",
">",
"1",
")",
":",
"return",
"t",
".",
"Tuple",
"(",
"*",
"(",
"construct",
"(",
"a",
")",
"for",
"a",
"in",
"arg",
")",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"list",
")",
":",
"# if len(arg) == 1",
"return",
"t",
".",
"List",
"(",
"construct",
"(",
"arg",
"[",
"0",
"]",
")",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"return",
"t",
".",
"Dict",
"(",
"{",
"construct_key",
"(",
"key",
")",
":",
"construct",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"arg",
".",
"items",
"(",
")",
"}",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"str",
")",
":",
"return",
"t",
".",
"Atom",
"(",
"arg",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"type",
")",
":",
"if",
"arg",
"is",
"int",
":",
"return",
"t",
".",
"Int",
"(",
")",
"elif",
"arg",
"is",
"float",
":",
"return",
"t",
".",
"Float",
"(",
")",
"elif",
"arg",
"is",
"str",
":",
"return",
"t",
".",
"String",
"(",
")",
"elif",
"arg",
"is",
"bool",
":",
"return",
"t",
".",
"Bool",
"(",
")",
"else",
":",
"return",
"t",
".",
"Type",
"(",
"arg",
")",
"elif",
"callable",
"(",
"arg",
")",
":",
"return",
"t",
".",
"Call",
"(",
"arg",
")",
"else",
":",
"return",
"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.Dict. If key has '?' at the and it will be optional and '?' will be removed
- any callable will be t.Call
- otherwise it will be returned as is
construct is recursive and will try construct all lists, tuples and dicts args
|
[
"Shortcut",
"syntax",
"to",
"define",
"trafarets",
"."
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/constructor.py#L23-L61
|
14,155
|
Deepwalker/trafaret
|
trafaret/keys.py
|
subdict
|
def subdict(name, *keys, **kw):
"""
Subdict key.
Takes a `name`, any number of keys as args and keyword argument `trafaret`.
Use it like:
def check_passwords_equal(data):
if data['password'] != data['password_confirm']:
return t.DataError('Passwords are not equal')
return data['password']
passwords_key = subdict(
'password',
t.Key('password', trafaret=check_password),
t.Key('password_confirm', trafaret=check_password),
trafaret=check_passwords_equal,
)
signup_trafaret = t.Dict(
t.Key('email', trafaret=t.Email),
passwords_key,
)
"""
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(data, context=context):
touched.update(names)
preserve_output.append((k, v, names))
if isinstance(v, t.DataError):
errors = True
else:
collect[k] = v
if errors:
for out in preserve_output:
yield out
elif collect:
yield name, t.catch(trafaret, collect), touched
return inner
|
python
|
def subdict(name, *keys, **kw):
"""
Subdict key.
Takes a `name`, any number of keys as args and keyword argument `trafaret`.
Use it like:
def check_passwords_equal(data):
if data['password'] != data['password_confirm']:
return t.DataError('Passwords are not equal')
return data['password']
passwords_key = subdict(
'password',
t.Key('password', trafaret=check_password),
t.Key('password_confirm', trafaret=check_password),
trafaret=check_passwords_equal,
)
signup_trafaret = t.Dict(
t.Key('email', trafaret=t.Email),
passwords_key,
)
"""
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(data, context=context):
touched.update(names)
preserve_output.append((k, v, names))
if isinstance(v, t.DataError):
errors = True
else:
collect[k] = v
if errors:
for out in preserve_output:
yield out
elif collect:
yield name, t.catch(trafaret, collect), touched
return inner
|
[
"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",
"(",
"data",
",",
"context",
"=",
"context",
")",
":",
"touched",
".",
"update",
"(",
"names",
")",
"preserve_output",
".",
"append",
"(",
"(",
"k",
",",
"v",
",",
"names",
")",
")",
"if",
"isinstance",
"(",
"v",
",",
"t",
".",
"DataError",
")",
":",
"errors",
"=",
"True",
"else",
":",
"collect",
"[",
"k",
"]",
"=",
"v",
"if",
"errors",
":",
"for",
"out",
"in",
"preserve_output",
":",
"yield",
"out",
"elif",
"collect",
":",
"yield",
"name",
",",
"t",
".",
"catch",
"(",
"trafaret",
",",
"collect",
")",
",",
"touched",
"return",
"inner"
] |
Subdict key.
Takes a `name`, any number of keys as args and keyword argument `trafaret`.
Use it like:
def check_passwords_equal(data):
if data['password'] != data['password_confirm']:
return t.DataError('Passwords are not equal')
return data['password']
passwords_key = subdict(
'password',
t.Key('password', trafaret=check_password),
t.Key('password_confirm', trafaret=check_password),
trafaret=check_passwords_equal,
)
signup_trafaret = t.Dict(
t.Key('email', trafaret=t.Email),
passwords_key,
)
|
[
"Subdict",
"key",
"."
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/keys.py#L4-L50
|
14,156
|
Deepwalker/trafaret
|
trafaret/keys.py
|
xor_key
|
def xor_key(first, second, trafaret):
"""
xor_key - takes `first` and `second` key names and `trafaret`.
Checks if we have only `first` or only `second` in data, not both,
and at least one.
Then checks key value against trafaret.
"""
trafaret = t.Trafaret._trafaret(trafaret)
def check_(value):
if (first in value) ^ (second in value):
key = first if first in value else second
yield first, t.catch_error(trafaret, value[key]), (key,)
elif first in value and second in value:
yield first, t.DataError(error='correct only if {} is not defined'.format(second)), (first,)
yield second, t.DataError(error='correct only if {} is not defined'.format(first)), (second,)
else:
yield first, t.DataError(error='is required if {} is not defined'.format('second')), (first,)
yield second, t.DataError(error='is required if {} is not defined'.format('first')), (second,)
return check_
|
python
|
def xor_key(first, second, trafaret):
"""
xor_key - takes `first` and `second` key names and `trafaret`.
Checks if we have only `first` or only `second` in data, not both,
and at least one.
Then checks key value against trafaret.
"""
trafaret = t.Trafaret._trafaret(trafaret)
def check_(value):
if (first in value) ^ (second in value):
key = first if first in value else second
yield first, t.catch_error(trafaret, value[key]), (key,)
elif first in value and second in value:
yield first, t.DataError(error='correct only if {} is not defined'.format(second)), (first,)
yield second, t.DataError(error='correct only if {} is not defined'.format(first)), (second,)
else:
yield first, t.DataError(error='is required if {} is not defined'.format('second')), (first,)
yield second, t.DataError(error='is required if {} is not defined'.format('first')), (second,)
return check_
|
[
"def",
"xor_key",
"(",
"first",
",",
"second",
",",
"trafaret",
")",
":",
"trafaret",
"=",
"t",
".",
"Trafaret",
".",
"_trafaret",
"(",
"trafaret",
")",
"def",
"check_",
"(",
"value",
")",
":",
"if",
"(",
"first",
"in",
"value",
")",
"^",
"(",
"second",
"in",
"value",
")",
":",
"key",
"=",
"first",
"if",
"first",
"in",
"value",
"else",
"second",
"yield",
"first",
",",
"t",
".",
"catch_error",
"(",
"trafaret",
",",
"value",
"[",
"key",
"]",
")",
",",
"(",
"key",
",",
")",
"elif",
"first",
"in",
"value",
"and",
"second",
"in",
"value",
":",
"yield",
"first",
",",
"t",
".",
"DataError",
"(",
"error",
"=",
"'correct only if {} is not defined'",
".",
"format",
"(",
"second",
")",
")",
",",
"(",
"first",
",",
")",
"yield",
"second",
",",
"t",
".",
"DataError",
"(",
"error",
"=",
"'correct only if {} is not defined'",
".",
"format",
"(",
"first",
")",
")",
",",
"(",
"second",
",",
")",
"else",
":",
"yield",
"first",
",",
"t",
".",
"DataError",
"(",
"error",
"=",
"'is required if {} is not defined'",
".",
"format",
"(",
"'second'",
")",
")",
",",
"(",
"first",
",",
")",
"yield",
"second",
",",
"t",
".",
"DataError",
"(",
"error",
"=",
"'is required if {} is not defined'",
".",
"format",
"(",
"'first'",
")",
")",
",",
"(",
"second",
",",
")",
"return",
"check_"
] |
xor_key - takes `first` and `second` key names and `trafaret`.
Checks if we have only `first` or only `second` in data, not both,
and at least one.
Then checks key value against trafaret.
|
[
"xor_key",
"-",
"takes",
"first",
"and",
"second",
"key",
"names",
"and",
"trafaret",
"."
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/keys.py#L53-L75
|
14,157
|
Deepwalker/trafaret
|
trafaret/keys.py
|
confirm_key
|
def confirm_key(name, confirm_name, trafaret):
"""
confirm_key - takes `name`, `confirm_name` and `trafaret`.
Checks if data['name'] equals data['confirm_name'] and both
are valid against `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:
second = value[confirm_name]
else:
yield confirm_name, t.DataError('is required'), (confirm_name,)
if not (first and second):
return
yield name, t.catch_error(trafaret, first), (name,)
yield confirm_name, t.catch_error(trafaret, second), (confirm_name,)
if first != second:
yield confirm_name, t.DataError('must be equal to {}'.format(name)), (confirm_name,)
return check_
|
python
|
def confirm_key(name, confirm_name, trafaret):
"""
confirm_key - takes `name`, `confirm_name` and `trafaret`.
Checks if data['name'] equals data['confirm_name'] and both
are valid against `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:
second = value[confirm_name]
else:
yield confirm_name, t.DataError('is required'), (confirm_name,)
if not (first and second):
return
yield name, t.catch_error(trafaret, first), (name,)
yield confirm_name, t.catch_error(trafaret, second), (confirm_name,)
if first != second:
yield confirm_name, t.DataError('must be equal to {}'.format(name)), (confirm_name,)
return check_
|
[
"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",
":",
"second",
"=",
"value",
"[",
"confirm_name",
"]",
"else",
":",
"yield",
"confirm_name",
",",
"t",
".",
"DataError",
"(",
"'is required'",
")",
",",
"(",
"confirm_name",
",",
")",
"if",
"not",
"(",
"first",
"and",
"second",
")",
":",
"return",
"yield",
"name",
",",
"t",
".",
"catch_error",
"(",
"trafaret",
",",
"first",
")",
",",
"(",
"name",
",",
")",
"yield",
"confirm_name",
",",
"t",
".",
"catch_error",
"(",
"trafaret",
",",
"second",
")",
",",
"(",
"confirm_name",
",",
")",
"if",
"first",
"!=",
"second",
":",
"yield",
"confirm_name",
",",
"t",
".",
"DataError",
"(",
"'must be equal to {}'",
".",
"format",
"(",
"name",
")",
")",
",",
"(",
"confirm_name",
",",
")",
"return",
"check_"
] |
confirm_key - takes `name`, `confirm_name` and `trafaret`.
Checks if data['name'] equals data['confirm_name'] and both
are valid against `trafaret`.
|
[
"confirm_key",
"-",
"takes",
"name",
"confirm_name",
"and",
"trafaret",
"."
] |
4cbe4226e7f65133ba184b946faa2d3cd0e39d17
|
https://github.com/Deepwalker/trafaret/blob/4cbe4226e7f65133ba184b946faa2d3cd0e39d17/trafaret/keys.py#L78-L101
|
14,158
|
packethost/packet-python
|
packet/Manager.py
|
Manager.get_capacity
|
def get_capacity(self, legacy=None):
"""Get capacity of all facilities.
:param legacy: Indicate set of server types to include in response
Validation of `legacy` is left to the packet api to avoid going out of date if any new value is introduced.
The currently known values are:
- only (current default, will be switched "soon")
- include
- exclude (soon to be default)
"""
params = None
if legacy:
params = {'legacy': legacy}
return self.call_api('/capacity', params=params)['capacity']
|
python
|
def get_capacity(self, legacy=None):
"""Get capacity of all facilities.
:param legacy: Indicate set of server types to include in response
Validation of `legacy` is left to the packet api to avoid going out of date if any new value is introduced.
The currently known values are:
- only (current default, will be switched "soon")
- include
- exclude (soon to be default)
"""
params = None
if legacy:
params = {'legacy': legacy}
return self.call_api('/capacity', params=params)['capacity']
|
[
"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.
:param legacy: Indicate set of server types to include in response
Validation of `legacy` is left to the packet api to avoid going out of date if any new value is introduced.
The currently known values are:
- only (current default, will be switched "soon")
- include
- exclude (soon to be default)
|
[
"Get",
"capacity",
"of",
"all",
"facilities",
"."
] |
075ad8e3e5c12c1654b3598dc1e993818aeac061
|
https://github.com/packethost/packet-python/blob/075ad8e3e5c12c1654b3598dc1e993818aeac061/packet/Manager.py#L170-L185
|
14,159
|
priestc/moneywagon
|
moneywagon/currency_support.py
|
CurrencySupport.altcore_data
|
def altcore_data(self):
"""
Returns the crypto_data for all currencies defined in moneywagon that also
meet the minimum support for altcore. Data is keyed according to the
bitcore specification.
"""
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')
hha = data.get('header_hash_algo')
shb = data.get('script_hash_byte')
supported = collections.OrderedDict()
supported['name'] = data['name']
supported['alias'] = symbol
if pub is not None:
supported['pubkeyhash'] = int(pub)
if priv:
supported['privatekey'] = priv
supported['scripthash'] = shb if shb else 5
if 'transaction_form' in data:
supported['transactionForm'] = data['transaction_form']
if 'private_key_form' in data:
supported['privateKeyForm'] = data['private_key_form']
#if 'message_magic' in data and data['message_magic']:
# supported['networkMagic'] = '0x%s' % binascii.hexlify(data['message_magic'])
supported['port'] = data.get('port') or None
if hha not in (None, 'double-sha256'):
supported['headerHashAlgo'] = hha
if data.get('script_hash_algo', 'double-sha256') not in (None, 'double-sha256'):
supported['scriptHashAlgo'] = data['script_hash_algo']
if data.get('transaction_hash_algo', 'double-sha256') not in (None, 'double-sha256'):
supported['transactionHashAlgo'] = data['transaction_hash_algo']
if data.get('seed_nodes'):
supported['dnsSeeds'] = data['seed_nodes']
ret.append(supported)
return ret
|
python
|
def altcore_data(self):
"""
Returns the crypto_data for all currencies defined in moneywagon that also
meet the minimum support for altcore. Data is keyed according to the
bitcore specification.
"""
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')
hha = data.get('header_hash_algo')
shb = data.get('script_hash_byte')
supported = collections.OrderedDict()
supported['name'] = data['name']
supported['alias'] = symbol
if pub is not None:
supported['pubkeyhash'] = int(pub)
if priv:
supported['privatekey'] = priv
supported['scripthash'] = shb if shb else 5
if 'transaction_form' in data:
supported['transactionForm'] = data['transaction_form']
if 'private_key_form' in data:
supported['privateKeyForm'] = data['private_key_form']
#if 'message_magic' in data and data['message_magic']:
# supported['networkMagic'] = '0x%s' % binascii.hexlify(data['message_magic'])
supported['port'] = data.get('port') or None
if hha not in (None, 'double-sha256'):
supported['headerHashAlgo'] = hha
if data.get('script_hash_algo', 'double-sha256') not in (None, 'double-sha256'):
supported['scriptHashAlgo'] = data['script_hash_algo']
if data.get('transaction_hash_algo', 'double-sha256') not in (None, 'double-sha256'):
supported['transactionHashAlgo'] = data['transaction_hash_algo']
if data.get('seed_nodes'):
supported['dnsSeeds'] = data['seed_nodes']
ret.append(supported)
return ret
|
[
"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'",
")",
"hha",
"=",
"data",
".",
"get",
"(",
"'header_hash_algo'",
")",
"shb",
"=",
"data",
".",
"get",
"(",
"'script_hash_byte'",
")",
"supported",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"supported",
"[",
"'name'",
"]",
"=",
"data",
"[",
"'name'",
"]",
"supported",
"[",
"'alias'",
"]",
"=",
"symbol",
"if",
"pub",
"is",
"not",
"None",
":",
"supported",
"[",
"'pubkeyhash'",
"]",
"=",
"int",
"(",
"pub",
")",
"if",
"priv",
":",
"supported",
"[",
"'privatekey'",
"]",
"=",
"priv",
"supported",
"[",
"'scripthash'",
"]",
"=",
"shb",
"if",
"shb",
"else",
"5",
"if",
"'transaction_form'",
"in",
"data",
":",
"supported",
"[",
"'transactionForm'",
"]",
"=",
"data",
"[",
"'transaction_form'",
"]",
"if",
"'private_key_form'",
"in",
"data",
":",
"supported",
"[",
"'privateKeyForm'",
"]",
"=",
"data",
"[",
"'private_key_form'",
"]",
"#if 'message_magic' in data and data['message_magic']:",
"# supported['networkMagic'] = '0x%s' % binascii.hexlify(data['message_magic'])",
"supported",
"[",
"'port'",
"]",
"=",
"data",
".",
"get",
"(",
"'port'",
")",
"or",
"None",
"if",
"hha",
"not",
"in",
"(",
"None",
",",
"'double-sha256'",
")",
":",
"supported",
"[",
"'headerHashAlgo'",
"]",
"=",
"hha",
"if",
"data",
".",
"get",
"(",
"'script_hash_algo'",
",",
"'double-sha256'",
")",
"not",
"in",
"(",
"None",
",",
"'double-sha256'",
")",
":",
"supported",
"[",
"'scriptHashAlgo'",
"]",
"=",
"data",
"[",
"'script_hash_algo'",
"]",
"if",
"data",
".",
"get",
"(",
"'transaction_hash_algo'",
",",
"'double-sha256'",
")",
"not",
"in",
"(",
"None",
",",
"'double-sha256'",
")",
":",
"supported",
"[",
"'transactionHashAlgo'",
"]",
"=",
"data",
"[",
"'transaction_hash_algo'",
"]",
"if",
"data",
".",
"get",
"(",
"'seed_nodes'",
")",
":",
"supported",
"[",
"'dnsSeeds'",
"]",
"=",
"data",
"[",
"'seed_nodes'",
"]",
"ret",
".",
"append",
"(",
"supported",
")",
"return",
"ret"
] |
Returns the crypto_data for all currencies defined in moneywagon that also
meet the minimum support for altcore. Data is keyed according to the
bitcore specification.
|
[
"Returns",
"the",
"crypto_data",
"for",
"all",
"currencies",
"defined",
"in",
"moneywagon",
"that",
"also",
"meet",
"the",
"minimum",
"support",
"for",
"altcore",
".",
"Data",
"is",
"keyed",
"according",
"to",
"the",
"bitcore",
"specification",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/currency_support.py#L101-L142
|
14,160
|
priestc/moneywagon
|
moneywagon/tx.py
|
Transaction.from_unit_to_satoshi
|
def from_unit_to_satoshi(self, value, unit='satoshi'):
"""
Convert a value to satoshis. units can be any fiat currency.
By default the unit is 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
convert = get_current_price(self.crypto, unit)
return int(value / convert * 1e8)
|
python
|
def from_unit_to_satoshi(self, value, unit='satoshi'):
"""
Convert a value to satoshis. units can be any fiat currency.
By default the unit is 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
convert = get_current_price(self.crypto, unit)
return int(value / convert * 1e8)
|
[
"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",
"convert",
"=",
"get_current_price",
"(",
"self",
".",
"crypto",
",",
"unit",
")",
"return",
"int",
"(",
"value",
"/",
"convert",
"*",
"1e8",
")"
] |
Convert a value to satoshis. units can be any fiat currency.
By default the unit is satoshi.
|
[
"Convert",
"a",
"value",
"to",
"satoshis",
".",
"units",
"can",
"be",
"any",
"fiat",
"currency",
".",
"By",
"default",
"the",
"unit",
"is",
"satoshi",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/tx.py#L31-L43
|
14,161
|
priestc/moneywagon
|
moneywagon/tx.py
|
Transaction._get_utxos
|
def _get_utxos(self, address, services, **modes):
"""
Using the service fallback engine, get utxos from remote service.
"""
return get_unspent_outputs(
self.crypto, address, services=services,
**modes
)
|
python
|
def _get_utxos(self, address, services, **modes):
"""
Using the service fallback engine, get utxos from remote service.
"""
return get_unspent_outputs(
self.crypto, address, services=services,
**modes
)
|
[
"def",
"_get_utxos",
"(",
"self",
",",
"address",
",",
"services",
",",
"*",
"*",
"modes",
")",
":",
"return",
"get_unspent_outputs",
"(",
"self",
".",
"crypto",
",",
"address",
",",
"services",
"=",
"services",
",",
"*",
"*",
"modes",
")"
] |
Using the service fallback engine, get utxos from remote service.
|
[
"Using",
"the",
"service",
"fallback",
"engine",
"get",
"utxos",
"from",
"remote",
"service",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/tx.py#L58-L65
|
14,162
|
priestc/moneywagon
|
moneywagon/tx.py
|
Transaction.total_input_satoshis
|
def total_input_satoshis(self):
"""
Add up all the satoshis coming from all input tx's.
"""
just_inputs = [x['input'] for x in self.ins]
return sum([x['amount'] for x in just_inputs])
|
python
|
def total_input_satoshis(self):
"""
Add up all the satoshis coming from all input tx's.
"""
just_inputs = [x['input'] for x in self.ins]
return sum([x['amount'] for x in just_inputs])
|
[
"def",
"total_input_satoshis",
"(",
"self",
")",
":",
"just_inputs",
"=",
"[",
"x",
"[",
"'input'",
"]",
"for",
"x",
"in",
"self",
".",
"ins",
"]",
"return",
"sum",
"(",
"[",
"x",
"[",
"'amount'",
"]",
"for",
"x",
"in",
"just_inputs",
"]",
")"
] |
Add up all the satoshis coming from all input tx's.
|
[
"Add",
"up",
"all",
"the",
"satoshis",
"coming",
"from",
"all",
"input",
"tx",
"s",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/tx.py#L116-L121
|
14,163
|
priestc/moneywagon
|
moneywagon/tx.py
|
Transaction.select_inputs
|
def select_inputs(self, amount):
'''Maximize transaction priority. Select the oldest inputs,
that are sufficient to cover the spent amount. Then,
remove any unneeded inputs, starting with
the smallest in value.
Returns sum of amounts of inputs selected'''
sorted_txin = sorted(self.ins, key=lambda x:-x['input']['confirmations'])
total_amount = 0
for (idx, tx_in) in enumerate(sorted_txin):
total_amount += tx_in['input']['amount']
if (total_amount >= amount):
break
sorted_txin = sorted(sorted_txin[:idx+1], key=lambda x:x['input']['amount'])
for (idx, tx_in) in enumerate(sorted_txin):
value = tx_in['input']['amount']
if (total_amount - value < amount):
break
else:
total_amount -= value
self.ins = sorted_txin[idx:]
return total_amount
|
python
|
def select_inputs(self, amount):
'''Maximize transaction priority. Select the oldest inputs,
that are sufficient to cover the spent amount. Then,
remove any unneeded inputs, starting with
the smallest in value.
Returns sum of amounts of inputs selected'''
sorted_txin = sorted(self.ins, key=lambda x:-x['input']['confirmations'])
total_amount = 0
for (idx, tx_in) in enumerate(sorted_txin):
total_amount += tx_in['input']['amount']
if (total_amount >= amount):
break
sorted_txin = sorted(sorted_txin[:idx+1], key=lambda x:x['input']['amount'])
for (idx, tx_in) in enumerate(sorted_txin):
value = tx_in['input']['amount']
if (total_amount - value < amount):
break
else:
total_amount -= value
self.ins = sorted_txin[idx:]
return total_amount
|
[
"def",
"select_inputs",
"(",
"self",
",",
"amount",
")",
":",
"sorted_txin",
"=",
"sorted",
"(",
"self",
".",
"ins",
",",
"key",
"=",
"lambda",
"x",
":",
"-",
"x",
"[",
"'input'",
"]",
"[",
"'confirmations'",
"]",
")",
"total_amount",
"=",
"0",
"for",
"(",
"idx",
",",
"tx_in",
")",
"in",
"enumerate",
"(",
"sorted_txin",
")",
":",
"total_amount",
"+=",
"tx_in",
"[",
"'input'",
"]",
"[",
"'amount'",
"]",
"if",
"(",
"total_amount",
">=",
"amount",
")",
":",
"break",
"sorted_txin",
"=",
"sorted",
"(",
"sorted_txin",
"[",
":",
"idx",
"+",
"1",
"]",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"'input'",
"]",
"[",
"'amount'",
"]",
")",
"for",
"(",
"idx",
",",
"tx_in",
")",
"in",
"enumerate",
"(",
"sorted_txin",
")",
":",
"value",
"=",
"tx_in",
"[",
"'input'",
"]",
"[",
"'amount'",
"]",
"if",
"(",
"total_amount",
"-",
"value",
"<",
"amount",
")",
":",
"break",
"else",
":",
"total_amount",
"-=",
"value",
"self",
".",
"ins",
"=",
"sorted_txin",
"[",
"idx",
":",
"]",
"return",
"total_amount"
] |
Maximize transaction priority. Select the oldest inputs,
that are sufficient to cover the spent amount. Then,
remove any unneeded inputs, starting with
the smallest in value.
Returns sum of amounts of inputs selected
|
[
"Maximize",
"transaction",
"priority",
".",
"Select",
"the",
"oldest",
"inputs",
"that",
"are",
"sufficient",
"to",
"cover",
"the",
"spent",
"amount",
".",
"Then",
"remove",
"any",
"unneeded",
"inputs",
"starting",
"with",
"the",
"smallest",
"in",
"value",
".",
"Returns",
"sum",
"of",
"amounts",
"of",
"inputs",
"selected"
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/tx.py#L123-L143
|
14,164
|
priestc/moneywagon
|
moneywagon/tx.py
|
Transaction.onchain_exchange
|
def onchain_exchange(self, withdraw_crypto, withdraw_address, value, unit='satoshi'):
"""
This method is like `add_output` but it sends to another
"""
self.onchain_rate = get_onchain_exchange_rates(
self.crypto, withdraw_crypto, best=True, verbose=self.verbose
)
exchange_rate = float(self.onchain_rate['rate'])
result = self.onchain_rate['service'].get_onchain_exchange_address(
self.crypto, withdraw_crypto, withdraw_address
)
address = result['deposit']
value_satoshi = self.from_unit_to_satoshi(value, unit)
if self.verbose:
print("Adding output of: %s satoshi (%.8f) via onchain exchange, converting to %s %s" % (
value_satoshi, (value_satoshi / 1e8),
exchange_rate * value_satoshi / 1e8, withdraw_crypto.upper()
))
self.outs.append({
'address': address,
'value': value_satoshi
})
|
python
|
def onchain_exchange(self, withdraw_crypto, withdraw_address, value, unit='satoshi'):
"""
This method is like `add_output` but it sends to another
"""
self.onchain_rate = get_onchain_exchange_rates(
self.crypto, withdraw_crypto, best=True, verbose=self.verbose
)
exchange_rate = float(self.onchain_rate['rate'])
result = self.onchain_rate['service'].get_onchain_exchange_address(
self.crypto, withdraw_crypto, withdraw_address
)
address = result['deposit']
value_satoshi = self.from_unit_to_satoshi(value, unit)
if self.verbose:
print("Adding output of: %s satoshi (%.8f) via onchain exchange, converting to %s %s" % (
value_satoshi, (value_satoshi / 1e8),
exchange_rate * value_satoshi / 1e8, withdraw_crypto.upper()
))
self.outs.append({
'address': address,
'value': value_satoshi
})
|
[
"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",
".",
"onchain_rate",
"[",
"'rate'",
"]",
")",
"result",
"=",
"self",
".",
"onchain_rate",
"[",
"'service'",
"]",
".",
"get_onchain_exchange_address",
"(",
"self",
".",
"crypto",
",",
"withdraw_crypto",
",",
"withdraw_address",
")",
"address",
"=",
"result",
"[",
"'deposit'",
"]",
"value_satoshi",
"=",
"self",
".",
"from_unit_to_satoshi",
"(",
"value",
",",
"unit",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Adding output of: %s satoshi (%.8f) via onchain exchange, converting to %s %s\"",
"%",
"(",
"value_satoshi",
",",
"(",
"value_satoshi",
"/",
"1e8",
")",
",",
"exchange_rate",
"*",
"value_satoshi",
"/",
"1e8",
",",
"withdraw_crypto",
".",
"upper",
"(",
")",
")",
")",
"self",
".",
"outs",
".",
"append",
"(",
"{",
"'address'",
":",
"address",
",",
"'value'",
":",
"value_satoshi",
"}",
")"
] |
This method is like `add_output` but it sends to another
|
[
"This",
"method",
"is",
"like",
"add_output",
"but",
"it",
"sends",
"to",
"another"
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/tx.py#L162-L187
|
14,165
|
priestc/moneywagon
|
moneywagon/tx.py
|
Transaction.fee
|
def fee(self, value=None, unit='satoshi'):
"""
Set the miner fee, if unit is not set, assumes value is satoshi.
If using 'optimal', make sure you have already added all outputs.
"""
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)
verbose = "Using default fee of:"
elif value == 'optimal':
self.fee_satoshi = get_optimal_fee(
self.crypto, self.estimate_size(), verbose=self.verbose
)
verbose = "Using optimal fee of:"
else:
self.fee_satoshi = self.from_unit_to_satoshi(value, unit)
verbose = "Using manually set fee of:"
if self.verbose:
if not convert:
convert = get_current_price(self.crypto, "usd")
fee_dollar = convert * self.fee_satoshi / 1e8
print(verbose + " %s satoshis ($%.2f)" % (self.fee_satoshi, fee_dollar))
|
python
|
def fee(self, value=None, unit='satoshi'):
"""
Set the miner fee, if unit is not set, assumes value is satoshi.
If using 'optimal', make sure you have already added all outputs.
"""
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)
verbose = "Using default fee of:"
elif value == 'optimal':
self.fee_satoshi = get_optimal_fee(
self.crypto, self.estimate_size(), verbose=self.verbose
)
verbose = "Using optimal fee of:"
else:
self.fee_satoshi = self.from_unit_to_satoshi(value, unit)
verbose = "Using manually set fee of:"
if self.verbose:
if not convert:
convert = get_current_price(self.crypto, "usd")
fee_dollar = convert * self.fee_satoshi / 1e8
print(verbose + " %s satoshis ($%.2f)" % (self.fee_satoshi, fee_dollar))
|
[
"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",
")",
"verbose",
"=",
"\"Using default fee of:\"",
"elif",
"value",
"==",
"'optimal'",
":",
"self",
".",
"fee_satoshi",
"=",
"get_optimal_fee",
"(",
"self",
".",
"crypto",
",",
"self",
".",
"estimate_size",
"(",
")",
",",
"verbose",
"=",
"self",
".",
"verbose",
")",
"verbose",
"=",
"\"Using optimal fee of:\"",
"else",
":",
"self",
".",
"fee_satoshi",
"=",
"self",
".",
"from_unit_to_satoshi",
"(",
"value",
",",
"unit",
")",
"verbose",
"=",
"\"Using manually set fee of:\"",
"if",
"self",
".",
"verbose",
":",
"if",
"not",
"convert",
":",
"convert",
"=",
"get_current_price",
"(",
"self",
".",
"crypto",
",",
"\"usd\"",
")",
"fee_dollar",
"=",
"convert",
"*",
"self",
".",
"fee_satoshi",
"/",
"1e8",
"print",
"(",
"verbose",
"+",
"\" %s satoshis ($%.2f)\"",
"%",
"(",
"self",
".",
"fee_satoshi",
",",
"fee_dollar",
")",
")"
] |
Set the miner fee, if unit is not set, assumes value is satoshi.
If using 'optimal', make sure you have already added all outputs.
|
[
"Set",
"the",
"miner",
"fee",
"if",
"unit",
"is",
"not",
"set",
"assumes",
"value",
"is",
"satoshi",
".",
"If",
"using",
"optimal",
"make",
"sure",
"you",
"have",
"already",
"added",
"all",
"outputs",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/tx.py#L190-L215
|
14,166
|
priestc/moneywagon
|
moneywagon/tx.py
|
Transaction.get_hex
|
def get_hex(self, signed=True):
"""
Given all the data the user has given so far, make the hex using pybitcointools
"""
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 transactions)
total_outs_satoshi = sum([x['value'] for x in self.outs])
if not self.fee_satoshi:
self.fee() # use default of $0.02
change_satoshi = total_ins_satoshi - (total_outs_satoshi + self.fee_satoshi)
if change_satoshi < 0:
raise ValueError(
"Input amount (%s) must be more than all output amounts (%s) plus fees (%s). You need more %s."
% (total_ins_satoshi, total_outs_satoshi, self.fee_satoshi, self.crypto.upper())
)
ins = [x['input'] for x in self.ins]
if change_satoshi > 0:
if self.verbose:
print("Adding change address of %s satoshis to %s" % (change_satoshi, self.change_address))
change = [{'value': change_satoshi, 'address': self.change_address}]
else:
change = [] # no change ?!
if self.verbose: print("Inputs == Outputs, no change address needed.")
tx = mktx(ins, self.outs + change)
if signed:
for i, input_data in enumerate(self.ins):
if not input_data['private_key']:
raise Exception("Can't sign transaction, missing private key for input %s" % i)
tx = sign(tx, i, input_data['private_key'])
return tx
|
python
|
def get_hex(self, signed=True):
"""
Given all the data the user has given so far, make the hex using pybitcointools
"""
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 transactions)
total_outs_satoshi = sum([x['value'] for x in self.outs])
if not self.fee_satoshi:
self.fee() # use default of $0.02
change_satoshi = total_ins_satoshi - (total_outs_satoshi + self.fee_satoshi)
if change_satoshi < 0:
raise ValueError(
"Input amount (%s) must be more than all output amounts (%s) plus fees (%s). You need more %s."
% (total_ins_satoshi, total_outs_satoshi, self.fee_satoshi, self.crypto.upper())
)
ins = [x['input'] for x in self.ins]
if change_satoshi > 0:
if self.verbose:
print("Adding change address of %s satoshis to %s" % (change_satoshi, self.change_address))
change = [{'value': change_satoshi, 'address': self.change_address}]
else:
change = [] # no change ?!
if self.verbose: print("Inputs == Outputs, no change address needed.")
tx = mktx(ins, self.outs + change)
if signed:
for i, input_data in enumerate(self.ins):
if not input_data['private_key']:
raise Exception("Can't sign transaction, missing private key for input %s" % i)
tx = sign(tx, i, input_data['private_key'])
return tx
|
[
"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 transactions)",
"total_outs_satoshi",
"=",
"sum",
"(",
"[",
"x",
"[",
"'value'",
"]",
"for",
"x",
"in",
"self",
".",
"outs",
"]",
")",
"if",
"not",
"self",
".",
"fee_satoshi",
":",
"self",
".",
"fee",
"(",
")",
"# use default of $0.02",
"change_satoshi",
"=",
"total_ins_satoshi",
"-",
"(",
"total_outs_satoshi",
"+",
"self",
".",
"fee_satoshi",
")",
"if",
"change_satoshi",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Input amount (%s) must be more than all output amounts (%s) plus fees (%s). You need more %s.\"",
"%",
"(",
"total_ins_satoshi",
",",
"total_outs_satoshi",
",",
"self",
".",
"fee_satoshi",
",",
"self",
".",
"crypto",
".",
"upper",
"(",
")",
")",
")",
"ins",
"=",
"[",
"x",
"[",
"'input'",
"]",
"for",
"x",
"in",
"self",
".",
"ins",
"]",
"if",
"change_satoshi",
">",
"0",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Adding change address of %s satoshis to %s\"",
"%",
"(",
"change_satoshi",
",",
"self",
".",
"change_address",
")",
")",
"change",
"=",
"[",
"{",
"'value'",
":",
"change_satoshi",
",",
"'address'",
":",
"self",
".",
"change_address",
"}",
"]",
"else",
":",
"change",
"=",
"[",
"]",
"# no change ?!",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Inputs == Outputs, no change address needed.\"",
")",
"tx",
"=",
"mktx",
"(",
"ins",
",",
"self",
".",
"outs",
"+",
"change",
")",
"if",
"signed",
":",
"for",
"i",
",",
"input_data",
"in",
"enumerate",
"(",
"self",
".",
"ins",
")",
":",
"if",
"not",
"input_data",
"[",
"'private_key'",
"]",
":",
"raise",
"Exception",
"(",
"\"Can't sign transaction, missing private key for input %s\"",
"%",
"i",
")",
"tx",
"=",
"sign",
"(",
"tx",
",",
"i",
",",
"input_data",
"[",
"'private_key'",
"]",
")",
"return",
"tx"
] |
Given all the data the user has given so far, make the hex using pybitcointools
|
[
"Given",
"all",
"the",
"data",
"the",
"user",
"has",
"given",
"so",
"far",
"make",
"the",
"hex",
"using",
"pybitcointools"
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/tx.py#L227-L267
|
14,167
|
priestc/moneywagon
|
moneywagon/__init__.py
|
get_current_price
|
def get_current_price(crypto, fiat, services=None, convert_to=None, helper_prices=None, **modes):
"""
High level function for getting current exchange rate for a cryptocurrency.
If the fiat value is not explicitly defined, it will try the wildcard service.
if that does not work, it tries converting to an intermediate cryptocurrency
if available.
"""
fiat = fiat.lower()
args = {'crypto': crypto, 'fiat': fiat, 'convert_to': convert_to}
if not services:
services = get_optimal_services(crypto, 'current_price')
if fiat in services:
# first, try service with explicit fiat support
try_services = services[fiat]
result = _try_price_fetch(try_services, args, modes)
if not isinstance(result, Exception):
return result
if '*' in services:
# then try wildcard service
try_services = services['*']
result = _try_price_fetch(try_services, args, modes)
if not isinstance(result, Exception):
return result
def _do_composite_price_fetch(crypto, convert_crypto, fiat, helpers, modes):
before = modes.get('report_services', False)
modes['report_services'] = True
services1, converted_price = get_current_price(crypto, convert_crypto, **modes)
if not helpers or convert_crypto not in helpers[fiat]:
services2, fiat_price = get_current_price(convert_crypto, fiat, **modes)
else:
services2, fiat_price = helpers[fiat][convert_crypto]
modes['report_services'] = before
if modes.get('report_services', False):
#print("composit service:", crypto, fiat, services1, services2)
serv = CompositeService(services1, services2, convert_crypto)
return [serv], converted_price * fiat_price
else:
return converted_price * fiat_price
all_composite_cryptos = ['btc', 'ltc', 'doge', 'uno']
if crypto in all_composite_cryptos: all_composite_cryptos.remove(crypto)
for composite_attempt in all_composite_cryptos:
if composite_attempt in services and services[composite_attempt]:
result = _do_composite_price_fetch(
crypto, composite_attempt, fiat, helper_prices, modes
)
if not isinstance(result, Exception):
return result
raise result
|
python
|
def get_current_price(crypto, fiat, services=None, convert_to=None, helper_prices=None, **modes):
"""
High level function for getting current exchange rate for a cryptocurrency.
If the fiat value is not explicitly defined, it will try the wildcard service.
if that does not work, it tries converting to an intermediate cryptocurrency
if available.
"""
fiat = fiat.lower()
args = {'crypto': crypto, 'fiat': fiat, 'convert_to': convert_to}
if not services:
services = get_optimal_services(crypto, 'current_price')
if fiat in services:
# first, try service with explicit fiat support
try_services = services[fiat]
result = _try_price_fetch(try_services, args, modes)
if not isinstance(result, Exception):
return result
if '*' in services:
# then try wildcard service
try_services = services['*']
result = _try_price_fetch(try_services, args, modes)
if not isinstance(result, Exception):
return result
def _do_composite_price_fetch(crypto, convert_crypto, fiat, helpers, modes):
before = modes.get('report_services', False)
modes['report_services'] = True
services1, converted_price = get_current_price(crypto, convert_crypto, **modes)
if not helpers or convert_crypto not in helpers[fiat]:
services2, fiat_price = get_current_price(convert_crypto, fiat, **modes)
else:
services2, fiat_price = helpers[fiat][convert_crypto]
modes['report_services'] = before
if modes.get('report_services', False):
#print("composit service:", crypto, fiat, services1, services2)
serv = CompositeService(services1, services2, convert_crypto)
return [serv], converted_price * fiat_price
else:
return converted_price * fiat_price
all_composite_cryptos = ['btc', 'ltc', 'doge', 'uno']
if crypto in all_composite_cryptos: all_composite_cryptos.remove(crypto)
for composite_attempt in all_composite_cryptos:
if composite_attempt in services and services[composite_attempt]:
result = _do_composite_price_fetch(
crypto, composite_attempt, fiat, helper_prices, modes
)
if not isinstance(result, Exception):
return result
raise result
|
[
"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_price'",
")",
"if",
"fiat",
"in",
"services",
":",
"# first, try service with explicit fiat support",
"try_services",
"=",
"services",
"[",
"fiat",
"]",
"result",
"=",
"_try_price_fetch",
"(",
"try_services",
",",
"args",
",",
"modes",
")",
"if",
"not",
"isinstance",
"(",
"result",
",",
"Exception",
")",
":",
"return",
"result",
"if",
"'*'",
"in",
"services",
":",
"# then try wildcard service",
"try_services",
"=",
"services",
"[",
"'*'",
"]",
"result",
"=",
"_try_price_fetch",
"(",
"try_services",
",",
"args",
",",
"modes",
")",
"if",
"not",
"isinstance",
"(",
"result",
",",
"Exception",
")",
":",
"return",
"result",
"def",
"_do_composite_price_fetch",
"(",
"crypto",
",",
"convert_crypto",
",",
"fiat",
",",
"helpers",
",",
"modes",
")",
":",
"before",
"=",
"modes",
".",
"get",
"(",
"'report_services'",
",",
"False",
")",
"modes",
"[",
"'report_services'",
"]",
"=",
"True",
"services1",
",",
"converted_price",
"=",
"get_current_price",
"(",
"crypto",
",",
"convert_crypto",
",",
"*",
"*",
"modes",
")",
"if",
"not",
"helpers",
"or",
"convert_crypto",
"not",
"in",
"helpers",
"[",
"fiat",
"]",
":",
"services2",
",",
"fiat_price",
"=",
"get_current_price",
"(",
"convert_crypto",
",",
"fiat",
",",
"*",
"*",
"modes",
")",
"else",
":",
"services2",
",",
"fiat_price",
"=",
"helpers",
"[",
"fiat",
"]",
"[",
"convert_crypto",
"]",
"modes",
"[",
"'report_services'",
"]",
"=",
"before",
"if",
"modes",
".",
"get",
"(",
"'report_services'",
",",
"False",
")",
":",
"#print(\"composit service:\", crypto, fiat, services1, services2)",
"serv",
"=",
"CompositeService",
"(",
"services1",
",",
"services2",
",",
"convert_crypto",
")",
"return",
"[",
"serv",
"]",
",",
"converted_price",
"*",
"fiat_price",
"else",
":",
"return",
"converted_price",
"*",
"fiat_price",
"all_composite_cryptos",
"=",
"[",
"'btc'",
",",
"'ltc'",
",",
"'doge'",
",",
"'uno'",
"]",
"if",
"crypto",
"in",
"all_composite_cryptos",
":",
"all_composite_cryptos",
".",
"remove",
"(",
"crypto",
")",
"for",
"composite_attempt",
"in",
"all_composite_cryptos",
":",
"if",
"composite_attempt",
"in",
"services",
"and",
"services",
"[",
"composite_attempt",
"]",
":",
"result",
"=",
"_do_composite_price_fetch",
"(",
"crypto",
",",
"composite_attempt",
",",
"fiat",
",",
"helper_prices",
",",
"modes",
")",
"if",
"not",
"isinstance",
"(",
"result",
",",
"Exception",
")",
":",
"return",
"result",
"raise",
"result"
] |
High level function for getting current exchange rate for a cryptocurrency.
If the fiat value is not explicitly defined, it will try the wildcard service.
if that does not work, it tries converting to an intermediate cryptocurrency
if available.
|
[
"High",
"level",
"function",
"for",
"getting",
"current",
"exchange",
"rate",
"for",
"a",
"cryptocurrency",
".",
"If",
"the",
"fiat",
"value",
"is",
"not",
"explicitly",
"defined",
"it",
"will",
"try",
"the",
"wildcard",
"service",
".",
"if",
"that",
"does",
"not",
"work",
"it",
"tries",
"converting",
"to",
"an",
"intermediate",
"cryptocurrency",
"if",
"available",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L65-L120
|
14,168
|
priestc/moneywagon
|
moneywagon/__init__.py
|
get_onchain_exchange_rates
|
def get_onchain_exchange_rates(deposit_crypto=None, withdraw_crypto=None, **modes):
"""
Gets exchange rates for all defined on-chain exchange services.
"""
from moneywagon.onchain_exchange import ALL_SERVICES
rates = []
for Service in ALL_SERVICES:
srv = Service(verbose=modes.get('verbose', False))
rates.extend(srv.onchain_exchange_rates())
if deposit_crypto:
rates = [x for x in rates if x['deposit_currency']['code'] == deposit_crypto.upper()]
if withdraw_crypto:
rates = [x for x in rates if x['withdraw_currency']['code'] == withdraw_crypto.upper()]
if modes.get('best', False):
return max(rates, key=lambda x: float(x['rate']))
return rates
|
python
|
def get_onchain_exchange_rates(deposit_crypto=None, withdraw_crypto=None, **modes):
"""
Gets exchange rates for all defined on-chain exchange services.
"""
from moneywagon.onchain_exchange import ALL_SERVICES
rates = []
for Service in ALL_SERVICES:
srv = Service(verbose=modes.get('verbose', False))
rates.extend(srv.onchain_exchange_rates())
if deposit_crypto:
rates = [x for x in rates if x['deposit_currency']['code'] == deposit_crypto.upper()]
if withdraw_crypto:
rates = [x for x in rates if x['withdraw_currency']['code'] == withdraw_crypto.upper()]
if modes.get('best', False):
return max(rates, key=lambda x: float(x['rate']))
return rates
|
[
"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",
"(",
"srv",
".",
"onchain_exchange_rates",
"(",
")",
")",
"if",
"deposit_crypto",
":",
"rates",
"=",
"[",
"x",
"for",
"x",
"in",
"rates",
"if",
"x",
"[",
"'deposit_currency'",
"]",
"[",
"'code'",
"]",
"==",
"deposit_crypto",
".",
"upper",
"(",
")",
"]",
"if",
"withdraw_crypto",
":",
"rates",
"=",
"[",
"x",
"for",
"x",
"in",
"rates",
"if",
"x",
"[",
"'withdraw_currency'",
"]",
"[",
"'code'",
"]",
"==",
"withdraw_crypto",
".",
"upper",
"(",
")",
"]",
"if",
"modes",
".",
"get",
"(",
"'best'",
",",
"False",
")",
":",
"return",
"max",
"(",
"rates",
",",
"key",
"=",
"lambda",
"x",
":",
"float",
"(",
"x",
"[",
"'rate'",
"]",
")",
")",
"return",
"rates"
] |
Gets exchange rates for all defined on-chain exchange services.
|
[
"Gets",
"exchange",
"rates",
"for",
"all",
"defined",
"on",
"-",
"chain",
"exchange",
"services",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L301-L321
|
14,169
|
priestc/moneywagon
|
moneywagon/__init__.py
|
generate_keypair
|
def generate_keypair(crypto, seed, password=None):
"""
Generate a private key and publickey for any currency, given a seed.
That seed can be random, or a brainwallet phrase.
"""
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 = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
if password:
# pycrypto etc. must be installed or this will raise ImportError, hence inline import.
from .bip38 import Bip38EncryptedPrivateKey
priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password))
compressed_pub = encode_pubkey(pub, 'hex_compressed')
ret = {
'public': {
'hex_uncompressed': pub,
'hex': compressed_pub,
'address': pubtoaddr(compressed_pub, pub_byte)
},
'private': {
'wif': priv_wif
}
}
if not password:
# only these are valid when no bip38 password is supplied
ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)
return ret
|
python
|
def generate_keypair(crypto, seed, password=None):
"""
Generate a private key and publickey for any currency, given a seed.
That seed can be random, or a brainwallet phrase.
"""
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 = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
if password:
# pycrypto etc. must be installed or this will raise ImportError, hence inline import.
from .bip38 import Bip38EncryptedPrivateKey
priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password))
compressed_pub = encode_pubkey(pub, 'hex_compressed')
ret = {
'public': {
'hex_uncompressed': pub,
'hex': compressed_pub,
'address': pubtoaddr(compressed_pub, pub_byte)
},
'private': {
'wif': priv_wif
}
}
if not password:
# only these are valid when no bip38 password is supplied
ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)
return ret
|
[
"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",
"=",
"encode_privkey",
"(",
"priv",
",",
"'wif_compressed'",
",",
"vbyte",
"=",
"priv_byte",
")",
"if",
"password",
":",
"# pycrypto etc. must be installed or this will raise ImportError, hence inline import.",
"from",
".",
"bip38",
"import",
"Bip38EncryptedPrivateKey",
"priv_wif",
"=",
"str",
"(",
"Bip38EncryptedPrivateKey",
".",
"encrypt",
"(",
"crypto",
",",
"priv_wif",
",",
"password",
")",
")",
"compressed_pub",
"=",
"encode_pubkey",
"(",
"pub",
",",
"'hex_compressed'",
")",
"ret",
"=",
"{",
"'public'",
":",
"{",
"'hex_uncompressed'",
":",
"pub",
",",
"'hex'",
":",
"compressed_pub",
",",
"'address'",
":",
"pubtoaddr",
"(",
"compressed_pub",
",",
"pub_byte",
")",
"}",
",",
"'private'",
":",
"{",
"'wif'",
":",
"priv_wif",
"}",
"}",
"if",
"not",
"password",
":",
"# only these are valid when no bip38 password is supplied",
"ret",
"[",
"'private'",
"]",
"[",
"'hex'",
"]",
"=",
"encode_privkey",
"(",
"priv",
",",
"'hex_compressed'",
",",
"vbyte",
"=",
"priv_byte",
")",
"ret",
"[",
"'private'",
"]",
"[",
"'hex_uncompressed'",
"]",
"=",
"encode_privkey",
"(",
"priv",
",",
"'hex'",
",",
"vbyte",
"=",
"priv_byte",
")",
"ret",
"[",
"'private'",
"]",
"[",
"'wif_uncompressed'",
"]",
"=",
"encode_privkey",
"(",
"priv",
",",
"'wif'",
",",
"vbyte",
"=",
"priv_byte",
")",
"return",
"ret"
] |
Generate a private key and publickey for any currency, given a seed.
That seed can be random, or a brainwallet phrase.
|
[
"Generate",
"a",
"private",
"key",
"and",
"publickey",
"for",
"any",
"currency",
"given",
"a",
"seed",
".",
"That",
"seed",
"can",
"be",
"random",
"or",
"a",
"brainwallet",
"phrase",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L324-L359
|
14,170
|
priestc/moneywagon
|
moneywagon/__init__.py
|
sweep
|
def sweep(crypto, private_key, to_address, fee=None, password=None, **modes):
"""
Move all funds by private key to another address.
"""
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_address = to_address
tx.fee(fee)
return tx.push()
|
python
|
def sweep(crypto, private_key, to_address, fee=None, password=None, **modes):
"""
Move all funds by private key to another address.
"""
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_address = to_address
tx.fee(fee)
return tx.push()
|
[
"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_address",
"=",
"to_address",
"tx",
".",
"fee",
"(",
"fee",
")",
"return",
"tx",
".",
"push",
"(",
")"
] |
Move all funds by private key to another address.
|
[
"Move",
"all",
"funds",
"by",
"private",
"key",
"to",
"another",
"address",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L367-L377
|
14,171
|
priestc/moneywagon
|
moneywagon/__init__.py
|
guess_currency_from_address
|
def guess_currency_from_address(address):
"""
Given a crypto address, find which currency it likely belongs to.
Raises an exception if it can't find a match. Raises exception if address
is invalid.
"""
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)[:2])
hits = []
for currency, data in crypto_data.items():
if hasattr(data, 'get'): # skip incomplete data listings
version = data.get('address_version_byte', None)
if version is not None and version in [double_first_byte, first_byte]:
hits.append([currency, data['name']])
if hits:
return hits
raise ValueError("Unknown Currency with first byte: %s" % first_byte)
|
python
|
def guess_currency_from_address(address):
"""
Given a crypto address, find which currency it likely belongs to.
Raises an exception if it can't find a match. Raises exception if address
is invalid.
"""
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)[:2])
hits = []
for currency, data in crypto_data.items():
if hasattr(data, 'get'): # skip incomplete data listings
version = data.get('address_version_byte', None)
if version is not None and version in [double_first_byte, first_byte]:
hits.append([currency, data['name']])
if hits:
return hits
raise ValueError("Unknown Currency with first byte: %s" % first_byte)
|
[
"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",
")",
"[",
":",
"2",
"]",
")",
"hits",
"=",
"[",
"]",
"for",
"currency",
",",
"data",
"in",
"crypto_data",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"data",
",",
"'get'",
")",
":",
"# skip incomplete data listings",
"version",
"=",
"data",
".",
"get",
"(",
"'address_version_byte'",
",",
"None",
")",
"if",
"version",
"is",
"not",
"None",
"and",
"version",
"in",
"[",
"double_first_byte",
",",
"first_byte",
"]",
":",
"hits",
".",
"append",
"(",
"[",
"currency",
",",
"data",
"[",
"'name'",
"]",
"]",
")",
"if",
"hits",
":",
"return",
"hits",
"raise",
"ValueError",
"(",
"\"Unknown Currency with first byte: %s\"",
"%",
"first_byte",
")"
] |
Given a crypto address, find which currency it likely belongs to.
Raises an exception if it can't find a match. Raises exception if address
is invalid.
|
[
"Given",
"a",
"crypto",
"address",
"find",
"which",
"currency",
"it",
"likely",
"belongs",
"to",
".",
"Raises",
"an",
"exception",
"if",
"it",
"can",
"t",
"find",
"a",
"match",
".",
"Raises",
"exception",
"if",
"address",
"is",
"invalid",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L414-L438
|
14,172
|
priestc/moneywagon
|
moneywagon/__init__.py
|
service_table
|
def service_table(format='simple', authenticated=False):
"""
Returns a string depicting all services currently installed.
"""
if authenticated:
all_services = ExchangeUniverse.get_authenticated_services()
else:
all_services = ALL_SERVICES
if format == 'html':
linkify = lambda x: "<a href='{0}' target='_blank'>{0}</a>".format(x)
else:
linkify = lambda x: x
ret = []
for service in sorted(all_services, key=lambda x: x.service_id):
ret.append([
service.service_id,
service.__name__, linkify(service.api_homepage.format(
domain=service.domain, protocol=service.protocol
)),
", ".join(service.supported_cryptos or [])
])
return tabulate(ret, headers=['ID', 'Name', 'URL', 'Supported Currencies'], tablefmt=format)
|
python
|
def service_table(format='simple', authenticated=False):
"""
Returns a string depicting all services currently installed.
"""
if authenticated:
all_services = ExchangeUniverse.get_authenticated_services()
else:
all_services = ALL_SERVICES
if format == 'html':
linkify = lambda x: "<a href='{0}' target='_blank'>{0}</a>".format(x)
else:
linkify = lambda x: x
ret = []
for service in sorted(all_services, key=lambda x: x.service_id):
ret.append([
service.service_id,
service.__name__, linkify(service.api_homepage.format(
domain=service.domain, protocol=service.protocol
)),
", ".join(service.supported_cryptos or [])
])
return tabulate(ret, headers=['ID', 'Name', 'URL', 'Supported Currencies'], tablefmt=format)
|
[
"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='_blank'>{0}</a>\"",
".",
"format",
"(",
"x",
")",
"else",
":",
"linkify",
"=",
"lambda",
"x",
":",
"x",
"ret",
"=",
"[",
"]",
"for",
"service",
"in",
"sorted",
"(",
"all_services",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"service_id",
")",
":",
"ret",
".",
"append",
"(",
"[",
"service",
".",
"service_id",
",",
"service",
".",
"__name__",
",",
"linkify",
"(",
"service",
".",
"api_homepage",
".",
"format",
"(",
"domain",
"=",
"service",
".",
"domain",
",",
"protocol",
"=",
"service",
".",
"protocol",
")",
")",
",",
"\", \"",
".",
"join",
"(",
"service",
".",
"supported_cryptos",
"or",
"[",
"]",
")",
"]",
")",
"return",
"tabulate",
"(",
"ret",
",",
"headers",
"=",
"[",
"'ID'",
",",
"'Name'",
",",
"'URL'",
",",
"'Supported Currencies'",
"]",
",",
"tablefmt",
"=",
"format",
")"
] |
Returns a string depicting all services currently installed.
|
[
"Returns",
"a",
"string",
"depicting",
"all",
"services",
"currently",
"installed",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L637-L661
|
14,173
|
priestc/moneywagon
|
moneywagon/__init__.py
|
ExchangeUniverse.find_pair
|
def find_pair(self, crypto="", fiat="", verbose=False):
"""
This utility is used to find an exchange that supports a given exchange pair.
"""
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:
return pair.startswith("%s-" % crypto)
if crypto and fiat:
return pair == "%s-%s" % (crypto, fiat)
if not crypto:
return pair.endswith("-%s" % fiat)
matched_pairs = {}
for Service, pairs in self._all_pairs.items():
matched = [p for p in pairs if is_matched(crypto, fiat, p)]
if matched:
matched_pairs[Service] = matched
return matched_pairs
|
python
|
def find_pair(self, crypto="", fiat="", verbose=False):
"""
This utility is used to find an exchange that supports a given exchange pair.
"""
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:
return pair.startswith("%s-" % crypto)
if crypto and fiat:
return pair == "%s-%s" % (crypto, fiat)
if not crypto:
return pair.endswith("-%s" % fiat)
matched_pairs = {}
for Service, pairs in self._all_pairs.items():
matched = [p for p in pairs if is_matched(crypto, fiat, p)]
if matched:
matched_pairs[Service] = matched
return matched_pairs
|
[
"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",
":",
"return",
"pair",
".",
"startswith",
"(",
"\"%s-\"",
"%",
"crypto",
")",
"if",
"crypto",
"and",
"fiat",
":",
"return",
"pair",
"==",
"\"%s-%s\"",
"%",
"(",
"crypto",
",",
"fiat",
")",
"if",
"not",
"crypto",
":",
"return",
"pair",
".",
"endswith",
"(",
"\"-%s\"",
"%",
"fiat",
")",
"matched_pairs",
"=",
"{",
"}",
"for",
"Service",
",",
"pairs",
"in",
"self",
".",
"_all_pairs",
".",
"items",
"(",
")",
":",
"matched",
"=",
"[",
"p",
"for",
"p",
"in",
"pairs",
"if",
"is_matched",
"(",
"crypto",
",",
"fiat",
",",
"p",
")",
"]",
"if",
"matched",
":",
"matched_pairs",
"[",
"Service",
"]",
"=",
"matched",
"return",
"matched_pairs"
] |
This utility is used to find an exchange that supports a given exchange pair.
|
[
"This",
"utility",
"is",
"used",
"to",
"find",
"an",
"exchange",
"that",
"supports",
"a",
"given",
"exchange",
"pair",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/__init__.py#L703-L725
|
14,174
|
priestc/moneywagon
|
moneywagon/arbitrage.py
|
all_balances
|
def all_balances(currency, services=None, verbose=False, timeout=None):
"""
Get balances for passed in currency for all exchanges.
"""
balances = {}
if not services:
services = [
x(verbose=verbose, timeout=timeout)
for x in ExchangeUniverse.get_authenticated_services()
]
for e in services:
try:
balances[e] = e.get_exchange_balance(currency)
except NotImplementedError:
if verbose:
print(e.name, "balance not implemented")
except Exception as exc:
if verbose:
print(e.name, "failed:", exc.__class__.__name__, str(exc))
return balances
|
python
|
def all_balances(currency, services=None, verbose=False, timeout=None):
"""
Get balances for passed in currency for all exchanges.
"""
balances = {}
if not services:
services = [
x(verbose=verbose, timeout=timeout)
for x in ExchangeUniverse.get_authenticated_services()
]
for e in services:
try:
balances[e] = e.get_exchange_balance(currency)
except NotImplementedError:
if verbose:
print(e.name, "balance not implemented")
except Exception as exc:
if verbose:
print(e.name, "failed:", exc.__class__.__name__, str(exc))
return balances
|
[
"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",
"services",
":",
"try",
":",
"balances",
"[",
"e",
"]",
"=",
"e",
".",
"get_exchange_balance",
"(",
"currency",
")",
"except",
"NotImplementedError",
":",
"if",
"verbose",
":",
"print",
"(",
"e",
".",
"name",
",",
"\"balance not implemented\"",
")",
"except",
"Exception",
"as",
"exc",
":",
"if",
"verbose",
":",
"print",
"(",
"e",
".",
"name",
",",
"\"failed:\"",
",",
"exc",
".",
"__class__",
".",
"__name__",
",",
"str",
"(",
"exc",
")",
")",
"return",
"balances"
] |
Get balances for passed in currency for all exchanges.
|
[
"Get",
"balances",
"for",
"passed",
"in",
"currency",
"for",
"all",
"exchanges",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/arbitrage.py#L8-L29
|
14,175
|
priestc/moneywagon
|
moneywagon/arbitrage.py
|
total_exchange_balances
|
def total_exchange_balances(services=None, verbose=None, timeout=None, by_service=False):
"""
Returns all balances for all currencies for all exchanges
"""
balances = defaultdict(lambda: 0)
if not services:
services = [
x(verbose=verbose, timeout=timeout)
for x in ExchangeUniverse.get_authenticated_services()
]
for e in services:
try:
more_balances = e.get_total_exchange_balances()
if by_service:
balances[e.__class__] = more_balances
else:
for code, bal in more_balances.items():
balances[code] += bal
except NotImplementedError:
if verbose:
print(e.name, "total balance not implemented")
except Exception as exc:
if verbose:
print(e.name, "failed:", exc.__class__.__name__, str(exc))
return balances
|
python
|
def total_exchange_balances(services=None, verbose=None, timeout=None, by_service=False):
"""
Returns all balances for all currencies for all exchanges
"""
balances = defaultdict(lambda: 0)
if not services:
services = [
x(verbose=verbose, timeout=timeout)
for x in ExchangeUniverse.get_authenticated_services()
]
for e in services:
try:
more_balances = e.get_total_exchange_balances()
if by_service:
balances[e.__class__] = more_balances
else:
for code, bal in more_balances.items():
balances[code] += bal
except NotImplementedError:
if verbose:
print(e.name, "total balance not implemented")
except Exception as exc:
if verbose:
print(e.name, "failed:", exc.__class__.__name__, str(exc))
return balances
|
[
"def",
"total_exchange_balances",
"(",
"services",
"=",
"None",
",",
"verbose",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"by_service",
"=",
"False",
")",
":",
"balances",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"if",
"not",
"services",
":",
"services",
"=",
"[",
"x",
"(",
"verbose",
"=",
"verbose",
",",
"timeout",
"=",
"timeout",
")",
"for",
"x",
"in",
"ExchangeUniverse",
".",
"get_authenticated_services",
"(",
")",
"]",
"for",
"e",
"in",
"services",
":",
"try",
":",
"more_balances",
"=",
"e",
".",
"get_total_exchange_balances",
"(",
")",
"if",
"by_service",
":",
"balances",
"[",
"e",
".",
"__class__",
"]",
"=",
"more_balances",
"else",
":",
"for",
"code",
",",
"bal",
"in",
"more_balances",
".",
"items",
"(",
")",
":",
"balances",
"[",
"code",
"]",
"+=",
"bal",
"except",
"NotImplementedError",
":",
"if",
"verbose",
":",
"print",
"(",
"e",
".",
"name",
",",
"\"total balance not implemented\"",
")",
"except",
"Exception",
"as",
"exc",
":",
"if",
"verbose",
":",
"print",
"(",
"e",
".",
"name",
",",
"\"failed:\"",
",",
"exc",
".",
"__class__",
".",
"__name__",
",",
"str",
"(",
"exc",
")",
")",
"return",
"balances"
] |
Returns all balances for all currencies for all exchanges
|
[
"Returns",
"all",
"balances",
"for",
"all",
"currencies",
"for",
"all",
"exchanges"
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/arbitrage.py#L31-L57
|
14,176
|
priestc/moneywagon
|
moneywagon/bip38.py
|
compress
|
def compress(x, y):
"""
Given a x,y coordinate, encode in "compressed format"
Returned is always 33 bytes.
"""
polarity = "02" if y % 2 == 0 else "03"
wrap = lambda x: x
if not is_py2:
wrap = lambda x: bytes(x, 'ascii')
return unhexlify(wrap("%s%0.64x" % (polarity, x)))
|
python
|
def compress(x, y):
"""
Given a x,y coordinate, encode in "compressed format"
Returned is always 33 bytes.
"""
polarity = "02" if y % 2 == 0 else "03"
wrap = lambda x: x
if not is_py2:
wrap = lambda x: bytes(x, 'ascii')
return unhexlify(wrap("%s%0.64x" % (polarity, x)))
|
[
"def",
"compress",
"(",
"x",
",",
"y",
")",
":",
"polarity",
"=",
"\"02\"",
"if",
"y",
"%",
"2",
"==",
"0",
"else",
"\"03\"",
"wrap",
"=",
"lambda",
"x",
":",
"x",
"if",
"not",
"is_py2",
":",
"wrap",
"=",
"lambda",
"x",
":",
"bytes",
"(",
"x",
",",
"'ascii'",
")",
"return",
"unhexlify",
"(",
"wrap",
"(",
"\"%s%0.64x\"",
"%",
"(",
"polarity",
",",
"x",
")",
")",
")"
] |
Given a x,y coordinate, encode in "compressed format"
Returned is always 33 bytes.
|
[
"Given",
"a",
"x",
"y",
"coordinate",
"encode",
"in",
"compressed",
"format",
"Returned",
"is",
"always",
"33",
"bytes",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/bip38.py#L36-L47
|
14,177
|
priestc/moneywagon
|
moneywagon/bip38.py
|
Bip38EncryptedPrivateKey.decrypt
|
def decrypt(self, passphrase, wif=False):
"""
BIP0038 non-ec-multiply decryption. Returns hex privkey.
"""
passphrase = normalize('NFC', unicode(passphrase))
if is_py2:
passphrase = passphrase.encode('utf8')
if self.ec_multiply:
raise Exception("Not supported yet")
key = scrypt.hash(passphrase, self.addresshash, 16384, 8, 8)
derivedhalf1 = key[0:32]
derivedhalf2 = key[32:64]
aes = AES.new(derivedhalf2)
decryptedhalf2 = aes.decrypt(self.encryptedhalf2)
decryptedhalf1 = aes.decrypt(self.encryptedhalf1)
priv = decryptedhalf1 + decryptedhalf2
priv = unhexlify('%064x' % (long(hexlify(priv), 16) ^ long(hexlify(derivedhalf1), 16)))
pub = privtopub(priv)
if self.compressed:
pub = encode_pubkey(pub, 'hex_compressed')
addr = pubtoaddr(pub, self.pub_byte)
if is_py2:
ascii_key = addr
else:
ascii_key = bytes(addr,'ascii')
if sha256(sha256(ascii_key).digest()).digest()[0:4] != self.addresshash:
raise Exception('Bip38 password decrypt failed: Wrong password?')
else:
formatt = 'wif' if wif else 'hex'
if self.compressed:
return encode_privkey(priv, formatt + '_compressed', self.priv_byte)
else:
return encode_privkey(priv, formatt, self.priv_byte)
|
python
|
def decrypt(self, passphrase, wif=False):
"""
BIP0038 non-ec-multiply decryption. Returns hex privkey.
"""
passphrase = normalize('NFC', unicode(passphrase))
if is_py2:
passphrase = passphrase.encode('utf8')
if self.ec_multiply:
raise Exception("Not supported yet")
key = scrypt.hash(passphrase, self.addresshash, 16384, 8, 8)
derivedhalf1 = key[0:32]
derivedhalf2 = key[32:64]
aes = AES.new(derivedhalf2)
decryptedhalf2 = aes.decrypt(self.encryptedhalf2)
decryptedhalf1 = aes.decrypt(self.encryptedhalf1)
priv = decryptedhalf1 + decryptedhalf2
priv = unhexlify('%064x' % (long(hexlify(priv), 16) ^ long(hexlify(derivedhalf1), 16)))
pub = privtopub(priv)
if self.compressed:
pub = encode_pubkey(pub, 'hex_compressed')
addr = pubtoaddr(pub, self.pub_byte)
if is_py2:
ascii_key = addr
else:
ascii_key = bytes(addr,'ascii')
if sha256(sha256(ascii_key).digest()).digest()[0:4] != self.addresshash:
raise Exception('Bip38 password decrypt failed: Wrong password?')
else:
formatt = 'wif' if wif else 'hex'
if self.compressed:
return encode_privkey(priv, formatt + '_compressed', self.priv_byte)
else:
return encode_privkey(priv, formatt, self.priv_byte)
|
[
"def",
"decrypt",
"(",
"self",
",",
"passphrase",
",",
"wif",
"=",
"False",
")",
":",
"passphrase",
"=",
"normalize",
"(",
"'NFC'",
",",
"unicode",
"(",
"passphrase",
")",
")",
"if",
"is_py2",
":",
"passphrase",
"=",
"passphrase",
".",
"encode",
"(",
"'utf8'",
")",
"if",
"self",
".",
"ec_multiply",
":",
"raise",
"Exception",
"(",
"\"Not supported yet\"",
")",
"key",
"=",
"scrypt",
".",
"hash",
"(",
"passphrase",
",",
"self",
".",
"addresshash",
",",
"16384",
",",
"8",
",",
"8",
")",
"derivedhalf1",
"=",
"key",
"[",
"0",
":",
"32",
"]",
"derivedhalf2",
"=",
"key",
"[",
"32",
":",
"64",
"]",
"aes",
"=",
"AES",
".",
"new",
"(",
"derivedhalf2",
")",
"decryptedhalf2",
"=",
"aes",
".",
"decrypt",
"(",
"self",
".",
"encryptedhalf2",
")",
"decryptedhalf1",
"=",
"aes",
".",
"decrypt",
"(",
"self",
".",
"encryptedhalf1",
")",
"priv",
"=",
"decryptedhalf1",
"+",
"decryptedhalf2",
"priv",
"=",
"unhexlify",
"(",
"'%064x'",
"%",
"(",
"long",
"(",
"hexlify",
"(",
"priv",
")",
",",
"16",
")",
"^",
"long",
"(",
"hexlify",
"(",
"derivedhalf1",
")",
",",
"16",
")",
")",
")",
"pub",
"=",
"privtopub",
"(",
"priv",
")",
"if",
"self",
".",
"compressed",
":",
"pub",
"=",
"encode_pubkey",
"(",
"pub",
",",
"'hex_compressed'",
")",
"addr",
"=",
"pubtoaddr",
"(",
"pub",
",",
"self",
".",
"pub_byte",
")",
"if",
"is_py2",
":",
"ascii_key",
"=",
"addr",
"else",
":",
"ascii_key",
"=",
"bytes",
"(",
"addr",
",",
"'ascii'",
")",
"if",
"sha256",
"(",
"sha256",
"(",
"ascii_key",
")",
".",
"digest",
"(",
")",
")",
".",
"digest",
"(",
")",
"[",
"0",
":",
"4",
"]",
"!=",
"self",
".",
"addresshash",
":",
"raise",
"Exception",
"(",
"'Bip38 password decrypt failed: Wrong password?'",
")",
"else",
":",
"formatt",
"=",
"'wif'",
"if",
"wif",
"else",
"'hex'",
"if",
"self",
".",
"compressed",
":",
"return",
"encode_privkey",
"(",
"priv",
",",
"formatt",
"+",
"'_compressed'",
",",
"self",
".",
"priv_byte",
")",
"else",
":",
"return",
"encode_privkey",
"(",
"priv",
",",
"formatt",
",",
"self",
".",
"priv_byte",
")"
] |
BIP0038 non-ec-multiply decryption. Returns hex privkey.
|
[
"BIP0038",
"non",
"-",
"ec",
"-",
"multiply",
"decryption",
".",
"Returns",
"hex",
"privkey",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/bip38.py#L115-L153
|
14,178
|
priestc/moneywagon
|
moneywagon/bip38.py
|
Bip38EncryptedPrivateKey.encrypt
|
def encrypt(cls, crypto, privkey, passphrase):
"""
BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.
"""
pub_byte, priv_byte = get_magic_bytes(crypto)
privformat = get_privkey_format(privkey)
if privformat in ['wif_compressed','hex_compressed']:
compressed = True
flagbyte = b'\xe0'
if privformat == 'wif_compressed':
privkey = encode_privkey(privkey, 'hex_compressed')
privformat = get_privkey_format(privkey)
if privformat in ['wif', 'hex']:
compressed = False
flagbyte = b'\xc0'
if privformat == 'wif':
privkey = encode_privkey(privkey,'hex')
privformat = get_privkey_format(privkey)
pubkey = privtopub(privkey)
addr = pubtoaddr(pubkey, pub_byte)
passphrase = normalize('NFC', unicode(passphrase))
if is_py2:
ascii_key = addr
passphrase = passphrase.encode('utf8')
else:
ascii_key = bytes(addr,'ascii')
salt = sha256(sha256(ascii_key).digest()).digest()[0:4]
key = scrypt.hash(passphrase, salt, 16384, 8, 8)
derivedhalf1, derivedhalf2 = key[:32], key[32:]
aes = AES.new(derivedhalf2)
encryptedhalf1 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[0:32], 16) ^ long(hexlify(derivedhalf1[0:16]), 16))))
encryptedhalf2 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[32:64], 16) ^ long(hexlify(derivedhalf1[16:32]), 16))))
# 39 bytes 2 (6P) 1(R/Y) 4 16 16
payload = b'\x01\x42' + flagbyte + salt + encryptedhalf1 + encryptedhalf2
return cls(crypto, b58encode_check(payload))
|
python
|
def encrypt(cls, crypto, privkey, passphrase):
"""
BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.
"""
pub_byte, priv_byte = get_magic_bytes(crypto)
privformat = get_privkey_format(privkey)
if privformat in ['wif_compressed','hex_compressed']:
compressed = True
flagbyte = b'\xe0'
if privformat == 'wif_compressed':
privkey = encode_privkey(privkey, 'hex_compressed')
privformat = get_privkey_format(privkey)
if privformat in ['wif', 'hex']:
compressed = False
flagbyte = b'\xc0'
if privformat == 'wif':
privkey = encode_privkey(privkey,'hex')
privformat = get_privkey_format(privkey)
pubkey = privtopub(privkey)
addr = pubtoaddr(pubkey, pub_byte)
passphrase = normalize('NFC', unicode(passphrase))
if is_py2:
ascii_key = addr
passphrase = passphrase.encode('utf8')
else:
ascii_key = bytes(addr,'ascii')
salt = sha256(sha256(ascii_key).digest()).digest()[0:4]
key = scrypt.hash(passphrase, salt, 16384, 8, 8)
derivedhalf1, derivedhalf2 = key[:32], key[32:]
aes = AES.new(derivedhalf2)
encryptedhalf1 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[0:32], 16) ^ long(hexlify(derivedhalf1[0:16]), 16))))
encryptedhalf2 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[32:64], 16) ^ long(hexlify(derivedhalf1[16:32]), 16))))
# 39 bytes 2 (6P) 1(R/Y) 4 16 16
payload = b'\x01\x42' + flagbyte + salt + encryptedhalf1 + encryptedhalf2
return cls(crypto, b58encode_check(payload))
|
[
"def",
"encrypt",
"(",
"cls",
",",
"crypto",
",",
"privkey",
",",
"passphrase",
")",
":",
"pub_byte",
",",
"priv_byte",
"=",
"get_magic_bytes",
"(",
"crypto",
")",
"privformat",
"=",
"get_privkey_format",
"(",
"privkey",
")",
"if",
"privformat",
"in",
"[",
"'wif_compressed'",
",",
"'hex_compressed'",
"]",
":",
"compressed",
"=",
"True",
"flagbyte",
"=",
"b'\\xe0'",
"if",
"privformat",
"==",
"'wif_compressed'",
":",
"privkey",
"=",
"encode_privkey",
"(",
"privkey",
",",
"'hex_compressed'",
")",
"privformat",
"=",
"get_privkey_format",
"(",
"privkey",
")",
"if",
"privformat",
"in",
"[",
"'wif'",
",",
"'hex'",
"]",
":",
"compressed",
"=",
"False",
"flagbyte",
"=",
"b'\\xc0'",
"if",
"privformat",
"==",
"'wif'",
":",
"privkey",
"=",
"encode_privkey",
"(",
"privkey",
",",
"'hex'",
")",
"privformat",
"=",
"get_privkey_format",
"(",
"privkey",
")",
"pubkey",
"=",
"privtopub",
"(",
"privkey",
")",
"addr",
"=",
"pubtoaddr",
"(",
"pubkey",
",",
"pub_byte",
")",
"passphrase",
"=",
"normalize",
"(",
"'NFC'",
",",
"unicode",
"(",
"passphrase",
")",
")",
"if",
"is_py2",
":",
"ascii_key",
"=",
"addr",
"passphrase",
"=",
"passphrase",
".",
"encode",
"(",
"'utf8'",
")",
"else",
":",
"ascii_key",
"=",
"bytes",
"(",
"addr",
",",
"'ascii'",
")",
"salt",
"=",
"sha256",
"(",
"sha256",
"(",
"ascii_key",
")",
".",
"digest",
"(",
")",
")",
".",
"digest",
"(",
")",
"[",
"0",
":",
"4",
"]",
"key",
"=",
"scrypt",
".",
"hash",
"(",
"passphrase",
",",
"salt",
",",
"16384",
",",
"8",
",",
"8",
")",
"derivedhalf1",
",",
"derivedhalf2",
"=",
"key",
"[",
":",
"32",
"]",
",",
"key",
"[",
"32",
":",
"]",
"aes",
"=",
"AES",
".",
"new",
"(",
"derivedhalf2",
")",
"encryptedhalf1",
"=",
"aes",
".",
"encrypt",
"(",
"unhexlify",
"(",
"'%0.32x'",
"%",
"(",
"long",
"(",
"privkey",
"[",
"0",
":",
"32",
"]",
",",
"16",
")",
"^",
"long",
"(",
"hexlify",
"(",
"derivedhalf1",
"[",
"0",
":",
"16",
"]",
")",
",",
"16",
")",
")",
")",
")",
"encryptedhalf2",
"=",
"aes",
".",
"encrypt",
"(",
"unhexlify",
"(",
"'%0.32x'",
"%",
"(",
"long",
"(",
"privkey",
"[",
"32",
":",
"64",
"]",
",",
"16",
")",
"^",
"long",
"(",
"hexlify",
"(",
"derivedhalf1",
"[",
"16",
":",
"32",
"]",
")",
",",
"16",
")",
")",
")",
")",
"# 39 bytes 2 (6P) 1(R/Y) 4 16 16",
"payload",
"=",
"b'\\x01\\x42'",
"+",
"flagbyte",
"+",
"salt",
"+",
"encryptedhalf1",
"+",
"encryptedhalf2",
"return",
"cls",
"(",
"crypto",
",",
"b58encode_check",
"(",
"payload",
")",
")"
] |
BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.
|
[
"BIP0038",
"non",
"-",
"ec",
"-",
"multiply",
"encryption",
".",
"Returns",
"BIP0038",
"encrypted",
"privkey",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/bip38.py#L156-L195
|
14,179
|
priestc/moneywagon
|
moneywagon/bip38.py
|
Bip38EncryptedPrivateKey.create_from_intermediate
|
def create_from_intermediate(cls, crypto, intermediate_point, seed, compressed=True, include_cfrm=True):
"""
Given an intermediate point, given to us by "owner", generate an address
and encrypted private key that can be decoded by the passphrase used to generate
the intermediate point.
"""
flagbyte = b'\x20' if compressed else b'\x00'
payload = b58decode_check(str(intermediate_point))
ownerentropy = payload[8:16]
passpoint = payload[16:-4]
x, y = uncompress(passpoint)
if not is_py2:
seed = bytes(seed, 'ascii')
seedb = hexlify(sha256(seed).digest())[:24]
factorb = int(hexlify(sha256(sha256(seedb).digest()).digest()), 16)
generatedaddress = pubtoaddr(fast_multiply((x, y), factorb))
wrap = lambda x: x
if not is_py2:
wrap = lambda x: bytes(x, 'ascii')
addresshash = sha256(sha256(wrap(generatedaddress)).digest()).digest()[:4]
encrypted_seedb = scrypt.hash(passpoint, addresshash + ownerentropy, 1024, 1, 1, 64)
derivedhalf1, derivedhalf2 = encrypted_seedb[:32], encrypted_seedb[32:]
aes = AES.new(derivedhalf2)
block1 = long(seedb[0:16], 16) ^ long(hexlify(derivedhalf1[0:16]), 16)
encryptedpart1 = aes.encrypt(unhexlify('%0.32x' % block1))
block2 = long(hexlify(encryptedpart1[8:16]) + seedb[16:24], 16) ^ long(hexlify(derivedhalf1[16:32]), 16)
encryptedpart2 = aes.encrypt(unhexlify('%0.32x' % block2))
# 39 bytes 2 1 4 8 8 16
payload = b"\x01\x43" + flagbyte + addresshash + ownerentropy + encryptedpart1[:8] + encryptedpart2
encrypted_pk = b58encode_check(payload)
if not include_cfrm:
return generatedaddress, encrypted_pk
confirmation_code = Bip38ConfirmationCode.create(flagbyte, ownerentropy, factorb, derivedhalf1, derivedhalf2, addresshash)
return generatedaddress, cls(crypto, encrypted_pk), confirmation_code
|
python
|
def create_from_intermediate(cls, crypto, intermediate_point, seed, compressed=True, include_cfrm=True):
"""
Given an intermediate point, given to us by "owner", generate an address
and encrypted private key that can be decoded by the passphrase used to generate
the intermediate point.
"""
flagbyte = b'\x20' if compressed else b'\x00'
payload = b58decode_check(str(intermediate_point))
ownerentropy = payload[8:16]
passpoint = payload[16:-4]
x, y = uncompress(passpoint)
if not is_py2:
seed = bytes(seed, 'ascii')
seedb = hexlify(sha256(seed).digest())[:24]
factorb = int(hexlify(sha256(sha256(seedb).digest()).digest()), 16)
generatedaddress = pubtoaddr(fast_multiply((x, y), factorb))
wrap = lambda x: x
if not is_py2:
wrap = lambda x: bytes(x, 'ascii')
addresshash = sha256(sha256(wrap(generatedaddress)).digest()).digest()[:4]
encrypted_seedb = scrypt.hash(passpoint, addresshash + ownerentropy, 1024, 1, 1, 64)
derivedhalf1, derivedhalf2 = encrypted_seedb[:32], encrypted_seedb[32:]
aes = AES.new(derivedhalf2)
block1 = long(seedb[0:16], 16) ^ long(hexlify(derivedhalf1[0:16]), 16)
encryptedpart1 = aes.encrypt(unhexlify('%0.32x' % block1))
block2 = long(hexlify(encryptedpart1[8:16]) + seedb[16:24], 16) ^ long(hexlify(derivedhalf1[16:32]), 16)
encryptedpart2 = aes.encrypt(unhexlify('%0.32x' % block2))
# 39 bytes 2 1 4 8 8 16
payload = b"\x01\x43" + flagbyte + addresshash + ownerentropy + encryptedpart1[:8] + encryptedpart2
encrypted_pk = b58encode_check(payload)
if not include_cfrm:
return generatedaddress, encrypted_pk
confirmation_code = Bip38ConfirmationCode.create(flagbyte, ownerentropy, factorb, derivedhalf1, derivedhalf2, addresshash)
return generatedaddress, cls(crypto, encrypted_pk), confirmation_code
|
[
"def",
"create_from_intermediate",
"(",
"cls",
",",
"crypto",
",",
"intermediate_point",
",",
"seed",
",",
"compressed",
"=",
"True",
",",
"include_cfrm",
"=",
"True",
")",
":",
"flagbyte",
"=",
"b'\\x20'",
"if",
"compressed",
"else",
"b'\\x00'",
"payload",
"=",
"b58decode_check",
"(",
"str",
"(",
"intermediate_point",
")",
")",
"ownerentropy",
"=",
"payload",
"[",
"8",
":",
"16",
"]",
"passpoint",
"=",
"payload",
"[",
"16",
":",
"-",
"4",
"]",
"x",
",",
"y",
"=",
"uncompress",
"(",
"passpoint",
")",
"if",
"not",
"is_py2",
":",
"seed",
"=",
"bytes",
"(",
"seed",
",",
"'ascii'",
")",
"seedb",
"=",
"hexlify",
"(",
"sha256",
"(",
"seed",
")",
".",
"digest",
"(",
")",
")",
"[",
":",
"24",
"]",
"factorb",
"=",
"int",
"(",
"hexlify",
"(",
"sha256",
"(",
"sha256",
"(",
"seedb",
")",
".",
"digest",
"(",
")",
")",
".",
"digest",
"(",
")",
")",
",",
"16",
")",
"generatedaddress",
"=",
"pubtoaddr",
"(",
"fast_multiply",
"(",
"(",
"x",
",",
"y",
")",
",",
"factorb",
")",
")",
"wrap",
"=",
"lambda",
"x",
":",
"x",
"if",
"not",
"is_py2",
":",
"wrap",
"=",
"lambda",
"x",
":",
"bytes",
"(",
"x",
",",
"'ascii'",
")",
"addresshash",
"=",
"sha256",
"(",
"sha256",
"(",
"wrap",
"(",
"generatedaddress",
")",
")",
".",
"digest",
"(",
")",
")",
".",
"digest",
"(",
")",
"[",
":",
"4",
"]",
"encrypted_seedb",
"=",
"scrypt",
".",
"hash",
"(",
"passpoint",
",",
"addresshash",
"+",
"ownerentropy",
",",
"1024",
",",
"1",
",",
"1",
",",
"64",
")",
"derivedhalf1",
",",
"derivedhalf2",
"=",
"encrypted_seedb",
"[",
":",
"32",
"]",
",",
"encrypted_seedb",
"[",
"32",
":",
"]",
"aes",
"=",
"AES",
".",
"new",
"(",
"derivedhalf2",
")",
"block1",
"=",
"long",
"(",
"seedb",
"[",
"0",
":",
"16",
"]",
",",
"16",
")",
"^",
"long",
"(",
"hexlify",
"(",
"derivedhalf1",
"[",
"0",
":",
"16",
"]",
")",
",",
"16",
")",
"encryptedpart1",
"=",
"aes",
".",
"encrypt",
"(",
"unhexlify",
"(",
"'%0.32x'",
"%",
"block1",
")",
")",
"block2",
"=",
"long",
"(",
"hexlify",
"(",
"encryptedpart1",
"[",
"8",
":",
"16",
"]",
")",
"+",
"seedb",
"[",
"16",
":",
"24",
"]",
",",
"16",
")",
"^",
"long",
"(",
"hexlify",
"(",
"derivedhalf1",
"[",
"16",
":",
"32",
"]",
")",
",",
"16",
")",
"encryptedpart2",
"=",
"aes",
".",
"encrypt",
"(",
"unhexlify",
"(",
"'%0.32x'",
"%",
"block2",
")",
")",
"# 39 bytes 2 1 4 8 8 16",
"payload",
"=",
"b\"\\x01\\x43\"",
"+",
"flagbyte",
"+",
"addresshash",
"+",
"ownerentropy",
"+",
"encryptedpart1",
"[",
":",
"8",
"]",
"+",
"encryptedpart2",
"encrypted_pk",
"=",
"b58encode_check",
"(",
"payload",
")",
"if",
"not",
"include_cfrm",
":",
"return",
"generatedaddress",
",",
"encrypted_pk",
"confirmation_code",
"=",
"Bip38ConfirmationCode",
".",
"create",
"(",
"flagbyte",
",",
"ownerentropy",
",",
"factorb",
",",
"derivedhalf1",
",",
"derivedhalf2",
",",
"addresshash",
")",
"return",
"generatedaddress",
",",
"cls",
"(",
"crypto",
",",
"encrypted_pk",
")",
",",
"confirmation_code"
] |
Given an intermediate point, given to us by "owner", generate an address
and encrypted private key that can be decoded by the passphrase used to generate
the intermediate point.
|
[
"Given",
"an",
"intermediate",
"point",
"given",
"to",
"us",
"by",
"owner",
"generate",
"an",
"address",
"and",
"encrypted",
"private",
"key",
"that",
"can",
"be",
"decoded",
"by",
"the",
"passphrase",
"used",
"to",
"generate",
"the",
"intermediate",
"point",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/bip38.py#L198-L242
|
14,180
|
priestc/moneywagon
|
moneywagon/bip38.py
|
Bip38ConfirmationCode.generate_address
|
def generate_address(self, passphrase):
"""
Make sure the confirm code is valid for the given password and address.
"""
inter = Bip38IntermediatePoint.create(passphrase, ownersalt=self.ownersalt)
public_key = privtopub(inter.passpoint)
# from Bip38EncryptedPrivateKey.create_from_intermediate
derived = scrypt.hash(inter.passpoint, self.addresshash + inter.ownerentropy, 1024, 1, 1, 64)
derivedhalf1, derivedhalf2 = derived[:32], derived[32:]
unencrypted_prefix = bytes_to_int(self.pointbprefix) ^ (bytes_to_int(derived[63]) & 0x01);
aes = AES.new(derivedhalf2)
block1 = aes.decrypt(self.pointbx1)
block2 = aes.decrypt(self.pointbx2)
raise Exception("Not done yet")
return
block2 = long(hexlify(pointb2), 16) ^ long(hexlify(derivedhalf1[16:]), 16)
return pubtoaddr(*fast_multiply(pointb, passfactor))
|
python
|
def generate_address(self, passphrase):
"""
Make sure the confirm code is valid for the given password and address.
"""
inter = Bip38IntermediatePoint.create(passphrase, ownersalt=self.ownersalt)
public_key = privtopub(inter.passpoint)
# from Bip38EncryptedPrivateKey.create_from_intermediate
derived = scrypt.hash(inter.passpoint, self.addresshash + inter.ownerentropy, 1024, 1, 1, 64)
derivedhalf1, derivedhalf2 = derived[:32], derived[32:]
unencrypted_prefix = bytes_to_int(self.pointbprefix) ^ (bytes_to_int(derived[63]) & 0x01);
aes = AES.new(derivedhalf2)
block1 = aes.decrypt(self.pointbx1)
block2 = aes.decrypt(self.pointbx2)
raise Exception("Not done yet")
return
block2 = long(hexlify(pointb2), 16) ^ long(hexlify(derivedhalf1[16:]), 16)
return pubtoaddr(*fast_multiply(pointb, passfactor))
|
[
"def",
"generate_address",
"(",
"self",
",",
"passphrase",
")",
":",
"inter",
"=",
"Bip38IntermediatePoint",
".",
"create",
"(",
"passphrase",
",",
"ownersalt",
"=",
"self",
".",
"ownersalt",
")",
"public_key",
"=",
"privtopub",
"(",
"inter",
".",
"passpoint",
")",
"# from Bip38EncryptedPrivateKey.create_from_intermediate",
"derived",
"=",
"scrypt",
".",
"hash",
"(",
"inter",
".",
"passpoint",
",",
"self",
".",
"addresshash",
"+",
"inter",
".",
"ownerentropy",
",",
"1024",
",",
"1",
",",
"1",
",",
"64",
")",
"derivedhalf1",
",",
"derivedhalf2",
"=",
"derived",
"[",
":",
"32",
"]",
",",
"derived",
"[",
"32",
":",
"]",
"unencrypted_prefix",
"=",
"bytes_to_int",
"(",
"self",
".",
"pointbprefix",
")",
"^",
"(",
"bytes_to_int",
"(",
"derived",
"[",
"63",
"]",
")",
"&",
"0x01",
")",
"aes",
"=",
"AES",
".",
"new",
"(",
"derivedhalf2",
")",
"block1",
"=",
"aes",
".",
"decrypt",
"(",
"self",
".",
"pointbx1",
")",
"block2",
"=",
"aes",
".",
"decrypt",
"(",
"self",
".",
"pointbx2",
")",
"raise",
"Exception",
"(",
"\"Not done yet\"",
")",
"return",
"block2",
"=",
"long",
"(",
"hexlify",
"(",
"pointb2",
")",
",",
"16",
")",
"^",
"long",
"(",
"hexlify",
"(",
"derivedhalf1",
"[",
"16",
":",
"]",
")",
",",
"16",
")",
"return",
"pubtoaddr",
"(",
"*",
"fast_multiply",
"(",
"pointb",
",",
"passfactor",
")",
")"
] |
Make sure the confirm code is valid for the given password and address.
|
[
"Make",
"sure",
"the",
"confirm",
"code",
"is",
"valid",
"for",
"the",
"given",
"password",
"and",
"address",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/bip38.py#L372-L397
|
14,181
|
priestc/moneywagon
|
moneywagon/services/blockchain_services.py
|
SmartBitAU.push_tx
|
def push_tx(self, crypto, tx_hex):
"""
This method is untested.
"""
url = "%s/pushtx" % self.base_url
return self.post_url(url, {'hex': tx_hex}).content
|
python
|
def push_tx(self, crypto, tx_hex):
"""
This method is untested.
"""
url = "%s/pushtx" % self.base_url
return self.post_url(url, {'hex': tx_hex}).content
|
[
"def",
"push_tx",
"(",
"self",
",",
"crypto",
",",
"tx_hex",
")",
":",
"url",
"=",
"\"%s/pushtx\"",
"%",
"self",
".",
"base_url",
"return",
"self",
".",
"post_url",
"(",
"url",
",",
"{",
"'hex'",
":",
"tx_hex",
"}",
")",
".",
"content"
] |
This method is untested.
|
[
"This",
"method",
"is",
"untested",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/services/blockchain_services.py#L339-L344
|
14,182
|
priestc/moneywagon
|
moneywagon/network_replay.py
|
NetworkReplay.replay_block
|
def replay_block(self, block_to_replay, limit=5):
"""
Replay all transactions in parent currency to passed in "source" currency.
Block_to_replay can either be an integer or a block object.
"""
if block_to_replay == 'latest':
if self.verbose:
print("Getting latest %s block header" % source.upper())
block = get_block(self.source, latest=True, verbose=self.verbose)
if self.verbose:
print("Latest %s block is #%s" % (self.source.upper(), block['block_number']))
else:
blocknum = block_to_replay if type(block_to_replay) == int else block_to_replay['block_number']
if blocknum < self.parent_fork_block or blocknum < self.child_fork_block:
raise Exception("Can't replay blocks mined before the fork")
if type(block_to_replay) is not dict:
if self.verbose:
print("Getting %s block header #%s" % (self.source.upper(), block_to_replay))
block = get_block(self.source, block_number=int(block_to_replay), verbose=self.verbose)
else:
block = block_to_replay
if self.verbose:
print("Using %s for pushing to %s" % (self.pusher.name, self.destination.upper()))
print("Using %s for getting %s transactions" % (self.tx_fetcher.name, self.source.upper()))
print("Finished getting block header,", len(block['txids']), "transactions in block, will replay", (limit or "all of them"))
results = []
enforced_limit = (limit or len(block['txids']))
for i, txid in enumerate(block['txids'][:enforced_limit]):
print("outside", txid)
self._replay_tx(txid, i)
|
python
|
def replay_block(self, block_to_replay, limit=5):
"""
Replay all transactions in parent currency to passed in "source" currency.
Block_to_replay can either be an integer or a block object.
"""
if block_to_replay == 'latest':
if self.verbose:
print("Getting latest %s block header" % source.upper())
block = get_block(self.source, latest=True, verbose=self.verbose)
if self.verbose:
print("Latest %s block is #%s" % (self.source.upper(), block['block_number']))
else:
blocknum = block_to_replay if type(block_to_replay) == int else block_to_replay['block_number']
if blocknum < self.parent_fork_block or blocknum < self.child_fork_block:
raise Exception("Can't replay blocks mined before the fork")
if type(block_to_replay) is not dict:
if self.verbose:
print("Getting %s block header #%s" % (self.source.upper(), block_to_replay))
block = get_block(self.source, block_number=int(block_to_replay), verbose=self.verbose)
else:
block = block_to_replay
if self.verbose:
print("Using %s for pushing to %s" % (self.pusher.name, self.destination.upper()))
print("Using %s for getting %s transactions" % (self.tx_fetcher.name, self.source.upper()))
print("Finished getting block header,", len(block['txids']), "transactions in block, will replay", (limit or "all of them"))
results = []
enforced_limit = (limit or len(block['txids']))
for i, txid in enumerate(block['txids'][:enforced_limit]):
print("outside", txid)
self._replay_tx(txid, i)
|
[
"def",
"replay_block",
"(",
"self",
",",
"block_to_replay",
",",
"limit",
"=",
"5",
")",
":",
"if",
"block_to_replay",
"==",
"'latest'",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Getting latest %s block header\"",
"%",
"source",
".",
"upper",
"(",
")",
")",
"block",
"=",
"get_block",
"(",
"self",
".",
"source",
",",
"latest",
"=",
"True",
",",
"verbose",
"=",
"self",
".",
"verbose",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Latest %s block is #%s\"",
"%",
"(",
"self",
".",
"source",
".",
"upper",
"(",
")",
",",
"block",
"[",
"'block_number'",
"]",
")",
")",
"else",
":",
"blocknum",
"=",
"block_to_replay",
"if",
"type",
"(",
"block_to_replay",
")",
"==",
"int",
"else",
"block_to_replay",
"[",
"'block_number'",
"]",
"if",
"blocknum",
"<",
"self",
".",
"parent_fork_block",
"or",
"blocknum",
"<",
"self",
".",
"child_fork_block",
":",
"raise",
"Exception",
"(",
"\"Can't replay blocks mined before the fork\"",
")",
"if",
"type",
"(",
"block_to_replay",
")",
"is",
"not",
"dict",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Getting %s block header #%s\"",
"%",
"(",
"self",
".",
"source",
".",
"upper",
"(",
")",
",",
"block_to_replay",
")",
")",
"block",
"=",
"get_block",
"(",
"self",
".",
"source",
",",
"block_number",
"=",
"int",
"(",
"block_to_replay",
")",
",",
"verbose",
"=",
"self",
".",
"verbose",
")",
"else",
":",
"block",
"=",
"block_to_replay",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Using %s for pushing to %s\"",
"%",
"(",
"self",
".",
"pusher",
".",
"name",
",",
"self",
".",
"destination",
".",
"upper",
"(",
")",
")",
")",
"print",
"(",
"\"Using %s for getting %s transactions\"",
"%",
"(",
"self",
".",
"tx_fetcher",
".",
"name",
",",
"self",
".",
"source",
".",
"upper",
"(",
")",
")",
")",
"print",
"(",
"\"Finished getting block header,\"",
",",
"len",
"(",
"block",
"[",
"'txids'",
"]",
")",
",",
"\"transactions in block, will replay\"",
",",
"(",
"limit",
"or",
"\"all of them\"",
")",
")",
"results",
"=",
"[",
"]",
"enforced_limit",
"=",
"(",
"limit",
"or",
"len",
"(",
"block",
"[",
"'txids'",
"]",
")",
")",
"for",
"i",
",",
"txid",
"in",
"enumerate",
"(",
"block",
"[",
"'txids'",
"]",
"[",
":",
"enforced_limit",
"]",
")",
":",
"print",
"(",
"\"outside\"",
",",
"txid",
")",
"self",
".",
"_replay_tx",
"(",
"txid",
",",
"i",
")"
] |
Replay all transactions in parent currency to passed in "source" currency.
Block_to_replay can either be an integer or a block object.
|
[
"Replay",
"all",
"transactions",
"in",
"parent",
"currency",
"to",
"passed",
"in",
"source",
"currency",
".",
"Block_to_replay",
"can",
"either",
"be",
"an",
"integer",
"or",
"a",
"block",
"object",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/network_replay.py#L39-L73
|
14,183
|
priestc/moneywagon
|
moneywagon/supply_estimator.py
|
get_block_adjustments
|
def get_block_adjustments(crypto, points=None, intervals=None, **modes):
"""
This utility is used to determine the actual block rate. The output can be
directly copied to the `blocktime_adjustments` setting.
"""
from moneywagon import get_block
all_points = []
if intervals:
latest_block_height = get_block(crypto, latest=True, **modes)['block_number']
interval = int(latest_block_height / float(intervals))
all_points = [x * interval for x in range(1, intervals - 1)]
if points:
all_points.extend(points)
all_points.sort()
adjustments = []
previous_point = 0
previous_time = (crypto_data[crypto.lower()].get('genesis_date').replace(tzinfo=pytz.UTC)
or get_block(crypto, block_number=0, **modes)['time']
)
for point in all_points:
if point == 0:
continue
point_time = get_block(crypto, block_number=point, **modes)['time']
length = point - previous_point
minutes = (point_time - previous_time).total_seconds() / 60
rate = minutes / length
adjustments.append([previous_point, rate])
previous_time = point_time
previous_point = point
return adjustments
|
python
|
def get_block_adjustments(crypto, points=None, intervals=None, **modes):
"""
This utility is used to determine the actual block rate. The output can be
directly copied to the `blocktime_adjustments` setting.
"""
from moneywagon import get_block
all_points = []
if intervals:
latest_block_height = get_block(crypto, latest=True, **modes)['block_number']
interval = int(latest_block_height / float(intervals))
all_points = [x * interval for x in range(1, intervals - 1)]
if points:
all_points.extend(points)
all_points.sort()
adjustments = []
previous_point = 0
previous_time = (crypto_data[crypto.lower()].get('genesis_date').replace(tzinfo=pytz.UTC)
or get_block(crypto, block_number=0, **modes)['time']
)
for point in all_points:
if point == 0:
continue
point_time = get_block(crypto, block_number=point, **modes)['time']
length = point - previous_point
minutes = (point_time - previous_time).total_seconds() / 60
rate = minutes / length
adjustments.append([previous_point, rate])
previous_time = point_time
previous_point = point
return adjustments
|
[
"def",
"get_block_adjustments",
"(",
"crypto",
",",
"points",
"=",
"None",
",",
"intervals",
"=",
"None",
",",
"*",
"*",
"modes",
")",
":",
"from",
"moneywagon",
"import",
"get_block",
"all_points",
"=",
"[",
"]",
"if",
"intervals",
":",
"latest_block_height",
"=",
"get_block",
"(",
"crypto",
",",
"latest",
"=",
"True",
",",
"*",
"*",
"modes",
")",
"[",
"'block_number'",
"]",
"interval",
"=",
"int",
"(",
"latest_block_height",
"/",
"float",
"(",
"intervals",
")",
")",
"all_points",
"=",
"[",
"x",
"*",
"interval",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"intervals",
"-",
"1",
")",
"]",
"if",
"points",
":",
"all_points",
".",
"extend",
"(",
"points",
")",
"all_points",
".",
"sort",
"(",
")",
"adjustments",
"=",
"[",
"]",
"previous_point",
"=",
"0",
"previous_time",
"=",
"(",
"crypto_data",
"[",
"crypto",
".",
"lower",
"(",
")",
"]",
".",
"get",
"(",
"'genesis_date'",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"UTC",
")",
"or",
"get_block",
"(",
"crypto",
",",
"block_number",
"=",
"0",
",",
"*",
"*",
"modes",
")",
"[",
"'time'",
"]",
")",
"for",
"point",
"in",
"all_points",
":",
"if",
"point",
"==",
"0",
":",
"continue",
"point_time",
"=",
"get_block",
"(",
"crypto",
",",
"block_number",
"=",
"point",
",",
"*",
"*",
"modes",
")",
"[",
"'time'",
"]",
"length",
"=",
"point",
"-",
"previous_point",
"minutes",
"=",
"(",
"point_time",
"-",
"previous_time",
")",
".",
"total_seconds",
"(",
")",
"/",
"60",
"rate",
"=",
"minutes",
"/",
"length",
"adjustments",
".",
"append",
"(",
"[",
"previous_point",
",",
"rate",
"]",
")",
"previous_time",
"=",
"point_time",
"previous_point",
"=",
"point",
"return",
"adjustments"
] |
This utility is used to determine the actual block rate. The output can be
directly copied to the `blocktime_adjustments` setting.
|
[
"This",
"utility",
"is",
"used",
"to",
"determine",
"the",
"actual",
"block",
"rate",
".",
"The",
"output",
"can",
"be",
"directly",
"copied",
"to",
"the",
"blocktime_adjustments",
"setting",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/supply_estimator.py#L217-L253
|
14,184
|
priestc/moneywagon
|
moneywagon/supply_estimator.py
|
SupplyEstimator._per_era_supply
|
def _per_era_supply(self, block_height):
"""
Calculate the coin supply based on 'eras' defined in crypto_data. Some
currencies don't have a simple algorithmically defined halfing schedule
so coins supply has to be defined explicitly per era.
"""
coins = 0
for era in self.supply_data['eras']:
end_block = era['end']
start_block = era['start']
reward = era['reward']
if not end_block or block_height <= end_block:
blocks_this_era = block_height - start_block
coins += blocks_this_era * reward
break
blocks_per_era = end_block - start_block
coins += reward * blocks_per_era
return coins
|
python
|
def _per_era_supply(self, block_height):
"""
Calculate the coin supply based on 'eras' defined in crypto_data. Some
currencies don't have a simple algorithmically defined halfing schedule
so coins supply has to be defined explicitly per era.
"""
coins = 0
for era in self.supply_data['eras']:
end_block = era['end']
start_block = era['start']
reward = era['reward']
if not end_block or block_height <= end_block:
blocks_this_era = block_height - start_block
coins += blocks_this_era * reward
break
blocks_per_era = end_block - start_block
coins += reward * blocks_per_era
return coins
|
[
"def",
"_per_era_supply",
"(",
"self",
",",
"block_height",
")",
":",
"coins",
"=",
"0",
"for",
"era",
"in",
"self",
".",
"supply_data",
"[",
"'eras'",
"]",
":",
"end_block",
"=",
"era",
"[",
"'end'",
"]",
"start_block",
"=",
"era",
"[",
"'start'",
"]",
"reward",
"=",
"era",
"[",
"'reward'",
"]",
"if",
"not",
"end_block",
"or",
"block_height",
"<=",
"end_block",
":",
"blocks_this_era",
"=",
"block_height",
"-",
"start_block",
"coins",
"+=",
"blocks_this_era",
"*",
"reward",
"break",
"blocks_per_era",
"=",
"end_block",
"-",
"start_block",
"coins",
"+=",
"reward",
"*",
"blocks_per_era",
"return",
"coins"
] |
Calculate the coin supply based on 'eras' defined in crypto_data. Some
currencies don't have a simple algorithmically defined halfing schedule
so coins supply has to be defined explicitly per era.
|
[
"Calculate",
"the",
"coin",
"supply",
"based",
"on",
"eras",
"defined",
"in",
"crypto_data",
".",
"Some",
"currencies",
"don",
"t",
"have",
"a",
"simple",
"algorithmically",
"defined",
"halfing",
"schedule",
"so",
"coins",
"supply",
"has",
"to",
"be",
"defined",
"explicitly",
"per",
"era",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/supply_estimator.py#L169-L189
|
14,185
|
priestc/moneywagon
|
moneywagon/core.py
|
_prepare_consensus
|
def _prepare_consensus(FetcherClass, results):
"""
Given a list of results, return a list that is simplified to make consensus
determination possible. Returns two item tuple, first arg is simplified list,
the second argument is a list of all services used in making these results.
"""
# _get_results returns lists of 2 item list, first element is service, second is the returned value.
# when determining consensus amoung services, only take into account values returned.
if hasattr(FetcherClass, "strip_for_consensus"):
to_compare = [
FetcherClass.strip_for_consensus(value) for (fetcher, value) in results
]
else:
to_compare = [value for fetcher, value in results]
return to_compare, [fetcher._successful_service for fetcher, values in results]
|
python
|
def _prepare_consensus(FetcherClass, results):
"""
Given a list of results, return a list that is simplified to make consensus
determination possible. Returns two item tuple, first arg is simplified list,
the second argument is a list of all services used in making these results.
"""
# _get_results returns lists of 2 item list, first element is service, second is the returned value.
# when determining consensus amoung services, only take into account values returned.
if hasattr(FetcherClass, "strip_for_consensus"):
to_compare = [
FetcherClass.strip_for_consensus(value) for (fetcher, value) in results
]
else:
to_compare = [value for fetcher, value in results]
return to_compare, [fetcher._successful_service for fetcher, values in results]
|
[
"def",
"_prepare_consensus",
"(",
"FetcherClass",
",",
"results",
")",
":",
"# _get_results returns lists of 2 item list, first element is service, second is the returned value.",
"# when determining consensus amoung services, only take into account values returned.",
"if",
"hasattr",
"(",
"FetcherClass",
",",
"\"strip_for_consensus\"",
")",
":",
"to_compare",
"=",
"[",
"FetcherClass",
".",
"strip_for_consensus",
"(",
"value",
")",
"for",
"(",
"fetcher",
",",
"value",
")",
"in",
"results",
"]",
"else",
":",
"to_compare",
"=",
"[",
"value",
"for",
"fetcher",
",",
"value",
"in",
"results",
"]",
"return",
"to_compare",
",",
"[",
"fetcher",
".",
"_successful_service",
"for",
"fetcher",
",",
"values",
"in",
"results",
"]"
] |
Given a list of results, return a list that is simplified to make consensus
determination possible. Returns two item tuple, first arg is simplified list,
the second argument is a list of all services used in making these results.
|
[
"Given",
"a",
"list",
"of",
"results",
"return",
"a",
"list",
"that",
"is",
"simplified",
"to",
"make",
"consensus",
"determination",
"possible",
".",
"Returns",
"two",
"item",
"tuple",
"first",
"arg",
"is",
"simplified",
"list",
"the",
"second",
"argument",
"is",
"a",
"list",
"of",
"all",
"services",
"used",
"in",
"making",
"these",
"results",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L692-L707
|
14,186
|
priestc/moneywagon
|
moneywagon/core.py
|
_get_results
|
def _get_results(FetcherClass, services, kwargs, num_results=None, fast=0, verbose=False, timeout=None):
"""
Does the fetching in multiple threads of needed. Used by paranoid and fast mode.
"""
results = []
if not num_results or fast:
num_results = len(services)
with futures.ThreadPoolExecutor(max_workers=len(services)) as executor:
fetches = {}
for service in services[:num_results]:
tail = [x for x in services if x is not service]
random.shuffle(tail)
srv = FetcherClass(services=[service] + tail, verbose=verbose, timeout=timeout)
fetches[executor.submit(srv.action, **kwargs)] = srv
if fast == 1:
raise NotImplementedError
# ths code is a work in progress. futures.FIRST_COMPLETED works differently than I thought...
to_iterate, still_going = futures.wait(fetches, return_when=futures.FIRST_COMPLETED)
for x in still_going:
try:
x.result(timeout=1.001)
except futures._base.TimeoutError:
pass
elif fast > 1:
raise Exception("fast level greater than 1 not yet implemented")
else:
to_iterate = futures.as_completed(fetches)
for future in to_iterate:
service = fetches[future]
results.append([service, future.result()])
return results
|
python
|
def _get_results(FetcherClass, services, kwargs, num_results=None, fast=0, verbose=False, timeout=None):
"""
Does the fetching in multiple threads of needed. Used by paranoid and fast mode.
"""
results = []
if not num_results or fast:
num_results = len(services)
with futures.ThreadPoolExecutor(max_workers=len(services)) as executor:
fetches = {}
for service in services[:num_results]:
tail = [x for x in services if x is not service]
random.shuffle(tail)
srv = FetcherClass(services=[service] + tail, verbose=verbose, timeout=timeout)
fetches[executor.submit(srv.action, **kwargs)] = srv
if fast == 1:
raise NotImplementedError
# ths code is a work in progress. futures.FIRST_COMPLETED works differently than I thought...
to_iterate, still_going = futures.wait(fetches, return_when=futures.FIRST_COMPLETED)
for x in still_going:
try:
x.result(timeout=1.001)
except futures._base.TimeoutError:
pass
elif fast > 1:
raise Exception("fast level greater than 1 not yet implemented")
else:
to_iterate = futures.as_completed(fetches)
for future in to_iterate:
service = fetches[future]
results.append([service, future.result()])
return results
|
[
"def",
"_get_results",
"(",
"FetcherClass",
",",
"services",
",",
"kwargs",
",",
"num_results",
"=",
"None",
",",
"fast",
"=",
"0",
",",
"verbose",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"not",
"num_results",
"or",
"fast",
":",
"num_results",
"=",
"len",
"(",
"services",
")",
"with",
"futures",
".",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"len",
"(",
"services",
")",
")",
"as",
"executor",
":",
"fetches",
"=",
"{",
"}",
"for",
"service",
"in",
"services",
"[",
":",
"num_results",
"]",
":",
"tail",
"=",
"[",
"x",
"for",
"x",
"in",
"services",
"if",
"x",
"is",
"not",
"service",
"]",
"random",
".",
"shuffle",
"(",
"tail",
")",
"srv",
"=",
"FetcherClass",
"(",
"services",
"=",
"[",
"service",
"]",
"+",
"tail",
",",
"verbose",
"=",
"verbose",
",",
"timeout",
"=",
"timeout",
")",
"fetches",
"[",
"executor",
".",
"submit",
"(",
"srv",
".",
"action",
",",
"*",
"*",
"kwargs",
")",
"]",
"=",
"srv",
"if",
"fast",
"==",
"1",
":",
"raise",
"NotImplementedError",
"# ths code is a work in progress. futures.FIRST_COMPLETED works differently than I thought...",
"to_iterate",
",",
"still_going",
"=",
"futures",
".",
"wait",
"(",
"fetches",
",",
"return_when",
"=",
"futures",
".",
"FIRST_COMPLETED",
")",
"for",
"x",
"in",
"still_going",
":",
"try",
":",
"x",
".",
"result",
"(",
"timeout",
"=",
"1.001",
")",
"except",
"futures",
".",
"_base",
".",
"TimeoutError",
":",
"pass",
"elif",
"fast",
">",
"1",
":",
"raise",
"Exception",
"(",
"\"fast level greater than 1 not yet implemented\"",
")",
"else",
":",
"to_iterate",
"=",
"futures",
".",
"as_completed",
"(",
"fetches",
")",
"for",
"future",
"in",
"to_iterate",
":",
"service",
"=",
"fetches",
"[",
"future",
"]",
"results",
".",
"append",
"(",
"[",
"service",
",",
"future",
".",
"result",
"(",
")",
"]",
")",
"return",
"results"
] |
Does the fetching in multiple threads of needed. Used by paranoid and fast mode.
|
[
"Does",
"the",
"fetching",
"in",
"multiple",
"threads",
"of",
"needed",
".",
"Used",
"by",
"paranoid",
"and",
"fast",
"mode",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L709-L745
|
14,187
|
priestc/moneywagon
|
moneywagon/core.py
|
_do_private_mode
|
def _do_private_mode(FetcherClass, services, kwargs, random_wait_seconds, timeout, verbose):
"""
Private mode is only applicable to address_balance, unspent_outputs, and
historical_transactions. There will always be a list for the `addresses`
argument. Each address goes to a random service. Also a random delay is
performed before the external fetch for improved privacy.
"""
addresses = kwargs.pop('addresses')
results = {}
with futures.ThreadPoolExecutor(max_workers=len(addresses)) as executor:
fetches = {}
for address in addresses:
k = kwargs
k['address'] = address
random.shuffle(services)
srv = FetcherClass(
services=services, verbose=verbose, timeout=timeout or 5.0,
random_wait_seconds=random_wait_seconds
)
# address is returned because balance needs to be returned
# attached to the address. Other methods (get_transaction, unspent_outputs, etc)
# do not need to be indexed by address. (upstream they are stripped out)
fetches[executor.submit(srv.action, **k)] = (srv, address)
to_iterate = futures.as_completed(fetches)
for future in to_iterate:
service, address = fetches[future]
results[address] = future.result()
return results
|
python
|
def _do_private_mode(FetcherClass, services, kwargs, random_wait_seconds, timeout, verbose):
"""
Private mode is only applicable to address_balance, unspent_outputs, and
historical_transactions. There will always be a list for the `addresses`
argument. Each address goes to a random service. Also a random delay is
performed before the external fetch for improved privacy.
"""
addresses = kwargs.pop('addresses')
results = {}
with futures.ThreadPoolExecutor(max_workers=len(addresses)) as executor:
fetches = {}
for address in addresses:
k = kwargs
k['address'] = address
random.shuffle(services)
srv = FetcherClass(
services=services, verbose=verbose, timeout=timeout or 5.0,
random_wait_seconds=random_wait_seconds
)
# address is returned because balance needs to be returned
# attached to the address. Other methods (get_transaction, unspent_outputs, etc)
# do not need to be indexed by address. (upstream they are stripped out)
fetches[executor.submit(srv.action, **k)] = (srv, address)
to_iterate = futures.as_completed(fetches)
for future in to_iterate:
service, address = fetches[future]
results[address] = future.result()
return results
|
[
"def",
"_do_private_mode",
"(",
"FetcherClass",
",",
"services",
",",
"kwargs",
",",
"random_wait_seconds",
",",
"timeout",
",",
"verbose",
")",
":",
"addresses",
"=",
"kwargs",
".",
"pop",
"(",
"'addresses'",
")",
"results",
"=",
"{",
"}",
"with",
"futures",
".",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"len",
"(",
"addresses",
")",
")",
"as",
"executor",
":",
"fetches",
"=",
"{",
"}",
"for",
"address",
"in",
"addresses",
":",
"k",
"=",
"kwargs",
"k",
"[",
"'address'",
"]",
"=",
"address",
"random",
".",
"shuffle",
"(",
"services",
")",
"srv",
"=",
"FetcherClass",
"(",
"services",
"=",
"services",
",",
"verbose",
"=",
"verbose",
",",
"timeout",
"=",
"timeout",
"or",
"5.0",
",",
"random_wait_seconds",
"=",
"random_wait_seconds",
")",
"# address is returned because balance needs to be returned",
"# attached to the address. Other methods (get_transaction, unspent_outputs, etc)",
"# do not need to be indexed by address. (upstream they are stripped out)",
"fetches",
"[",
"executor",
".",
"submit",
"(",
"srv",
".",
"action",
",",
"*",
"*",
"k",
")",
"]",
"=",
"(",
"srv",
",",
"address",
")",
"to_iterate",
"=",
"futures",
".",
"as_completed",
"(",
"fetches",
")",
"for",
"future",
"in",
"to_iterate",
":",
"service",
",",
"address",
"=",
"fetches",
"[",
"future",
"]",
"results",
"[",
"address",
"]",
"=",
"future",
".",
"result",
"(",
")",
"return",
"results"
] |
Private mode is only applicable to address_balance, unspent_outputs, and
historical_transactions. There will always be a list for the `addresses`
argument. Each address goes to a random service. Also a random delay is
performed before the external fetch for improved privacy.
|
[
"Private",
"mode",
"is",
"only",
"applicable",
"to",
"address_balance",
"unspent_outputs",
"and",
"historical_transactions",
".",
"There",
"will",
"always",
"be",
"a",
"list",
"for",
"the",
"addresses",
"argument",
".",
"Each",
"address",
"goes",
"to",
"a",
"random",
"service",
".",
"Also",
"a",
"random",
"delay",
"is",
"performed",
"before",
"the",
"external",
"fetch",
"for",
"improved",
"privacy",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L747-L778
|
14,188
|
priestc/moneywagon
|
moneywagon/core.py
|
currency_to_protocol
|
def currency_to_protocol(amount):
"""
Convert a string of 'currency units' to 'protocol units'. For instance
converts 19.1 bitcoin to 1910000000 satoshis.
Input is a float, output is an integer that is 1e8 times larger.
It is hard to do this conversion because multiplying
floats causes rounding nubers which will mess up the transactions creation
process.
examples:
19.1 -> 1910000000
0.001 -> 100000
"""
if type(amount) in [float, int]:
amount = "%.8f" % amount
return int(amount.replace(".", ''))
|
python
|
def currency_to_protocol(amount):
"""
Convert a string of 'currency units' to 'protocol units'. For instance
converts 19.1 bitcoin to 1910000000 satoshis.
Input is a float, output is an integer that is 1e8 times larger.
It is hard to do this conversion because multiplying
floats causes rounding nubers which will mess up the transactions creation
process.
examples:
19.1 -> 1910000000
0.001 -> 100000
"""
if type(amount) in [float, int]:
amount = "%.8f" % amount
return int(amount.replace(".", ''))
|
[
"def",
"currency_to_protocol",
"(",
"amount",
")",
":",
"if",
"type",
"(",
"amount",
")",
"in",
"[",
"float",
",",
"int",
"]",
":",
"amount",
"=",
"\"%.8f\"",
"%",
"amount",
"return",
"int",
"(",
"amount",
".",
"replace",
"(",
"\".\"",
",",
"''",
")",
")"
] |
Convert a string of 'currency units' to 'protocol units'. For instance
converts 19.1 bitcoin to 1910000000 satoshis.
Input is a float, output is an integer that is 1e8 times larger.
It is hard to do this conversion because multiplying
floats causes rounding nubers which will mess up the transactions creation
process.
examples:
19.1 -> 1910000000
0.001 -> 100000
|
[
"Convert",
"a",
"string",
"of",
"currency",
"units",
"to",
"protocol",
"units",
".",
"For",
"instance",
"converts",
"19",
".",
"1",
"bitcoin",
"to",
"1910000000",
"satoshis",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L781-L801
|
14,189
|
priestc/moneywagon
|
moneywagon/core.py
|
to_rawtx
|
def to_rawtx(tx):
"""
Take a tx object in the moneywagon format and convert it to the format
that pybitcointools's `serialize` funcion takes, then return in raw hex
format.
"""
if tx.get('hex'):
return tx['hex']
new_tx = {}
locktime = tx.get('locktime', 0)
new_tx['locktime'] = locktime
new_tx['version'] = tx.get('version', 1)
new_tx['ins'] = [
{
'outpoint': {'hash': str(x['txid']), 'index': x['n']},
'script': str(x['scriptSig'].replace(' ', '')),
'sequence': x.get('sequence', 0xFFFFFFFF if locktime == 0 else None)
} for x in tx['inputs']
]
new_tx['outs'] = [
{
'script': str(x['scriptPubKey']),
'value': x['amount']
} for x in tx['outputs']
]
return serialize(new_tx)
|
python
|
def to_rawtx(tx):
"""
Take a tx object in the moneywagon format and convert it to the format
that pybitcointools's `serialize` funcion takes, then return in raw hex
format.
"""
if tx.get('hex'):
return tx['hex']
new_tx = {}
locktime = tx.get('locktime', 0)
new_tx['locktime'] = locktime
new_tx['version'] = tx.get('version', 1)
new_tx['ins'] = [
{
'outpoint': {'hash': str(x['txid']), 'index': x['n']},
'script': str(x['scriptSig'].replace(' ', '')),
'sequence': x.get('sequence', 0xFFFFFFFF if locktime == 0 else None)
} for x in tx['inputs']
]
new_tx['outs'] = [
{
'script': str(x['scriptPubKey']),
'value': x['amount']
} for x in tx['outputs']
]
return serialize(new_tx)
|
[
"def",
"to_rawtx",
"(",
"tx",
")",
":",
"if",
"tx",
".",
"get",
"(",
"'hex'",
")",
":",
"return",
"tx",
"[",
"'hex'",
"]",
"new_tx",
"=",
"{",
"}",
"locktime",
"=",
"tx",
".",
"get",
"(",
"'locktime'",
",",
"0",
")",
"new_tx",
"[",
"'locktime'",
"]",
"=",
"locktime",
"new_tx",
"[",
"'version'",
"]",
"=",
"tx",
".",
"get",
"(",
"'version'",
",",
"1",
")",
"new_tx",
"[",
"'ins'",
"]",
"=",
"[",
"{",
"'outpoint'",
":",
"{",
"'hash'",
":",
"str",
"(",
"x",
"[",
"'txid'",
"]",
")",
",",
"'index'",
":",
"x",
"[",
"'n'",
"]",
"}",
",",
"'script'",
":",
"str",
"(",
"x",
"[",
"'scriptSig'",
"]",
".",
"replace",
"(",
"' '",
",",
"''",
")",
")",
",",
"'sequence'",
":",
"x",
".",
"get",
"(",
"'sequence'",
",",
"0xFFFFFFFF",
"if",
"locktime",
"==",
"0",
"else",
"None",
")",
"}",
"for",
"x",
"in",
"tx",
"[",
"'inputs'",
"]",
"]",
"new_tx",
"[",
"'outs'",
"]",
"=",
"[",
"{",
"'script'",
":",
"str",
"(",
"x",
"[",
"'scriptPubKey'",
"]",
")",
",",
"'value'",
":",
"x",
"[",
"'amount'",
"]",
"}",
"for",
"x",
"in",
"tx",
"[",
"'outputs'",
"]",
"]",
"return",
"serialize",
"(",
"new_tx",
")"
] |
Take a tx object in the moneywagon format and convert it to the format
that pybitcointools's `serialize` funcion takes, then return in raw hex
format.
|
[
"Take",
"a",
"tx",
"object",
"in",
"the",
"moneywagon",
"format",
"and",
"convert",
"it",
"to",
"the",
"format",
"that",
"pybitcointools",
"s",
"serialize",
"funcion",
"takes",
"then",
"return",
"in",
"raw",
"hex",
"format",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L862-L891
|
14,190
|
priestc/moneywagon
|
moneywagon/core.py
|
Service.check_error
|
def check_error(self, response):
"""
If the service is returning an error, this function should raise an exception.
such as SkipThisService
"""
if response.status_code == 500:
raise ServiceError("500 - " + response.content)
if response.status_code == 503:
if "DDoS protection by Cloudflare" in response.content:
raise ServiceError("Foiled by Cloudfare's DDoS protection")
raise ServiceError("503 - Temporarily out of service.")
if response.status_code == 429:
raise ServiceError("429 - Too many requests")
if response.status_code == 404:
raise ServiceError("404 - Not Found")
if response.status_code == 400:
raise ServiceError("400 - Bad Request")
|
python
|
def check_error(self, response):
"""
If the service is returning an error, this function should raise an exception.
such as SkipThisService
"""
if response.status_code == 500:
raise ServiceError("500 - " + response.content)
if response.status_code == 503:
if "DDoS protection by Cloudflare" in response.content:
raise ServiceError("Foiled by Cloudfare's DDoS protection")
raise ServiceError("503 - Temporarily out of service.")
if response.status_code == 429:
raise ServiceError("429 - Too many requests")
if response.status_code == 404:
raise ServiceError("404 - Not Found")
if response.status_code == 400:
raise ServiceError("400 - Bad Request")
|
[
"def",
"check_error",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"500",
":",
"raise",
"ServiceError",
"(",
"\"500 - \"",
"+",
"response",
".",
"content",
")",
"if",
"response",
".",
"status_code",
"==",
"503",
":",
"if",
"\"DDoS protection by Cloudflare\"",
"in",
"response",
".",
"content",
":",
"raise",
"ServiceError",
"(",
"\"Foiled by Cloudfare's DDoS protection\"",
")",
"raise",
"ServiceError",
"(",
"\"503 - Temporarily out of service.\"",
")",
"if",
"response",
".",
"status_code",
"==",
"429",
":",
"raise",
"ServiceError",
"(",
"\"429 - Too many requests\"",
")",
"if",
"response",
".",
"status_code",
"==",
"404",
":",
"raise",
"ServiceError",
"(",
"\"404 - Not Found\"",
")",
"if",
"response",
".",
"status_code",
"==",
"400",
":",
"raise",
"ServiceError",
"(",
"\"400 - Bad Request\"",
")"
] |
If the service is returning an error, this function should raise an exception.
such as SkipThisService
|
[
"If",
"the",
"service",
"is",
"returning",
"an",
"error",
"this",
"function",
"should",
"raise",
"an",
"exception",
".",
"such",
"as",
"SkipThisService"
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L111-L131
|
14,191
|
priestc/moneywagon
|
moneywagon/core.py
|
Service.convert_currency
|
def convert_currency(self, base_fiat, base_amount, target_fiat):
"""
Convert one fiat amount to another fiat. Uses the fixer.io service.
"""
url = "http://api.fixer.io/latest?base=%s" % base_fiat
data = self.get_url(url).json()
try:
return data['rates'][target_fiat.upper()] * base_amount
except KeyError:
raise Exception("Can not convert %s to %s" % (base_fiat, target_fiat))
|
python
|
def convert_currency(self, base_fiat, base_amount, target_fiat):
"""
Convert one fiat amount to another fiat. Uses the fixer.io service.
"""
url = "http://api.fixer.io/latest?base=%s" % base_fiat
data = self.get_url(url).json()
try:
return data['rates'][target_fiat.upper()] * base_amount
except KeyError:
raise Exception("Can not convert %s to %s" % (base_fiat, target_fiat))
|
[
"def",
"convert_currency",
"(",
"self",
",",
"base_fiat",
",",
"base_amount",
",",
"target_fiat",
")",
":",
"url",
"=",
"\"http://api.fixer.io/latest?base=%s\"",
"%",
"base_fiat",
"data",
"=",
"self",
".",
"get_url",
"(",
"url",
")",
".",
"json",
"(",
")",
"try",
":",
"return",
"data",
"[",
"'rates'",
"]",
"[",
"target_fiat",
".",
"upper",
"(",
")",
"]",
"*",
"base_amount",
"except",
"KeyError",
":",
"raise",
"Exception",
"(",
"\"Can not convert %s to %s\"",
"%",
"(",
"base_fiat",
",",
"target_fiat",
")",
")"
] |
Convert one fiat amount to another fiat. Uses the fixer.io service.
|
[
"Convert",
"one",
"fiat",
"amount",
"to",
"another",
"fiat",
".",
"Uses",
"the",
"fixer",
".",
"io",
"service",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L133-L142
|
14,192
|
priestc/moneywagon
|
moneywagon/core.py
|
Service.fix_symbol
|
def fix_symbol(self, symbol, reverse=False):
"""
In comes a moneywagon format symbol, and returned in the symbol converted
to one the service can understand.
"""
if not self.symbol_mapping:
return symbol
for old, new in self.symbol_mapping:
if reverse:
if symbol == new:
return old
else:
if symbol == old:
return new
return symbol
|
python
|
def fix_symbol(self, symbol, reverse=False):
"""
In comes a moneywagon format symbol, and returned in the symbol converted
to one the service can understand.
"""
if not self.symbol_mapping:
return symbol
for old, new in self.symbol_mapping:
if reverse:
if symbol == new:
return old
else:
if symbol == old:
return new
return symbol
|
[
"def",
"fix_symbol",
"(",
"self",
",",
"symbol",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"symbol_mapping",
":",
"return",
"symbol",
"for",
"old",
",",
"new",
"in",
"self",
".",
"symbol_mapping",
":",
"if",
"reverse",
":",
"if",
"symbol",
"==",
"new",
":",
"return",
"old",
"else",
":",
"if",
"symbol",
"==",
"old",
":",
"return",
"new",
"return",
"symbol"
] |
In comes a moneywagon format symbol, and returned in the symbol converted
to one the service can understand.
|
[
"In",
"comes",
"a",
"moneywagon",
"format",
"symbol",
"and",
"returned",
"in",
"the",
"symbol",
"converted",
"to",
"one",
"the",
"service",
"can",
"understand",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L151-L167
|
14,193
|
priestc/moneywagon
|
moneywagon/core.py
|
Service.parse_market
|
def parse_market(self, market, split_char='_'):
"""
In comes the market identifier directly from the service. Returned is
the crypto and fiat identifier in moneywagon format.
"""
crypto, fiat = market.lower().split(split_char)
return (
self.fix_symbol(crypto, reverse=True),
self.fix_symbol(fiat, reverse=True)
)
|
python
|
def parse_market(self, market, split_char='_'):
"""
In comes the market identifier directly from the service. Returned is
the crypto and fiat identifier in moneywagon format.
"""
crypto, fiat = market.lower().split(split_char)
return (
self.fix_symbol(crypto, reverse=True),
self.fix_symbol(fiat, reverse=True)
)
|
[
"def",
"parse_market",
"(",
"self",
",",
"market",
",",
"split_char",
"=",
"'_'",
")",
":",
"crypto",
",",
"fiat",
"=",
"market",
".",
"lower",
"(",
")",
".",
"split",
"(",
"split_char",
")",
"return",
"(",
"self",
".",
"fix_symbol",
"(",
"crypto",
",",
"reverse",
"=",
"True",
")",
",",
"self",
".",
"fix_symbol",
"(",
"fiat",
",",
"reverse",
"=",
"True",
")",
")"
] |
In comes the market identifier directly from the service. Returned is
the crypto and fiat identifier in moneywagon format.
|
[
"In",
"comes",
"the",
"market",
"identifier",
"directly",
"from",
"the",
"service",
".",
"Returned",
"is",
"the",
"crypto",
"and",
"fiat",
"identifier",
"in",
"moneywagon",
"format",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L169-L178
|
14,194
|
priestc/moneywagon
|
moneywagon/core.py
|
Service.make_market
|
def make_market(self, crypto, fiat, seperator="_"):
"""
Convert a crypto and fiat to a "market" string. All exchanges use their
own format for specifying markets. Subclasses can define their own
implementation.
"""
return ("%s%s%s" % (
self.fix_symbol(crypto), seperator, self.fix_symbol(fiat))
).lower()
|
python
|
def make_market(self, crypto, fiat, seperator="_"):
"""
Convert a crypto and fiat to a "market" string. All exchanges use their
own format for specifying markets. Subclasses can define their own
implementation.
"""
return ("%s%s%s" % (
self.fix_symbol(crypto), seperator, self.fix_symbol(fiat))
).lower()
|
[
"def",
"make_market",
"(",
"self",
",",
"crypto",
",",
"fiat",
",",
"seperator",
"=",
"\"_\"",
")",
":",
"return",
"(",
"\"%s%s%s\"",
"%",
"(",
"self",
".",
"fix_symbol",
"(",
"crypto",
")",
",",
"seperator",
",",
"self",
".",
"fix_symbol",
"(",
"fiat",
")",
")",
")",
".",
"lower",
"(",
")"
] |
Convert a crypto and fiat to a "market" string. All exchanges use their
own format for specifying markets. Subclasses can define their own
implementation.
|
[
"Convert",
"a",
"crypto",
"and",
"fiat",
"to",
"a",
"market",
"string",
".",
"All",
"exchanges",
"use",
"their",
"own",
"format",
"for",
"specifying",
"markets",
".",
"Subclasses",
"can",
"define",
"their",
"own",
"implementation",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L180-L188
|
14,195
|
priestc/moneywagon
|
moneywagon/core.py
|
Service._external_request
|
def _external_request(self, method, url, *args, **kwargs):
"""
Wrapper for requests.get with useragent automatically set.
And also all requests are reponses are cached.
"""
self.last_url = url
if url in self.responses.keys() and method == 'get':
return self.responses[url] # return from cache if its there
headers = kwargs.pop('headers', None)
custom = {'User-Agent': useragent}
if headers:
headers.update(custom)
kwargs['headers'] = headers
else:
kwargs['headers'] = custom
if self.timeout:
# add timeout parameter to requests.get if one was passed in on construction...
kwargs['timeout'] = self.timeout
start = datetime.datetime.now()
response = getattr(requests, method)(url, verify=self.ssl_verify, *args, **kwargs)
self.total_external_fetch_duration += datetime.datetime.now() - start
if self.verbose:
print("Got Response: %s (took %s)" % (url, (datetime.datetime.now() - start)))
self.last_raw_response = response
self.check_error(response)
if method == 'get':
self.responses[url] = response # cache for later
return response
|
python
|
def _external_request(self, method, url, *args, **kwargs):
"""
Wrapper for requests.get with useragent automatically set.
And also all requests are reponses are cached.
"""
self.last_url = url
if url in self.responses.keys() and method == 'get':
return self.responses[url] # return from cache if its there
headers = kwargs.pop('headers', None)
custom = {'User-Agent': useragent}
if headers:
headers.update(custom)
kwargs['headers'] = headers
else:
kwargs['headers'] = custom
if self.timeout:
# add timeout parameter to requests.get if one was passed in on construction...
kwargs['timeout'] = self.timeout
start = datetime.datetime.now()
response = getattr(requests, method)(url, verify=self.ssl_verify, *args, **kwargs)
self.total_external_fetch_duration += datetime.datetime.now() - start
if self.verbose:
print("Got Response: %s (took %s)" % (url, (datetime.datetime.now() - start)))
self.last_raw_response = response
self.check_error(response)
if method == 'get':
self.responses[url] = response # cache for later
return response
|
[
"def",
"_external_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"last_url",
"=",
"url",
"if",
"url",
"in",
"self",
".",
"responses",
".",
"keys",
"(",
")",
"and",
"method",
"==",
"'get'",
":",
"return",
"self",
".",
"responses",
"[",
"url",
"]",
"# return from cache if its there",
"headers",
"=",
"kwargs",
".",
"pop",
"(",
"'headers'",
",",
"None",
")",
"custom",
"=",
"{",
"'User-Agent'",
":",
"useragent",
"}",
"if",
"headers",
":",
"headers",
".",
"update",
"(",
"custom",
")",
"kwargs",
"[",
"'headers'",
"]",
"=",
"headers",
"else",
":",
"kwargs",
"[",
"'headers'",
"]",
"=",
"custom",
"if",
"self",
".",
"timeout",
":",
"# add timeout parameter to requests.get if one was passed in on construction...",
"kwargs",
"[",
"'timeout'",
"]",
"=",
"self",
".",
"timeout",
"start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"response",
"=",
"getattr",
"(",
"requests",
",",
"method",
")",
"(",
"url",
",",
"verify",
"=",
"self",
".",
"ssl_verify",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"total_external_fetch_duration",
"+=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"start",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Got Response: %s (took %s)\"",
"%",
"(",
"url",
",",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"start",
")",
")",
")",
"self",
".",
"last_raw_response",
"=",
"response",
"self",
".",
"check_error",
"(",
"response",
")",
"if",
"method",
"==",
"'get'",
":",
"self",
".",
"responses",
"[",
"url",
"]",
"=",
"response",
"# cache for later",
"return",
"response"
] |
Wrapper for requests.get with useragent automatically set.
And also all requests are reponses are cached.
|
[
"Wrapper",
"for",
"requests",
".",
"get",
"with",
"useragent",
"automatically",
"set",
".",
"And",
"also",
"all",
"requests",
"are",
"reponses",
"are",
"cached",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L211-L246
|
14,196
|
priestc/moneywagon
|
moneywagon/core.py
|
Service.get_block
|
def get_block(self, crypto, block_hash='', block_number='', latest=False):
"""
Get block based on either block height, block number or get the latest
block. Only one of the previous arguments must be passed on.
Returned is a dictionary object with the following keys:
* required fields:
block_number - int
size - size of block
time - datetime object of when the block was made
hash - str (must be all lowercase)
tx_count - int, the number of transactions included in thi block.
* optional fields:
confirmations - int
sent_value - total value moved from all included transactions
total_fees - total amount of tx fees from all included transactions
mining_difficulty - what the difficulty was when this block was made.
merkle_root - str (lower case)
previous_hash - str (lower case)
next_hash - str (lower case) (or `None` of its the latest block)
miner - name of miner that first relayed this block
version - block version
"""
raise NotImplementedError(
self.name + " does not support getting getting block data. "
"Or rather it has no defined 'get_block' method."
)
|
python
|
def get_block(self, crypto, block_hash='', block_number='', latest=False):
"""
Get block based on either block height, block number or get the latest
block. Only one of the previous arguments must be passed on.
Returned is a dictionary object with the following keys:
* required fields:
block_number - int
size - size of block
time - datetime object of when the block was made
hash - str (must be all lowercase)
tx_count - int, the number of transactions included in thi block.
* optional fields:
confirmations - int
sent_value - total value moved from all included transactions
total_fees - total amount of tx fees from all included transactions
mining_difficulty - what the difficulty was when this block was made.
merkle_root - str (lower case)
previous_hash - str (lower case)
next_hash - str (lower case) (or `None` of its the latest block)
miner - name of miner that first relayed this block
version - block version
"""
raise NotImplementedError(
self.name + " does not support getting getting block data. "
"Or rather it has no defined 'get_block' method."
)
|
[
"def",
"get_block",
"(",
"self",
",",
"crypto",
",",
"block_hash",
"=",
"''",
",",
"block_number",
"=",
"''",
",",
"latest",
"=",
"False",
")",
":",
"raise",
"NotImplementedError",
"(",
"self",
".",
"name",
"+",
"\" does not support getting getting block data. \"",
"\"Or rather it has no defined 'get_block' method.\"",
")"
] |
Get block based on either block height, block number or get the latest
block. Only one of the previous arguments must be passed on.
Returned is a dictionary object with the following keys:
* required fields:
block_number - int
size - size of block
time - datetime object of when the block was made
hash - str (must be all lowercase)
tx_count - int, the number of transactions included in thi block.
* optional fields:
confirmations - int
sent_value - total value moved from all included transactions
total_fees - total amount of tx fees from all included transactions
mining_difficulty - what the difficulty was when this block was made.
merkle_root - str (lower case)
previous_hash - str (lower case)
next_hash - str (lower case) (or `None` of its the latest block)
miner - name of miner that first relayed this block
version - block version
|
[
"Get",
"block",
"based",
"on",
"either",
"block",
"height",
"block",
"number",
"or",
"get",
"the",
"latest",
"block",
".",
"Only",
"one",
"of",
"the",
"previous",
"arguments",
"must",
"be",
"passed",
"on",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L381-L411
|
14,197
|
priestc/moneywagon
|
moneywagon/core.py
|
Service.make_order
|
def make_order(self, crypto, fiat, amount, price, type="limit"):
"""
This method buys or sells `crypto` on an exchange using `fiat` balance.
Type can either be "fill-or-kill", "post-only", "market", or "limit".
To get what modes are supported, consult make_order.supported_types
if one is defined.
"""
raise NotImplementedError(
self.name + " does not support making orders. "
"Or rather it has no defined 'make_order' method."
)
|
python
|
def make_order(self, crypto, fiat, amount, price, type="limit"):
"""
This method buys or sells `crypto` on an exchange using `fiat` balance.
Type can either be "fill-or-kill", "post-only", "market", or "limit".
To get what modes are supported, consult make_order.supported_types
if one is defined.
"""
raise NotImplementedError(
self.name + " does not support making orders. "
"Or rather it has no defined 'make_order' method."
)
|
[
"def",
"make_order",
"(",
"self",
",",
"crypto",
",",
"fiat",
",",
"amount",
",",
"price",
",",
"type",
"=",
"\"limit\"",
")",
":",
"raise",
"NotImplementedError",
"(",
"self",
".",
"name",
"+",
"\" does not support making orders. \"",
"\"Or rather it has no defined 'make_order' method.\"",
")"
] |
This method buys or sells `crypto` on an exchange using `fiat` balance.
Type can either be "fill-or-kill", "post-only", "market", or "limit".
To get what modes are supported, consult make_order.supported_types
if one is defined.
|
[
"This",
"method",
"buys",
"or",
"sells",
"crypto",
"on",
"an",
"exchange",
"using",
"fiat",
"balance",
".",
"Type",
"can",
"either",
"be",
"fill",
"-",
"or",
"-",
"kill",
"post",
"-",
"only",
"market",
"or",
"limit",
".",
"To",
"get",
"what",
"modes",
"are",
"supported",
"consult",
"make_order",
".",
"supported_types",
"if",
"one",
"is",
"defined",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L440-L450
|
14,198
|
priestc/moneywagon
|
moneywagon/core.py
|
AutoFallbackFetcher._try_services
|
def _try_services(self, method_name, *args, **kwargs):
"""
Try each service until one returns a response. This function only
catches the bare minimum of exceptions from the service class. We want
exceptions to be raised so the service classes can be debugged and
fixed quickly.
"""
crypto = ((args and args[0]) or kwargs['crypto']).lower()
address = kwargs.get('address', '').lower()
fiat = kwargs.get('fiat', '').lower()
if not self.services:
raise CurrencyNotSupported("No services defined for %s for %s" % (method_name, crypto))
if self.random_wait_seconds > 0:
# for privacy... To avoid correlating addresses to same origin
# only gets called before the first service call. Does not pause
# before each and every call.
pause_time = random.random() * self.random_wait_seconds
if self.verbose:
print("Pausing for: %.2f seconds" % pause_time)
time.sleep(pause_time)
for service in self.services:
if service.supported_cryptos and (crypto not in service.supported_cryptos):
if self.verbose:
print("SKIP:", "%s not supported for %s" % (crypto, service.__class__.__name__))
continue
try:
if self.verbose: print("* Trying:", service, crypto, "%s%s" % (address, fiat))
ret = getattr(service, method_name)(*args, **kwargs)
self._successful_service = service
return ret
except (KeyError, IndexError, TypeError, ValueError,
requests.exceptions.Timeout, requests.exceptions.ConnectionError) as exc:
# API has probably changed, therefore service class broken
if self.verbose: print("FAIL:", service, exc.__class__.__name__, exc)
self._failed_services.append({
'service': service,
'error': "%s %s" % (exc.__class__.__name__, exc)
})
except NoService as exc:
# service classes can raise this exception if for whatever reason
# that service can't return a response, but maybe another one can.
if self.verbose: print("SKIP:", exc.__class__.__name__, exc)
self._failed_services.append({'service': service, 'error': "Skipped: %s" % str(exc)})
except NotImplementedError as exc:
if self.verbose: print("SKIP:", exc.__class__.__name__, exc)
self._failed_services.append({'service': service, 'error': "Not Implemented"})
if not self._failed_services:
raise NotImplementedError(
"No Services defined for %s and %s" % (crypto, method_name)
)
if set(x['error'] for x in self._failed_services) == set(['Not Implemented']) and method_name.endswith("multi"):
# some currencies may not have any multi functions defined, so retry
# with private mode (which tries multiple services).
raise RevertToPrivateMode("All services do not implement %s service" % method_name)
failed_msg = ', '.join(
["{service.name} -> {error}".format(**x) for x in self._failed_services]
)
raise NoService(self.no_service_msg(*args, **kwargs) + "! Tried: " + failed_msg)
|
python
|
def _try_services(self, method_name, *args, **kwargs):
"""
Try each service until one returns a response. This function only
catches the bare minimum of exceptions from the service class. We want
exceptions to be raised so the service classes can be debugged and
fixed quickly.
"""
crypto = ((args and args[0]) or kwargs['crypto']).lower()
address = kwargs.get('address', '').lower()
fiat = kwargs.get('fiat', '').lower()
if not self.services:
raise CurrencyNotSupported("No services defined for %s for %s" % (method_name, crypto))
if self.random_wait_seconds > 0:
# for privacy... To avoid correlating addresses to same origin
# only gets called before the first service call. Does not pause
# before each and every call.
pause_time = random.random() * self.random_wait_seconds
if self.verbose:
print("Pausing for: %.2f seconds" % pause_time)
time.sleep(pause_time)
for service in self.services:
if service.supported_cryptos and (crypto not in service.supported_cryptos):
if self.verbose:
print("SKIP:", "%s not supported for %s" % (crypto, service.__class__.__name__))
continue
try:
if self.verbose: print("* Trying:", service, crypto, "%s%s" % (address, fiat))
ret = getattr(service, method_name)(*args, **kwargs)
self._successful_service = service
return ret
except (KeyError, IndexError, TypeError, ValueError,
requests.exceptions.Timeout, requests.exceptions.ConnectionError) as exc:
# API has probably changed, therefore service class broken
if self.verbose: print("FAIL:", service, exc.__class__.__name__, exc)
self._failed_services.append({
'service': service,
'error': "%s %s" % (exc.__class__.__name__, exc)
})
except NoService as exc:
# service classes can raise this exception if for whatever reason
# that service can't return a response, but maybe another one can.
if self.verbose: print("SKIP:", exc.__class__.__name__, exc)
self._failed_services.append({'service': service, 'error': "Skipped: %s" % str(exc)})
except NotImplementedError as exc:
if self.verbose: print("SKIP:", exc.__class__.__name__, exc)
self._failed_services.append({'service': service, 'error': "Not Implemented"})
if not self._failed_services:
raise NotImplementedError(
"No Services defined for %s and %s" % (crypto, method_name)
)
if set(x['error'] for x in self._failed_services) == set(['Not Implemented']) and method_name.endswith("multi"):
# some currencies may not have any multi functions defined, so retry
# with private mode (which tries multiple services).
raise RevertToPrivateMode("All services do not implement %s service" % method_name)
failed_msg = ', '.join(
["{service.name} -> {error}".format(**x) for x in self._failed_services]
)
raise NoService(self.no_service_msg(*args, **kwargs) + "! Tried: " + failed_msg)
|
[
"def",
"_try_services",
"(",
"self",
",",
"method_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"crypto",
"=",
"(",
"(",
"args",
"and",
"args",
"[",
"0",
"]",
")",
"or",
"kwargs",
"[",
"'crypto'",
"]",
")",
".",
"lower",
"(",
")",
"address",
"=",
"kwargs",
".",
"get",
"(",
"'address'",
",",
"''",
")",
".",
"lower",
"(",
")",
"fiat",
"=",
"kwargs",
".",
"get",
"(",
"'fiat'",
",",
"''",
")",
".",
"lower",
"(",
")",
"if",
"not",
"self",
".",
"services",
":",
"raise",
"CurrencyNotSupported",
"(",
"\"No services defined for %s for %s\"",
"%",
"(",
"method_name",
",",
"crypto",
")",
")",
"if",
"self",
".",
"random_wait_seconds",
">",
"0",
":",
"# for privacy... To avoid correlating addresses to same origin",
"# only gets called before the first service call. Does not pause",
"# before each and every call.",
"pause_time",
"=",
"random",
".",
"random",
"(",
")",
"*",
"self",
".",
"random_wait_seconds",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Pausing for: %.2f seconds\"",
"%",
"pause_time",
")",
"time",
".",
"sleep",
"(",
"pause_time",
")",
"for",
"service",
"in",
"self",
".",
"services",
":",
"if",
"service",
".",
"supported_cryptos",
"and",
"(",
"crypto",
"not",
"in",
"service",
".",
"supported_cryptos",
")",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"SKIP:\"",
",",
"\"%s not supported for %s\"",
"%",
"(",
"crypto",
",",
"service",
".",
"__class__",
".",
"__name__",
")",
")",
"continue",
"try",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"* Trying:\"",
",",
"service",
",",
"crypto",
",",
"\"%s%s\"",
"%",
"(",
"address",
",",
"fiat",
")",
")",
"ret",
"=",
"getattr",
"(",
"service",
",",
"method_name",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_successful_service",
"=",
"service",
"return",
"ret",
"except",
"(",
"KeyError",
",",
"IndexError",
",",
"TypeError",
",",
"ValueError",
",",
"requests",
".",
"exceptions",
".",
"Timeout",
",",
"requests",
".",
"exceptions",
".",
"ConnectionError",
")",
"as",
"exc",
":",
"# API has probably changed, therefore service class broken",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"FAIL:\"",
",",
"service",
",",
"exc",
".",
"__class__",
".",
"__name__",
",",
"exc",
")",
"self",
".",
"_failed_services",
".",
"append",
"(",
"{",
"'service'",
":",
"service",
",",
"'error'",
":",
"\"%s %s\"",
"%",
"(",
"exc",
".",
"__class__",
".",
"__name__",
",",
"exc",
")",
"}",
")",
"except",
"NoService",
"as",
"exc",
":",
"# service classes can raise this exception if for whatever reason",
"# that service can't return a response, but maybe another one can.",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"SKIP:\"",
",",
"exc",
".",
"__class__",
".",
"__name__",
",",
"exc",
")",
"self",
".",
"_failed_services",
".",
"append",
"(",
"{",
"'service'",
":",
"service",
",",
"'error'",
":",
"\"Skipped: %s\"",
"%",
"str",
"(",
"exc",
")",
"}",
")",
"except",
"NotImplementedError",
"as",
"exc",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"SKIP:\"",
",",
"exc",
".",
"__class__",
".",
"__name__",
",",
"exc",
")",
"self",
".",
"_failed_services",
".",
"append",
"(",
"{",
"'service'",
":",
"service",
",",
"'error'",
":",
"\"Not Implemented\"",
"}",
")",
"if",
"not",
"self",
".",
"_failed_services",
":",
"raise",
"NotImplementedError",
"(",
"\"No Services defined for %s and %s\"",
"%",
"(",
"crypto",
",",
"method_name",
")",
")",
"if",
"set",
"(",
"x",
"[",
"'error'",
"]",
"for",
"x",
"in",
"self",
".",
"_failed_services",
")",
"==",
"set",
"(",
"[",
"'Not Implemented'",
"]",
")",
"and",
"method_name",
".",
"endswith",
"(",
"\"multi\"",
")",
":",
"# some currencies may not have any multi functions defined, so retry",
"# with private mode (which tries multiple services).",
"raise",
"RevertToPrivateMode",
"(",
"\"All services do not implement %s service\"",
"%",
"method_name",
")",
"failed_msg",
"=",
"', '",
".",
"join",
"(",
"[",
"\"{service.name} -> {error}\"",
".",
"format",
"(",
"*",
"*",
"x",
")",
"for",
"x",
"in",
"self",
".",
"_failed_services",
"]",
")",
"raise",
"NoService",
"(",
"self",
".",
"no_service_msg",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"! Tried: \"",
"+",
"failed_msg",
")"
] |
Try each service until one returns a response. This function only
catches the bare minimum of exceptions from the service class. We want
exceptions to be raised so the service classes can be debugged and
fixed quickly.
|
[
"Try",
"each",
"service",
"until",
"one",
"returns",
"a",
"response",
".",
"This",
"function",
"only",
"catches",
"the",
"bare",
"minimum",
"of",
"exceptions",
"from",
"the",
"service",
"class",
".",
"We",
"want",
"exceptions",
"to",
"be",
"raised",
"so",
"the",
"service",
"classes",
"can",
"be",
"debugged",
"and",
"fixed",
"quickly",
"."
] |
00518f1f557dcca8b3031f46d3564c2baa0227a3
|
https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L528-L592
|
14,199
|
yt-project/unyt
|
unyt/array.py
|
uconcatenate
|
def uconcatenate(arrs, axis=0):
"""Concatenate a sequence of arrays.
This wrapper around numpy.concatenate preserves units. All input arrays
must have the same units. See the documentation of numpy.concatenate for
full details.
Examples
--------
>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>> B = [2, 3, 4]*cm
>>> uconcatenate((A, B))
unyt_array([1, 2, 3, 2, 3, 4], 'cm')
"""
v = np.concatenate(arrs, axis=axis)
v = _validate_numpy_wrapper_units(v, arrs)
return v
|
python
|
def uconcatenate(arrs, axis=0):
"""Concatenate a sequence of arrays.
This wrapper around numpy.concatenate preserves units. All input arrays
must have the same units. See the documentation of numpy.concatenate for
full details.
Examples
--------
>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>> B = [2, 3, 4]*cm
>>> uconcatenate((A, B))
unyt_array([1, 2, 3, 2, 3, 4], 'cm')
"""
v = np.concatenate(arrs, axis=axis)
v = _validate_numpy_wrapper_units(v, arrs)
return v
|
[
"def",
"uconcatenate",
"(",
"arrs",
",",
"axis",
"=",
"0",
")",
":",
"v",
"=",
"np",
".",
"concatenate",
"(",
"arrs",
",",
"axis",
"=",
"axis",
")",
"v",
"=",
"_validate_numpy_wrapper_units",
"(",
"v",
",",
"arrs",
")",
"return",
"v"
] |
Concatenate a sequence of arrays.
This wrapper around numpy.concatenate preserves units. All input arrays
must have the same units. See the documentation of numpy.concatenate for
full details.
Examples
--------
>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>> B = [2, 3, 4]*cm
>>> uconcatenate((A, B))
unyt_array([1, 2, 3, 2, 3, 4], 'cm')
|
[
"Concatenate",
"a",
"sequence",
"of",
"arrays",
"."
] |
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
|
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1945-L1963
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.