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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
yt-project/unyt
unyt/array.py
ucross
def ucross(arr1, arr2, registry=None, axisa=-1, axisb=-1, axisc=-1, axis=None): """Applies the cross product to two YT arrays. This wrapper around numpy.cross preserves units. See the documentation of numpy.cross for full details. """ v = np.cross(arr1, arr2, axisa=axisa, axisb=axisb, axisc=axisc, axis=axis) units = arr1.units * arr2.units arr = unyt_array(v, units, registry=registry) return arr
python
def ucross(arr1, arr2, registry=None, axisa=-1, axisb=-1, axisc=-1, axis=None): """Applies the cross product to two YT arrays. This wrapper around numpy.cross preserves units. See the documentation of numpy.cross for full details. """ v = np.cross(arr1, arr2, axisa=axisa, axisb=axisb, axisc=axisc, axis=axis) units = arr1.units * arr2.units arr = unyt_array(v, units, registry=registry) return arr
[ "def", "ucross", "(", "arr1", ",", "arr2", ",", "registry", "=", "None", ",", "axisa", "=", "-", "1", ",", "axisb", "=", "-", "1", ",", "axisc", "=", "-", "1", ",", "axis", "=", "None", ")", ":", "v", "=", "np", ".", "cross", "(", "arr1", ",", "arr2", ",", "axisa", "=", "axisa", ",", "axisb", "=", "axisb", ",", "axisc", "=", "axisc", ",", "axis", "=", "axis", ")", "units", "=", "arr1", ".", "units", "*", "arr2", ".", "units", "arr", "=", "unyt_array", "(", "v", ",", "units", ",", "registry", "=", "registry", ")", "return", "arr" ]
Applies the cross product to two YT arrays. This wrapper around numpy.cross preserves units. See the documentation of numpy.cross for full details.
[ "Applies", "the", "cross", "product", "to", "two", "YT", "arrays", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1966-L1976
train
yt-project/unyt
unyt/array.py
uintersect1d
def uintersect1d(arr1, arr2, assume_unique=False): """Find the sorted unique elements of the two input arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uintersect1d(A, B) unyt_array([2, 3], 'cm') """ v = np.intersect1d(arr1, arr2, assume_unique=assume_unique) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
python
def uintersect1d(arr1, arr2, assume_unique=False): """Find the sorted unique elements of the two input arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uintersect1d(A, B) unyt_array([2, 3], 'cm') """ v = np.intersect1d(arr1, arr2, assume_unique=assume_unique) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
[ "def", "uintersect1d", "(", "arr1", ",", "arr2", ",", "assume_unique", "=", "False", ")", ":", "v", "=", "np", ".", "intersect1d", "(", "arr1", ",", "arr2", ",", "assume_unique", "=", "assume_unique", ")", "v", "=", "_validate_numpy_wrapper_units", "(", "v", ",", "[", "arr1", ",", "arr2", "]", ")", "return", "v" ]
Find the sorted unique elements of the two input arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uintersect1d(A, B) unyt_array([2, 3], 'cm')
[ "Find", "the", "sorted", "unique", "elements", "of", "the", "two", "input", "arrays", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1979-L1997
train
yt-project/unyt
unyt/array.py
uunion1d
def uunion1d(arr1, arr2): """Find the union of two arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uunion1d(A, B) unyt_array([1, 2, 3, 4], 'cm') """ v = np.union1d(arr1, arr2) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
python
def uunion1d(arr1, arr2): """Find the union of two arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uunion1d(A, B) unyt_array([1, 2, 3, 4], 'cm') """ v = np.union1d(arr1, arr2) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
[ "def", "uunion1d", "(", "arr1", ",", "arr2", ")", ":", "v", "=", "np", ".", "union1d", "(", "arr1", ",", "arr2", ")", "v", "=", "_validate_numpy_wrapper_units", "(", "v", ",", "[", "arr1", ",", "arr2", "]", ")", "return", "v" ]
Find the union of two arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uunion1d(A, B) unyt_array([1, 2, 3, 4], 'cm')
[ "Find", "the", "union", "of", "two", "arrays", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2000-L2018
train
yt-project/unyt
unyt/array.py
unorm
def unorm(data, ord=None, axis=None, keepdims=False): """Matrix or vector norm that preserves units This is a wrapper around np.linalg.norm that preserves units. See the documentation for that function for descriptions of the keyword arguments. Examples -------- >>> from unyt import km >>> data = [1, 2, 3]*km >>> print(unorm(data)) 3.7416573867739413 km """ norm = np.linalg.norm(data, ord=ord, axis=axis, keepdims=keepdims) if norm.shape == (): return unyt_quantity(norm, data.units) return unyt_array(norm, data.units)
python
def unorm(data, ord=None, axis=None, keepdims=False): """Matrix or vector norm that preserves units This is a wrapper around np.linalg.norm that preserves units. See the documentation for that function for descriptions of the keyword arguments. Examples -------- >>> from unyt import km >>> data = [1, 2, 3]*km >>> print(unorm(data)) 3.7416573867739413 km """ norm = np.linalg.norm(data, ord=ord, axis=axis, keepdims=keepdims) if norm.shape == (): return unyt_quantity(norm, data.units) return unyt_array(norm, data.units)
[ "def", "unorm", "(", "data", ",", "ord", "=", "None", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "norm", "=", "np", ".", "linalg", ".", "norm", "(", "data", ",", "ord", "=", "ord", ",", "axis", "=", "axis", ",", "keepdims", "=", "keepdims", ")", "if", "norm", ".", "shape", "==", "(", ")", ":", "return", "unyt_quantity", "(", "norm", ",", "data", ".", "units", ")", "return", "unyt_array", "(", "norm", ",", "data", ".", "units", ")" ]
Matrix or vector norm that preserves units This is a wrapper around np.linalg.norm that preserves units. See the documentation for that function for descriptions of the keyword arguments. Examples -------- >>> from unyt import km >>> data = [1, 2, 3]*km >>> print(unorm(data)) 3.7416573867739413 km
[ "Matrix", "or", "vector", "norm", "that", "preserves", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2021-L2038
train
yt-project/unyt
unyt/array.py
udot
def udot(op1, op2): """Matrix or vector dot product that preserves units This is a wrapper around np.dot that preserves units. Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(udot(a, b)) [[2. 2.] [2. 2.]] km*s """ dot = np.dot(op1.d, op2.d) units = op1.units * op2.units if dot.shape == (): return unyt_quantity(dot, units) return unyt_array(dot, units)
python
def udot(op1, op2): """Matrix or vector dot product that preserves units This is a wrapper around np.dot that preserves units. Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(udot(a, b)) [[2. 2.] [2. 2.]] km*s """ dot = np.dot(op1.d, op2.d) units = op1.units * op2.units if dot.shape == (): return unyt_quantity(dot, units) return unyt_array(dot, units)
[ "def", "udot", "(", "op1", ",", "op2", ")", ":", "dot", "=", "np", ".", "dot", "(", "op1", ".", "d", ",", "op2", ".", "d", ")", "units", "=", "op1", ".", "units", "*", "op2", ".", "units", "if", "dot", ".", "shape", "==", "(", ")", ":", "return", "unyt_quantity", "(", "dot", ",", "units", ")", "return", "unyt_array", "(", "dot", ",", "units", ")" ]
Matrix or vector dot product that preserves units This is a wrapper around np.dot that preserves units. Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(udot(a, b)) [[2. 2.] [2. 2.]] km*s
[ "Matrix", "or", "vector", "dot", "product", "that", "preserves", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2041-L2059
train
yt-project/unyt
unyt/array.py
uhstack
def uhstack(arrs): """Stack arrays in sequence horizontally while preserving units This is a wrapper around np.hstack that preserves units. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(uhstack([a, b])) [1 2 3 2 3 4] km >>> a = [[1],[2],[3]]*km >>> b = [[2],[3],[4]]*km >>> print(uhstack([a, b])) [[1 2] [2 3] [3 4]] km """ v = np.hstack(arrs) v = _validate_numpy_wrapper_units(v, arrs) return v
python
def uhstack(arrs): """Stack arrays in sequence horizontally while preserving units This is a wrapper around np.hstack that preserves units. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(uhstack([a, b])) [1 2 3 2 3 4] km >>> a = [[1],[2],[3]]*km >>> b = [[2],[3],[4]]*km >>> print(uhstack([a, b])) [[1 2] [2 3] [3 4]] km """ v = np.hstack(arrs) v = _validate_numpy_wrapper_units(v, arrs) return v
[ "def", "uhstack", "(", "arrs", ")", ":", "v", "=", "np", ".", "hstack", "(", "arrs", ")", "v", "=", "_validate_numpy_wrapper_units", "(", "v", ",", "arrs", ")", "return", "v" ]
Stack arrays in sequence horizontally while preserving units This is a wrapper around np.hstack that preserves units. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(uhstack([a, b])) [1 2 3 2 3 4] km >>> a = [[1],[2],[3]]*km >>> b = [[2],[3],[4]]*km >>> print(uhstack([a, b])) [[1 2] [2 3] [3 4]] km
[ "Stack", "arrays", "in", "sequence", "horizontally", "while", "preserving", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2081-L2102
train
yt-project/unyt
unyt/array.py
ustack
def ustack(arrs, axis=0): """Join a sequence of arrays along a new axis while preserving units The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension. This is a wrapper around np.stack that preserves units. See the documentation for np.stack for full details. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(ustack([a, b])) [[1 2 3] [2 3 4]] km """ v = np.stack(arrs, axis=axis) v = _validate_numpy_wrapper_units(v, arrs) return v
python
def ustack(arrs, axis=0): """Join a sequence of arrays along a new axis while preserving units The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension. This is a wrapper around np.stack that preserves units. See the documentation for np.stack for full details. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(ustack([a, b])) [[1 2 3] [2 3 4]] km """ v = np.stack(arrs, axis=axis) v = _validate_numpy_wrapper_units(v, arrs) return v
[ "def", "ustack", "(", "arrs", ",", "axis", "=", "0", ")", ":", "v", "=", "np", ".", "stack", "(", "arrs", ",", "axis", "=", "axis", ")", "v", "=", "_validate_numpy_wrapper_units", "(", "v", ",", "arrs", ")", "return", "v" ]
Join a sequence of arrays along a new axis while preserving units The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension. This is a wrapper around np.stack that preserves units. See the documentation for np.stack for full details. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(ustack([a, b])) [[1 2 3] [2 3 4]] km
[ "Join", "a", "sequence", "of", "arrays", "along", "a", "new", "axis", "while", "preserving", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2105-L2126
train
yt-project/unyt
unyt/array.py
loadtxt
def loadtxt(fname, dtype="float", delimiter="\t", usecols=None, comments="#"): r""" Load unyt_arrays with unit information from a text file. Each row in the text file must have the same number of values. Parameters ---------- fname : str Filename to read. dtype : data-type, optional Data-type of the resulting array; default: float. delimiter : str, optional The string used to separate values. By default, this is any whitespace. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. comments : str, optional The character used to indicate the start of a comment; default: '#'. Examples -------- >>> temp, velx = loadtxt( ... "sphere.dat", usecols=(1,2), delimiter="\t") # doctest: +SKIP """ f = open(fname, "r") next_one = False units = [] num_cols = -1 for line in f.readlines(): words = line.strip().split() if len(words) == 0: continue if line[0] == comments: if next_one: units = words[1:] if len(words) == 2 and words[1] == "Units": next_one = True else: # Here we catch the first line of numbers col_words = line.strip().split(delimiter) for word in col_words: float(word) num_cols = len(col_words) break f.close() if len(units) != num_cols: units = ["dimensionless"] * num_cols arrays = np.loadtxt( fname, dtype=dtype, comments=comments, delimiter=delimiter, converters=None, unpack=True, usecols=usecols, ndmin=0, ) if len(arrays.shape) < 2: arrays = [arrays] if usecols is not None: units = [units[col] for col in usecols] ret = tuple([unyt_array(arr, unit) for arr, unit in zip(arrays, units)]) if len(ret) == 1: return ret[0] return ret
python
def loadtxt(fname, dtype="float", delimiter="\t", usecols=None, comments="#"): r""" Load unyt_arrays with unit information from a text file. Each row in the text file must have the same number of values. Parameters ---------- fname : str Filename to read. dtype : data-type, optional Data-type of the resulting array; default: float. delimiter : str, optional The string used to separate values. By default, this is any whitespace. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. comments : str, optional The character used to indicate the start of a comment; default: '#'. Examples -------- >>> temp, velx = loadtxt( ... "sphere.dat", usecols=(1,2), delimiter="\t") # doctest: +SKIP """ f = open(fname, "r") next_one = False units = [] num_cols = -1 for line in f.readlines(): words = line.strip().split() if len(words) == 0: continue if line[0] == comments: if next_one: units = words[1:] if len(words) == 2 and words[1] == "Units": next_one = True else: # Here we catch the first line of numbers col_words = line.strip().split(delimiter) for word in col_words: float(word) num_cols = len(col_words) break f.close() if len(units) != num_cols: units = ["dimensionless"] * num_cols arrays = np.loadtxt( fname, dtype=dtype, comments=comments, delimiter=delimiter, converters=None, unpack=True, usecols=usecols, ndmin=0, ) if len(arrays.shape) < 2: arrays = [arrays] if usecols is not None: units = [units[col] for col in usecols] ret = tuple([unyt_array(arr, unit) for arr, unit in zip(arrays, units)]) if len(ret) == 1: return ret[0] return ret
[ "def", "loadtxt", "(", "fname", ",", "dtype", "=", "\"float\"", ",", "delimiter", "=", "\"\\t\"", ",", "usecols", "=", "None", ",", "comments", "=", "\"#\"", ")", ":", "f", "=", "open", "(", "fname", ",", "\"r\"", ")", "next_one", "=", "False", "units", "=", "[", "]", "num_cols", "=", "-", "1", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "words", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "if", "len", "(", "words", ")", "==", "0", ":", "continue", "if", "line", "[", "0", "]", "==", "comments", ":", "if", "next_one", ":", "units", "=", "words", "[", "1", ":", "]", "if", "len", "(", "words", ")", "==", "2", "and", "words", "[", "1", "]", "==", "\"Units\"", ":", "next_one", "=", "True", "else", ":", "# Here we catch the first line of numbers", "col_words", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "delimiter", ")", "for", "word", "in", "col_words", ":", "float", "(", "word", ")", "num_cols", "=", "len", "(", "col_words", ")", "break", "f", ".", "close", "(", ")", "if", "len", "(", "units", ")", "!=", "num_cols", ":", "units", "=", "[", "\"dimensionless\"", "]", "*", "num_cols", "arrays", "=", "np", ".", "loadtxt", "(", "fname", ",", "dtype", "=", "dtype", ",", "comments", "=", "comments", ",", "delimiter", "=", "delimiter", ",", "converters", "=", "None", ",", "unpack", "=", "True", ",", "usecols", "=", "usecols", ",", "ndmin", "=", "0", ",", ")", "if", "len", "(", "arrays", ".", "shape", ")", "<", "2", ":", "arrays", "=", "[", "arrays", "]", "if", "usecols", "is", "not", "None", ":", "units", "=", "[", "units", "[", "col", "]", "for", "col", "in", "usecols", "]", "ret", "=", "tuple", "(", "[", "unyt_array", "(", "arr", ",", "unit", ")", "for", "arr", ",", "unit", "in", "zip", "(", "arrays", ",", "units", ")", "]", ")", "if", "len", "(", "ret", ")", "==", "1", ":", "return", "ret", "[", "0", "]", "return", "ret" ]
r""" Load unyt_arrays with unit information from a text file. Each row in the text file must have the same number of values. Parameters ---------- fname : str Filename to read. dtype : data-type, optional Data-type of the resulting array; default: float. delimiter : str, optional The string used to separate values. By default, this is any whitespace. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. comments : str, optional The character used to indicate the start of a comment; default: '#'. Examples -------- >>> temp, velx = loadtxt( ... "sphere.dat", usecols=(1,2), delimiter="\t") # doctest: +SKIP
[ "r", "Load", "unyt_arrays", "with", "unit", "information", "from", "a", "text", "file", ".", "Each", "row", "in", "the", "text", "file", "must", "have", "the", "same", "number", "of", "values", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2155-L2222
train
yt-project/unyt
unyt/array.py
savetxt
def savetxt( fname, arrays, fmt="%.18e", delimiter="\t", header="", footer="", comments="#" ): r""" Write unyt_arrays with unit information to a text file. Parameters ---------- fname : str The file to write the unyt_arrays to. arrays : list of unyt_arrays or single unyt_array The array(s) to write to the file. fmt : str or sequence of strs, optional A single format (%10.5f), or a sequence of formats. delimiter : str, optional String or character separating columns. header : str, optional String that will be written at the beginning of the file, before the unit header. footer : str, optional String that will be written at the end of the file. comments : str, optional String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# ', as expected by e.g. ``unyt.loadtxt``. Examples -------- >>> import unyt as u >>> a = [1, 2, 3]*u.cm >>> b = [8, 10, 12]*u.cm/u.s >>> c = [2, 85, 9]*u.g >>> savetxt("sphere.dat", [a,b,c], header='My sphere stuff', ... delimiter="\t") # doctest: +SKIP """ if not isinstance(arrays, list): arrays = [arrays] units = [] for array in arrays: if hasattr(array, "units"): units.append(str(array.units)) else: units.append("dimensionless") if header != "" and not header.endswith("\n"): header += "\n" header += " Units\n " + "\t".join(units) np.savetxt( fname, np.transpose(arrays), header=header, fmt=fmt, delimiter=delimiter, footer=footer, newline="\n", comments=comments, )
python
def savetxt( fname, arrays, fmt="%.18e", delimiter="\t", header="", footer="", comments="#" ): r""" Write unyt_arrays with unit information to a text file. Parameters ---------- fname : str The file to write the unyt_arrays to. arrays : list of unyt_arrays or single unyt_array The array(s) to write to the file. fmt : str or sequence of strs, optional A single format (%10.5f), or a sequence of formats. delimiter : str, optional String or character separating columns. header : str, optional String that will be written at the beginning of the file, before the unit header. footer : str, optional String that will be written at the end of the file. comments : str, optional String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# ', as expected by e.g. ``unyt.loadtxt``. Examples -------- >>> import unyt as u >>> a = [1, 2, 3]*u.cm >>> b = [8, 10, 12]*u.cm/u.s >>> c = [2, 85, 9]*u.g >>> savetxt("sphere.dat", [a,b,c], header='My sphere stuff', ... delimiter="\t") # doctest: +SKIP """ if not isinstance(arrays, list): arrays = [arrays] units = [] for array in arrays: if hasattr(array, "units"): units.append(str(array.units)) else: units.append("dimensionless") if header != "" and not header.endswith("\n"): header += "\n" header += " Units\n " + "\t".join(units) np.savetxt( fname, np.transpose(arrays), header=header, fmt=fmt, delimiter=delimiter, footer=footer, newline="\n", comments=comments, )
[ "def", "savetxt", "(", "fname", ",", "arrays", ",", "fmt", "=", "\"%.18e\"", ",", "delimiter", "=", "\"\\t\"", ",", "header", "=", "\"\"", ",", "footer", "=", "\"\"", ",", "comments", "=", "\"#\"", ")", ":", "if", "not", "isinstance", "(", "arrays", ",", "list", ")", ":", "arrays", "=", "[", "arrays", "]", "units", "=", "[", "]", "for", "array", "in", "arrays", ":", "if", "hasattr", "(", "array", ",", "\"units\"", ")", ":", "units", ".", "append", "(", "str", "(", "array", ".", "units", ")", ")", "else", ":", "units", ".", "append", "(", "\"dimensionless\"", ")", "if", "header", "!=", "\"\"", "and", "not", "header", ".", "endswith", "(", "\"\\n\"", ")", ":", "header", "+=", "\"\\n\"", "header", "+=", "\" Units\\n \"", "+", "\"\\t\"", ".", "join", "(", "units", ")", "np", ".", "savetxt", "(", "fname", ",", "np", ".", "transpose", "(", "arrays", ")", ",", "header", "=", "header", ",", "fmt", "=", "fmt", ",", "delimiter", "=", "delimiter", ",", "footer", "=", "footer", ",", "newline", "=", "\"\\n\"", ",", "comments", "=", "comments", ",", ")" ]
r""" Write unyt_arrays with unit information to a text file. Parameters ---------- fname : str The file to write the unyt_arrays to. arrays : list of unyt_arrays or single unyt_array The array(s) to write to the file. fmt : str or sequence of strs, optional A single format (%10.5f), or a sequence of formats. delimiter : str, optional String or character separating columns. header : str, optional String that will be written at the beginning of the file, before the unit header. footer : str, optional String that will be written at the end of the file. comments : str, optional String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# ', as expected by e.g. ``unyt.loadtxt``. Examples -------- >>> import unyt as u >>> a = [1, 2, 3]*u.cm >>> b = [8, 10, 12]*u.cm/u.s >>> c = [2, 85, 9]*u.g >>> savetxt("sphere.dat", [a,b,c], header='My sphere stuff', ... delimiter="\t") # doctest: +SKIP
[ "r", "Write", "unyt_arrays", "with", "unit", "information", "to", "a", "text", "file", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2225-L2280
train
yt-project/unyt
unyt/array.py
unyt_array.convert_to_units
def convert_to_units(self, units, equivalence=None, **kwargs): """ Convert the array to the given units in-place. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- units : Unit object or string The units you want to convert to. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import cm, km >>> length = [3000, 2000, 1000]*cm >>> length.convert_to_units('m') >>> print(length) [30. 20. 10.] m """ units = _sanitize_units_convert(units, self.units.registry) if equivalence is None: conv_data = _check_em_conversion( self.units, units, registry=self.units.registry ) if any(conv_data): new_units, (conv_factor, offset) = _em_conversion( self.units, conv_data, units ) else: new_units = units (conv_factor, offset) = self.units.get_conversion_factor( new_units, self.dtype ) self.units = new_units values = self.d # if our dtype is an integer do the following somewhat awkward # dance to change the dtype in-place. We can't use astype # directly because that will create a copy and not update self if self.dtype.kind in ("u", "i"): # create a copy of the original data in floating point # form, it's possible this may lose precision for very # large integers dsize = values.dtype.itemsize new_dtype = "f" + str(dsize) large = LARGE_INPUT.get(dsize, 0) if large and np.any(np.abs(values) > large): warnings.warn( "Overflow encountered while converting to units '%s'" % new_units, RuntimeWarning, stacklevel=2, ) float_values = values.astype(new_dtype) # change the dtypes in-place, this does not change the # underlying memory buffer values.dtype = new_dtype self.dtype = new_dtype # actually fill in the new float values now that our # dtype is correct np.copyto(values, float_values) values *= conv_factor if offset: np.subtract(values, offset, values) else: self.convert_to_equivalent(units, equivalence, **kwargs)
python
def convert_to_units(self, units, equivalence=None, **kwargs): """ Convert the array to the given units in-place. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- units : Unit object or string The units you want to convert to. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import cm, km >>> length = [3000, 2000, 1000]*cm >>> length.convert_to_units('m') >>> print(length) [30. 20. 10.] m """ units = _sanitize_units_convert(units, self.units.registry) if equivalence is None: conv_data = _check_em_conversion( self.units, units, registry=self.units.registry ) if any(conv_data): new_units, (conv_factor, offset) = _em_conversion( self.units, conv_data, units ) else: new_units = units (conv_factor, offset) = self.units.get_conversion_factor( new_units, self.dtype ) self.units = new_units values = self.d # if our dtype is an integer do the following somewhat awkward # dance to change the dtype in-place. We can't use astype # directly because that will create a copy and not update self if self.dtype.kind in ("u", "i"): # create a copy of the original data in floating point # form, it's possible this may lose precision for very # large integers dsize = values.dtype.itemsize new_dtype = "f" + str(dsize) large = LARGE_INPUT.get(dsize, 0) if large and np.any(np.abs(values) > large): warnings.warn( "Overflow encountered while converting to units '%s'" % new_units, RuntimeWarning, stacklevel=2, ) float_values = values.astype(new_dtype) # change the dtypes in-place, this does not change the # underlying memory buffer values.dtype = new_dtype self.dtype = new_dtype # actually fill in the new float values now that our # dtype is correct np.copyto(values, float_values) values *= conv_factor if offset: np.subtract(values, offset, values) else: self.convert_to_equivalent(units, equivalence, **kwargs)
[ "def", "convert_to_units", "(", "self", ",", "units", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "units", "=", "_sanitize_units_convert", "(", "units", ",", "self", ".", "units", ".", "registry", ")", "if", "equivalence", "is", "None", ":", "conv_data", "=", "_check_em_conversion", "(", "self", ".", "units", ",", "units", ",", "registry", "=", "self", ".", "units", ".", "registry", ")", "if", "any", "(", "conv_data", ")", ":", "new_units", ",", "(", "conv_factor", ",", "offset", ")", "=", "_em_conversion", "(", "self", ".", "units", ",", "conv_data", ",", "units", ")", "else", ":", "new_units", "=", "units", "(", "conv_factor", ",", "offset", ")", "=", "self", ".", "units", ".", "get_conversion_factor", "(", "new_units", ",", "self", ".", "dtype", ")", "self", ".", "units", "=", "new_units", "values", "=", "self", ".", "d", "# if our dtype is an integer do the following somewhat awkward", "# dance to change the dtype in-place. We can't use astype", "# directly because that will create a copy and not update self", "if", "self", ".", "dtype", ".", "kind", "in", "(", "\"u\"", ",", "\"i\"", ")", ":", "# create a copy of the original data in floating point", "# form, it's possible this may lose precision for very", "# large integers", "dsize", "=", "values", ".", "dtype", ".", "itemsize", "new_dtype", "=", "\"f\"", "+", "str", "(", "dsize", ")", "large", "=", "LARGE_INPUT", ".", "get", "(", "dsize", ",", "0", ")", "if", "large", "and", "np", ".", "any", "(", "np", ".", "abs", "(", "values", ")", ">", "large", ")", ":", "warnings", ".", "warn", "(", "\"Overflow encountered while converting to units '%s'\"", "%", "new_units", ",", "RuntimeWarning", ",", "stacklevel", "=", "2", ",", ")", "float_values", "=", "values", ".", "astype", "(", "new_dtype", ")", "# change the dtypes in-place, this does not change the", "# underlying memory buffer", "values", ".", "dtype", "=", "new_dtype", "self", ".", "dtype", "=", "new_dtype", "# actually fill in the new float values now that our", "# dtype is correct", "np", ".", "copyto", "(", "values", ",", "float_values", ")", "values", "*=", "conv_factor", "if", "offset", ":", "np", ".", "subtract", "(", "values", ",", "offset", ",", "values", ")", "else", ":", "self", ".", "convert_to_equivalent", "(", "units", ",", "equivalence", ",", "*", "*", "kwargs", ")" ]
Convert the array to the given units in-place. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- units : Unit object or string The units you want to convert to. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import cm, km >>> length = [3000, 2000, 1000]*cm >>> length.convert_to_units('m') >>> print(length) [30. 20. 10.] m
[ "Convert", "the", "array", "to", "the", "given", "units", "in", "-", "place", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L552-L631
train
yt-project/unyt
unyt/array.py
unyt_array.convert_to_base
def convert_to_base(self, unit_system=None, equivalence=None, **kwargs): """ Convert the array in-place to the equivalent base units in the specified unit system. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured base units are used (defaults to MKS). equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> E.convert_to_base("mks") >>> E unyt_quantity(2.5e-07, 'W') """ self.convert_to_units( self.units.get_base_equivalent(unit_system), equivalence=equivalence, **kwargs )
python
def convert_to_base(self, unit_system=None, equivalence=None, **kwargs): """ Convert the array in-place to the equivalent base units in the specified unit system. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured base units are used (defaults to MKS). equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> E.convert_to_base("mks") >>> E unyt_quantity(2.5e-07, 'W') """ self.convert_to_units( self.units.get_base_equivalent(unit_system), equivalence=equivalence, **kwargs )
[ "def", "convert_to_base", "(", "self", ",", "unit_system", "=", "None", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "convert_to_units", "(", "self", ".", "units", ".", "get_base_equivalent", "(", "unit_system", ")", ",", "equivalence", "=", "equivalence", ",", "*", "*", "kwargs", ")" ]
Convert the array in-place to the equivalent base units in the specified unit system. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured base units are used (defaults to MKS). equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> E.convert_to_base("mks") >>> E unyt_quantity(2.5e-07, 'W')
[ "Convert", "the", "array", "in", "-", "place", "to", "the", "equivalent", "base", "units", "in", "the", "specified", "unit", "system", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L633-L670
train
yt-project/unyt
unyt/array.py
unyt_array.convert_to_cgs
def convert_to_cgs(self, equivalence=None, **kwargs): """ Convert the array and in-place to the equivalent cgs units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import Newton >>> data = [1., 2., 3.]*Newton >>> data.convert_to_cgs() >>> data unyt_array([100000., 200000., 300000.], 'dyn') """ self.convert_to_units( self.units.get_cgs_equivalent(), equivalence=equivalence, **kwargs )
python
def convert_to_cgs(self, equivalence=None, **kwargs): """ Convert the array and in-place to the equivalent cgs units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import Newton >>> data = [1., 2., 3.]*Newton >>> data.convert_to_cgs() >>> data unyt_array([100000., 200000., 300000.], 'dyn') """ self.convert_to_units( self.units.get_cgs_equivalent(), equivalence=equivalence, **kwargs )
[ "def", "convert_to_cgs", "(", "self", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "convert_to_units", "(", "self", ".", "units", ".", "get_cgs_equivalent", "(", ")", ",", "equivalence", "=", "equivalence", ",", "*", "*", "kwargs", ")" ]
Convert the array and in-place to the equivalent cgs units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import Newton >>> data = [1., 2., 3.]*Newton >>> data.convert_to_cgs() >>> data unyt_array([100000., 200000., 300000.], 'dyn')
[ "Convert", "the", "array", "and", "in", "-", "place", "to", "the", "equivalent", "cgs", "units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L672-L704
train
yt-project/unyt
unyt/array.py
unyt_array.convert_to_mks
def convert_to_mks(self, equivalence=None, **kwargs): """ Convert the array and units to the equivalent mks units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import dyne, erg >>> data = [1., 2., 3.]*erg >>> data unyt_array([1., 2., 3.], 'erg') >>> data.convert_to_mks() >>> data unyt_array([1.e-07, 2.e-07, 3.e-07], 'J') """ self.convert_to_units(self.units.get_mks_equivalent(), equivalence, **kwargs)
python
def convert_to_mks(self, equivalence=None, **kwargs): """ Convert the array and units to the equivalent mks units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import dyne, erg >>> data = [1., 2., 3.]*erg >>> data unyt_array([1., 2., 3.], 'erg') >>> data.convert_to_mks() >>> data unyt_array([1.e-07, 2.e-07, 3.e-07], 'J') """ self.convert_to_units(self.units.get_mks_equivalent(), equivalence, **kwargs)
[ "def", "convert_to_mks", "(", "self", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "convert_to_units", "(", "self", ".", "units", ".", "get_mks_equivalent", "(", ")", ",", "equivalence", ",", "*", "*", "kwargs", ")" ]
Convert the array and units to the equivalent mks units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import dyne, erg >>> data = [1., 2., 3.]*erg >>> data unyt_array([1., 2., 3.], 'erg') >>> data.convert_to_mks() >>> data unyt_array([1.e-07, 2.e-07, 3.e-07], 'J')
[ "Convert", "the", "array", "and", "units", "to", "the", "equivalent", "mks", "units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L706-L737
train
yt-project/unyt
unyt/array.py
unyt_array.to_value
def to_value(self, units=None, equivalence=None, **kwargs): """ Creates a copy of this array with the data in the supplied units, and returns it without units. Output is therefore a bare NumPy array. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. .. note:: All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them. Parameters ---------- units : Unit object or string, optional The units you want to get the bare quantity in. If not specified, the value will be returned in the current units. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this unitful quantity, try the :meth:`list_equivalencies` method. Default: None Examples -------- >>> from unyt import km >>> a = [3, 4, 5]*km >>> print(a.to_value('cm')) [300000. 400000. 500000.] """ if units is None: v = self.value else: v = self.in_units(units, equivalence=equivalence, **kwargs).value if isinstance(self, unyt_quantity): return float(v) else: return v
python
def to_value(self, units=None, equivalence=None, **kwargs): """ Creates a copy of this array with the data in the supplied units, and returns it without units. Output is therefore a bare NumPy array. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. .. note:: All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them. Parameters ---------- units : Unit object or string, optional The units you want to get the bare quantity in. If not specified, the value will be returned in the current units. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this unitful quantity, try the :meth:`list_equivalencies` method. Default: None Examples -------- >>> from unyt import km >>> a = [3, 4, 5]*km >>> print(a.to_value('cm')) [300000. 400000. 500000.] """ if units is None: v = self.value else: v = self.in_units(units, equivalence=equivalence, **kwargs).value if isinstance(self, unyt_quantity): return float(v) else: return v
[ "def", "to_value", "(", "self", ",", "units", "=", "None", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "units", "is", "None", ":", "v", "=", "self", ".", "value", "else", ":", "v", "=", "self", ".", "in_units", "(", "units", ",", "equivalence", "=", "equivalence", ",", "*", "*", "kwargs", ")", ".", "value", "if", "isinstance", "(", "self", ",", "unyt_quantity", ")", ":", "return", "float", "(", "v", ")", "else", ":", "return", "v" ]
Creates a copy of this array with the data in the supplied units, and returns it without units. Output is therefore a bare NumPy array. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. .. note:: All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them. Parameters ---------- units : Unit object or string, optional The units you want to get the bare quantity in. If not specified, the value will be returned in the current units. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this unitful quantity, try the :meth:`list_equivalencies` method. Default: None Examples -------- >>> from unyt import km >>> a = [3, 4, 5]*km >>> print(a.to_value('cm')) [300000. 400000. 500000.]
[ "Creates", "a", "copy", "of", "this", "array", "with", "the", "data", "in", "the", "supplied", "units", "and", "returns", "it", "without", "units", ".", "Output", "is", "therefore", "a", "bare", "NumPy", "array", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L855-L896
train
yt-project/unyt
unyt/array.py
unyt_array.in_base
def in_base(self, unit_system=None): """ Creates a copy of this array with the data in the specified unit system, and returns it in that system's base units. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured default base units of are used (defaults to MKS). Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> print(E.in_base("mks")) 2.5e-07 W """ us = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, unit_system=us, registry=self.units.registry ) except MKSCGSConversionError: raise UnitsNotReducible(self.units, us) if any(conv_data): to_units, (conv, offset) = _em_conversion( self.units, conv_data, unit_system=us ) else: to_units = self.units.get_base_equivalent(unit_system) conv, offset = self.units.get_conversion_factor(to_units, self.dtype) new_dtype = np.dtype("f" + str(self.dtype.itemsize)) conv = new_dtype.type(conv) ret = self.v * conv if offset: ret = ret - offset return type(self)(ret, to_units)
python
def in_base(self, unit_system=None): """ Creates a copy of this array with the data in the specified unit system, and returns it in that system's base units. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured default base units of are used (defaults to MKS). Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> print(E.in_base("mks")) 2.5e-07 W """ us = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, unit_system=us, registry=self.units.registry ) except MKSCGSConversionError: raise UnitsNotReducible(self.units, us) if any(conv_data): to_units, (conv, offset) = _em_conversion( self.units, conv_data, unit_system=us ) else: to_units = self.units.get_base_equivalent(unit_system) conv, offset = self.units.get_conversion_factor(to_units, self.dtype) new_dtype = np.dtype("f" + str(self.dtype.itemsize)) conv = new_dtype.type(conv) ret = self.v * conv if offset: ret = ret - offset return type(self)(ret, to_units)
[ "def", "in_base", "(", "self", ",", "unit_system", "=", "None", ")", ":", "us", "=", "_sanitize_unit_system", "(", "unit_system", ",", "self", ")", "try", ":", "conv_data", "=", "_check_em_conversion", "(", "self", ".", "units", ",", "unit_system", "=", "us", ",", "registry", "=", "self", ".", "units", ".", "registry", ")", "except", "MKSCGSConversionError", ":", "raise", "UnitsNotReducible", "(", "self", ".", "units", ",", "us", ")", "if", "any", "(", "conv_data", ")", ":", "to_units", ",", "(", "conv", ",", "offset", ")", "=", "_em_conversion", "(", "self", ".", "units", ",", "conv_data", ",", "unit_system", "=", "us", ")", "else", ":", "to_units", "=", "self", ".", "units", ".", "get_base_equivalent", "(", "unit_system", ")", "conv", ",", "offset", "=", "self", ".", "units", ".", "get_conversion_factor", "(", "to_units", ",", "self", ".", "dtype", ")", "new_dtype", "=", "np", ".", "dtype", "(", "\"f\"", "+", "str", "(", "self", ".", "dtype", ".", "itemsize", ")", ")", "conv", "=", "new_dtype", ".", "type", "(", "conv", ")", "ret", "=", "self", ".", "v", "*", "conv", "if", "offset", ":", "ret", "=", "ret", "-", "offset", "return", "type", "(", "self", ")", "(", "ret", ",", "to_units", ")" ]
Creates a copy of this array with the data in the specified unit system, and returns it in that system's base units. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured default base units of are used (defaults to MKS). Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> print(E.in_base("mks")) 2.5e-07 W
[ "Creates", "a", "copy", "of", "this", "array", "with", "the", "data", "in", "the", "specified", "unit", "system", "and", "returns", "it", "in", "that", "system", "s", "base", "units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L898-L935
train
yt-project/unyt
unyt/array.py
unyt_array.argsort
def argsort(self, axis=-1, kind="quicksort", order=None): """ Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments. Example ------- >>> from unyt import km >>> data = [3, 8, 7]*km >>> print(np.argsort(data)) [0 2 1] >>> print(data.argsort()) [0 2 1] """ return self.view(np.ndarray).argsort(axis, kind, order)
python
def argsort(self, axis=-1, kind="quicksort", order=None): """ Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments. Example ------- >>> from unyt import km >>> data = [3, 8, 7]*km >>> print(np.argsort(data)) [0 2 1] >>> print(data.argsort()) [0 2 1] """ return self.view(np.ndarray).argsort(axis, kind, order)
[ "def", "argsort", "(", "self", ",", "axis", "=", "-", "1", ",", "kind", "=", "\"quicksort\"", ",", "order", "=", "None", ")", ":", "return", "self", ".", "view", "(", "np", ".", "ndarray", ")", ".", "argsort", "(", "axis", ",", "kind", ",", "order", ")" ]
Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments. Example ------- >>> from unyt import km >>> data = [3, 8, 7]*km >>> print(np.argsort(data)) [0 2 1] >>> print(data.argsort()) [0 2 1]
[ "Returns", "the", "indices", "that", "would", "sort", "the", "array", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1126-L1142
train
yt-project/unyt
unyt/array.py
unyt_array.from_astropy
def from_astropy(cls, arr, unit_registry=None): """ Convert an AstroPy "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : AstroPy Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Example ------- >>> from astropy.units import km >>> unyt_quantity.from_astropy(km) unyt_quantity(1., 'km') >>> a = [1, 2, 3]*km >>> a <Quantity [1., 2., 3.] km> >>> unyt_array.from_astropy(a) unyt_array([1., 2., 3.], 'km') """ # Converting from AstroPy Quantity try: u = arr.unit _arr = arr except AttributeError: u = arr _arr = 1.0 * u ap_units = [] for base, exponent in zip(u.bases, u.powers): unit_str = base.to_string() # we have to do this because AstroPy is silly and defines # hour as "h" if unit_str == "h": unit_str = "hr" ap_units.append("%s**(%s)" % (unit_str, Rational(exponent))) ap_units = "*".join(ap_units) if isinstance(_arr.value, np.ndarray) and _arr.shape != (): return unyt_array(_arr.value, ap_units, registry=unit_registry) else: return unyt_quantity(_arr.value, ap_units, registry=unit_registry)
python
def from_astropy(cls, arr, unit_registry=None): """ Convert an AstroPy "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : AstroPy Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Example ------- >>> from astropy.units import km >>> unyt_quantity.from_astropy(km) unyt_quantity(1., 'km') >>> a = [1, 2, 3]*km >>> a <Quantity [1., 2., 3.] km> >>> unyt_array.from_astropy(a) unyt_array([1., 2., 3.], 'km') """ # Converting from AstroPy Quantity try: u = arr.unit _arr = arr except AttributeError: u = arr _arr = 1.0 * u ap_units = [] for base, exponent in zip(u.bases, u.powers): unit_str = base.to_string() # we have to do this because AstroPy is silly and defines # hour as "h" if unit_str == "h": unit_str = "hr" ap_units.append("%s**(%s)" % (unit_str, Rational(exponent))) ap_units = "*".join(ap_units) if isinstance(_arr.value, np.ndarray) and _arr.shape != (): return unyt_array(_arr.value, ap_units, registry=unit_registry) else: return unyt_quantity(_arr.value, ap_units, registry=unit_registry)
[ "def", "from_astropy", "(", "cls", ",", "arr", ",", "unit_registry", "=", "None", ")", ":", "# Converting from AstroPy Quantity", "try", ":", "u", "=", "arr", ".", "unit", "_arr", "=", "arr", "except", "AttributeError", ":", "u", "=", "arr", "_arr", "=", "1.0", "*", "u", "ap_units", "=", "[", "]", "for", "base", ",", "exponent", "in", "zip", "(", "u", ".", "bases", ",", "u", ".", "powers", ")", ":", "unit_str", "=", "base", ".", "to_string", "(", ")", "# we have to do this because AstroPy is silly and defines", "# hour as \"h\"", "if", "unit_str", "==", "\"h\"", ":", "unit_str", "=", "\"hr\"", "ap_units", ".", "append", "(", "\"%s**(%s)\"", "%", "(", "unit_str", ",", "Rational", "(", "exponent", ")", ")", ")", "ap_units", "=", "\"*\"", ".", "join", "(", "ap_units", ")", "if", "isinstance", "(", "_arr", ".", "value", ",", "np", ".", "ndarray", ")", "and", "_arr", ".", "shape", "!=", "(", ")", ":", "return", "unyt_array", "(", "_arr", ".", "value", ",", "ap_units", ",", "registry", "=", "unit_registry", ")", "else", ":", "return", "unyt_quantity", "(", "_arr", ".", "value", ",", "ap_units", ",", "registry", "=", "unit_registry", ")" ]
Convert an AstroPy "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : AstroPy Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Example ------- >>> from astropy.units import km >>> unyt_quantity.from_astropy(km) unyt_quantity(1., 'km') >>> a = [1, 2, 3]*km >>> a <Quantity [1., 2., 3.] km> >>> unyt_array.from_astropy(a) unyt_array([1., 2., 3.], 'km')
[ "Convert", "an", "AstroPy", "Quantity", "to", "a", "unyt_array", "or", "unyt_quantity", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1145-L1187
train
yt-project/unyt
unyt/array.py
unyt_array.to_astropy
def to_astropy(self, **kwargs): """ Creates a new AstroPy quantity with the same unit information. Example ------- >>> from unyt import g, cm >>> data = [3, 4, 5]*g/cm**3 >>> data.to_astropy() <Quantity [3., 4., 5.] g / cm3> """ return self.value * _astropy.units.Unit(str(self.units), **kwargs)
python
def to_astropy(self, **kwargs): """ Creates a new AstroPy quantity with the same unit information. Example ------- >>> from unyt import g, cm >>> data = [3, 4, 5]*g/cm**3 >>> data.to_astropy() <Quantity [3., 4., 5.] g / cm3> """ return self.value * _astropy.units.Unit(str(self.units), **kwargs)
[ "def", "to_astropy", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "value", "*", "_astropy", ".", "units", ".", "Unit", "(", "str", "(", "self", ".", "units", ")", ",", "*", "*", "kwargs", ")" ]
Creates a new AstroPy quantity with the same unit information. Example ------- >>> from unyt import g, cm >>> data = [3, 4, 5]*g/cm**3 >>> data.to_astropy() <Quantity [3., 4., 5.] g / cm3>
[ "Creates", "a", "new", "AstroPy", "quantity", "with", "the", "same", "unit", "information", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1189-L1200
train
yt-project/unyt
unyt/array.py
unyt_array.from_pint
def from_pint(cls, arr, unit_registry=None): """ Convert a Pint "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : Pint Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Examples -------- >>> from pint import UnitRegistry >>> import numpy as np >>> ureg = UnitRegistry() >>> a = np.arange(4) >>> b = ureg.Quantity(a, "erg/cm**3") >>> b <Quantity([0 1 2 3], 'erg / centimeter ** 3')> >>> c = unyt_array.from_pint(b) >>> c unyt_array([0, 1, 2, 3], 'erg/cm**3') """ p_units = [] for base, exponent in arr._units.items(): bs = convert_pint_units(base) p_units.append("%s**(%s)" % (bs, Rational(exponent))) p_units = "*".join(p_units) if isinstance(arr.magnitude, np.ndarray): return unyt_array(arr.magnitude, p_units, registry=unit_registry) else: return unyt_quantity(arr.magnitude, p_units, registry=unit_registry)
python
def from_pint(cls, arr, unit_registry=None): """ Convert a Pint "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : Pint Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Examples -------- >>> from pint import UnitRegistry >>> import numpy as np >>> ureg = UnitRegistry() >>> a = np.arange(4) >>> b = ureg.Quantity(a, "erg/cm**3") >>> b <Quantity([0 1 2 3], 'erg / centimeter ** 3')> >>> c = unyt_array.from_pint(b) >>> c unyt_array([0, 1, 2, 3], 'erg/cm**3') """ p_units = [] for base, exponent in arr._units.items(): bs = convert_pint_units(base) p_units.append("%s**(%s)" % (bs, Rational(exponent))) p_units = "*".join(p_units) if isinstance(arr.magnitude, np.ndarray): return unyt_array(arr.magnitude, p_units, registry=unit_registry) else: return unyt_quantity(arr.magnitude, p_units, registry=unit_registry)
[ "def", "from_pint", "(", "cls", ",", "arr", ",", "unit_registry", "=", "None", ")", ":", "p_units", "=", "[", "]", "for", "base", ",", "exponent", "in", "arr", ".", "_units", ".", "items", "(", ")", ":", "bs", "=", "convert_pint_units", "(", "base", ")", "p_units", ".", "append", "(", "\"%s**(%s)\"", "%", "(", "bs", ",", "Rational", "(", "exponent", ")", ")", ")", "p_units", "=", "\"*\"", ".", "join", "(", "p_units", ")", "if", "isinstance", "(", "arr", ".", "magnitude", ",", "np", ".", "ndarray", ")", ":", "return", "unyt_array", "(", "arr", ".", "magnitude", ",", "p_units", ",", "registry", "=", "unit_registry", ")", "else", ":", "return", "unyt_quantity", "(", "arr", ".", "magnitude", ",", "p_units", ",", "registry", "=", "unit_registry", ")" ]
Convert a Pint "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : Pint Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Examples -------- >>> from pint import UnitRegistry >>> import numpy as np >>> ureg = UnitRegistry() >>> a = np.arange(4) >>> b = ureg.Quantity(a, "erg/cm**3") >>> b <Quantity([0 1 2 3], 'erg / centimeter ** 3')> >>> c = unyt_array.from_pint(b) >>> c unyt_array([0, 1, 2, 3], 'erg/cm**3')
[ "Convert", "a", "Pint", "Quantity", "to", "a", "unyt_array", "or", "unyt_quantity", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1203-L1236
train
yt-project/unyt
unyt/array.py
unyt_array.to_pint
def to_pint(self, unit_registry=None): """ Convert a unyt_array or unyt_quantity to a Pint Quantity. Parameters ---------- arr : unyt_array or unyt_quantity The unitful quantity to convert from. unit_registry : Pint UnitRegistry, optional The Pint UnitRegistry to use in the conversion. If one is not supplied, the default one will be used. NOTE: This is not the same as a yt UnitRegistry object. Examples -------- >>> from unyt import cm, s >>> a = 4*cm**2/s >>> print(a) 4 cm**2/s >>> a.to_pint() <Quantity(4, 'centimeter ** 2 / second')> """ if unit_registry is None: unit_registry = _pint.UnitRegistry() powers_dict = self.units.expr.as_powers_dict() units = [] for unit, pow in powers_dict.items(): # we have to do this because Pint doesn't recognize # "yr" as "year" if str(unit).endswith("yr") and len(str(unit)) in [2, 3]: unit = str(unit).replace("yr", "year") units.append("%s**(%s)" % (unit, Rational(pow))) units = "*".join(units) return unit_registry.Quantity(self.value, units)
python
def to_pint(self, unit_registry=None): """ Convert a unyt_array or unyt_quantity to a Pint Quantity. Parameters ---------- arr : unyt_array or unyt_quantity The unitful quantity to convert from. unit_registry : Pint UnitRegistry, optional The Pint UnitRegistry to use in the conversion. If one is not supplied, the default one will be used. NOTE: This is not the same as a yt UnitRegistry object. Examples -------- >>> from unyt import cm, s >>> a = 4*cm**2/s >>> print(a) 4 cm**2/s >>> a.to_pint() <Quantity(4, 'centimeter ** 2 / second')> """ if unit_registry is None: unit_registry = _pint.UnitRegistry() powers_dict = self.units.expr.as_powers_dict() units = [] for unit, pow in powers_dict.items(): # we have to do this because Pint doesn't recognize # "yr" as "year" if str(unit).endswith("yr") and len(str(unit)) in [2, 3]: unit = str(unit).replace("yr", "year") units.append("%s**(%s)" % (unit, Rational(pow))) units = "*".join(units) return unit_registry.Quantity(self.value, units)
[ "def", "to_pint", "(", "self", ",", "unit_registry", "=", "None", ")", ":", "if", "unit_registry", "is", "None", ":", "unit_registry", "=", "_pint", ".", "UnitRegistry", "(", ")", "powers_dict", "=", "self", ".", "units", ".", "expr", ".", "as_powers_dict", "(", ")", "units", "=", "[", "]", "for", "unit", ",", "pow", "in", "powers_dict", ".", "items", "(", ")", ":", "# we have to do this because Pint doesn't recognize", "# \"yr\" as \"year\"", "if", "str", "(", "unit", ")", ".", "endswith", "(", "\"yr\"", ")", "and", "len", "(", "str", "(", "unit", ")", ")", "in", "[", "2", ",", "3", "]", ":", "unit", "=", "str", "(", "unit", ")", ".", "replace", "(", "\"yr\"", ",", "\"year\"", ")", "units", ".", "append", "(", "\"%s**(%s)\"", "%", "(", "unit", ",", "Rational", "(", "pow", ")", ")", ")", "units", "=", "\"*\"", ".", "join", "(", "units", ")", "return", "unit_registry", ".", "Quantity", "(", "self", ".", "value", ",", "units", ")" ]
Convert a unyt_array or unyt_quantity to a Pint Quantity. Parameters ---------- arr : unyt_array or unyt_quantity The unitful quantity to convert from. unit_registry : Pint UnitRegistry, optional The Pint UnitRegistry to use in the conversion. If one is not supplied, the default one will be used. NOTE: This is not the same as a yt UnitRegistry object. Examples -------- >>> from unyt import cm, s >>> a = 4*cm**2/s >>> print(a) 4 cm**2/s >>> a.to_pint() <Quantity(4, 'centimeter ** 2 / second')>
[ "Convert", "a", "unyt_array", "or", "unyt_quantity", "to", "a", "Pint", "Quantity", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1238-L1271
train
yt-project/unyt
unyt/array.py
unyt_array.write_hdf5
def write_hdf5(self, filename, dataset_name=None, info=None, group_name=None): r"""Writes a unyt_array to hdf5 file. Parameters ---------- filename: string The filename to create and write a dataset to dataset_name: string The name of the dataset to create in the file. info: dictionary A dictionary of supplementary info to write to append as attributes to the dataset. group_name: string An optional group to write the arrays to. If not specified, the arrays are datasets at the top level by default. Examples -------- >>> from unyt import cm >>> a = [1,2,3]*cm >>> myinfo = {'field':'dinosaurs', 'type':'field_data'} >>> a.write_hdf5('test_array_data.h5', dataset_name='dinosaurs', ... info=myinfo) # doctest: +SKIP """ from unyt._on_demand_imports import _h5py as h5py import pickle if info is None: info = {} info["units"] = str(self.units) info["unit_registry"] = np.void(pickle.dumps(self.units.registry.lut)) if dataset_name is None: dataset_name = "array_data" f = h5py.File(filename) if group_name is not None: if group_name in f: g = f[group_name] else: g = f.create_group(group_name) else: g = f if dataset_name in g.keys(): d = g[dataset_name] # Overwrite without deleting if we can get away with it. if d.shape == self.shape and d.dtype == self.dtype: d[...] = self for k in d.attrs.keys(): del d.attrs[k] else: del f[dataset_name] d = g.create_dataset(dataset_name, data=self) else: d = g.create_dataset(dataset_name, data=self) for k, v in info.items(): d.attrs[k] = v f.close()
python
def write_hdf5(self, filename, dataset_name=None, info=None, group_name=None): r"""Writes a unyt_array to hdf5 file. Parameters ---------- filename: string The filename to create and write a dataset to dataset_name: string The name of the dataset to create in the file. info: dictionary A dictionary of supplementary info to write to append as attributes to the dataset. group_name: string An optional group to write the arrays to. If not specified, the arrays are datasets at the top level by default. Examples -------- >>> from unyt import cm >>> a = [1,2,3]*cm >>> myinfo = {'field':'dinosaurs', 'type':'field_data'} >>> a.write_hdf5('test_array_data.h5', dataset_name='dinosaurs', ... info=myinfo) # doctest: +SKIP """ from unyt._on_demand_imports import _h5py as h5py import pickle if info is None: info = {} info["units"] = str(self.units) info["unit_registry"] = np.void(pickle.dumps(self.units.registry.lut)) if dataset_name is None: dataset_name = "array_data" f = h5py.File(filename) if group_name is not None: if group_name in f: g = f[group_name] else: g = f.create_group(group_name) else: g = f if dataset_name in g.keys(): d = g[dataset_name] # Overwrite without deleting if we can get away with it. if d.shape == self.shape and d.dtype == self.dtype: d[...] = self for k in d.attrs.keys(): del d.attrs[k] else: del f[dataset_name] d = g.create_dataset(dataset_name, data=self) else: d = g.create_dataset(dataset_name, data=self) for k, v in info.items(): d.attrs[k] = v f.close()
[ "def", "write_hdf5", "(", "self", ",", "filename", ",", "dataset_name", "=", "None", ",", "info", "=", "None", ",", "group_name", "=", "None", ")", ":", "from", "unyt", ".", "_on_demand_imports", "import", "_h5py", "as", "h5py", "import", "pickle", "if", "info", "is", "None", ":", "info", "=", "{", "}", "info", "[", "\"units\"", "]", "=", "str", "(", "self", ".", "units", ")", "info", "[", "\"unit_registry\"", "]", "=", "np", ".", "void", "(", "pickle", ".", "dumps", "(", "self", ".", "units", ".", "registry", ".", "lut", ")", ")", "if", "dataset_name", "is", "None", ":", "dataset_name", "=", "\"array_data\"", "f", "=", "h5py", ".", "File", "(", "filename", ")", "if", "group_name", "is", "not", "None", ":", "if", "group_name", "in", "f", ":", "g", "=", "f", "[", "group_name", "]", "else", ":", "g", "=", "f", ".", "create_group", "(", "group_name", ")", "else", ":", "g", "=", "f", "if", "dataset_name", "in", "g", ".", "keys", "(", ")", ":", "d", "=", "g", "[", "dataset_name", "]", "# Overwrite without deleting if we can get away with it.", "if", "d", ".", "shape", "==", "self", ".", "shape", "and", "d", ".", "dtype", "==", "self", ".", "dtype", ":", "d", "[", "...", "]", "=", "self", "for", "k", "in", "d", ".", "attrs", ".", "keys", "(", ")", ":", "del", "d", ".", "attrs", "[", "k", "]", "else", ":", "del", "f", "[", "dataset_name", "]", "d", "=", "g", ".", "create_dataset", "(", "dataset_name", ",", "data", "=", "self", ")", "else", ":", "d", "=", "g", ".", "create_dataset", "(", "dataset_name", ",", "data", "=", "self", ")", "for", "k", ",", "v", "in", "info", ".", "items", "(", ")", ":", "d", ".", "attrs", "[", "k", "]", "=", "v", "f", ".", "close", "(", ")" ]
r"""Writes a unyt_array to hdf5 file. Parameters ---------- filename: string The filename to create and write a dataset to dataset_name: string The name of the dataset to create in the file. info: dictionary A dictionary of supplementary info to write to append as attributes to the dataset. group_name: string An optional group to write the arrays to. If not specified, the arrays are datasets at the top level by default. Examples -------- >>> from unyt import cm >>> a = [1,2,3]*cm >>> myinfo = {'field':'dinosaurs', 'type':'field_data'} >>> a.write_hdf5('test_array_data.h5', dataset_name='dinosaurs', ... info=myinfo) # doctest: +SKIP
[ "r", "Writes", "a", "unyt_array", "to", "hdf5", "file", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1277-L1339
train
yt-project/unyt
unyt/array.py
unyt_array.from_hdf5
def from_hdf5(cls, filename, dataset_name=None, group_name=None): r"""Attempts read in and convert a dataset in an hdf5 file into a unyt_array. Parameters ---------- filename: string The filename to of the hdf5 file. dataset_name: string The name of the dataset to read from. If the dataset has a units attribute, attempt to infer units as well. group_name: string An optional group to read the arrays from. If not specified, the arrays are datasets at the top level by default. """ from unyt._on_demand_imports import _h5py as h5py import pickle if dataset_name is None: dataset_name = "array_data" f = h5py.File(filename) if group_name is not None: g = f[group_name] else: g = f dataset = g[dataset_name] data = dataset[:] units = dataset.attrs.get("units", "") unit_lut = pickle.loads(dataset.attrs["unit_registry"].tostring()) f.close() registry = UnitRegistry(lut=unit_lut, add_default_symbols=False) return cls(data, units, registry=registry)
python
def from_hdf5(cls, filename, dataset_name=None, group_name=None): r"""Attempts read in and convert a dataset in an hdf5 file into a unyt_array. Parameters ---------- filename: string The filename to of the hdf5 file. dataset_name: string The name of the dataset to read from. If the dataset has a units attribute, attempt to infer units as well. group_name: string An optional group to read the arrays from. If not specified, the arrays are datasets at the top level by default. """ from unyt._on_demand_imports import _h5py as h5py import pickle if dataset_name is None: dataset_name = "array_data" f = h5py.File(filename) if group_name is not None: g = f[group_name] else: g = f dataset = g[dataset_name] data = dataset[:] units = dataset.attrs.get("units", "") unit_lut = pickle.loads(dataset.attrs["unit_registry"].tostring()) f.close() registry = UnitRegistry(lut=unit_lut, add_default_symbols=False) return cls(data, units, registry=registry)
[ "def", "from_hdf5", "(", "cls", ",", "filename", ",", "dataset_name", "=", "None", ",", "group_name", "=", "None", ")", ":", "from", "unyt", ".", "_on_demand_imports", "import", "_h5py", "as", "h5py", "import", "pickle", "if", "dataset_name", "is", "None", ":", "dataset_name", "=", "\"array_data\"", "f", "=", "h5py", ".", "File", "(", "filename", ")", "if", "group_name", "is", "not", "None", ":", "g", "=", "f", "[", "group_name", "]", "else", ":", "g", "=", "f", "dataset", "=", "g", "[", "dataset_name", "]", "data", "=", "dataset", "[", ":", "]", "units", "=", "dataset", ".", "attrs", ".", "get", "(", "\"units\"", ",", "\"\"", ")", "unit_lut", "=", "pickle", ".", "loads", "(", "dataset", ".", "attrs", "[", "\"unit_registry\"", "]", ".", "tostring", "(", ")", ")", "f", ".", "close", "(", ")", "registry", "=", "UnitRegistry", "(", "lut", "=", "unit_lut", ",", "add_default_symbols", "=", "False", ")", "return", "cls", "(", "data", ",", "units", ",", "registry", "=", "registry", ")" ]
r"""Attempts read in and convert a dataset in an hdf5 file into a unyt_array. Parameters ---------- filename: string The filename to of the hdf5 file. dataset_name: string The name of the dataset to read from. If the dataset has a units attribute, attempt to infer units as well. group_name: string An optional group to read the arrays from. If not specified, the arrays are datasets at the top level by default.
[ "r", "Attempts", "read", "in", "and", "convert", "a", "dataset", "in", "an", "hdf5", "file", "into", "a", "unyt_array", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1342-L1377
train
yt-project/unyt
unyt/array.py
unyt_array.copy
def copy(self, order="C"): """ Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :func:`numpy.copy` are very similar, but have different default values for their order= arguments.) See also -------- numpy.copy numpy.copyto Examples -------- >>> from unyt import km >>> x = [[1,2,3],[4,5,6]] * km >>> y = x.copy() >>> x.fill(0) >>> print(x) [[0 0 0] [0 0 0]] km >>> print(y) [[1 2 3] [4 5 6]] km """ return type(self)(np.copy(np.asarray(self)), self.units)
python
def copy(self, order="C"): """ Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :func:`numpy.copy` are very similar, but have different default values for their order= arguments.) See also -------- numpy.copy numpy.copyto Examples -------- >>> from unyt import km >>> x = [[1,2,3],[4,5,6]] * km >>> y = x.copy() >>> x.fill(0) >>> print(x) [[0 0 0] [0 0 0]] km >>> print(y) [[1 2 3] [4 5 6]] km """ return type(self)(np.copy(np.asarray(self)), self.units)
[ "def", "copy", "(", "self", ",", "order", "=", "\"C\"", ")", ":", "return", "type", "(", "self", ")", "(", "np", ".", "copy", "(", "np", ".", "asarray", "(", "self", ")", ")", ",", "self", ".", "units", ")" ]
Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :func:`numpy.copy` are very similar, but have different default values for their order= arguments.) See also -------- numpy.copy numpy.copyto Examples -------- >>> from unyt import km >>> x = [[1,2,3],[4,5,6]] * km >>> y = x.copy() >>> x.fill(0) >>> print(x) [[0 0 0] [0 0 0]] km >>> print(y) [[1 2 3] [4 5 6]] km
[ "Return", "a", "copy", "of", "the", "array", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1738-L1772
train
yt-project/unyt
unyt/array.py
unyt_array.dot
def dot(self, b, out=None): """dot product of two arrays. Refer to `numpy.dot` for full documentation. See Also -------- numpy.dot : equivalent function Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(a.dot(b)) [[2. 2.] [2. 2.]] km*s This array method can be conveniently chained: >>> print(a.dot(b).dot(b)) [[8. 8.] [8. 8.]] km*s**2 """ res_units = self.units * getattr(b, "units", NULL_UNIT) ret = self.view(np.ndarray).dot(np.asarray(b), out=out) * res_units if out is not None: out.units = res_units return ret
python
def dot(self, b, out=None): """dot product of two arrays. Refer to `numpy.dot` for full documentation. See Also -------- numpy.dot : equivalent function Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(a.dot(b)) [[2. 2.] [2. 2.]] km*s This array method can be conveniently chained: >>> print(a.dot(b).dot(b)) [[8. 8.] [8. 8.]] km*s**2 """ res_units = self.units * getattr(b, "units", NULL_UNIT) ret = self.view(np.ndarray).dot(np.asarray(b), out=out) * res_units if out is not None: out.units = res_units return ret
[ "def", "dot", "(", "self", ",", "b", ",", "out", "=", "None", ")", ":", "res_units", "=", "self", ".", "units", "*", "getattr", "(", "b", ",", "\"units\"", ",", "NULL_UNIT", ")", "ret", "=", "self", ".", "view", "(", "np", ".", "ndarray", ")", ".", "dot", "(", "np", ".", "asarray", "(", "b", ")", ",", "out", "=", "out", ")", "*", "res_units", "if", "out", "is", "not", "None", ":", "out", ".", "units", "=", "res_units", "return", "ret" ]
dot product of two arrays. Refer to `numpy.dot` for full documentation. See Also -------- numpy.dot : equivalent function Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(a.dot(b)) [[2. 2.] [2. 2.]] km*s This array method can be conveniently chained: >>> print(a.dot(b).dot(b)) [[8. 8.] [8. 8.]] km*s**2
[ "dot", "product", "of", "two", "arrays", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1783-L1811
train
yt-project/unyt
unyt/__init__.py
import_units
def import_units(module, namespace): """Import Unit objects from a module into a namespace""" for key, value in module.__dict__.items(): if isinstance(value, (unyt_quantity, Unit)): namespace[key] = value
python
def import_units(module, namespace): """Import Unit objects from a module into a namespace""" for key, value in module.__dict__.items(): if isinstance(value, (unyt_quantity, Unit)): namespace[key] = value
[ "def", "import_units", "(", "module", ",", "namespace", ")", ":", "for", "key", ",", "value", "in", "module", ".", "__dict__", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "(", "unyt_quantity", ",", "Unit", ")", ")", ":", "namespace", "[", "key", "]", "=", "value" ]
Import Unit objects from a module into a namespace
[ "Import", "Unit", "objects", "from", "a", "module", "into", "a", "namespace" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/__init__.py#L98-L102
train
yt-project/unyt
unyt/unit_registry.py
_lookup_unit_symbol
def _lookup_unit_symbol(symbol_str, unit_symbol_lut): """ Searches for the unit data tuple corresponding to the given symbol. Parameters ---------- symbol_str : str The unit symbol to look up. unit_symbol_lut : dict Dictionary with symbols as keys and unit data tuples as values. """ if symbol_str in unit_symbol_lut: # lookup successful, return the tuple directly return unit_symbol_lut[symbol_str] # could still be a known symbol with a prefix prefix, symbol_wo_prefix = _split_prefix(symbol_str, unit_symbol_lut) if prefix: # lookup successful, it's a symbol with a prefix unit_data = unit_symbol_lut[symbol_wo_prefix] prefix_value = unit_prefixes[prefix][0] # Need to add some special handling for comoving units # this is fine for now, but it wouldn't work for a general # unit that has an arbitrary LaTeX representation if symbol_wo_prefix != "cm" and symbol_wo_prefix.endswith("cm"): sub_symbol_wo_prefix = symbol_wo_prefix[:-2] sub_symbol_str = symbol_str[:-2] else: sub_symbol_wo_prefix = symbol_wo_prefix sub_symbol_str = symbol_str latex_repr = unit_data[3].replace( "{" + sub_symbol_wo_prefix + "}", "{" + sub_symbol_str + "}" ) # Leave offset and dimensions the same, but adjust scale factor and # LaTeX representation ret = ( unit_data[0] * prefix_value, unit_data[1], unit_data[2], latex_repr, False, ) unit_symbol_lut[symbol_str] = ret return ret # no dice raise UnitParseError( "Could not find unit symbol '%s' in the provided " "symbols." % symbol_str )
python
def _lookup_unit_symbol(symbol_str, unit_symbol_lut): """ Searches for the unit data tuple corresponding to the given symbol. Parameters ---------- symbol_str : str The unit symbol to look up. unit_symbol_lut : dict Dictionary with symbols as keys and unit data tuples as values. """ if symbol_str in unit_symbol_lut: # lookup successful, return the tuple directly return unit_symbol_lut[symbol_str] # could still be a known symbol with a prefix prefix, symbol_wo_prefix = _split_prefix(symbol_str, unit_symbol_lut) if prefix: # lookup successful, it's a symbol with a prefix unit_data = unit_symbol_lut[symbol_wo_prefix] prefix_value = unit_prefixes[prefix][0] # Need to add some special handling for comoving units # this is fine for now, but it wouldn't work for a general # unit that has an arbitrary LaTeX representation if symbol_wo_prefix != "cm" and symbol_wo_prefix.endswith("cm"): sub_symbol_wo_prefix = symbol_wo_prefix[:-2] sub_symbol_str = symbol_str[:-2] else: sub_symbol_wo_prefix = symbol_wo_prefix sub_symbol_str = symbol_str latex_repr = unit_data[3].replace( "{" + sub_symbol_wo_prefix + "}", "{" + sub_symbol_str + "}" ) # Leave offset and dimensions the same, but adjust scale factor and # LaTeX representation ret = ( unit_data[0] * prefix_value, unit_data[1], unit_data[2], latex_repr, False, ) unit_symbol_lut[symbol_str] = ret return ret # no dice raise UnitParseError( "Could not find unit symbol '%s' in the provided " "symbols." % symbol_str )
[ "def", "_lookup_unit_symbol", "(", "symbol_str", ",", "unit_symbol_lut", ")", ":", "if", "symbol_str", "in", "unit_symbol_lut", ":", "# lookup successful, return the tuple directly", "return", "unit_symbol_lut", "[", "symbol_str", "]", "# could still be a known symbol with a prefix", "prefix", ",", "symbol_wo_prefix", "=", "_split_prefix", "(", "symbol_str", ",", "unit_symbol_lut", ")", "if", "prefix", ":", "# lookup successful, it's a symbol with a prefix", "unit_data", "=", "unit_symbol_lut", "[", "symbol_wo_prefix", "]", "prefix_value", "=", "unit_prefixes", "[", "prefix", "]", "[", "0", "]", "# Need to add some special handling for comoving units", "# this is fine for now, but it wouldn't work for a general", "# unit that has an arbitrary LaTeX representation", "if", "symbol_wo_prefix", "!=", "\"cm\"", "and", "symbol_wo_prefix", ".", "endswith", "(", "\"cm\"", ")", ":", "sub_symbol_wo_prefix", "=", "symbol_wo_prefix", "[", ":", "-", "2", "]", "sub_symbol_str", "=", "symbol_str", "[", ":", "-", "2", "]", "else", ":", "sub_symbol_wo_prefix", "=", "symbol_wo_prefix", "sub_symbol_str", "=", "symbol_str", "latex_repr", "=", "unit_data", "[", "3", "]", ".", "replace", "(", "\"{\"", "+", "sub_symbol_wo_prefix", "+", "\"}\"", ",", "\"{\"", "+", "sub_symbol_str", "+", "\"}\"", ")", "# Leave offset and dimensions the same, but adjust scale factor and", "# LaTeX representation", "ret", "=", "(", "unit_data", "[", "0", "]", "*", "prefix_value", ",", "unit_data", "[", "1", "]", ",", "unit_data", "[", "2", "]", ",", "latex_repr", ",", "False", ",", ")", "unit_symbol_lut", "[", "symbol_str", "]", "=", "ret", "return", "ret", "# no dice", "raise", "UnitParseError", "(", "\"Could not find unit symbol '%s' in the provided \"", "\"symbols.\"", "%", "symbol_str", ")" ]
Searches for the unit data tuple corresponding to the given symbol. Parameters ---------- symbol_str : str The unit symbol to look up. unit_symbol_lut : dict Dictionary with symbols as keys and unit data tuples as values.
[ "Searches", "for", "the", "unit", "data", "tuple", "corresponding", "to", "the", "given", "symbol", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L272-L326
train
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.unit_system_id
def unit_system_id(self): """ This is a unique identifier for the unit registry created from a FNV hash. It is needed to register a dataset's code unit system in the unit system registry. """ if self._unit_system_id is None: hash_data = bytearray() for k, v in sorted(self.lut.items()): hash_data.extend(k.encode("utf8")) hash_data.extend(repr(v).encode("utf8")) m = md5() m.update(hash_data) self._unit_system_id = str(m.hexdigest()) return self._unit_system_id
python
def unit_system_id(self): """ This is a unique identifier for the unit registry created from a FNV hash. It is needed to register a dataset's code unit system in the unit system registry. """ if self._unit_system_id is None: hash_data = bytearray() for k, v in sorted(self.lut.items()): hash_data.extend(k.encode("utf8")) hash_data.extend(repr(v).encode("utf8")) m = md5() m.update(hash_data) self._unit_system_id = str(m.hexdigest()) return self._unit_system_id
[ "def", "unit_system_id", "(", "self", ")", ":", "if", "self", ".", "_unit_system_id", "is", "None", ":", "hash_data", "=", "bytearray", "(", ")", "for", "k", ",", "v", "in", "sorted", "(", "self", ".", "lut", ".", "items", "(", ")", ")", ":", "hash_data", ".", "extend", "(", "k", ".", "encode", "(", "\"utf8\"", ")", ")", "hash_data", ".", "extend", "(", "repr", "(", "v", ")", ".", "encode", "(", "\"utf8\"", ")", ")", "m", "=", "md5", "(", ")", "m", ".", "update", "(", "hash_data", ")", "self", ".", "_unit_system_id", "=", "str", "(", "m", ".", "hexdigest", "(", ")", ")", "return", "self", ".", "_unit_system_id" ]
This is a unique identifier for the unit registry created from a FNV hash. It is needed to register a dataset's code unit system in the unit system registry.
[ "This", "is", "a", "unique", "identifier", "for", "the", "unit", "registry", "created", "from", "a", "FNV", "hash", ".", "It", "is", "needed", "to", "register", "a", "dataset", "s", "code", "unit", "system", "in", "the", "unit", "system", "registry", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L82-L96
train
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.add
def add( self, symbol, base_value, dimensions, tex_repr=None, offset=None, prefixable=False, ): """ Add a symbol to this registry. Parameters ---------- symbol : str The name of the unit base_value : float The scaling from the units value to the equivalent SI unit with the same dimensions dimensions : expr The dimensions of the unit tex_repr : str, optional The LaTeX representation of the unit. If not provided a LaTeX representation is automatically generated from the name of the unit. offset : float, optional If set, the zero-point offset to apply to the unit to convert to SI. This is mostly used for units like Farhenheit and Celcius that are not defined on an absolute scale. prefixable : bool If True, then SI-prefix versions of the unit will be created along with the unit itself. """ from unyt.unit_object import _validate_dimensions self._unit_system_id = None # Validate if not isinstance(base_value, float): raise UnitParseError( "base_value (%s) must be a float, got a %s." % (base_value, type(base_value)) ) if offset is not None: if not isinstance(offset, float): raise UnitParseError( "offset value (%s) must be a float, got a %s." % (offset, type(offset)) ) else: offset = 0.0 _validate_dimensions(dimensions) if tex_repr is None: # make educated guess that will look nice in most cases tex_repr = r"\rm{" + symbol.replace("_", r"\ ") + "}" # Add to lut self.lut[symbol] = (base_value, dimensions, offset, tex_repr, prefixable)
python
def add( self, symbol, base_value, dimensions, tex_repr=None, offset=None, prefixable=False, ): """ Add a symbol to this registry. Parameters ---------- symbol : str The name of the unit base_value : float The scaling from the units value to the equivalent SI unit with the same dimensions dimensions : expr The dimensions of the unit tex_repr : str, optional The LaTeX representation of the unit. If not provided a LaTeX representation is automatically generated from the name of the unit. offset : float, optional If set, the zero-point offset to apply to the unit to convert to SI. This is mostly used for units like Farhenheit and Celcius that are not defined on an absolute scale. prefixable : bool If True, then SI-prefix versions of the unit will be created along with the unit itself. """ from unyt.unit_object import _validate_dimensions self._unit_system_id = None # Validate if not isinstance(base_value, float): raise UnitParseError( "base_value (%s) must be a float, got a %s." % (base_value, type(base_value)) ) if offset is not None: if not isinstance(offset, float): raise UnitParseError( "offset value (%s) must be a float, got a %s." % (offset, type(offset)) ) else: offset = 0.0 _validate_dimensions(dimensions) if tex_repr is None: # make educated guess that will look nice in most cases tex_repr = r"\rm{" + symbol.replace("_", r"\ ") + "}" # Add to lut self.lut[symbol] = (base_value, dimensions, offset, tex_repr, prefixable)
[ "def", "add", "(", "self", ",", "symbol", ",", "base_value", ",", "dimensions", ",", "tex_repr", "=", "None", ",", "offset", "=", "None", ",", "prefixable", "=", "False", ",", ")", ":", "from", "unyt", ".", "unit_object", "import", "_validate_dimensions", "self", ".", "_unit_system_id", "=", "None", "# Validate", "if", "not", "isinstance", "(", "base_value", ",", "float", ")", ":", "raise", "UnitParseError", "(", "\"base_value (%s) must be a float, got a %s.\"", "%", "(", "base_value", ",", "type", "(", "base_value", ")", ")", ")", "if", "offset", "is", "not", "None", ":", "if", "not", "isinstance", "(", "offset", ",", "float", ")", ":", "raise", "UnitParseError", "(", "\"offset value (%s) must be a float, got a %s.\"", "%", "(", "offset", ",", "type", "(", "offset", ")", ")", ")", "else", ":", "offset", "=", "0.0", "_validate_dimensions", "(", "dimensions", ")", "if", "tex_repr", "is", "None", ":", "# make educated guess that will look nice in most cases", "tex_repr", "=", "r\"\\rm{\"", "+", "symbol", ".", "replace", "(", "\"_\"", ",", "r\"\\ \"", ")", "+", "\"}\"", "# Add to lut", "self", ".", "lut", "[", "symbol", "]", "=", "(", "base_value", ",", "dimensions", ",", "offset", ",", "tex_repr", ",", "prefixable", ")" ]
Add a symbol to this registry. Parameters ---------- symbol : str The name of the unit base_value : float The scaling from the units value to the equivalent SI unit with the same dimensions dimensions : expr The dimensions of the unit tex_repr : str, optional The LaTeX representation of the unit. If not provided a LaTeX representation is automatically generated from the name of the unit. offset : float, optional If set, the zero-point offset to apply to the unit to convert to SI. This is mostly used for units like Farhenheit and Celcius that are not defined on an absolute scale. prefixable : bool If True, then SI-prefix versions of the unit will be created along with the unit itself.
[ "Add", "a", "symbol", "to", "this", "registry", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L102-L164
train
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.remove
def remove(self, symbol): """ Remove the entry for the unit matching `symbol`. Parameters ---------- symbol : str The name of the unit symbol to remove from the registry. """ self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to remove the symbol '%s', but it does not exist " "in this registry." % symbol ) del self.lut[symbol]
python
def remove(self, symbol): """ Remove the entry for the unit matching `symbol`. Parameters ---------- symbol : str The name of the unit symbol to remove from the registry. """ self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to remove the symbol '%s', but it does not exist " "in this registry." % symbol ) del self.lut[symbol]
[ "def", "remove", "(", "self", ",", "symbol", ")", ":", "self", ".", "_unit_system_id", "=", "None", "if", "symbol", "not", "in", "self", ".", "lut", ":", "raise", "SymbolNotFoundError", "(", "\"Tried to remove the symbol '%s', but it does not exist \"", "\"in this registry.\"", "%", "symbol", ")", "del", "self", ".", "lut", "[", "symbol", "]" ]
Remove the entry for the unit matching `symbol`. Parameters ---------- symbol : str The name of the unit symbol to remove from the registry.
[ "Remove", "the", "entry", "for", "the", "unit", "matching", "symbol", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L166-L185
train
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.modify
def modify(self, symbol, base_value): """ Change the base value of a unit symbol. Useful for adjusting code units after parsing parameters. Parameters ---------- symbol : str The name of the symbol to modify base_value : float The new base_value for the symbol. """ self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to modify the symbol '%s', but it does not exist " "in this registry." % symbol ) if hasattr(base_value, "in_base"): new_dimensions = base_value.units.dimensions base_value = base_value.in_base("mks") base_value = base_value.value else: new_dimensions = self.lut[symbol][1] self.lut[symbol] = (float(base_value), new_dimensions) + self.lut[symbol][2:]
python
def modify(self, symbol, base_value): """ Change the base value of a unit symbol. Useful for adjusting code units after parsing parameters. Parameters ---------- symbol : str The name of the symbol to modify base_value : float The new base_value for the symbol. """ self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to modify the symbol '%s', but it does not exist " "in this registry." % symbol ) if hasattr(base_value, "in_base"): new_dimensions = base_value.units.dimensions base_value = base_value.in_base("mks") base_value = base_value.value else: new_dimensions = self.lut[symbol][1] self.lut[symbol] = (float(base_value), new_dimensions) + self.lut[symbol][2:]
[ "def", "modify", "(", "self", ",", "symbol", ",", "base_value", ")", ":", "self", ".", "_unit_system_id", "=", "None", "if", "symbol", "not", "in", "self", ".", "lut", ":", "raise", "SymbolNotFoundError", "(", "\"Tried to modify the symbol '%s', but it does not exist \"", "\"in this registry.\"", "%", "symbol", ")", "if", "hasattr", "(", "base_value", ",", "\"in_base\"", ")", ":", "new_dimensions", "=", "base_value", ".", "units", ".", "dimensions", "base_value", "=", "base_value", ".", "in_base", "(", "\"mks\"", ")", "base_value", "=", "base_value", ".", "value", "else", ":", "new_dimensions", "=", "self", ".", "lut", "[", "symbol", "]", "[", "1", "]", "self", ".", "lut", "[", "symbol", "]", "=", "(", "float", "(", "base_value", ")", ",", "new_dimensions", ")", "+", "self", ".", "lut", "[", "symbol", "]", "[", "2", ":", "]" ]
Change the base value of a unit symbol. Useful for adjusting code units after parsing parameters. Parameters ---------- symbol : str The name of the symbol to modify base_value : float The new base_value for the symbol.
[ "Change", "the", "base", "value", "of", "a", "unit", "symbol", ".", "Useful", "for", "adjusting", "code", "units", "after", "parsing", "parameters", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L187-L216
train
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.to_json
def to_json(self): """ Returns a json-serialized version of the unit registry """ sanitized_lut = {} for k, v in self.lut.items(): san_v = list(v) repr_dims = str(v[1]) san_v[1] = repr_dims sanitized_lut[k] = tuple(san_v) return json.dumps(sanitized_lut)
python
def to_json(self): """ Returns a json-serialized version of the unit registry """ sanitized_lut = {} for k, v in self.lut.items(): san_v = list(v) repr_dims = str(v[1]) san_v[1] = repr_dims sanitized_lut[k] = tuple(san_v) return json.dumps(sanitized_lut)
[ "def", "to_json", "(", "self", ")", ":", "sanitized_lut", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "lut", ".", "items", "(", ")", ":", "san_v", "=", "list", "(", "v", ")", "repr_dims", "=", "str", "(", "v", "[", "1", "]", ")", "san_v", "[", "1", "]", "=", "repr_dims", "sanitized_lut", "[", "k", "]", "=", "tuple", "(", "san_v", ")", "return", "json", ".", "dumps", "(", "sanitized_lut", ")" ]
Returns a json-serialized version of the unit registry
[ "Returns", "a", "json", "-", "serialized", "version", "of", "the", "unit", "registry" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L225-L236
train
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.from_json
def from_json(cls, json_text): """ Returns a UnitRegistry object from a json-serialized unit registry Parameters ---------- json_text : str A string containing a json represention of a UnitRegistry """ data = json.loads(json_text) lut = {} for k, v in data.items(): unsan_v = list(v) unsan_v[1] = sympify(v[1], locals=vars(unyt_dims)) lut[k] = tuple(unsan_v) return cls(lut=lut, add_default_symbols=False)
python
def from_json(cls, json_text): """ Returns a UnitRegistry object from a json-serialized unit registry Parameters ---------- json_text : str A string containing a json represention of a UnitRegistry """ data = json.loads(json_text) lut = {} for k, v in data.items(): unsan_v = list(v) unsan_v[1] = sympify(v[1], locals=vars(unyt_dims)) lut[k] = tuple(unsan_v) return cls(lut=lut, add_default_symbols=False)
[ "def", "from_json", "(", "cls", ",", "json_text", ")", ":", "data", "=", "json", ".", "loads", "(", "json_text", ")", "lut", "=", "{", "}", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "unsan_v", "=", "list", "(", "v", ")", "unsan_v", "[", "1", "]", "=", "sympify", "(", "v", "[", "1", "]", ",", "locals", "=", "vars", "(", "unyt_dims", ")", ")", "lut", "[", "k", "]", "=", "tuple", "(", "unsan_v", ")", "return", "cls", "(", "lut", "=", "lut", ",", "add_default_symbols", "=", "False", ")" ]
Returns a UnitRegistry object from a json-serialized unit registry Parameters ---------- json_text : str A string containing a json represention of a UnitRegistry
[ "Returns", "a", "UnitRegistry", "object", "from", "a", "json", "-", "serialized", "unit", "registry" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L239-L256
train
yt-project/unyt
unyt/unit_object.py
_em_conversion
def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None): """Convert between E&M & MKS base units. If orig_units is a CGS (or MKS) E&M unit, conv_data contains the corresponding MKS (or CGS) unit and scale factor converting between them. This must be done by replacing the expression of the original unit with the new one in the unit expression and multiplying by the scale factor. """ conv_unit, canonical_unit, scale = conv_data if conv_unit is None: conv_unit = canonical_unit new_expr = scale * canonical_unit.expr if unit_system is not None: # we don't know the to_units, so we get it directly from the # conv_data to_units = Unit(conv_unit.expr, registry=orig_units.registry) new_units = Unit(new_expr, registry=orig_units.registry) conv = new_units.get_conversion_factor(to_units) return to_units, conv
python
def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None): """Convert between E&M & MKS base units. If orig_units is a CGS (or MKS) E&M unit, conv_data contains the corresponding MKS (or CGS) unit and scale factor converting between them. This must be done by replacing the expression of the original unit with the new one in the unit expression and multiplying by the scale factor. """ conv_unit, canonical_unit, scale = conv_data if conv_unit is None: conv_unit = canonical_unit new_expr = scale * canonical_unit.expr if unit_system is not None: # we don't know the to_units, so we get it directly from the # conv_data to_units = Unit(conv_unit.expr, registry=orig_units.registry) new_units = Unit(new_expr, registry=orig_units.registry) conv = new_units.get_conversion_factor(to_units) return to_units, conv
[ "def", "_em_conversion", "(", "orig_units", ",", "conv_data", ",", "to_units", "=", "None", ",", "unit_system", "=", "None", ")", ":", "conv_unit", ",", "canonical_unit", ",", "scale", "=", "conv_data", "if", "conv_unit", "is", "None", ":", "conv_unit", "=", "canonical_unit", "new_expr", "=", "scale", "*", "canonical_unit", ".", "expr", "if", "unit_system", "is", "not", "None", ":", "# we don't know the to_units, so we get it directly from the", "# conv_data", "to_units", "=", "Unit", "(", "conv_unit", ".", "expr", ",", "registry", "=", "orig_units", ".", "registry", ")", "new_units", "=", "Unit", "(", "new_expr", ",", "registry", "=", "orig_units", ".", "registry", ")", "conv", "=", "new_units", ".", "get_conversion_factor", "(", "to_units", ")", "return", "to_units", ",", "conv" ]
Convert between E&M & MKS base units. If orig_units is a CGS (or MKS) E&M unit, conv_data contains the corresponding MKS (or CGS) unit and scale factor converting between them. This must be done by replacing the expression of the original unit with the new one in the unit expression and multiplying by the scale factor.
[ "Convert", "between", "E&M", "&", "MKS", "base", "units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L786-L805
train
yt-project/unyt
unyt/unit_object.py
_check_em_conversion
def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None): """Check to see if the units contain E&M units This function supports unyt's ability to convert data to and from E&M electromagnetic units. However, this support is limited and only very simple unit expressions can be readily converted. This function tries to see if the unit is an atomic base unit that is present in the em_conversions dict. If it does not contain E&M units, the function returns an empty tuple. If it does contain an atomic E&M unit in the em_conversions dict, it returns a tuple containing the unit to convert to and scale factor. If it contains a more complicated E&M unit and we are trying to convert between CGS & MKS E&M units, it raises an error. """ em_map = () if unit == to_unit or unit.dimensions not in em_conversion_dims: return em_map if unit.is_atomic: prefix, unit_wo_prefix = _split_prefix(str(unit), unit.registry.lut) else: prefix, unit_wo_prefix = "", str(unit) if (unit_wo_prefix, unit.dimensions) in em_conversions: em_info = em_conversions[unit_wo_prefix, unit.dimensions] em_unit = Unit(prefix + em_info[1], registry=registry) if to_unit is None: cmks_in_unit = current_mks in unit.dimensions.atoms() cmks_in_unit_system = unit_system.units_map[current_mks] cmks_in_unit_system = cmks_in_unit_system is not None if cmks_in_unit and cmks_in_unit_system: em_map = (unit_system[unit.dimensions], unit, 1.0) else: em_map = (None, em_unit, em_info[2]) elif to_unit.dimensions == em_unit.dimensions: em_map = (to_unit, em_unit, em_info[2]) if em_map: return em_map if unit_system is None: from unyt.unit_systems import unit_system_registry unit_system = unit_system_registry["mks"] for unit_atom in unit.expr.atoms(): if unit_atom.is_Number: continue bu = str(unit_atom) budims = Unit(bu, registry=registry).dimensions try: if str(unit_system[budims]) == bu: continue except MissingMKSCurrent: raise MKSCGSConversionError(unit) return em_map
python
def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None): """Check to see if the units contain E&M units This function supports unyt's ability to convert data to and from E&M electromagnetic units. However, this support is limited and only very simple unit expressions can be readily converted. This function tries to see if the unit is an atomic base unit that is present in the em_conversions dict. If it does not contain E&M units, the function returns an empty tuple. If it does contain an atomic E&M unit in the em_conversions dict, it returns a tuple containing the unit to convert to and scale factor. If it contains a more complicated E&M unit and we are trying to convert between CGS & MKS E&M units, it raises an error. """ em_map = () if unit == to_unit or unit.dimensions not in em_conversion_dims: return em_map if unit.is_atomic: prefix, unit_wo_prefix = _split_prefix(str(unit), unit.registry.lut) else: prefix, unit_wo_prefix = "", str(unit) if (unit_wo_prefix, unit.dimensions) in em_conversions: em_info = em_conversions[unit_wo_prefix, unit.dimensions] em_unit = Unit(prefix + em_info[1], registry=registry) if to_unit is None: cmks_in_unit = current_mks in unit.dimensions.atoms() cmks_in_unit_system = unit_system.units_map[current_mks] cmks_in_unit_system = cmks_in_unit_system is not None if cmks_in_unit and cmks_in_unit_system: em_map = (unit_system[unit.dimensions], unit, 1.0) else: em_map = (None, em_unit, em_info[2]) elif to_unit.dimensions == em_unit.dimensions: em_map = (to_unit, em_unit, em_info[2]) if em_map: return em_map if unit_system is None: from unyt.unit_systems import unit_system_registry unit_system = unit_system_registry["mks"] for unit_atom in unit.expr.atoms(): if unit_atom.is_Number: continue bu = str(unit_atom) budims = Unit(bu, registry=registry).dimensions try: if str(unit_system[budims]) == bu: continue except MissingMKSCurrent: raise MKSCGSConversionError(unit) return em_map
[ "def", "_check_em_conversion", "(", "unit", ",", "to_unit", "=", "None", ",", "unit_system", "=", "None", ",", "registry", "=", "None", ")", ":", "em_map", "=", "(", ")", "if", "unit", "==", "to_unit", "or", "unit", ".", "dimensions", "not", "in", "em_conversion_dims", ":", "return", "em_map", "if", "unit", ".", "is_atomic", ":", "prefix", ",", "unit_wo_prefix", "=", "_split_prefix", "(", "str", "(", "unit", ")", ",", "unit", ".", "registry", ".", "lut", ")", "else", ":", "prefix", ",", "unit_wo_prefix", "=", "\"\"", ",", "str", "(", "unit", ")", "if", "(", "unit_wo_prefix", ",", "unit", ".", "dimensions", ")", "in", "em_conversions", ":", "em_info", "=", "em_conversions", "[", "unit_wo_prefix", ",", "unit", ".", "dimensions", "]", "em_unit", "=", "Unit", "(", "prefix", "+", "em_info", "[", "1", "]", ",", "registry", "=", "registry", ")", "if", "to_unit", "is", "None", ":", "cmks_in_unit", "=", "current_mks", "in", "unit", ".", "dimensions", ".", "atoms", "(", ")", "cmks_in_unit_system", "=", "unit_system", ".", "units_map", "[", "current_mks", "]", "cmks_in_unit_system", "=", "cmks_in_unit_system", "is", "not", "None", "if", "cmks_in_unit", "and", "cmks_in_unit_system", ":", "em_map", "=", "(", "unit_system", "[", "unit", ".", "dimensions", "]", ",", "unit", ",", "1.0", ")", "else", ":", "em_map", "=", "(", "None", ",", "em_unit", ",", "em_info", "[", "2", "]", ")", "elif", "to_unit", ".", "dimensions", "==", "em_unit", ".", "dimensions", ":", "em_map", "=", "(", "to_unit", ",", "em_unit", ",", "em_info", "[", "2", "]", ")", "if", "em_map", ":", "return", "em_map", "if", "unit_system", "is", "None", ":", "from", "unyt", ".", "unit_systems", "import", "unit_system_registry", "unit_system", "=", "unit_system_registry", "[", "\"mks\"", "]", "for", "unit_atom", "in", "unit", ".", "expr", ".", "atoms", "(", ")", ":", "if", "unit_atom", ".", "is_Number", ":", "continue", "bu", "=", "str", "(", "unit_atom", ")", "budims", "=", "Unit", "(", "bu", ",", "registry", "=", "registry", ")", ".", "dimensions", "try", ":", "if", "str", "(", "unit_system", "[", "budims", "]", ")", "==", "bu", ":", "continue", "except", "MissingMKSCurrent", ":", "raise", "MKSCGSConversionError", "(", "unit", ")", "return", "em_map" ]
Check to see if the units contain E&M units This function supports unyt's ability to convert data to and from E&M electromagnetic units. However, this support is limited and only very simple unit expressions can be readily converted. This function tries to see if the unit is an atomic base unit that is present in the em_conversions dict. If it does not contain E&M units, the function returns an empty tuple. If it does contain an atomic E&M unit in the em_conversions dict, it returns a tuple containing the unit to convert to and scale factor. If it contains a more complicated E&M unit and we are trying to convert between CGS & MKS E&M units, it raises an error.
[ "Check", "to", "see", "if", "the", "units", "contain", "E&M", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L809-L858
train
yt-project/unyt
unyt/unit_object.py
_get_conversion_factor
def _get_conversion_factor(old_units, new_units, dtype): """ Get the conversion factor between two units of equivalent dimensions. This is the number you multiply data by to convert from values in `old_units` to values in `new_units`. Parameters ---------- old_units: str or Unit object The current units. new_units : str or Unit object The units we want. dtype: NumPy dtype The dtype of the conversion factor Returns ------- conversion_factor : float `old_units / new_units` offset : float or None Offset between the old unit and new unit. """ if old_units.dimensions != new_units.dimensions: raise UnitConversionError( old_units, old_units.dimensions, new_units, new_units.dimensions ) ratio = old_units.base_value / new_units.base_value if old_units.base_offset == 0 and new_units.base_offset == 0: return (ratio, None) else: # the dimensions are the same, so both are temperatures, where # it's legal to convert units so no need to do error checking return ratio, ratio * old_units.base_offset - new_units.base_offset
python
def _get_conversion_factor(old_units, new_units, dtype): """ Get the conversion factor between two units of equivalent dimensions. This is the number you multiply data by to convert from values in `old_units` to values in `new_units`. Parameters ---------- old_units: str or Unit object The current units. new_units : str or Unit object The units we want. dtype: NumPy dtype The dtype of the conversion factor Returns ------- conversion_factor : float `old_units / new_units` offset : float or None Offset between the old unit and new unit. """ if old_units.dimensions != new_units.dimensions: raise UnitConversionError( old_units, old_units.dimensions, new_units, new_units.dimensions ) ratio = old_units.base_value / new_units.base_value if old_units.base_offset == 0 and new_units.base_offset == 0: return (ratio, None) else: # the dimensions are the same, so both are temperatures, where # it's legal to convert units so no need to do error checking return ratio, ratio * old_units.base_offset - new_units.base_offset
[ "def", "_get_conversion_factor", "(", "old_units", ",", "new_units", ",", "dtype", ")", ":", "if", "old_units", ".", "dimensions", "!=", "new_units", ".", "dimensions", ":", "raise", "UnitConversionError", "(", "old_units", ",", "old_units", ".", "dimensions", ",", "new_units", ",", "new_units", ".", "dimensions", ")", "ratio", "=", "old_units", ".", "base_value", "/", "new_units", ".", "base_value", "if", "old_units", ".", "base_offset", "==", "0", "and", "new_units", ".", "base_offset", "==", "0", ":", "return", "(", "ratio", ",", "None", ")", "else", ":", "# the dimensions are the same, so both are temperatures, where", "# it's legal to convert units so no need to do error checking", "return", "ratio", ",", "ratio", "*", "old_units", ".", "base_offset", "-", "new_units", ".", "base_offset" ]
Get the conversion factor between two units of equivalent dimensions. This is the number you multiply data by to convert from values in `old_units` to values in `new_units`. Parameters ---------- old_units: str or Unit object The current units. new_units : str or Unit object The units we want. dtype: NumPy dtype The dtype of the conversion factor Returns ------- conversion_factor : float `old_units / new_units` offset : float or None Offset between the old unit and new unit.
[ "Get", "the", "conversion", "factor", "between", "two", "units", "of", "equivalent", "dimensions", ".", "This", "is", "the", "number", "you", "multiply", "data", "by", "to", "convert", "from", "values", "in", "old_units", "to", "values", "in", "new_units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L861-L894
train
yt-project/unyt
unyt/unit_object.py
_get_unit_data_from_expr
def _get_unit_data_from_expr(unit_expr, unit_symbol_lut): """ Grabs the total base_value and dimensions from a valid unit expression. Parameters ---------- unit_expr: Unit object, or sympy Expr object The expression containing unit symbols. unit_symbol_lut: dict Provides the unit data for each valid unit symbol. """ # Now for the sympy possibilities if isinstance(unit_expr, Number): if unit_expr is sympy_one: return (1.0, sympy_one) return (float(unit_expr), sympy_one) if isinstance(unit_expr, Symbol): return _lookup_unit_symbol(unit_expr.name, unit_symbol_lut) if isinstance(unit_expr, Pow): unit_data = _get_unit_data_from_expr(unit_expr.args[0], unit_symbol_lut) power = unit_expr.args[1] if isinstance(power, Symbol): raise UnitParseError("Invalid unit expression '%s'." % unit_expr) conv = float(unit_data[0] ** power) unit = unit_data[1] ** power return (conv, unit) if isinstance(unit_expr, Mul): base_value = 1.0 dimensions = 1 for expr in unit_expr.args: unit_data = _get_unit_data_from_expr(expr, unit_symbol_lut) base_value *= unit_data[0] dimensions *= unit_data[1] return (float(base_value), dimensions) raise UnitParseError( "Cannot parse for unit data from '%s'. Please supply" " an expression of only Unit, Symbol, Pow, and Mul" "objects." % str(unit_expr) )
python
def _get_unit_data_from_expr(unit_expr, unit_symbol_lut): """ Grabs the total base_value and dimensions from a valid unit expression. Parameters ---------- unit_expr: Unit object, or sympy Expr object The expression containing unit symbols. unit_symbol_lut: dict Provides the unit data for each valid unit symbol. """ # Now for the sympy possibilities if isinstance(unit_expr, Number): if unit_expr is sympy_one: return (1.0, sympy_one) return (float(unit_expr), sympy_one) if isinstance(unit_expr, Symbol): return _lookup_unit_symbol(unit_expr.name, unit_symbol_lut) if isinstance(unit_expr, Pow): unit_data = _get_unit_data_from_expr(unit_expr.args[0], unit_symbol_lut) power = unit_expr.args[1] if isinstance(power, Symbol): raise UnitParseError("Invalid unit expression '%s'." % unit_expr) conv = float(unit_data[0] ** power) unit = unit_data[1] ** power return (conv, unit) if isinstance(unit_expr, Mul): base_value = 1.0 dimensions = 1 for expr in unit_expr.args: unit_data = _get_unit_data_from_expr(expr, unit_symbol_lut) base_value *= unit_data[0] dimensions *= unit_data[1] return (float(base_value), dimensions) raise UnitParseError( "Cannot parse for unit data from '%s'. Please supply" " an expression of only Unit, Symbol, Pow, and Mul" "objects." % str(unit_expr) )
[ "def", "_get_unit_data_from_expr", "(", "unit_expr", ",", "unit_symbol_lut", ")", ":", "# Now for the sympy possibilities", "if", "isinstance", "(", "unit_expr", ",", "Number", ")", ":", "if", "unit_expr", "is", "sympy_one", ":", "return", "(", "1.0", ",", "sympy_one", ")", "return", "(", "float", "(", "unit_expr", ")", ",", "sympy_one", ")", "if", "isinstance", "(", "unit_expr", ",", "Symbol", ")", ":", "return", "_lookup_unit_symbol", "(", "unit_expr", ".", "name", ",", "unit_symbol_lut", ")", "if", "isinstance", "(", "unit_expr", ",", "Pow", ")", ":", "unit_data", "=", "_get_unit_data_from_expr", "(", "unit_expr", ".", "args", "[", "0", "]", ",", "unit_symbol_lut", ")", "power", "=", "unit_expr", ".", "args", "[", "1", "]", "if", "isinstance", "(", "power", ",", "Symbol", ")", ":", "raise", "UnitParseError", "(", "\"Invalid unit expression '%s'.\"", "%", "unit_expr", ")", "conv", "=", "float", "(", "unit_data", "[", "0", "]", "**", "power", ")", "unit", "=", "unit_data", "[", "1", "]", "**", "power", "return", "(", "conv", ",", "unit", ")", "if", "isinstance", "(", "unit_expr", ",", "Mul", ")", ":", "base_value", "=", "1.0", "dimensions", "=", "1", "for", "expr", "in", "unit_expr", ".", "args", ":", "unit_data", "=", "_get_unit_data_from_expr", "(", "expr", ",", "unit_symbol_lut", ")", "base_value", "*=", "unit_data", "[", "0", "]", "dimensions", "*=", "unit_data", "[", "1", "]", "return", "(", "float", "(", "base_value", ")", ",", "dimensions", ")", "raise", "UnitParseError", "(", "\"Cannot parse for unit data from '%s'. Please supply\"", "\" an expression of only Unit, Symbol, Pow, and Mul\"", "\"objects.\"", "%", "str", "(", "unit_expr", ")", ")" ]
Grabs the total base_value and dimensions from a valid unit expression. Parameters ---------- unit_expr: Unit object, or sympy Expr object The expression containing unit symbols. unit_symbol_lut: dict Provides the unit data for each valid unit symbol.
[ "Grabs", "the", "total", "base_value", "and", "dimensions", "from", "a", "valid", "unit", "expression", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L902-L946
train
yt-project/unyt
unyt/unit_object.py
define_unit
def define_unit( symbol, value, tex_repr=None, offset=None, prefixable=False, registry=None ): """ Define a new unit and add it to the specified unit registry. Parameters ---------- symbol : string The symbol for the new unit. value : tuple or :class:`unyt.array.unyt_quantity` The definition of the new unit in terms of some other units. For example, one would define a new "mph" unit with ``(1.0, "mile/hr")`` or with ``1.0*unyt.mile/unyt.hr`` tex_repr : string, optional The LaTeX representation of the new unit. If one is not supplied, it will be generated automatically based on the symbol string. offset : float, optional The default offset for the unit. If not set, an offset of 0 is assumed. prefixable : boolean, optional Whether or not the new unit can use SI prefixes. Default: False registry : :class:`unyt.unit_registry.UnitRegistry` or None The unit registry to add the unit to. If None, then defaults to the global default unit registry. If registry is set to None then the unit object will be added as an attribute to the top-level :mod:`unyt` namespace to ease working with the newly defined unit. See the example below. Examples -------- >>> from unyt import day >>> two_weeks = 14.0*day >>> one_day = 1.0*day >>> define_unit("two_weeks", two_weeks) >>> from unyt import two_weeks >>> print((3*two_weeks)/one_day) 42.0 dimensionless """ from unyt.array import unyt_quantity, _iterable import unyt if registry is None: registry = default_unit_registry if symbol in registry: raise RuntimeError( "Unit symbol '%s' already exists in the provided " "registry" % symbol ) if not isinstance(value, unyt_quantity): if _iterable(value) and len(value) == 2: value = unyt_quantity(value[0], value[1], registry=registry) else: raise RuntimeError( '"value" needs to be a quantity or ' "(value, unit) tuple!" ) base_value = float(value.in_base(unit_system="mks")) dimensions = value.units.dimensions registry.add( symbol, base_value, dimensions, prefixable=prefixable, tex_repr=tex_repr, offset=offset, ) if registry is default_unit_registry: u = Unit(symbol, registry=registry) setattr(unyt, symbol, u)
python
def define_unit( symbol, value, tex_repr=None, offset=None, prefixable=False, registry=None ): """ Define a new unit and add it to the specified unit registry. Parameters ---------- symbol : string The symbol for the new unit. value : tuple or :class:`unyt.array.unyt_quantity` The definition of the new unit in terms of some other units. For example, one would define a new "mph" unit with ``(1.0, "mile/hr")`` or with ``1.0*unyt.mile/unyt.hr`` tex_repr : string, optional The LaTeX representation of the new unit. If one is not supplied, it will be generated automatically based on the symbol string. offset : float, optional The default offset for the unit. If not set, an offset of 0 is assumed. prefixable : boolean, optional Whether or not the new unit can use SI prefixes. Default: False registry : :class:`unyt.unit_registry.UnitRegistry` or None The unit registry to add the unit to. If None, then defaults to the global default unit registry. If registry is set to None then the unit object will be added as an attribute to the top-level :mod:`unyt` namespace to ease working with the newly defined unit. See the example below. Examples -------- >>> from unyt import day >>> two_weeks = 14.0*day >>> one_day = 1.0*day >>> define_unit("two_weeks", two_weeks) >>> from unyt import two_weeks >>> print((3*two_weeks)/one_day) 42.0 dimensionless """ from unyt.array import unyt_quantity, _iterable import unyt if registry is None: registry = default_unit_registry if symbol in registry: raise RuntimeError( "Unit symbol '%s' already exists in the provided " "registry" % symbol ) if not isinstance(value, unyt_quantity): if _iterable(value) and len(value) == 2: value = unyt_quantity(value[0], value[1], registry=registry) else: raise RuntimeError( '"value" needs to be a quantity or ' "(value, unit) tuple!" ) base_value = float(value.in_base(unit_system="mks")) dimensions = value.units.dimensions registry.add( symbol, base_value, dimensions, prefixable=prefixable, tex_repr=tex_repr, offset=offset, ) if registry is default_unit_registry: u = Unit(symbol, registry=registry) setattr(unyt, symbol, u)
[ "def", "define_unit", "(", "symbol", ",", "value", ",", "tex_repr", "=", "None", ",", "offset", "=", "None", ",", "prefixable", "=", "False", ",", "registry", "=", "None", ")", ":", "from", "unyt", ".", "array", "import", "unyt_quantity", ",", "_iterable", "import", "unyt", "if", "registry", "is", "None", ":", "registry", "=", "default_unit_registry", "if", "symbol", "in", "registry", ":", "raise", "RuntimeError", "(", "\"Unit symbol '%s' already exists in the provided \"", "\"registry\"", "%", "symbol", ")", "if", "not", "isinstance", "(", "value", ",", "unyt_quantity", ")", ":", "if", "_iterable", "(", "value", ")", "and", "len", "(", "value", ")", "==", "2", ":", "value", "=", "unyt_quantity", "(", "value", "[", "0", "]", ",", "value", "[", "1", "]", ",", "registry", "=", "registry", ")", "else", ":", "raise", "RuntimeError", "(", "'\"value\" needs to be a quantity or '", "\"(value, unit) tuple!\"", ")", "base_value", "=", "float", "(", "value", ".", "in_base", "(", "unit_system", "=", "\"mks\"", ")", ")", "dimensions", "=", "value", ".", "units", ".", "dimensions", "registry", ".", "add", "(", "symbol", ",", "base_value", ",", "dimensions", ",", "prefixable", "=", "prefixable", ",", "tex_repr", "=", "tex_repr", ",", "offset", "=", "offset", ",", ")", "if", "registry", "is", "default_unit_registry", ":", "u", "=", "Unit", "(", "symbol", ",", "registry", "=", "registry", ")", "setattr", "(", "unyt", ",", "symbol", ",", "u", ")" ]
Define a new unit and add it to the specified unit registry. Parameters ---------- symbol : string The symbol for the new unit. value : tuple or :class:`unyt.array.unyt_quantity` The definition of the new unit in terms of some other units. For example, one would define a new "mph" unit with ``(1.0, "mile/hr")`` or with ``1.0*unyt.mile/unyt.hr`` tex_repr : string, optional The LaTeX representation of the new unit. If one is not supplied, it will be generated automatically based on the symbol string. offset : float, optional The default offset for the unit. If not set, an offset of 0 is assumed. prefixable : boolean, optional Whether or not the new unit can use SI prefixes. Default: False registry : :class:`unyt.unit_registry.UnitRegistry` or None The unit registry to add the unit to. If None, then defaults to the global default unit registry. If registry is set to None then the unit object will be added as an attribute to the top-level :mod:`unyt` namespace to ease working with the newly defined unit. See the example below. Examples -------- >>> from unyt import day >>> two_weeks = 14.0*day >>> one_day = 1.0*day >>> define_unit("two_weeks", two_weeks) >>> from unyt import two_weeks >>> print((3*two_weeks)/one_day) 42.0 dimensionless
[ "Define", "a", "new", "unit", "and", "add", "it", "to", "the", "specified", "unit", "registry", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L976-L1042
train
yt-project/unyt
unyt/unit_object.py
Unit.latex_repr
def latex_repr(self): """A LaTeX representation for the unit Examples -------- >>> from unyt import g, cm >>> (g/cm**3).units.latex_repr '\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}' """ if self._latex_repr is not None: return self._latex_repr if self.expr.is_Atom: expr = self.expr else: expr = self.expr.copy() self._latex_repr = _get_latex_representation(expr, self.registry) return self._latex_repr
python
def latex_repr(self): """A LaTeX representation for the unit Examples -------- >>> from unyt import g, cm >>> (g/cm**3).units.latex_repr '\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}' """ if self._latex_repr is not None: return self._latex_repr if self.expr.is_Atom: expr = self.expr else: expr = self.expr.copy() self._latex_repr = _get_latex_representation(expr, self.registry) return self._latex_repr
[ "def", "latex_repr", "(", "self", ")", ":", "if", "self", ".", "_latex_repr", "is", "not", "None", ":", "return", "self", ".", "_latex_repr", "if", "self", ".", "expr", ".", "is_Atom", ":", "expr", "=", "self", ".", "expr", "else", ":", "expr", "=", "self", ".", "expr", ".", "copy", "(", ")", "self", ".", "_latex_repr", "=", "_get_latex_representation", "(", "expr", ",", "self", ".", "registry", ")", "return", "self", ".", "_latex_repr" ]
A LaTeX representation for the unit Examples -------- >>> from unyt import g, cm >>> (g/cm**3).units.latex_repr '\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}'
[ "A", "LaTeX", "representation", "for", "the", "unit" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L261-L277
train
yt-project/unyt
unyt/unit_object.py
Unit.is_code_unit
def is_code_unit(self): """Is this a "code" unit? Returns ------- True if the unit consists of atom units that being with "code". False otherwise """ for atom in self.expr.atoms(): if not (str(atom).startswith("code") or atom.is_Number): return False return True
python
def is_code_unit(self): """Is this a "code" unit? Returns ------- True if the unit consists of atom units that being with "code". False otherwise """ for atom in self.expr.atoms(): if not (str(atom).startswith("code") or atom.is_Number): return False return True
[ "def", "is_code_unit", "(", "self", ")", ":", "for", "atom", "in", "self", ".", "expr", ".", "atoms", "(", ")", ":", "if", "not", "(", "str", "(", "atom", ")", ".", "startswith", "(", "\"code\"", ")", "or", "atom", ".", "is_Number", ")", ":", "return", "False", "return", "True" ]
Is this a "code" unit? Returns ------- True if the unit consists of atom units that being with "code". False otherwise
[ "Is", "this", "a", "code", "unit?" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L514-L526
train
yt-project/unyt
unyt/unit_object.py
Unit.list_equivalencies
def list_equivalencies(self): """Lists the possible equivalencies associated with this unit object Examples -------- >>> from unyt import km >>> km.units.list_equivalencies() spectral: length <-> spatial_frequency <-> frequency <-> energy schwarzschild: mass <-> length compton: mass <-> length """ from unyt.equivalencies import equivalence_registry for k, v in equivalence_registry.items(): if self.has_equivalent(k): print(v())
python
def list_equivalencies(self): """Lists the possible equivalencies associated with this unit object Examples -------- >>> from unyt import km >>> km.units.list_equivalencies() spectral: length <-> spatial_frequency <-> frequency <-> energy schwarzschild: mass <-> length compton: mass <-> length """ from unyt.equivalencies import equivalence_registry for k, v in equivalence_registry.items(): if self.has_equivalent(k): print(v())
[ "def", "list_equivalencies", "(", "self", ")", ":", "from", "unyt", ".", "equivalencies", "import", "equivalence_registry", "for", "k", ",", "v", "in", "equivalence_registry", ".", "items", "(", ")", ":", "if", "self", ".", "has_equivalent", "(", "k", ")", ":", "print", "(", "v", "(", ")", ")" ]
Lists the possible equivalencies associated with this unit object Examples -------- >>> from unyt import km >>> km.units.list_equivalencies() spectral: length <-> spatial_frequency <-> frequency <-> energy schwarzschild: mass <-> length compton: mass <-> length
[ "Lists", "the", "possible", "equivalencies", "associated", "with", "this", "unit", "object" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L528-L543
train
yt-project/unyt
unyt/unit_object.py
Unit.get_base_equivalent
def get_base_equivalent(self, unit_system=None): """Create and return dimensionally-equivalent units in a specified base. >>> from unyt import g, cm >>> (g/cm**3).get_base_equivalent('mks') kg/m**3 >>> (g/cm**3).get_base_equivalent('solar') Mearth/AU**3 """ from unyt.unit_registry import _sanitize_unit_system unit_system = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, registry=self.registry, unit_system=unit_system ) except MKSCGSConversionError: raise UnitsNotReducible(self.units, unit_system) if any(conv_data): new_units, _ = _em_conversion(self, conv_data, unit_system=unit_system) else: try: new_units = unit_system[self.dimensions] except MissingMKSCurrent: raise UnitsNotReducible(self.units, unit_system) return Unit(new_units, registry=self.registry)
python
def get_base_equivalent(self, unit_system=None): """Create and return dimensionally-equivalent units in a specified base. >>> from unyt import g, cm >>> (g/cm**3).get_base_equivalent('mks') kg/m**3 >>> (g/cm**3).get_base_equivalent('solar') Mearth/AU**3 """ from unyt.unit_registry import _sanitize_unit_system unit_system = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, registry=self.registry, unit_system=unit_system ) except MKSCGSConversionError: raise UnitsNotReducible(self.units, unit_system) if any(conv_data): new_units, _ = _em_conversion(self, conv_data, unit_system=unit_system) else: try: new_units = unit_system[self.dimensions] except MissingMKSCurrent: raise UnitsNotReducible(self.units, unit_system) return Unit(new_units, registry=self.registry)
[ "def", "get_base_equivalent", "(", "self", ",", "unit_system", "=", "None", ")", ":", "from", "unyt", ".", "unit_registry", "import", "_sanitize_unit_system", "unit_system", "=", "_sanitize_unit_system", "(", "unit_system", ",", "self", ")", "try", ":", "conv_data", "=", "_check_em_conversion", "(", "self", ".", "units", ",", "registry", "=", "self", ".", "registry", ",", "unit_system", "=", "unit_system", ")", "except", "MKSCGSConversionError", ":", "raise", "UnitsNotReducible", "(", "self", ".", "units", ",", "unit_system", ")", "if", "any", "(", "conv_data", ")", ":", "new_units", ",", "_", "=", "_em_conversion", "(", "self", ",", "conv_data", ",", "unit_system", "=", "unit_system", ")", "else", ":", "try", ":", "new_units", "=", "unit_system", "[", "self", ".", "dimensions", "]", "except", "MissingMKSCurrent", ":", "raise", "UnitsNotReducible", "(", "self", ".", "units", ",", "unit_system", ")", "return", "Unit", "(", "new_units", ",", "registry", "=", "self", ".", "registry", ")" ]
Create and return dimensionally-equivalent units in a specified base. >>> from unyt import g, cm >>> (g/cm**3).get_base_equivalent('mks') kg/m**3 >>> (g/cm**3).get_base_equivalent('solar') Mearth/AU**3
[ "Create", "and", "return", "dimensionally", "-", "equivalent", "units", "in", "a", "specified", "base", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L564-L589
train
yt-project/unyt
unyt/unit_object.py
Unit.as_coeff_unit
def as_coeff_unit(self): """Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coefficient and a new unit object for the unmultiplied unit. Example ------- >>> import unyt as u >>> unit = (u.m**2/u.cm).simplify() >>> unit 100*m >>> unit.as_coeff_unit() (100.0, m) """ coeff, mul = self.expr.as_coeff_Mul() coeff = float(coeff) ret = Unit( mul, self.base_value / coeff, self.base_offset, self.dimensions, self.registry, ) return coeff, ret
python
def as_coeff_unit(self): """Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coefficient and a new unit object for the unmultiplied unit. Example ------- >>> import unyt as u >>> unit = (u.m**2/u.cm).simplify() >>> unit 100*m >>> unit.as_coeff_unit() (100.0, m) """ coeff, mul = self.expr.as_coeff_Mul() coeff = float(coeff) ret = Unit( mul, self.base_value / coeff, self.base_offset, self.dimensions, self.registry, ) return coeff, ret
[ "def", "as_coeff_unit", "(", "self", ")", ":", "coeff", ",", "mul", "=", "self", ".", "expr", ".", "as_coeff_Mul", "(", ")", "coeff", "=", "float", "(", "coeff", ")", "ret", "=", "Unit", "(", "mul", ",", "self", ".", "base_value", "/", "coeff", ",", "self", ".", "base_offset", ",", "self", ".", "dimensions", ",", "self", ".", "registry", ",", ")", "return", "coeff", ",", "ret" ]
Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coefficient and a new unit object for the unmultiplied unit. Example ------- >>> import unyt as u >>> unit = (u.m**2/u.cm).simplify() >>> unit 100*m >>> unit.as_coeff_unit() (100.0, m)
[ "Factor", "the", "coefficient", "multiplying", "a", "unit" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L653-L679
train