text
stringlengths
0
1.05M
meta
dict
from __future__ import absolute_import, division, print_function from operator import getitem from tornado import gen from dask.compatibility import apply from dask.base import tokenize from distributed.client import default_client from .core import Stream from . import core, sources class DaskStream(Stream): """ A Parallel stream using Dask This object is fully compliant with the ``streamz.core.Stream`` object but uses a Dask client for execution. Operations like ``map`` and ``accumulate`` submit functions to run on the Dask instance using ``dask.distributed.Client.submit`` and pass around Dask futures. Time-based operations like ``timed_window``, buffer, and so on operate as normal. Typically one transfers between normal Stream and DaskStream objects using the ``Stream.scatter()`` and ``DaskStream.gather()`` methods. Examples -------- >>> from dask.distributed import Client >>> client = Client() >>> from streamz import Stream >>> source = Stream() >>> source.scatter().map(func).accumulate(binop).gather().sink(...) See Also -------- dask.distributed.Client """ def __init__(self, *args, **kwargs): if 'loop' not in kwargs: kwargs['loop'] = default_client().loop super(DaskStream, self).__init__(*args, **kwargs) @DaskStream.register_api() class map(DaskStream): def __init__(self, upstream, func, *args, **kwargs): self.func = func self.kwargs = kwargs self.args = args DaskStream.__init__(self, upstream) def update(self, x, who=None, metadata=None): client = default_client() result = client.submit(self.func, x, *self.args, **self.kwargs) return self._emit(result, metadata=metadata) @DaskStream.register_api() class accumulate(DaskStream): def __init__(self, upstream, func, start=core.no_default, returns_state=False, **kwargs): self.func = func self.state = start self.returns_state = returns_state self.kwargs = kwargs self.with_state = kwargs.pop('with_state', False) DaskStream.__init__(self, upstream) def update(self, x, who=None, metadata=None): if self.state is core.no_default: self.state = x if self.with_state: return self._emit((self.state, x), metadata=metadata) else: return self._emit(x, metadata=metadata) else: client = default_client() result = client.submit(self.func, self.state, x, **self.kwargs) if self.returns_state: state = client.submit(getitem, result, 0) result = client.submit(getitem, result, 1) else: state = result self.state = state if self.with_state: return self._emit((self.state, result), metadata=metadata) else: return self._emit(result, metadata=metadata) @core.Stream.register_api() @DaskStream.register_api() class scatter(DaskStream): """ Convert local stream to Dask Stream All elements flowing through the input will be scattered out to the cluster """ @gen.coroutine def update(self, x, who=None, metadata=None): client = default_client() self._retain_refs(metadata) # We need to make sure that x is treated as it is by dask # However, client.scatter works internally different for # lists and dicts. So we always use a dict here to be sure # we know the format exactly. The key will be taken as the # dask identifier of the data. tokenized_x = f"{type(x).__name__}-{tokenize(x)}" future_as_dict = yield client.scatter({tokenized_x: x}, asynchronous=True) future = future_as_dict[tokenized_x] f = yield self._emit(future, metadata=metadata) self._release_refs(metadata) raise gen.Return(f) @DaskStream.register_api() class gather(core.Stream): """ Wait on and gather results from DaskStream to local Stream This waits on every result in the stream and then gathers that result back to the local stream. Warning, this can restrict parallelism. It is common to combine a ``gather()`` node with a ``buffer()`` to allow unfinished futures to pile up. Examples -------- >>> local_stream = dask_stream.buffer(20).gather() See Also -------- buffer scatter """ @gen.coroutine def update(self, x, who=None, metadata=None): client = default_client() self._retain_refs(metadata) result = yield client.gather(x, asynchronous=True) result2 = yield self._emit(result, metadata=metadata) self._release_refs(metadata) raise gen.Return(result2) @DaskStream.register_api() class starmap(DaskStream): def __init__(self, upstream, func, **kwargs): self.func = func stream_name = kwargs.pop('stream_name', None) self.kwargs = kwargs DaskStream.__init__(self, upstream, stream_name=stream_name) def update(self, x, who=None, metadata=None): client = default_client() result = client.submit(apply, self.func, x, self.kwargs) return self._emit(result, metadata=metadata) @DaskStream.register_api() class buffer(DaskStream, core.buffer): pass @DaskStream.register_api() class combine_latest(DaskStream, core.combine_latest): pass @DaskStream.register_api() class delay(DaskStream, core.delay): pass @DaskStream.register_api() class latest(DaskStream, core.latest): pass @DaskStream.register_api() class partition(DaskStream, core.partition): pass @DaskStream.register_api() class rate_limit(DaskStream, core.rate_limit): pass @DaskStream.register_api() class sliding_window(DaskStream, core.sliding_window): pass @DaskStream.register_api() class timed_window(DaskStream, core.timed_window): pass @DaskStream.register_api() class union(DaskStream, core.union): pass @DaskStream.register_api() class zip(DaskStream, core.zip): pass @DaskStream.register_api(staticmethod) class filenames(DaskStream, sources.filenames): pass @DaskStream.register_api(staticmethod) class from_textfile(DaskStream, sources.from_textfile): pass
{ "repo_name": "mrocklin/streams", "path": "streamz/dask.py", "copies": "1", "size": "6367", "license": "bsd-3-clause", "hash": 5782393850780748000, "line_mean": 27.5515695067, "line_max": 82, "alpha_frac": 0.6461441809, "autogenerated": false, "ratio": 3.835542168674699, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4981686349574699, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from operator import getitem from tornado import gen import dask.distributed from distributed.utils import set_thread_state from distributed.client import default_client from . import core class DaskStream(core.Stream): def map(self, func, *args, **kwargs): """ Apply a function to every element in the stream """ return map(func, self, args=args, **kwargs) def gather(self): return gather(self) def accumulate(self, func, start=core.no_default, returns_state=False): """ Accumulate results with previous state """ return scan(func, self, start=start, returns_state=returns_state) scan = accumulate def zip(self, *other): """ Combine two streams together into a stream of tuples """ return zip(self, *other) def buffer(self, n, loop=None): """ Allow results to pile up at this point in the stream This allows results to buffer in place at various points in the stream. This can help to smooth flow through the system when backpressure is applied. """ return buffer(n, self, loop=loop) class map(DaskStream): def __init__(self, func, child, args=(), **kwargs): self.func = func self.kwargs = kwargs self.args = args DaskStream.__init__(self, child) def update(self, x, who=None): client = default_client() result = client.submit(self.func, x, *self.args, **self.kwargs) return self.emit(result) class scan(DaskStream): def __init__(self, func, child, start=core.no_default, returns_state=False): self.func = func self.state = start self.returns_state = returns_state DaskStream.__init__(self, child) def update(self, x, who=None): if self.state is core.no_default: self.state = x return self.emit(self.state) else: client = default_client() result = client.submit(self.func, self.state, x) if self.returns_state: state = client.submit(getitem, result, 0) result = client.submit(getitem, result, 1) else: state = result self.state = state return self.emit(result) class scatter(DaskStream): """ Convert local stream to Dask Stream All elements flowing through the input will be scattered out to the cluster """ @gen.coroutine def _update(self, x, who=None): client = default_client() future = yield client.scatter(x, asynchronous=True) yield self.emit(future) def update(self, x, who=None): client = default_client() return client.sync(self._update, x, who) class gather(core.Stream): """ Convert Dask stream to local Stream """ @gen.coroutine def _update(self, x, who=None): client = default_client() result = yield client.gather(x, asynchronous=True) with set_thread_state(asynchronous=True): result = self.emit(result) yield result def update(self, x, who=None): client = default_client() return client.sync(self._update, x, who) class zip(DaskStream, core.zip): pass class buffer(DaskStream): def __init__(self, n, child, loop=None): client = default_client() self.queue = dask.distributed.Queue(maxsize=n, client=client) core.Stream.__init__(self, child, loop=loop or client.loop) self.loop.add_callback(self.cb) @gen.coroutine def cb(self): while True: x = yield self.queue.get(asynchronous=True) with set_thread_state(asynchronous=True): result = self.emit(x) yield result @gen.coroutine def _update(self, x, who=None): result = yield self.queue.put(x, asynchronous=True) raise gen.Return(result) def update(self, x, who=None): return self.queue.put(x)
{ "repo_name": "jrmlhermitte/streamz", "path": "streamz/dask.py", "copies": "1", "size": "4034", "license": "bsd-3-clause", "hash": 1717457617279812600, "line_mean": 28.4452554745, "line_max": 80, "alpha_frac": 0.6152702033, "autogenerated": false, "ratio": 3.935609756097561, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5050879959397561, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from operator import getitem import numpy as np from toolz import valmap, partial from .core import getarray from ..core import flatten from ..optimize import cull, fuse, dealias, inline_functions from ..rewrite import RuleSet, RewriteRule def optimize(dsk, keys, **kwargs): """ Optimize dask for array computation 1. Cull tasks not necessary to evaluate keys 2. Remove full slicing, e.g. x[:] 3. Inline fast functions like getitem and np.transpose """ fast_functions=kwargs.get('fast_functions', set([getarray, getitem, np.transpose])) dsk2 = cull(dsk, list(flatten(keys))) dsk3 = remove_full_slices(dsk2) dsk4 = fuse(dsk3) dsk5 = valmap(rewrite_rules.rewrite, dsk4) dsk6 = inline_functions(dsk5, fast_functions=fast_functions) return dsk6 def is_full_slice(task): """ >>> is_full_slice((getitem, 'x', ... (slice(None, None, None), slice(None, None, None)))) True >>> is_full_slice((getitem, 'x', ... (slice(5, 20, 1), slice(None, None, None)))) False """ return (isinstance(task, tuple) and (task[0] in (getitem, getarray)) and (task[2] == slice(None, None, None) or isinstance(task[2], tuple) and all(ind == slice(None, None, None) for ind in task[2]))) def remove_full_slices(dsk): """ Remove full slices from dask See Also: dask.optimize.inline Examples -------- >>> dsk = {'a': (range, 5), ... 'b': (getitem, 'a', (slice(None, None, None),)), ... 'c': (getitem, 'b', (slice(None, None, None),)), ... 'd': (getitem, 'c', (slice(None, 5, None),)), ... 'e': (getitem, 'd', (slice(None, None, None),))} >>> remove_full_slices(dsk) # doctest: +SKIP {'a': (range, 5), 'e': (getitem, 'a', (slice(None, 5, None),))} """ full_slice_keys = set(k for k, task in dsk.items() if is_full_slice(task)) dsk2 = dict((k, task[1] if k in full_slice_keys else task) for k, task in dsk.items()) dsk3 = dealias(dsk2) return dsk3 a, b, x = '~a', '~b', '~x' def fuse_slice_dict(match, getter=getarray): # Making new dimensions? Need two getitems # TODO: well, we could still optimize the non-None axes try: c = fuse_slice(match[a], match[b]) return (getter, match[x], c) except NotImplementedError: return (getitem, (getter, match[x], match[a]), match[b]) rewrite_rules = RuleSet( RewriteRule((getitem, (getitem, x, a), b), partial(fuse_slice_dict, getter=getitem), (a, b, x)), RewriteRule((getarray, (getitem, x, a), b), fuse_slice_dict, (a, b, x)), RewriteRule((getarray, (getarray, x, a), b), fuse_slice_dict, (a, b, x)), RewriteRule((getitem, (getarray, x, a), b), fuse_slice_dict, (a, b, x))) def normalize_slice(s): """ Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) """ start, stop, step = s.start, s.stop, s.step if start is None: start = 0 if step is None: step = 1 if start < 0 or step < 0 or stop is not None and stop < 0: raise NotImplementedError() return slice(start, stop, step) def fuse_slice(a, b): """ Fuse stacked slices together Fuse a pair of repeated slices into a single slice: >>> fuse_slice(slice(1000, 2000), slice(10, 15)) slice(1010, 1015, None) This also works for tuples of slices >>> fuse_slice((slice(100, 200), slice(100, 200, 10)), ... (slice(10, 15), [5, 2])) (slice(110, 115, None), [150, 120]) And a variety of other interesting cases >>> fuse_slice(slice(1000, 2000), 10) # integers 1010 >>> fuse_slice(slice(1000, 2000, 5), slice(10, 20, 2)) slice(1050, 1100, 10) >>> fuse_slice(slice(1000, 2000, 5), [1, 2, 3]) # lists [1005, 1010, 1015] >>> fuse_slice(None, slice(None, None)) # doctest: +SKIP None """ # None only works if the second side is a full slice if a is None and b == slice(None, None): return None # Replace None with 0 and one in start and step if isinstance(a, slice): a = normalize_slice(a) if isinstance(b, slice): b = normalize_slice(b) if isinstance(a, slice) and isinstance(b, int): if b < 0: raise NotImplementedError() return a.start + b*a.step if isinstance(a, slice) and isinstance(b, slice): start = a.start + a.step * b.start if b.stop is not None: stop = a.start + a.step * b.stop else: stop = None if a.stop is not None: if stop is not None: stop = min(a.stop, stop) else: stop = a.stop stop = stop step = a.step * b.step if step == 1: step = None return slice(start, stop, step) if isinstance(b, list): return [fuse_slice(a, bb) for bb in b] if isinstance(a, list) and isinstance(b, (int, slice)): return a[b] if isinstance(a, tuple) and not isinstance(b, tuple): b = (b,) # If given two tuples walk through both, being mindful of uneven sizes # and newaxes if isinstance(a, tuple) and isinstance(b, tuple): if (any(isinstance(item, list) for item in a) and any(isinstance(item, list) for item in b)): raise NotImplementedError("Can't handle multiple list indexing") j = 0 result = list() for i in range(len(a)): # axis ceased to exist or we're out of b if isinstance(a[i], int) or j == len(b): result.append(a[i]) continue while b[j] is None: # insert any Nones on the rhs result.append(None) j += 1 result.append(fuse_slice(a[i], b[j])) # Common case j += 1 while j < len(b): # anything leftover on the right? result.append(b[j]) j += 1 return tuple(result) raise NotImplementedError()
{ "repo_name": "pombredanne/dask", "path": "dask/array/optimization.py", "copies": "2", "size": "6442", "license": "bsd-3-clause", "hash": -9110667694733270000, "line_mean": 29.5308056872, "line_max": 78, "alpha_frac": 0.544240919, "autogenerated": false, "ratio": 3.4897074756229687, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5033948394622968, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from operator import getitem import numpy as np from .core import Array, elemwise from .. import core, sharedict from ..utils import skip_doctest def __array_wrap__(numpy_ufunc, x, *args, **kwargs): return x.__array_wrap__(numpy_ufunc(x, *args, **kwargs)) def wrap_elemwise(numpy_ufunc, array_wrap=False): """ Wrap up numpy function into dask.array """ def wrapped(*args, **kwargs): dsk = [arg for arg in args if hasattr(arg, '_elemwise')] if len(dsk) > 0: if array_wrap: return dsk[0]._elemwise(__array_wrap__, numpy_ufunc, *args, **kwargs) else: return dsk[0]._elemwise(numpy_ufunc, *args, **kwargs) else: return numpy_ufunc(*args, **kwargs) # functools.wraps cannot wrap ufunc in Python 2.x wrapped.__name__ = numpy_ufunc.__name__ wrapped.__doc__ = skip_doctest(numpy_ufunc.__doc__) return wrapped # ufuncs, copied from this page: # http://docs.scipy.org/doc/numpy/reference/ufuncs.html # math operations logaddexp = wrap_elemwise(np.logaddexp) logaddexp2 = wrap_elemwise(np.logaddexp2) conj = wrap_elemwise(np.conj) exp = wrap_elemwise(np.exp) log = wrap_elemwise(np.log) log2 = wrap_elemwise(np.log2) log10 = wrap_elemwise(np.log10) log1p = wrap_elemwise(np.log1p) expm1 = wrap_elemwise(np.expm1) sqrt = wrap_elemwise(np.sqrt) square = wrap_elemwise(np.square) # trigonometric functions sin = wrap_elemwise(np.sin) cos = wrap_elemwise(np.cos) tan = wrap_elemwise(np.tan) arcsin = wrap_elemwise(np.arcsin) arccos = wrap_elemwise(np.arccos) arctan = wrap_elemwise(np.arctan) arctan2 = wrap_elemwise(np.arctan2) hypot = wrap_elemwise(np.hypot) sinh = wrap_elemwise(np.sinh) cosh = wrap_elemwise(np.cosh) tanh = wrap_elemwise(np.tanh) arcsinh = wrap_elemwise(np.arcsinh) arccosh = wrap_elemwise(np.arccosh) arctanh = wrap_elemwise(np.arctanh) deg2rad = wrap_elemwise(np.deg2rad) rad2deg = wrap_elemwise(np.rad2deg) # comparison functions logical_and = wrap_elemwise(np.logical_and) logical_or = wrap_elemwise(np.logical_or) logical_xor = wrap_elemwise(np.logical_xor) logical_not = wrap_elemwise(np.logical_not) maximum = wrap_elemwise(np.maximum) minimum = wrap_elemwise(np.minimum) fmax = wrap_elemwise(np.fmax) fmin = wrap_elemwise(np.fmin) # floating functions isreal = wrap_elemwise(np.isreal, array_wrap=True) iscomplex = wrap_elemwise(np.iscomplex, array_wrap=True) isfinite = wrap_elemwise(np.isfinite) isinf = wrap_elemwise(np.isinf) isnan = wrap_elemwise(np.isnan) signbit = wrap_elemwise(np.signbit) copysign = wrap_elemwise(np.copysign) nextafter = wrap_elemwise(np.nextafter) # modf: see below ldexp = wrap_elemwise(np.ldexp) # frexp: see below fmod = wrap_elemwise(np.fmod) floor = wrap_elemwise(np.floor) ceil = wrap_elemwise(np.ceil) trunc = wrap_elemwise(np.trunc) # more math routines, from this page: # http://docs.scipy.org/doc/numpy/reference/routines.math.html degrees = wrap_elemwise(np.degrees) radians = wrap_elemwise(np.radians) rint = wrap_elemwise(np.rint) fix = wrap_elemwise(np.fix, array_wrap=True) angle = wrap_elemwise(np.angle, array_wrap=True) real = wrap_elemwise(np.real, array_wrap=True) imag = wrap_elemwise(np.imag, array_wrap=True) clip = wrap_elemwise(np.clip) fabs = wrap_elemwise(np.fabs) sign = wrap_elemwise(np.sign) absolute = wrap_elemwise(np.absolute) def frexp(x): # Not actually object dtype, just need to specify something tmp = elemwise(np.frexp, x, dtype=object) left = 'mantissa-' + tmp.name right = 'exponent-' + tmp.name ldsk = dict(((left,) + key[1:], (getitem, key, 0)) for key in core.flatten(tmp._keys())) rdsk = dict(((right,) + key[1:], (getitem, key, 1)) for key in core.flatten(tmp._keys())) a = np.empty((1, ), dtype=x.dtype) l, r = np.frexp(a) ldt = l.dtype rdt = r.dtype L = Array(sharedict.merge(tmp.dask, (left, ldsk)), left, chunks=tmp.chunks, dtype=ldt) R = Array(sharedict.merge(tmp.dask, (right, rdsk)), right, chunks=tmp.chunks, dtype=rdt) return L, R frexp.__doc__ = skip_doctest(np.frexp.__doc__) def modf(x): # Not actually object dtype, just need to specify something tmp = elemwise(np.modf, x, dtype=object) left = 'modf1-' + tmp.name right = 'modf2-' + tmp.name ldsk = dict(((left,) + key[1:], (getitem, key, 0)) for key in core.flatten(tmp._keys())) rdsk = dict(((right,) + key[1:], (getitem, key, 1)) for key in core.flatten(tmp._keys())) a = np.empty((1,), dtype=x.dtype) l, r = np.modf(a) ldt = l.dtype rdt = r.dtype L = Array(sharedict.merge(tmp.dask, (left, ldsk)), left, chunks=tmp.chunks, dtype=ldt) R = Array(sharedict.merge(tmp.dask, (right, rdsk)), right, chunks=tmp.chunks, dtype=rdt) return L, R modf.__doc__ = skip_doctest(np.modf.__doc__)
{ "repo_name": "cpcloud/dask", "path": "dask/array/ufunc.py", "copies": "1", "size": "4960", "license": "bsd-3-clause", "hash": 5876824666004188000, "line_mean": 30.3924050633, "line_max": 92, "alpha_frac": 0.6685483871, "autogenerated": false, "ratio": 2.8803716608594656, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40489200479594656, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from operator import getitem import numpy as np from .core import getarray, getarray_nofancy, getarray_inline from ..context import defer_to_globals from ..compatibility import zip_longest from ..core import flatten, reverse_dict from ..optimize import cull, fuse, inline_functions, dont_optimize from ..utils import ensure_dict @defer_to_globals('array_optimize', falsey=dont_optimize) def optimize(dsk, keys, fuse_keys=None, fast_functions=None, inline_functions_fast_functions=(getarray_inline,), rename_fused_keys=True, **kwargs): """ Optimize dask for array computation 1. Cull tasks not necessary to evaluate keys 2. Remove full slicing, e.g. x[:] 3. Inline fast functions like getitem and np.transpose """ dsk = ensure_dict(dsk) keys = list(flatten(keys)) if fast_functions is not None: inline_functions_fast_functions = fast_functions dsk2, dependencies = cull(dsk, keys) hold = hold_keys(dsk2, dependencies) dsk3, dependencies = fuse(dsk2, hold + keys + (fuse_keys or []), dependencies, rename_keys=rename_fused_keys) if inline_functions_fast_functions: dsk4 = inline_functions(dsk3, keys, dependencies=dependencies, fast_functions=inline_functions_fast_functions) else: dsk4 = dsk3 dsk5 = optimize_slices(dsk4) return dsk5 def hold_keys(dsk, dependencies): """ Find keys to avoid fusion We don't want to fuse data present in the graph because it is easier to serialize as a raw value. We don't want to fuse getitem/getarrays because we want to move around only small pieces of data, rather than the underlying arrays. """ dependents = reverse_dict(dependencies) data = {k for k, v in dsk.items() if type(v) not in (tuple, str)} getters = (getitem, getarray, getarray_inline) hold_keys = list(data) for dat in data: deps = dependents[dat] for dep in deps: task = dsk[dep] try: if task[0] in getters: while len(dependents[dep]) == 1: new_dep = next(iter(dependents[dep])) new_task = dsk[new_dep] if new_task[0] in (getitem, getarray): dep = new_dep task = new_task else: break hold_keys.append(dep) except (IndexError, TypeError): pass return hold_keys def optimize_slices(dsk): """ Optimize slices 1. Fuse repeated slices, like x[5:][2:6] -> x[7:11] 2. Remove full slices, like x[:] -> x See also: fuse_slice_dict """ fancy_ind_types = (list, np.ndarray) getters = (getarray_nofancy, getarray, getitem, getarray_inline) dsk = dsk.copy() for k, v in dsk.items(): if type(v) is tuple and v[0] in getters and len(v) == 3: f, a, a_index = v getter = f while type(a) is tuple and a[0] in getters and len(a) == 3: f2, b, b_index = a if (type(a_index) is tuple) != (type(b_index) is tuple): break if type(a_index) is tuple: indices = b_index + a_index if (len(a_index) != len(b_index) and any(i is None for i in indices)): break if (f2 is getarray_nofancy and any(isinstance(i, fancy_ind_types) for i in indices)): break elif (f2 is getarray_nofancy and (type(a_index) in fancy_ind_types or type(b_index) in fancy_ind_types)): break try: c_index = fuse_slice(b_index, a_index) # rely on fact that nested gets never decrease in # strictness e.g. `(getarray, (getitem, ...))` never # happens getter = f2 if getter is getarray_inline: getter = getarray except NotImplementedError: break a, a_index = b, c_index if getter is not getitem: dsk[k] = (getter, a, a_index) elif (type(a_index) is slice and not a_index.start and a_index.stop is None and a_index.step is None): dsk[k] = a elif type(a_index) is tuple and all(type(s) is slice and not s.start and s.stop is None and s.step is None for s in a_index): dsk[k] = a else: dsk[k] = (getitem, a, a_index) return dsk def normalize_slice(s): """ Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) """ start, stop, step = s.start, s.stop, s.step if start is None: start = 0 if step is None: step = 1 if start < 0 or step < 0 or stop is not None and stop < 0: raise NotImplementedError() return slice(start, stop, step) def check_for_nonfusible_fancy_indexing(fancy, normal): # Check for fancy indexing and normal indexing, where the fancy # indexed dimensions != normal indexed dimensions with integers. E.g.: # disallow things like: # x[:, [1, 2], :][0, :, :] -> x[0, [1, 2], :] or # x[0, :, :][:, [1, 2], :] -> x[0, [1, 2], :] for f, n in zip_longest(fancy, normal, fillvalue=slice(None)): if type(f) is not list and isinstance(n, int): raise NotImplementedError("Can't handle normal indexing with " "integers and fancy indexing if the " "integers and fancy indices don't " "align with the same dimensions.") def fuse_slice(a, b): """ Fuse stacked slices together Fuse a pair of repeated slices into a single slice: >>> fuse_slice(slice(1000, 2000), slice(10, 15)) slice(1010, 1015, None) This also works for tuples of slices >>> fuse_slice((slice(100, 200), slice(100, 200, 10)), ... (slice(10, 15), [5, 2])) (slice(110, 115, None), [150, 120]) And a variety of other interesting cases >>> fuse_slice(slice(1000, 2000), 10) # integers 1010 >>> fuse_slice(slice(1000, 2000, 5), slice(10, 20, 2)) slice(1050, 1100, 10) >>> fuse_slice(slice(1000, 2000, 5), [1, 2, 3]) # lists [1005, 1010, 1015] >>> fuse_slice(None, slice(None, None)) # doctest: +SKIP None """ # None only works if the second side is a full slice if a is None and b == slice(None, None): return None # Replace None with 0 and one in start and step if isinstance(a, slice): a = normalize_slice(a) if isinstance(b, slice): b = normalize_slice(b) if isinstance(a, slice) and isinstance(b, int): if b < 0: raise NotImplementedError() return a.start + b * a.step if isinstance(a, slice) and isinstance(b, slice): start = a.start + a.step * b.start if b.stop is not None: stop = a.start + a.step * b.stop else: stop = None if a.stop is not None: if stop is not None: stop = min(a.stop, stop) else: stop = a.stop stop = stop step = a.step * b.step if step == 1: step = None return slice(start, stop, step) if isinstance(b, list): return [fuse_slice(a, bb) for bb in b] if isinstance(a, list) and isinstance(b, (int, slice)): return a[b] if isinstance(a, tuple) and not isinstance(b, tuple): b = (b,) # If given two tuples walk through both, being mindful of uneven sizes # and newaxes if isinstance(a, tuple) and isinstance(b, tuple): # Check for non-fusible cases with fancy-indexing a_has_lists = any(isinstance(item, list) for item in a) b_has_lists = any(isinstance(item, list) for item in b) if a_has_lists and b_has_lists: raise NotImplementedError("Can't handle multiple list indexing") elif a_has_lists: check_for_nonfusible_fancy_indexing(a, b) elif b_has_lists: check_for_nonfusible_fancy_indexing(b, a) j = 0 result = list() for i in range(len(a)): # axis ceased to exist or we're out of b if isinstance(a[i], int) or j == len(b): result.append(a[i]) continue while b[j] is None: # insert any Nones on the rhs result.append(None) j += 1 result.append(fuse_slice(a[i], b[j])) # Common case j += 1 while j < len(b): # anything leftover on the right? result.append(b[j]) j += 1 return tuple(result) raise NotImplementedError()
{ "repo_name": "mraspaud/dask", "path": "dask/array/optimization.py", "copies": "1", "size": "9493", "license": "bsd-3-clause", "hash": -441631903088059000, "line_mean": 34.421641791, "line_max": 88, "alpha_frac": 0.5282839987, "autogenerated": false, "ratio": 3.9049773755656108, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49332613742656106, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from operator import getitem import numpy as np from .core import getarray, getarray_nofancy, getarray_inline from ..core import flatten, reverse_dict from ..optimize import cull, fuse, inline_functions from ..utils import ensure_dict def optimize(dsk, keys, fuse_keys=None, fast_functions=None, inline_functions_fast_functions=(getarray_inline,), rename_fused_keys=True, **kwargs): """ Optimize dask for array computation 1. Cull tasks not necessary to evaluate keys 2. Remove full slicing, e.g. x[:] 3. Inline fast functions like getitem and np.transpose """ dsk = ensure_dict(dsk) keys = list(flatten(keys)) if fast_functions is not None: inline_functions_fast_functions = fast_functions dsk2, dependencies = cull(dsk, keys) hold = hold_keys(dsk2, dependencies) dsk3, dependencies = fuse(dsk2, hold + keys + (fuse_keys or []), dependencies, rename_keys=rename_fused_keys) if inline_functions_fast_functions: dsk4 = inline_functions(dsk3, keys, dependencies=dependencies, fast_functions=inline_functions_fast_functions) else: dsk4 = dsk3 dsk5 = optimize_slices(dsk4) return dsk5 def hold_keys(dsk, dependencies): """ Find keys to avoid fusion We don't want to fuse data present in the graph because it is easier to serialize as a raw value. We don't want to fuse getitem/getarrays because we want to move around only small pieces of data, rather than the underlying arrays. """ dependents = reverse_dict(dependencies) data = {k for k, v in dsk.items() if type(v) not in (tuple, str)} getters = (getitem, getarray, getarray_inline) hold_keys = list(data) for dat in data: deps = dependents[dat] for dep in deps: task = dsk[dep] try: if task[0] in getters: while len(dependents[dep]) == 1: new_dep = next(iter(dependents[dep])) new_task = dsk[new_dep] if new_task[0] in (getitem, getarray): dep = new_dep task = new_task else: break hold_keys.append(dep) except (IndexError, TypeError): pass return hold_keys def optimize_slices(dsk): """ Optimize slices 1. Fuse repeated slices, like x[5:][2:6] -> x[7:11] 2. Remove full slices, like x[:] -> x See also: fuse_slice_dict """ fancy_ind_types = (list, np.ndarray) getters = (getarray_nofancy, getarray, getitem, getarray_inline) dsk = dsk.copy() for k, v in dsk.items(): if type(v) is tuple and v[0] in getters and len(v) == 3: f, a, a_index = v getter = f while type(a) is tuple and a[0] in getters and len(a) == 3: f2, b, b_index = a if (type(a_index) is tuple) != (type(b_index) is tuple): break if type(a_index) is tuple: indices = b_index + a_index if (len(a_index) != len(b_index) and any(i is None for i in indices)): break if (f2 is getarray_nofancy and any(isinstance(i, fancy_ind_types) for i in indices)): break elif (f2 is getarray_nofancy and (type(a_index) in fancy_ind_types or type(b_index) in fancy_ind_types)): break try: c_index = fuse_slice(b_index, a_index) # rely on fact that nested gets never decrease in # strictness e.g. `(getarray, (getitem, ...))` never # happens getter = f2 if getter is getarray_inline: getter = getarray except NotImplementedError: break a, a_index = b, c_index if getter is not getitem: dsk[k] = (getter, a, a_index) elif (type(a_index) is slice and not a_index.start and a_index.stop is None and a_index.step is None): dsk[k] = a elif type(a_index) is tuple and all(type(s) is slice and not s.start and s.stop is None and s.step is None for s in a_index): dsk[k] = a else: dsk[k] = (getitem, a, a_index) return dsk def normalize_slice(s): """ Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) """ start, stop, step = s.start, s.stop, s.step if start is None: start = 0 if step is None: step = 1 if start < 0 or step < 0 or stop is not None and stop < 0: raise NotImplementedError() return slice(start, stop, step) def fuse_slice(a, b): """ Fuse stacked slices together Fuse a pair of repeated slices into a single slice: >>> fuse_slice(slice(1000, 2000), slice(10, 15)) slice(1010, 1015, None) This also works for tuples of slices >>> fuse_slice((slice(100, 200), slice(100, 200, 10)), ... (slice(10, 15), [5, 2])) (slice(110, 115, None), [150, 120]) And a variety of other interesting cases >>> fuse_slice(slice(1000, 2000), 10) # integers 1010 >>> fuse_slice(slice(1000, 2000, 5), slice(10, 20, 2)) slice(1050, 1100, 10) >>> fuse_slice(slice(1000, 2000, 5), [1, 2, 3]) # lists [1005, 1010, 1015] >>> fuse_slice(None, slice(None, None)) # doctest: +SKIP None """ # None only works if the second side is a full slice if a is None and b == slice(None, None): return None # Replace None with 0 and one in start and step if isinstance(a, slice): a = normalize_slice(a) if isinstance(b, slice): b = normalize_slice(b) if isinstance(a, slice) and isinstance(b, int): if b < 0: raise NotImplementedError() return a.start + b * a.step if isinstance(a, slice) and isinstance(b, slice): start = a.start + a.step * b.start if b.stop is not None: stop = a.start + a.step * b.stop else: stop = None if a.stop is not None: if stop is not None: stop = min(a.stop, stop) else: stop = a.stop stop = stop step = a.step * b.step if step == 1: step = None return slice(start, stop, step) if isinstance(b, list): return [fuse_slice(a, bb) for bb in b] if isinstance(a, list) and isinstance(b, (int, slice)): return a[b] if isinstance(a, tuple) and not isinstance(b, tuple): b = (b,) # If given two tuples walk through both, being mindful of uneven sizes # and newaxes if isinstance(a, tuple) and isinstance(b, tuple): if (any(isinstance(item, list) for item in a) and any(isinstance(item, list) for item in b)): raise NotImplementedError("Can't handle multiple list indexing") j = 0 result = list() for i in range(len(a)): # axis ceased to exist or we're out of b if isinstance(a[i], int) or j == len(b): result.append(a[i]) continue while b[j] is None: # insert any Nones on the rhs result.append(None) j += 1 result.append(fuse_slice(a[i], b[j])) # Common case j += 1 while j < len(b): # anything leftover on the right? result.append(b[j]) j += 1 return tuple(result) raise NotImplementedError()
{ "repo_name": "cpcloud/dask", "path": "dask/array/optimization.py", "copies": "1", "size": "8321", "license": "bsd-3-clause", "hash": 8832774116819168000, "line_mean": 32.9632653061, "line_max": 88, "alpha_frac": 0.5200096142, "autogenerated": false, "ratio": 3.9194536033914273, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4939463217591427, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from operator import getitem import numpy as np from .core import getarray, getarray_nofancy from ..core import flatten from ..optimize import cull, fuse, inline_functions def optimize(dsk, keys, fuse_keys=None, fast_functions=None, inline_functions_fast_functions=None, **kwargs): """ Optimize dask for array computation 1. Cull tasks not necessary to evaluate keys 2. Remove full slicing, e.g. x[:] 3. Inline fast functions like getitem and np.transpose """ keys = list(flatten(keys)) if fast_functions is not None: inline_functions_fast_functions = fast_functions if inline_functions_fast_functions is None: inline_functions_fast_functions = {getarray, getarray_nofancy, np.transpose} dsk2, dependencies = cull(dsk, keys) dsk4, dependencies = fuse(dsk2, keys + (fuse_keys or []), dependencies) dsk5 = optimize_slices(dsk4) dsk6 = inline_functions(dsk5, keys, dependencies=dependencies, fast_functions=inline_functions_fast_functions) return dsk6 def optimize_slices(dsk): """ Optimize slices 1. Fuse repeated slices, like x[5:][2:6] -> x[7:11] 2. Remove full slices, like x[:] -> x See also: fuse_slice_dict """ fancy_ind_types = (list, np.ndarray) getters = (getarray_nofancy, getarray, getitem) dsk = dsk.copy() for k, v in dsk.items(): if type(v) is tuple and v[0] in getters and len(v) == 3: f, a, a_index = v getter = f while type(a) is tuple and a[0] in getters and len(a) == 3: f2, b, b_index = a if (type(a_index) is tuple) != (type(b_index) is tuple): break if type(a_index) is tuple: indices = b_index + a_index if (len(a_index) != len(b_index) and any(i is None for i in indices)): break if (f2 is getarray_nofancy and any(isinstance(i, fancy_ind_types) for i in indices)): break elif (f2 is getarray_nofancy and (type(a_index) in fancy_ind_types or type(b_index) in fancy_ind_types)): break try: c_index = fuse_slice(b_index, a_index) # rely on fact that nested gets never decrease in # strictness e.g. `(getarray, (getitem, ...))` never # happens getter = f2 except NotImplementedError: break a, a_index = b, c_index if getter is not getitem: dsk[k] = (getter, a, a_index) elif (type(a_index) is slice and not a_index.start and a_index.stop is None and a_index.step is None): dsk[k] = a elif type(a_index) is tuple and all(type(s) is slice and not s.start and s.stop is None and s.step is None for s in a_index): dsk[k] = a else: dsk[k] = (getitem, a, a_index) return dsk def normalize_slice(s): """ Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) """ start, stop, step = s.start, s.stop, s.step if start is None: start = 0 if step is None: step = 1 if start < 0 or step < 0 or stop is not None and stop < 0: raise NotImplementedError() return slice(start, stop, step) def fuse_slice(a, b): """ Fuse stacked slices together Fuse a pair of repeated slices into a single slice: >>> fuse_slice(slice(1000, 2000), slice(10, 15)) slice(1010, 1015, None) This also works for tuples of slices >>> fuse_slice((slice(100, 200), slice(100, 200, 10)), ... (slice(10, 15), [5, 2])) (slice(110, 115, None), [150, 120]) And a variety of other interesting cases >>> fuse_slice(slice(1000, 2000), 10) # integers 1010 >>> fuse_slice(slice(1000, 2000, 5), slice(10, 20, 2)) slice(1050, 1100, 10) >>> fuse_slice(slice(1000, 2000, 5), [1, 2, 3]) # lists [1005, 1010, 1015] >>> fuse_slice(None, slice(None, None)) # doctest: +SKIP None """ # None only works if the second side is a full slice if a is None and b == slice(None, None): return None # Replace None with 0 and one in start and step if isinstance(a, slice): a = normalize_slice(a) if isinstance(b, slice): b = normalize_slice(b) if isinstance(a, slice) and isinstance(b, int): if b < 0: raise NotImplementedError() return a.start + b * a.step if isinstance(a, slice) and isinstance(b, slice): start = a.start + a.step * b.start if b.stop is not None: stop = a.start + a.step * b.stop else: stop = None if a.stop is not None: if stop is not None: stop = min(a.stop, stop) else: stop = a.stop stop = stop step = a.step * b.step if step == 1: step = None return slice(start, stop, step) if isinstance(b, list): return [fuse_slice(a, bb) for bb in b] if isinstance(a, list) and isinstance(b, (int, slice)): return a[b] if isinstance(a, tuple) and not isinstance(b, tuple): b = (b,) # If given two tuples walk through both, being mindful of uneven sizes # and newaxes if isinstance(a, tuple) and isinstance(b, tuple): if (any(isinstance(item, list) for item in a) and any(isinstance(item, list) for item in b)): raise NotImplementedError("Can't handle multiple list indexing") j = 0 result = list() for i in range(len(a)): # axis ceased to exist or we're out of b if isinstance(a[i], int) or j == len(b): result.append(a[i]) continue while b[j] is None: # insert any Nones on the rhs result.append(None) j += 1 result.append(fuse_slice(a[i], b[j])) # Common case j += 1 while j < len(b): # anything leftover on the right? result.append(b[j]) j += 1 return tuple(result) raise NotImplementedError()
{ "repo_name": "gameduell/dask", "path": "dask/array/optimization.py", "copies": "2", "size": "6875", "license": "bsd-3-clause", "hash": 8333226358619629000, "line_mean": 32.7009803922, "line_max": 82, "alpha_frac": 0.5197090909, "autogenerated": false, "ratio": 3.8601909039865245, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5379899994886524, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from operator import getitem import numpy as np from .core import getarray from ..core import flatten from ..optimize import cull, fuse, inline_functions def optimize(dsk, keys, **kwargs): """ Optimize dask for array computation 1. Cull tasks not necessary to evaluate keys 2. Remove full slicing, e.g. x[:] 3. Inline fast functions like getitem and np.transpose """ keys = list(flatten(keys)) fast_functions = kwargs.get('fast_functions', set([getarray, np.transpose])) dsk2, dependencies = cull(dsk, keys) dsk4, dependencies = fuse(dsk2, keys, dependencies) dsk5 = optimize_slices(dsk4) dsk6 = inline_functions(dsk5, keys, fast_functions=fast_functions, dependencies=dependencies) return dsk6 def optimize_slices(dsk): """ Optimize slices 1. Fuse repeated slices, like x[5:][2:6] -> x[7:11] 2. Remove full slices, like x[:] -> x See also: fuse_slice_dict """ getters = (getarray, getitem) dsk = dsk.copy() for k, v in dsk.items(): if type(v) is tuple: if v[0] in getters: try: func, a, a_index = v use_getarray = func is getarray except ValueError: # has four elements, includes a lock continue while type(a) is tuple and a[0] in getters: try: f2, b, b_index = a use_getarray |= f2 is getarray except ValueError: # has four elements, includes a lock break if (type(a_index) is tuple) != (type(b_index) is tuple): break if ((type(a_index) is tuple) and (len(a_index) != len(b_index)) and any(i is None for i in b_index + a_index)): break try: c_index = fuse_slice(b_index, a_index) except NotImplementedError: break (a, a_index) = (b, c_index) if use_getarray: dsk[k] = (getarray, a, a_index) elif (type(a_index) is slice and not a_index.start and a_index.stop is None and a_index.step is None): dsk[k] = a elif type(a_index) is tuple and all(type(s) is slice and not s.start and s.stop is None and s.step is None for s in a_index): dsk[k] = a else: dsk[k] = (getitem, a, a_index) return dsk def normalize_slice(s): """ Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) """ start, stop, step = s.start, s.stop, s.step if start is None: start = 0 if step is None: step = 1 if start < 0 or step < 0 or stop is not None and stop < 0: raise NotImplementedError() return slice(start, stop, step) def fuse_slice(a, b): """ Fuse stacked slices together Fuse a pair of repeated slices into a single slice: >>> fuse_slice(slice(1000, 2000), slice(10, 15)) slice(1010, 1015, None) This also works for tuples of slices >>> fuse_slice((slice(100, 200), slice(100, 200, 10)), ... (slice(10, 15), [5, 2])) (slice(110, 115, None), [150, 120]) And a variety of other interesting cases >>> fuse_slice(slice(1000, 2000), 10) # integers 1010 >>> fuse_slice(slice(1000, 2000, 5), slice(10, 20, 2)) slice(1050, 1100, 10) >>> fuse_slice(slice(1000, 2000, 5), [1, 2, 3]) # lists [1005, 1010, 1015] >>> fuse_slice(None, slice(None, None)) # doctest: +SKIP None """ # None only works if the second side is a full slice if a is None and b == slice(None, None): return None # Replace None with 0 and one in start and step if isinstance(a, slice): a = normalize_slice(a) if isinstance(b, slice): b = normalize_slice(b) if isinstance(a, slice) and isinstance(b, int): if b < 0: raise NotImplementedError() return a.start + b*a.step if isinstance(a, slice) and isinstance(b, slice): start = a.start + a.step * b.start if b.stop is not None: stop = a.start + a.step * b.stop else: stop = None if a.stop is not None: if stop is not None: stop = min(a.stop, stop) else: stop = a.stop stop = stop step = a.step * b.step if step == 1: step = None return slice(start, stop, step) if isinstance(b, list): return [fuse_slice(a, bb) for bb in b] if isinstance(a, list) and isinstance(b, (int, slice)): return a[b] if isinstance(a, tuple) and not isinstance(b, tuple): b = (b,) # If given two tuples walk through both, being mindful of uneven sizes # and newaxes if isinstance(a, tuple) and isinstance(b, tuple): if (any(isinstance(item, list) for item in a) and any(isinstance(item, list) for item in b)): raise NotImplementedError("Can't handle multiple list indexing") j = 0 result = list() for i in range(len(a)): # axis ceased to exist or we're out of b if isinstance(a[i], int) or j == len(b): result.append(a[i]) continue while b[j] is None: # insert any Nones on the rhs result.append(None) j += 1 result.append(fuse_slice(a[i], b[j])) # Common case j += 1 while j < len(b): # anything leftover on the right? result.append(b[j]) j += 1 return tuple(result) raise NotImplementedError()
{ "repo_name": "mikegraham/dask", "path": "dask/array/optimization.py", "copies": "2", "size": "6346", "license": "bsd-3-clause", "hash": 7372335749904146000, "line_mean": 32.0520833333, "line_max": 76, "alpha_frac": 0.5047273873, "autogenerated": false, "ratio": 3.93184634448575, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 192 }
from __future__ import absolute_import, division, print_function from operator import getitem import numpy as np from toolz.curried import merge from .core import Array, elemwise from .. import core from ..utils import skip_doctest def __array_wrap__(numpy_ufunc, x, *args, **kwargs): return x.__array_wrap__(numpy_ufunc(x, *args, **kwargs)) def wrap_elemwise(numpy_ufunc, array_wrap=False): """ Wrap up numpy function into dask.array """ def wrapped(*args, **kwargs): dsk = [arg for arg in args if hasattr(arg, '_elemwise')] if len(dsk) > 0: if array_wrap: return dsk[0]._elemwise(__array_wrap__, numpy_ufunc, *args, **kwargs) else: return dsk[0]._elemwise(numpy_ufunc, *args, **kwargs) else: return numpy_ufunc(*args, **kwargs) # functools.wraps cannot wrap ufunc in Python 2.x wrapped.__name__ = numpy_ufunc.__name__ wrapped.__doc__ = skip_doctest(numpy_ufunc.__doc__) return wrapped # ufuncs, copied from this page: # http://docs.scipy.org/doc/numpy/reference/ufuncs.html # math operations logaddexp = wrap_elemwise(np.logaddexp) logaddexp2 = wrap_elemwise(np.logaddexp2) conj = wrap_elemwise(np.conj) exp = wrap_elemwise(np.exp) log = wrap_elemwise(np.log) log2 = wrap_elemwise(np.log2) log10 = wrap_elemwise(np.log10) log1p = wrap_elemwise(np.log1p) expm1 = wrap_elemwise(np.expm1) sqrt = wrap_elemwise(np.sqrt) square = wrap_elemwise(np.square) # trigonometric functions sin = wrap_elemwise(np.sin) cos = wrap_elemwise(np.cos) tan = wrap_elemwise(np.tan) arcsin = wrap_elemwise(np.arcsin) arccos = wrap_elemwise(np.arccos) arctan = wrap_elemwise(np.arctan) arctan2 = wrap_elemwise(np.arctan2) hypot = wrap_elemwise(np.hypot) sinh = wrap_elemwise(np.sinh) cosh = wrap_elemwise(np.cosh) tanh = wrap_elemwise(np.tanh) arcsinh = wrap_elemwise(np.arcsinh) arccosh = wrap_elemwise(np.arccosh) arctanh = wrap_elemwise(np.arctanh) deg2rad = wrap_elemwise(np.deg2rad) rad2deg = wrap_elemwise(np.rad2deg) # comparison functions logical_and = wrap_elemwise(np.logical_and) logical_or = wrap_elemwise(np.logical_or) logical_xor = wrap_elemwise(np.logical_xor) logical_not = wrap_elemwise(np.logical_not) maximum = wrap_elemwise(np.maximum) minimum = wrap_elemwise(np.minimum) fmax = wrap_elemwise(np.fmax) fmin = wrap_elemwise(np.fmin) # floating functions isreal = wrap_elemwise(np.isreal, array_wrap=True) iscomplex = wrap_elemwise(np.iscomplex, array_wrap=True) isfinite = wrap_elemwise(np.isfinite) isinf = wrap_elemwise(np.isinf) isnan = wrap_elemwise(np.isnan) signbit = wrap_elemwise(np.signbit) copysign = wrap_elemwise(np.copysign) nextafter = wrap_elemwise(np.nextafter) # modf: see below ldexp = wrap_elemwise(np.ldexp) # frexp: see below fmod = wrap_elemwise(np.fmod) floor = wrap_elemwise(np.floor) ceil = wrap_elemwise(np.ceil) trunc = wrap_elemwise(np.trunc) # more math routines, from this page: # http://docs.scipy.org/doc/numpy/reference/routines.math.html degrees = wrap_elemwise(np.degrees) radians = wrap_elemwise(np.radians) rint = wrap_elemwise(np.rint) fix = wrap_elemwise(np.fix, array_wrap=True) angle = wrap_elemwise(np.angle, array_wrap=True) real = wrap_elemwise(np.real, array_wrap=True) imag = wrap_elemwise(np.imag, array_wrap=True) clip = wrap_elemwise(np.clip) fabs = wrap_elemwise(np.fabs) sign = wrap_elemwise(np.sign) absolute = wrap_elemwise(np.absolute) def frexp(x): # Not actually object dtype, just need to specify something tmp = elemwise(np.frexp, x, dtype=object) left = 'mantissa-' + tmp.name right = 'exponent-' + tmp.name ldsk = dict(((left,) + key[1:], (getitem, key, 0)) for key in core.flatten(tmp._keys())) rdsk = dict(((right,) + key[1:], (getitem, key, 1)) for key in core.flatten(tmp._keys())) a = np.empty((1, ), dtype=x.dtype) l, r = np.frexp(a) ldt = l.dtype rdt = r.dtype L = Array(merge(tmp.dask, ldsk), left, chunks=tmp.chunks, dtype=ldt) R = Array(merge(tmp.dask, rdsk), right, chunks=tmp.chunks, dtype=rdt) return L, R frexp.__doc__ = skip_doctest(np.frexp.__doc__) def modf(x): # Not actually object dtype, just need to specify something tmp = elemwise(np.modf, x, dtype=object) left = 'modf1-' + tmp.name right = 'modf2-' + tmp.name ldsk = dict(((left,) + key[1:], (getitem, key, 0)) for key in core.flatten(tmp._keys())) rdsk = dict(((right,) + key[1:], (getitem, key, 1)) for key in core.flatten(tmp._keys())) a = np.empty((1,), dtype=x.dtype) l, r = np.modf(a) ldt = l.dtype rdt = r.dtype L = Array(merge(tmp.dask, ldsk), left, chunks=tmp.chunks, dtype=ldt) R = Array(merge(tmp.dask, rdsk), right, chunks=tmp.chunks, dtype=rdt) return L, R modf.__doc__ = skip_doctest(np.modf.__doc__)
{ "repo_name": "chrisbarber/dask", "path": "dask/array/ufunc.py", "copies": "2", "size": "4907", "license": "bsd-3-clause", "hash": -8563166258834065000, "line_mean": 29.8616352201, "line_max": 73, "alpha_frac": 0.668432851, "autogenerated": false, "ratio": 2.879694835680751, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4548127686680752, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from operator import itemgetter import pytest pymongo = pytest.importorskip('pymongo') from datetime import datetime from toolz import pluck, reduceby, groupby from blaze import into, compute, compute_up, discover, dshape from blaze.compute.mongo import MongoQuery from blaze.expr import Symbol, by from blaze.compatibility import xfail @pytest.fixture(scope='module') def conn(): try: return pymongo.MongoClient() except pymongo.errors.ConnectionFailure: pytest.skip('No mongo server running') @pytest.fixture(scope='module') def db(conn): return conn.test_db bank_raw = [{'name': 'Alice', 'amount': 100}, {'name': 'Alice', 'amount': 200}, {'name': 'Bob', 'amount': 100}, {'name': 'Bob', 'amount': 200}, {'name': 'Bob', 'amount': 300}] @pytest.yield_fixture def big_bank(db): data = [{'name': 'Alice', 'amount': 100, 'city': 'New York City'}, {'name': 'Alice', 'amount': 200, 'city': 'Austin'}, {'name': 'Bob', 'amount': 100, 'city': 'New York City'}, {'name': 'Bob', 'amount': 200, 'city': 'New York City'}, {'name': 'Bob', 'amount': 300, 'city': 'San Francisco'}] coll = db.bigbank coll = into(coll, data) yield coll coll.drop() @pytest.yield_fixture def date_data(db): import numpy as np import pandas as pd n = 3 d = {'name': ['Alice', 'Bob', 'Joe'], 'when': [datetime(2010, 1, 1, i) for i in [1, 2, 3]], 'amount': [100, 200, 300], 'id': [1, 2, 3]} data = [dict(zip(d.keys(), [d[k][i] for k in d.keys()])) for i in range(n)] coll = into(db.date_coll, data) yield coll coll.drop() @pytest.yield_fixture def bank(db): coll = db.tmp_collection coll = into(coll, bank_raw) yield coll coll.drop() @pytest.yield_fixture def missing_vals(db): data = [{'x': 1, 'z': 100}, {'x': 2, 'y': 20, 'z': 200}, {'x': 3, 'z': 300}, {'x': 4, 'y': 40}] coll = db.tmp_collection coll = into(coll, data) yield coll coll.drop() @pytest.yield_fixture def points(db): data = [{'x': 1, 'y': 10, 'z': 100}, {'x': 2, 'y': 20, 'z': 200}, {'x': 3, 'y': 30, 'z': 300}, {'x': 4, 'y': 40, 'z': 400}] coll = db.tmp_collection coll = into(coll, data) yield coll coll.drop() @pytest.yield_fixture def events(db): data = [{'time': datetime(2012, 1, 1, 12, 00, 00), 'x': 1}, {'time': datetime(2012, 1, 2, 12, 00, 00), 'x': 2}, {'time': datetime(2012, 1, 3, 12, 00, 00), 'x': 3}] coll = db.tmp_collection coll = into(coll, data) yield coll coll.drop() t = Symbol('t', 'var * {name: string, amount: int}') bigt = Symbol('bigt', 'var * {name: string, amount: int, city: string}') p = Symbol('p', 'var * {x: int, y: int, z: int}') e = Symbol('e', 'var * {time: datetime, x: int}') q = MongoQuery('fake', []) def test_symbol_one(bank): assert compute_up(t, bank) == MongoQuery(bank, ()) def test_symbol(bank): assert compute(t, bank) == list(pluck(['name', 'amount'], bank_raw)) def test_projection_one(): assert compute_up(t[['name']], q).query == ({'$project': {'name': 1}},) def test_head_one(): assert compute_up(t.head(5), q).query == ({'$limit': 5},) def test_head(bank): assert len(compute(t.head(2), bank)) == 2 def test_projection(bank): assert set(compute(t.name, bank)) == set(['Alice', 'Bob']) assert set(compute(t[['name']], bank)) == set([('Alice',), ('Bob',)]) def test_selection(bank): assert set(compute(t[t.name=='Alice'], bank)) == set([('Alice', 100), ('Alice', 200)]) assert set(compute(t['Alice'==t.name], bank)) == set([('Alice', 100), ('Alice', 200)]) assert set(compute(t[t.amount > 200], bank)) == set([('Bob', 300)]) assert set(compute(t[t.amount >= 200], bank)) == set([('Bob', 300), ('Bob', 200), ('Alice', 200)]) assert set(compute(t[t.name!='Alice'].name, bank)) == set(['Bob']) assert set(compute(t[(t.name=='Alice') & (t.amount > 150)], bank)) == \ set([('Alice', 200)]) assert set(compute(t[(t.name=='Alice') | (t.amount > 250)], bank)) == \ set([('Alice', 200), ('Alice', 100), ('Bob', 300)]) def test_columnwise(points): assert set(compute(p.x + p.y, points)) == set([11, 22, 33, 44]) def test_columnwise_multiple_operands(points): expected = [x['x'] + x['y'] - x['z'] * x['x'] / 2 for x in points.find()] assert set(compute(p.x + p.y - p.z * p.x / 2, points)) == set(expected) def test_columnwise_mod(points): expected = [x['x'] % x['y'] - x['z'] * x['x'] / 2 + 1 for x in points.find()] expr = p.x % p.y - p.z * p.x / 2 + 1 assert set(compute(expr, points)) == set(expected) @xfail(raises=NotImplementedError, reason='MongoDB does not implement certain arith ops') def test_columnwise_pow(points): expected = [x['x'] ** x['y'] for x in points.find()] assert set(compute(p.x ** p.y, points)) == set(expected) def test_by_one(): assert compute_up(by(t.name, t.amount.sum()), q).query == \ ({'$group': {'_id': {'name': '$name'}, 'amount_sum': {'$sum': '$amount'}}}, {'$project': {'amount_sum': '$amount_sum', 'name': '$_id.name'}}) def test_by(bank): assert set(compute(by(t.name, t.amount.sum()), bank)) == \ set([('Alice', 300), ('Bob', 600)]) assert set(compute(by(t.name, t.amount.min()), bank)) == \ set([('Alice', 100), ('Bob', 100)]) assert set(compute(by(t.name, t.amount.max()), bank)) == \ set([('Alice', 200), ('Bob', 300)]) assert set(compute(by(t.name, t.name.count()), bank)) == \ set([('Alice', 2), ('Bob', 3)]) def test_reductions(bank): assert compute(t.amount.min(), bank) == 100 assert compute(t.amount.max(), bank) == 300 assert compute(t.amount.sum(), bank) == 900 def test_distinct(bank): assert set(compute(t.name.distinct(), bank)) == set(['Alice', 'Bob']) def test_sort(bank): assert compute(t.amount.sort('amount'), bank) == \ [100, 100, 200, 200, 300] assert compute(t.amount.sort('amount', ascending=False), bank) == \ [300, 200, 200, 100, 100] def test_by_multi_column(bank): assert set(compute(by(t[['name', 'amount']], t.count()), bank)) == \ set([(d['name'], d['amount'], 1) for d in bank_raw]) def test_datetime_handling(events): assert set(compute(e[e.time >= datetime(2012, 1, 2, 12, 0, 0)].x, events)) == set([2, 3]) assert set(compute(e[e.time >= "2012-01-02"].x, events)) == set([2, 3]) def test_summary_kwargs(bank): expr = by(t.name, total=t.amount.sum(), avg=t.amount.mean()) result = compute(expr, bank) assert result == [('Bob', 200.0, 600), ('Alice', 150.0, 300)] def test_summary_count(bank): expr = by(t.name, how_many=t.amount.count()) result = compute(expr, bank) assert result == [('Bob', 3), ('Alice', 2)] def test_summary_arith(bank): expr = by(t.name, add_one_and_sum=(t.amount + 1).sum()) result = compute(expr, bank) assert result == [('Bob', 603), ('Alice', 302)] def test_summary_arith_min(bank): expr = by(t.name, add_one_and_sum=(t.amount + 1).min()) result = compute(expr, bank) assert result == [('Bob', 101), ('Alice', 101)] def test_summary_arith_max(bank): expr = by(t.name, add_one_and_sum=(t.amount + 1).max()) result = compute(expr, bank) assert result == [('Bob', 301), ('Alice', 201)] def test_summary_complex_arith(bank): expr = by(t.name, arith=(100 - t.amount * 2 / 30.0).sum()) result = compute(expr, bank) reducer = lambda acc, x: (100 - x['amount'] * 2 / 30.0) + acc expected = reduceby('name', reducer, bank.find(), 0) assert set(result) == set(expected.items()) def test_summary_complex_arith_multiple(bank): expr = by(t.name, arith=(100 - t.amount * 2 / 30.0).sum(), other=t.amount.mean()) result = compute(expr, bank) reducer = lambda acc, x: (100 - x['amount'] * 2 / 30.0) + acc expected = reduceby('name', reducer, bank.find(), 0) mu = reduceby('name', lambda acc, x: acc + x['amount'], bank.find(), 0.0) values = list(mu.values()) items = expected.items() counts = groupby('name', bank.find()) items = [x + (float(v) / len(counts[x[0]]),) for x, v in zip(items, values)] assert set(result) == set(items) def test_like(bank): bank.create_index([('name', pymongo.TEXT)]) expr = t.like(name='*Alice*') result = compute(expr, bank) assert set(result) == set((('Alice', 100), ('Alice', 200))) def test_like_multiple(big_bank): expr = bigt.like(name='*Bob*', city='*York*') result = compute(expr, big_bank) assert set(result) == set((('Bob', 100, 'New York City'), ('Bob', 200, 'New York City'))) def test_like_mulitple_no_match(big_bank): # make sure we aren't OR-ing the matches expr = bigt.like(name='*York*', city='*Bob*') result = compute(expr, big_bank) assert not set(result) def test_missing_values(missing_vals): assert discover(missing_vals).subshape[0] == \ dshape('{x: int64, y: ?int64, z: ?int64}') assert set(compute(p.y, missing_vals)) == set([None, 20, None, 40]) def test_datetime_access(date_data): t = Symbol('t', 'var * {amount: float64, id: int64, name: string, when: datetime}') py_data = into(list, date_data) # a python version of the collection for attr in ['day', 'minute', 'second', 'year']: assert list(compute(getattr(t.when, attr), date_data)) == \ list(compute(getattr(t.when, attr), py_data))
{ "repo_name": "vitan/blaze", "path": "blaze/compute/tests/test_mongo_compute.py", "copies": "1", "size": "10164", "license": "bsd-3-clause", "hash": -7137227017217407000, "line_mean": 30.7625, "line_max": 80, "alpha_frac": 0.5424045651, "autogenerated": false, "ratio": 3.181220657276995, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9215284297299366, "avg_score": 0.0016681850155258588, "num_lines": 320 }
from __future__ import absolute_import, division, print_function from optparse import SUPPRESS_HELP, OptionParser import workflows import workflows.frontend import workflows.services import workflows.transport class ServiceStarter(object): '''A helper class to start a workflows service from the command line. A number of hooks are provided so that this class can be subclassed and used in a number of scenarios.''' @staticmethod def on_parser_preparation(parser): '''Plugin hook to manipulate the OptionParser object before command line parsing. If a value is returned here it will replace the OptionParser object.''' @staticmethod def on_parsing(options, args): '''Plugin hook to manipulate the command line parsing results. A tuple of values can be returned, which will replace (options, args). ''' @staticmethod def on_transport_factory_preparation(transport_factory): '''Plugin hook to intercept/manipulate newly created Transport factories before first invocation.''' @staticmethod def on_transport_preparation(transport): '''Plugin hook to intercept/manipulate newly created Transport objects before connecting.''' @staticmethod def before_frontend_construction(kwargs): '''Plugin hook to manipulate the Frontend object constructor arguments. If a value is returned here it will replace the keyword arguments dictionary passed to the constructor.''' @staticmethod def on_frontend_preparation(frontend): '''Plugin hook to manipulate the Frontend object before starting it. If a value is returned here it will replace the Frontend object.''' def run(self, cmdline_args=None, program_name='start_service', version=workflows.version(), **kwargs): '''Example command line interface to start services. :param cmdline_args: List of command line arguments to pass to parser :param program_name: Name of the command line tool to display in help :param version: Version number to print when run with '--version' ''' # Enumerate all known services known_services = workflows.services.get_known_services() # Set up parser parser = OptionParser( usage=program_name + ' [options]' if program_name else None, version=version ) parser.add_option("-?", action="help", help=SUPPRESS_HELP) parser.add_option("-s", "--service", dest="service", metavar="SVC", default=None, help="Name of the service to start. Known services: " + \ ", ".join(known_services)) parser.add_option("-t", "--transport", dest="transport", metavar="TRN", default="StompTransport", help="Transport mechanism. Known mechanisms: " + \ ", ".join(workflows.transport.get_known_transports()) + \ " (default: %default)") workflows.transport.add_command_line_options(parser) # Call on_parser_preparation hook parser = self.on_parser_preparation(parser) or parser # Parse command line options (options, args) = parser.parse_args(cmdline_args) # Call on_parsing hook (options, args) = self.on_parsing(options, args) or (options, args) # Create Transport factory transport_factory = workflows.transport.lookup(options.transport) # Call on_transport_factory_preparation hook transport_factory = self.on_transport_factory_preparation(transport_factory) or transport_factory # Set up on_transport_preparation hook to affect newly created transport objects true_transport_factory_call = transport_factory.__call__ def on_transport_preparation_hook(): transport_object = true_transport_factory_call() return self.on_transport_preparation(transport_object) or transport_object transport_factory.__call__ = on_transport_preparation_hook # When service name is specified, check if service exists or can be derived if options.service and options.service not in known_services: matching = [ s for s in known_services if s.startswith(options.service) ] if not matching: matching = [ s for s in known_services if s.lower().startswith(options.service.lower()) ] if matching and len(matching) == 1: options.service = matching[0] kwargs.update({ 'service': options.service, 'transport': transport_factory }) # Call before_frontend_construction hook kwargs = self.before_frontend_construction(kwargs) or kwargs # Create Frontend object frontend = workflows.frontend.Frontend(**kwargs) # Call on_frontend_preparation hook frontend = self.on_frontend_preparation(frontend) or frontend # Start Frontend try: frontend.run() except KeyboardInterrupt: print("\nShutdown via Ctrl+C") if __name__ == '__main__': # pragma: no cover ServiceStarter().run()
{ "repo_name": "xia2/workflows", "path": "workflows/contrib/start_service.py", "copies": "1", "size": "4870", "license": "bsd-3-clause", "hash": 6333848338698988000, "line_mean": 37.96, "line_max": 101, "alpha_frac": 0.7002053388, "autogenerated": false, "ratio": 4.332740213523132, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009253505850144585, "num_lines": 125 }
from __future__ import absolute_import, division, print_function from os import path import csv import yaml from dynd import nd, ndt import datashape from datashape.type_equation_solver import matches_datashape_pattern import blaze from .. import py2help def load_blaze_array(conf, dir): """Loads a blaze array from the catalog configuration and catalog path""" # This is a temporary hack, need to transition to using the # deferred data descriptors for various formats. fsdir = conf.get_fsdir(dir) if not path.isfile(fsdir + '.array'): raise RuntimeError('Could not find blaze array description file %r' % (fsdir + '.array')) with open(fsdir + '.array') as f: arrmeta = yaml.load(f) tp = arrmeta['type'] imp = arrmeta['import'] ds_str = arrmeta.get('datashape') # optional. HDF5 does not need that. if tp == 'csv': with open(fsdir + '.csv', 'r') as f: rd = csv.reader(f) if imp.get('headers', False): # Skip the header line next(rd) dat = list(rd) arr = nd.array(dat, ndt.type(ds_str))[:] return blaze.array(arr) elif tp == 'json': arr = nd.parse_json(ds_str, nd.memmap(fsdir + '.json')) return blaze.array(arr) elif tp == 'hdf5': import tables as tb from blaze.datadescriptor import HDF5_DDesc fname = fsdir + '.h5' # XXX .h5 assumed for HDF5 with tb.open_file(fname, 'r') as f: dp = imp.get('datapath') # specifies a path in HDF5 try: dparr = f.get_node(f.root, dp, 'Leaf') except tb.NoSuchNodeError: raise RuntimeError( 'HDF5 file does not have a dataset in %r' % dp) dd = HDF5_DDesc(fname, dp) return blaze.array(dd) elif tp == 'npy': import numpy as np use_memmap = imp.get('memmap', False) if use_memmap: arr = np.load(fsdir + '.npy', 'r') else: arr = np.load(fsdir + '.npy') arr = nd.array(arr) arr = blaze.array(arr) ds = datashape.dshape(ds_str) if not matches_datashape_pattern(arr.dshape, ds): raise RuntimeError(('NPY file for blaze catalog path %r ' + 'has the wrong datashape (%r instead of ' + '%r)') % (arr.dshape, ds)) return arr elif tp == 'py': ds = datashape.dshape(ds_str) # The script is run with the following globals, # and should put the loaded array in a global # called 'result'. gbl = {'catconf': conf, # Catalog configuration object 'impdata': imp, # Import data from the .array file 'catpath': dir, # Catalog path 'fspath': fsdir, # Equivalent filesystem path 'dshape': ds # Datashape the result should have } if py2help.PY2: execfile(fsdir + '.py', gbl, gbl) else: with open(fsdir + '.py') as f: code = compile(f.read(), fsdir + '.py', 'exec') exec(code, gbl, gbl) arr = gbl.get('result', None) if arr is None: raise RuntimeError(('Script for blaze catalog path %r did not ' + 'return anything in "result" variable') % (dir)) elif not isinstance(arr, blaze.Array): raise RuntimeError(('Script for blaze catalog path %r returned ' + 'wrong type of object (%r instead of ' + 'blaze.Array)') % (type(arr))) if not matches_datashape_pattern(arr.dshape, ds): raise RuntimeError(('Script for blaze catalog path %r returned ' + 'array with wrong datashape (%r instead of ' + '%r)') % (arr.dshape, ds)) return arr else: raise ValueError(('Unsupported array type %r from ' + 'blaze catalog entry %r') % (tp, dir)) def load_blaze_subcarray(conf, cdir, subcarray): import tables as tb from blaze.datadescriptor import HDF5_DDesc with tb.open_file(cdir.fname, 'r') as f: try: dparr = f.get_node(f.root, subcarray, 'Leaf') except tb.NoSuchNodeError: raise RuntimeError( 'HDF5 file does not have a dataset in %r' % dp) dd = HDF5_DDesc(cdir.fname, subcarray) return blaze.array(dd)
{ "repo_name": "talumbau/blaze", "path": "blaze/catalog/catalog_arr.py", "copies": "3", "size": "4642", "license": "bsd-3-clause", "hash": -2654660601699299000, "line_mean": 39.0172413793, "line_max": 78, "alpha_frac": 0.5329599311, "autogenerated": false, "ratio": 3.7986906710310966, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5831650602131097, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from os import path import csv import yaml from dynd import nd, ndt import datashape import blaze from .. import py2help def compatible_array_dshape(arr, ds): """Checks if the array is compatible with the given dshape. Examples -------- >>> compatible_array_dshape(blaze.array([1,2,3]), ... datashape.dshape("M, int32")) True >>> """ # To do this check, we unify the array's dshape and the # provided dshape. Because the array's dshape is concrete, # the result of unification should be equal, otherwise the # the unification promoted its type. try: unify_res = blaze.datashape.unify([(arr.dshape, ds)], broadcasting=[False]) [unified_ds], constraints = unify_res except blaze.error.UnificationError: return False return unified_ds == arr.dshape def load_blaze_array(conf, dir): """Loads a blaze array from the catalog configuration and catalog path""" # This is a temporary hack, need to transition to using the # deferred data descriptors for various formats. fsdir = conf.get_fsdir(dir) if not path.isfile(fsdir + '.array'): raise RuntimeError('Could not find blaze array description file %r' % (fsdir + '.array')) with open(fsdir + '.array') as f: arrmeta = yaml.load(f) tp = arrmeta['type'] imp = arrmeta['import'] ds_str = arrmeta.get('datashape') # optional. HDF5 does not need that. if tp == 'csv': with open(fsdir + '.csv', 'r') as f: rd = csv.reader(f) if imp.get('headers', False): # Skip the header line next(rd) dat = list(rd) arr = nd.array(dat, ndt.type(ds_str))[:] return blaze.array(arr) elif tp == 'json': arr = nd.parse_json(ds_str, nd.memmap(fsdir + '.json')) return blaze.array(arr) elif tp == 'hdf5': import tables as tb from blaze.datadescriptor import HDF5DataDescriptor fname = fsdir + '.h5' # XXX .h5 assumed for HDF5 with tb.open_file(fname, 'r') as f: dp = imp.get('datapath') # specifies a path in HDF5 try: dparr = f.get_node(f.root, dp, 'Leaf') except tb.NoSuchNodeError: raise RuntimeError( 'HDF5 file does not have a dataset in %r' % dp) dd = HDF5DataDescriptor(fname, dp) return blaze.array(dd) elif tp == 'npy': import numpy as np use_memmap = imp.get('memmap', False) if use_memmap: arr = np.load(fsdir + '.npy', 'r') else: arr = np.load(fsdir + '.npy') arr = nd.array(arr) arr = blaze.array(arr) ds = datashape.dshape(ds_str) if not compatible_array_dshape(arr, ds): raise RuntimeError(('NPY file for blaze catalog path %r ' + 'has the wrong datashape (%r instead of ' + '%r)') % (arr.dshape, ds)) return arr elif tp == 'py': ds = datashape.dshape(ds_str) # The script is run with the following globals, # and should put the loaded array in a global # called 'result'. gbl = {'catconf': conf, # Catalog configuration object 'impdata': imp, # Import data from the .array file 'catpath': dir, # Catalog path 'fspath': fsdir, # Equivalent filesystem path 'dshape': ds # Datashape the result should have } if py2help.PY2: execfile(fsdir + '.py', gbl, gbl) else: with open(fsdir + '.py') as f: code = compile(f.read(), fsdir + '.py', 'exec') exec(code, gbl, gbl) arr = gbl.get('result', None) if arr is None: raise RuntimeError(('Script for blaze catalog path %r did not ' + 'return anything in "result" variable') % (dir)) elif not isinstance(arr, blaze.Array): raise RuntimeError(('Script for blaze catalog path %r returned ' + 'wrong type of object (%r instead of ' + 'blaze.Array)') % (type(arr))) if not compatible_array_dshape(arr, ds): raise RuntimeError(('Script for blaze catalog path %r returned ' + 'array with wrong datashape (%r instead of ' + '%r)') % (arr.dshape, ds)) return arr else: raise ValueError(('Unsupported array type %r from ' + 'blaze catalog entry %r') % (tp, dir))
{ "repo_name": "cezary12/blaze", "path": "blaze/catalog/catalog_arr.py", "copies": "5", "size": "4922", "license": "bsd-3-clause", "hash": 4709029439740755000, "line_mean": 37.453125, "line_max": 78, "alpha_frac": 0.5286468915, "autogenerated": false, "ratio": 3.9407526020816652, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 128 }
from __future__ import absolute_import, division, print_function from os import path import yaml from .catalog_arr import load_blaze_array def is_valid_bpath(d): """Returns true if it's a valid blaze path""" # Disallow backslashes in blaze paths if '\\' in d: return False # There should not be multiple path separators in a row if '//' in d: return False return True def is_abs_bpath(d): """Returns true if it's an absolute blaze path""" return is_valid_bpath(d) and d.startswith('/') def is_rel_bpath(d): """Returns true if it's a relative blaze path""" return is_valid_bpath(d) and not d.startswith('/') def _clean_bpath_components(components): res = [] for c in components: if c == '.': # Remove '.' pass elif c == '..': if all(x == '..' for x in res): # Relative path starting with '..' res.append('..') elif res == ['']: # Root of absolute path raise ValueError('Cannot use ".." at root of blaze catalog') else: # Remove the last entry res.pop() else: res.append(c) return res def _split_bpath(d): if is_valid_bpath(d): if d == '': return [] elif d == '/': return [''] elif d.endswith('/'): d = d[:-1] return d.split('/') else: raise ValueError('Invalid blaze catalog path %r' % d) def _rejoin_bpath(components): if components == ['']: return '/' else: return '/'.join(components) def clean_bpath(d): if is_valid_bpath(d): components = _split_bpath(d) components = _clean_bpath_components(components) return _rejoin_bpath(components) else: raise ValueError('Invalid blaze catalog path %r' % d) def join_bpath(d1, d2): if is_abs_bpath(d2): return clean_bpath(d2) elif is_abs_bpath(d1): components = _split_bpath(d1) + _split_bpath(d2) components = _clean_bpath_components(components) return _rejoin_bpath(components) class CatalogDir(object): """This object represents a directory path within the blaze catalog""" def __init__(self, conf, dir): self.conf = conf self.dir = dir if not is_abs_bpath(dir): raise ValueError('Require an absolute blaze path: %r' % dir) self._fsdir = path.join(conf.root, dir[1:]) if not path.exists(self._fsdir) or not path.isdir(self._fsdir): raise RuntimeError('Blaze path not found: %r' % dir) def ls_arrs(self): """Return a list of all the arrays in this blaze dir""" return self.conf.ls_arrs(self.dir) def ls_dirs(self): """Return a list of all the directories in this blaze dir""" return self.conf.ls_dirs(self.dir) def ls(self): """ Returns a list of all the arrays and directories in this blaze dir """ return self.conf.ls(self.dir) def __getindex__(self, key): if isinstance(key, tuple): key = '/'.join(key) if not is_rel_bpath(key): raise ValueError('Require a relative blaze path: %r' % key) dir = '/'.join([self.dir, key]) fsdir = path.join(self._fsdir, dir) if path.isdir(fsdir): return CatalogDir(self.conf, dir) elif path.isfile(fsdir + '.array'): return load_blaze_array(self.conf, dir) else: raise RuntimeError('Blaze path not found: %r' % dir) def __repr__(self): return ("Blaze Catalog Directory\nconfig: %s\ndir: %s" % (self.conf.configfile, self.dir)) class CatalogCDir(CatalogDir): """This object represents a directory path within a special catalog""" def __init__(self, conf, dir, subdir='/'): self.conf = conf self.dir = dir self.subdir = subdir if not is_abs_bpath(dir): raise ValueError('Require a path to dir file: %r' % dir) self._fsdir = path.join(conf.root, dir[1:]) if not path.exists(self._fsdir + '.dir'): raise RuntimeError('Blaze path not found: %r' % dir) self.load_blaze_dir() def load_blaze_dir(self): fsdir = self.conf.get_fsdir(self.dir) with open(fsdir + '.dir') as f: dirmeta = yaml.load(f) self.ctype = dirmeta['type'] imp = dirmeta['import'] self.fname = imp.get('filename') def ls_arrs(self): """Return a list of all the arrays in this blaze dir""" if self.ctype == "hdf5": import tables as tb with tb.open_file(self.fname, 'r') as f: leafs = [l._v_name for l in f.iter_nodes(self.subdir, classname='Leaf')] return sorted(leafs) def ls_dirs(self): """Return a list of all the directories in this blaze dir""" if self.ctype == "hdf5": import tables as tb with tb.open_file(self.fname, 'r') as f: groups = [g._v_name for g in f.iter_nodes(self.subdir, classname='Group')] return sorted(groups) def ls(self): """ Returns a list of all the arrays and directories in this blaze dir """ if self.ctype == "hdf5": import tables as tb with tb.open_file(self.fname, 'r') as f: nodes = [n._v_name for n in f.iter_nodes(self.subdir)] return sorted(nodes) def ls_abs(self, cname=''): """ Returns a list of all the directories in this blaze dir """ if self.ctype == "hdf5": import tables as tb with tb.open_file(self.fname, 'r') as f: nodes = [n._v_pathname for n in f.walk_nodes(self.subdir, classname=cname)] return sorted(nodes) def __getindex__(self, key): # XXX Adapt this to HDF5 if isinstance(key, tuple): key = '/'.join(key) if not is_rel_bpath(key): raise ValueError('Require a relative blaze path: %r' % key) dir = '/'.join([self.dir, key]) fsdir = path.join(self._fsdir, dir) if path.isfile(fsdir + '.dir'): return CatalogCDir(self.conf, dir) elif path.isfile(fsdir + '.array'): return load_blaze_array(self.conf, dir) else: raise RuntimeError('Blaze path not found: %r' % dir)
{ "repo_name": "talumbau/blaze", "path": "blaze/catalog/catalog_dir.py", "copies": "5", "size": "6624", "license": "bsd-3-clause", "hash": 1464282579323672300, "line_mean": 31.1553398058, "line_max": 76, "alpha_frac": 0.5431763285, "autogenerated": false, "ratio": 3.7088465845464724, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6752022913046473, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from os import path from .catalog_arr import load_blaze_array def is_valid_bpath(d): """Returns true if it's a valid blaze path""" # Disallow backslashes in blaze paths if '\\' in d: return False # There should not be multiple path separators in a row if '//' in d: return False return True def is_abs_bpath(d): """Returns true if it's an absolute blaze path""" return is_valid_bpath(d) and d.startswith('/') def is_rel_bpath(d): """Returns true if it's a relative blaze path""" return is_valid_bpath(d) and not d.startswith('/') def _clean_bpath_components(components): res = [] for c in components: if c == '.': # Remove '.' pass elif c == '..': if all(x == '..' for x in res): # Relative path starting with '..' res.append('..') elif res == ['']: # Root of absolute path raise ValueError('Cannot use ".." at root of blaze catalog') else: # Remove the last entry res.pop() else: res.append(c) return res def _split_bpath(d): if is_valid_bpath(d): if d == '': return [] elif d == '/': return [''] elif d.endswith('/'): d = d[:-1] return d.split('/') else: raise ValueError('Invalid blaze catalog path %r' % d) def _rejoin_bpath(components): if components == ['']: return '/' else: return '/'.join(components) def clean_bpath(d): if is_valid_bpath(d): components = _split_bpath(d) components = _clean_bpath_components(components) return _rejoin_bpath(components) else: raise ValueError('Invalid blaze catalog path %r' % d) def join_bpath(d1, d2): if is_abs_bpath(d2): return clean_bpath(d2) elif is_abs_bpath(d1): components = _split_bpath(d1) + _split_bpath(d2) components = _clean_bpath_components(components) return _rejoin_bpath(components) class CatalogDir(object): """This object represents a directory path within the blaze catalog""" def __init__(self, conf, dir): self.conf = conf self.dir = dir if not is_abs_bpath(dir): raise ValueError('Require an absolute blaze path: %r' % dir) self._fsdir = path.join(conf.root, dir[1:]) if not path.exists(self._fsdir) or not path.isdir(self._fsdir): raise RuntimeError('Blaze path not found: %r' % dir) def ls_arrs(self): """Return a list of all the arrays in this blaze dir""" return self.conf.ls_arrs(self.dir) def ls_dirs(self): """Return a list of all the directories in this blaze dir""" return self.conf.ls_dirs(self.dir) def ls(self): """ Returns a list of all the arrays and directories in this blaze dir """ return self.conf.ls(self.dir) def __getindex__(self, key): if isinstance(key, tuple): key = '/'.join(key) if not is_rel_bpath(key): raise ValueError('Require a relative blaze path: %r' % key) dir = '/'.join([self.dir, key]) fsdir = path.join(self._fsdir, dir) if path.isdir(fsdir): return CatalogDir(self.conf, dir) elif path.isfile(fsdir + '.array'): return load_blaze_array(self.conf, dir) else: raise RuntimeError('Blaze path not found: %r' % dir) def __repr__(self): return ("Blaze Catalog Directory\nconfig: %s\ndir: %s" % (self.conf.configfile, self.dir))
{ "repo_name": "aaronmartin0303/blaze", "path": "blaze/catalog/catalog_dir.py", "copies": "1", "size": "3763", "license": "bsd-3-clause", "hash": 113395322033286660, "line_mean": 28.1705426357, "line_max": 76, "alpha_frac": 0.55593941, "autogenerated": false, "ratio": 3.6569484936831875, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4712887903683187, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from os.path import abspath, dirname, join from odm2api.ODM2 import models from odm2api.ODM2.services.readService import ReadODM2 from odm2api.ODMconnection import dbconnection import pytest import sqlalchemy from sqlalchemy.orm import class_mapper globals_vars = {} def rawSql2Alchemy(rawsqlresult, sqlalchemyClass): """ converts the results of a raw sql select query into SqlAlchemy converter Object :param rawsqlresult: array of values, sql select results :param sqlalchemyModelObj: converter object to convert into :return: populated converter object """ m = {} class_attributes = [ prop.key for prop in class_mapper(sqlalchemyClass).iterate_properties if isinstance(prop, sqlalchemy.orm.ColumnProperty) ] for i in range(len(class_attributes)): m[class_attributes[i]] = rawsqlresult[i] modelObj = sqlalchemyClass() modelObj.__dict__ = m return modelObj class TestReadService: @pytest.fixture(scope='class', autouse=True) def build_db(self): """ Builds a populated sqlite (in-memory) database for testing :return: None """ # path to the ddl script for building the database ddlpath = abspath(join(dirname(__file__), 'data/populated.sql')) # create and empty sqlite database for testing db = dbconnection.createConnection('sqlite', ':memory:') # read the ddl script and remove the first (BEGIN TRANSACTION) and last (COMMIT) lines ddl = open(ddlpath, 'r').read() ddl = ddl.replace('BEGIN TRANSACTION;', '') ddl = ddl.replace('COMMIT;', '') # execute each statement to build the odm2 database for line in ddl.split(');')[:-1]: try: db.engine.execute(line + ');') except Exception as e: print(e) self.reader = ReadODM2(db) self.engine = db.engine globals_vars['reader'] = self.reader globals_vars['engine'] = self.engine globals_vars['db'] = db def setup(self): self.reader = globals_vars['reader'] self.engine = globals_vars['engine'] self.db = globals_vars['db'] # Sampling Features def test_getAllSamplingFeatures(self): # get all models from the database res = self.engine.execute('SELECT * FROM SamplingFeatures').fetchall() # get all simulations using the api resapi = self.reader.getSamplingFeatures() assert len(res) == len(resapi) def test_getSamplingFeatureByID(self): # get all models from the database res = self.engine.execute('SELECT * FROM SamplingFeatures').fetchone() sfid = res[0] # get all simulations using the api resapi = self.reader.getSamplingFeatures(ids=[sfid]) assert resapi is not None def test_getSamplingFeatureByCode(self): # get all models from the database res = self.engine.execute('SELECT * FROM SamplingFeatures').fetchone() code = res[2] # get all simulations using the api resapi = self.reader.getSamplingFeatures(codes=[code]) assert resapi is not None # DataSets def test_getDataSets(self): # get all datasets from the database ds = self.engine.execute('SELECT * FROM DataSets').fetchone() dsid = ds[0] dsapi = self.reader.getDataSets(ids=[dsid]) assert dsapi is not None assert True def test_getDataSetsResults(self): # get all datasetresults from the database dsr = self.engine.execute('SELECT * FROM DataSetsResults').fetchone() dsid = dsr[2] dsrapi = self.reader.getDataSetsResults(ids=[dsid]) assert dsrapi is not None assert True def test_getDataSetsValues(self): dsr = self.engine.execute('SELECT * FROM DataSetsResults').fetchone() dsid = dsr[2] values = self.reader.getDataSetsValues(ids=[dsid]) assert values is not None assert len(values) > 0 def test_getSamplingFeatureDataSets(self): try: # find a sampling feature that is associated with a dataset sf = self.engine.execute( 'SELECT * from SamplingFeatures as sf ' 'inner join FeatureActions as fa on fa.SamplingFeatureID == sf.SamplingFeatureID ' 'inner join Results as r on fa.FeatureActionID == r.FeatureActionID ' 'inner join DataSetsResults as ds on r.ResultID == ds.ResultID ' ).fetchone() assert len(sf) > 0 # get the dataset associated with the sampling feature ds = self.engine.execute( 'SELECT * from DataSetsResults as ds ' 'inner join Results as r on r.ResultID == ds.ResultID ' 'inner join FeatureActions as fa on fa.FeatureActionID == r.FeatureActionID ' 'where fa.SamplingFeatureID = ' + str(sf[0]) ).fetchone() assert len(ds) > 0 print(sf[0]) # get the dataset associated with the sampling feature using hte api dsapi = self.reader.getSamplingFeatureDatasets(ids=[sf[0]]) assert dsapi is not None assert len(dsapi) > 0 assert dsapi[0].datasets is not None assert dsapi[0].SamplingFeatureID == sf[0] # assert ds[0] == dsapi[0] except Exception as ex: print(ex) assert False finally: self.reader._session.rollback() # Results def test_getAllResults(self): # get all results from the database res = self.engine.execute('SELECT * FROM Results').fetchall() print(res) # get all results using the api resapi = self.reader.getResults() assert len(res) == len(resapi) def test_getResultsByID(self): # get a result from the database res = self.engine.execute('SELECT * FROM Results').fetchone() resultid = res[1] # get the result using the api resapi = self.reader.getResults(ids=[resultid]) assert resapi is not None def test_getResultsBySFID(self): sf = self.engine.execute( 'SELECT * from SamplingFeatures as sf ' 'inner join FeatureActions as fa on fa.SamplingFeatureID == sf.SamplingFeatureID ' 'inner join Results as r on fa.FeatureActionID == r.FeatureActionID ' ).fetchone() assert len(sf) > 0 sfid = sf[0] res = self.engine.execute( 'SELECT * from Results as r ' 'inner join FeatureActions as fa on fa.FeatureActionID == r.FeatureActionID ' 'where fa.SamplingFeatureID = ' + str(sfid) ).fetchone() assert len(res) > 0 # get the result using the api resapi = self.reader.getResults(sfids=[sfid]) assert resapi is not None assert len(resapi) > 0 assert resapi[0].ResultID == res[0] # Models def test_getAllModels(self): # get all models from the database res = self.engine.execute('SELECT * FROM Models').fetchall() # get all simulations using the api resapi = self.reader.getModels() assert len(res) == len(resapi) def test_getModelByCode(self): # get a converter from the database res = self.engine.execute('SELECT * FROM Models').fetchone() modelCode = res[1] # get the converter using the api resapi = self.reader.getModels(codes=[modelCode]) assert resapi is not None # RelatedModels def test_getRelatedModelsByID(self): # get related models by id using the api resapi = self.reader.getRelatedModels(id=1) assert resapi is not None assert resapi[0].ModelCode == 'swat' def test_getRelatedModelsByCode(self): # get related models by id using the api resapi = self.reader.getRelatedModels(code='swat') assert resapi is not None assert len(resapi) > 0 # print(resapi[0].ModelCode) assert resapi[0].ModelCode == 'swat' # test converter code that doesn't exist resapi = self.reader.getRelatedModels(code='None') assert resapi is not None assert len(resapi) == 0 # test invalid argument resapi = self.reader.getRelatedModels(code=234123) assert not resapi # Simulations def test_getAllSimulations(self): # get all simulation from the database res = self.engine.execute('SELECT * FROM Simulations').fetchall() # get all simulations using the api resapi = self.reader.getSimulations() assert len(res) == len(resapi) def test_getSimulationByName(self): # get a simulation from the database res = self.engine.execute('SELECT * FROM Simulations').fetchone() simName = res[2] # get simulation by name using the api resapi = self.reader.getSimulations(name=simName) assert resapi is not None def test_getSimulationByActionID(self): # get a simulation from the database res = self.engine.execute('SELECT * FROM Simulations').fetchone() actionID = res[1] # get simulation by actionid using the api resapi = self.reader.getSimulations(actionid=actionID) assert resapi is not None def test_getResultsBySimulationID(self): # get a simulation from the database res = self.engine.execute('SELECT * FROM Simulations').fetchone() simulation = rawSql2Alchemy(res, models.Simulations) # get the results id associated with the simulation res = self.engine.execute( 'SELECT * from Results as r ' 'inner join FeatureActions as fa on fa.FeatureActionID == r.FeatureActionID ' 'inner join Actions as a on a.ActionID == fa.ActionID ' 'inner join Simulations as s on s.ActionID == a.ActionID ' 'where s.SimulationID = 1' ).first() assert len(res) > 0 res = rawSql2Alchemy(res, models.Results) # print(res) # get simulation by id using the api # resapi = self.reader.getResultsBySimulationID(simulation.SimulationID) resapi = self.reader.getResults(simulationid=simulation.SimulationID) assert resapi is not None assert len(resapi) > 0 assert res.ResultID == resapi[0].ResultID
{ "repo_name": "emiliom/ODM2PythonAPI", "path": "tests/test_odm2/test_readservice.py", "copies": "1", "size": "10562", "license": "bsd-3-clause", "hash": 1693367877777718000, "line_mean": 35.1712328767, "line_max": 98, "alpha_frac": 0.6240295399, "autogenerated": false, "ratio": 4.104935872522347, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5228965412422347, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from owscapable.util import nspath_eval from owscapable.namespaces import Namespaces from owscapable.util import testXMLAttribute, testXMLValue, InfiniteDateTime, NegativeInfiniteDateTime from dateutil import parser from datetime import timedelta from owscapable.etree import etree def get_namespaces(): ns = Namespaces() return ns.get_namespaces(["swe20", "xlink"]) namespaces = get_namespaces() def nspv(path): return nspath_eval(path, namespaces) def make_pair(string, cast=None): if string is None: return None string = string.split(" ") if cast is not None: try: string = map(lambda x: cast(x), string) except: print("Could not cast pair to correct type. Setting to an empty tuple!") string = "" return tuple(string) def get_uom(element): uom = testXMLAttribute(element, "code") if uom is None: uom = testXMLAttribute(element, nspv("xlink:href")) return uom def get_boolean(value): if value is None: return None if value is True or value.lower() in ["yes","true"]: return True elif value is False or value.lower() in ["no","false"]: return False else: return None def get_int(value): try: return int(value) except: return None def get_float(value): try: return float(value) except: return None AnyScalar = map(lambda x: nspv(x), ["swe20:Boolean", "swe20:Count", "swe20:Quantity", "swe20:Time", "swe20:Category", "swe20:Text"]) AnyNumerical = map(lambda x: nspv(x), ["swe20:Count", "swe20:Quantity", "swe20:Time"]) AnyRange = map(lambda x: nspv(x), ["swe20:QuantityRange", "swe20:TimeRange", "swe20:CountRange", "swe20:CategoryRange"]) class NamedObject(object): def __init__(self, element): # No call to super(), the type object will process that. self.name = testXMLAttribute(element, "name") try: self.content = eval(element[-1].tag.split("}")[-1])(element[-1]) except IndexError: self.content = None except BaseException: raise # Revert to the content if attribute does not exists def __getattr__(self, name): return getattr(self.content, name) class AbstractSWE(object): def __init__(self, element): # Attributes self.id = testXMLAttribute(element,"id") # string, optional # Elements self.extention = [] # anyType, min=0, max=X class AbstractSWEIdentifiable(AbstractSWE): def __init__(self, element): super(AbstractSWEIdentifiable, self).__init__(element) # Elements self.identifier = testXMLValue(element.find(nspv("swe20:identifier"))) # anyURI, min=0 self.label = testXMLValue(element.find(nspv("swe20:label"))) # string, min=0 self.description = testXMLValue(element.find(nspv("swe20:description"))) # string, min=0 class AbstractDataComponent(AbstractSWEIdentifiable): def __init__(self, element): super(AbstractDataComponent, self).__init__(element) # Attributes self.definition = testXMLAttribute(element,"definition") # anyURI, required self.updatable = get_boolean(testXMLAttribute(element,"updatable")) # boolean, optional self.optional = get_boolean(testXMLAttribute(element,"optional")) or False # boolean, default=False class AbstractSimpleComponent(AbstractDataComponent): def __init__(self, element): super(AbstractSimpleComponent, self).__init__(element) # Attributes self.referenceFrame = testXMLAttribute(element,"referenceFrame") # anyURI, optional self.axisID = testXMLAttribute(element,"axisID") # string, optional # Elements self.quality = filter(None, [Quality(q) for q in [e.find('*') for e in element.findall(nspv("swe20:quality"))] if q is not None]) try: self.nilValues = NilValues(element.find(nspv("swe20:nilValues"))) except: self.nilValues = None class Quality(object): def __new__(cls, element): t = element.tag.split("}")[-1] if t == "Quantity": return Quantity(element) elif t == "QuantityRange": return QuantityRange(element) elif t == "Category": return Category(element) elif t == "Text": return Text(element) else: return None class NilValues(AbstractSWE): def __init__(self, element): super(NilValues, self).__init__(element) self.nilValue = filter(None, [nilValue(x) for x in element.findall(nspv("swe20:nilValue"))]) # string, min=0, max=X class nilValue(object): def __init__(self, element): self.reason = testXMLAttribute(element, "reason") self.value = testXMLValue(element) class AllowedTokens(AbstractSWE): def __init__(self, element): super(AllowedTokens, self).__init__(element) self.value = filter(None, [testXMLValue(x) for x in element.findall(nspv("swe20:value"))]) # string, min=0, max=X self.pattern = testXMLValue(element.find(nspv("swe20:pattern"))) # string (Unicode Technical Standard #18, Version 13), min=0 class AllowedValues(AbstractSWE): def __init__(self, element): super(AllowedValues, self).__init__(element) self.value = filter(None, map(lambda x: get_float(x), [testXMLValue(x) for x in element.findall(nspv("swe20:value"))])) self.interval = filter(None, [make_pair(testXMLValue(x)) for x in element.findall(nspv("swe20:interval"))]) self.significantFigures = get_int(testXMLValue(element.find(nspv("swe20:significantFigures")))) # integer, min=0 class AllowedTimes(AbstractSWE): def __init__(self, element): super(AllowedTimes, self).__init__(element) self.value = filter(None, [testXMLValue(x) for x in element.findall(nspv("swe20:value"))]) self.interval = filter(None, [make_pair(testXMLValue(x)) for x in element.findall(nspv("swe20:interval"))]) self.significantFigures = get_int(testXMLValue(element.find(nspv("swe20:significantFigures")))) # integer, min=0 class Boolean(AbstractSimpleComponent): def __init__(self, element): super(Boolean, self).__init__(element) # Elements """ 6.2.1 Boolean A Boolean representation of a proptery can take only two values that should be "true/false" or "yes/no". """ value = get_boolean(testXMLValue(element.find(nspv("swe20:value")))) # boolean, min=0, max=1 class Text(AbstractSimpleComponent): def __init__(self, element): super(Text, self).__init__(element) # Elements """ Req 6. A textual representation shall at least consist of a character string. """ self.value = testXMLValue(element.find(nspv("swe20:value"))) # string, min=0, max=1 try: self.constraint = AllowedTokens(element.find(nspv("swe20:constraint/swe20:AllowedTokens"))) # AllowedTokens, min=0, max=1 except: self.constraint = None class Category(AbstractSimpleComponent): def __init__(self, element): super(Category, self).__init__(element) # Elements self.codeSpace = testXMLAttribute(element.find(nspv("swe20:codeSpace")), nspv("xlink:href")) # Reference, min=0, max=1 self.value = testXMLValue(element.find(nspv("swe20:value"))) # string, min=0, max=1 try: self.constraint = AllowedTokens(element.find(nspv("swe20:constraint/swe20:AllowedTokens"))) # AllowedTokens, min=0, max=1 except: self.constraint = None class CategoryRange(Category): def __init__(self, element): super(CategoryRange, self).__init__(element) # Elements value = testXMLValue(element.find(nspv("swe20:value"))) self.values = make_pair(value) if value is not None else None class Count(AbstractSimpleComponent): def __init__(self, element): super(Count, self).__init__(element) # Elements self.value = get_int(testXMLValue(element.find(nspv("swe20:value")))) # integer, min=0, max=1 try: self.constraint = AllowedValues(element.find(nspv("swe20:constraint/swe20:AllowedValues"))) # AllowedValues, min=0, max=1 except: self.constraint = None class CountRange(Count): def __init__(self, element): super(CountRange, self).__init__(element) # Elements value = testXMLValue(element.find(nspv("swe20:value"))) self.value = make_pair(value,int) if value is not None else None class Quantity(AbstractSimpleComponent): def __init__(self, element): super(Quantity, self).__init__(element) # Elements self.uom = get_uom(element.find(nspv("swe20:uom"))) self.value = get_float(testXMLValue(element.find(nspv("swe20:value")))) # double, min=0, max=1 try: self.constraint = AllowedValues(element.find(nspv("swe20:constraint/swe20:AllowedValues"))) # AllowedValues, min=0, max=1 except: self.constraint = None class QuantityRange(Quantity): def __init__(self, element): super(QuantityRange, self).__init__(element) # Elements value = testXMLValue(element.find(nspv("swe20:value"))) self.value = make_pair(value,float) if value is not None else None def get_time(value, referenceTime, uom): try: value = parser.parse(value) except (AttributeError, ValueError): # Most likely an integer/float using a referenceTime try: if uom.lower() == "s": value = referenceTime + timedelta(seconds=float(value)) elif uom.lower() == "min": value = referenceTime + timedelta(minutes=float(value)) elif uom.lower() == "h": value = referenceTime + timedelta(hours=float(value)) elif uom.lower() == "d": value = referenceTime + timedelta(days=float(value)) except (AttributeError, ValueError): pass except OverflowError: # Too many numbers (> 10) or INF/-INF if value.lower() == "inf": value = InfiniteDateTime() elif value.lower() == "-inf": value = NegativeInfiniteDateTime() return value class Time(AbstractSimpleComponent): def __init__(self, element): super(Time, self).__init__(element) # Elements self.uom = get_uom(element.find(nspv("swe20:uom"))) try: self.constraint = AllowedTimes(element.find(nspv("swe20:constraint/swe20:AllowedTimes"))) # AllowedTimes, min=0, max=1 except: self.constraint = None # Attributes self.localFrame = testXMLAttribute(element,"localFrame") # anyURI, optional try: self.referenceTime = parser.parse(testXMLAttribute(element,"referenceTime")) # dateTime, optional except (AttributeError, ValueError): self.referenceTime = None value = testXMLValue(element.find(nspv("swe20:value"))) # TimePosition, min=0, max=1 self.value = get_time(value, self.referenceTime, self.uom) class TimeRange(AbstractSimpleComponent): def __init__(self, element): super(TimeRange, self).__init__(element) # Elements self.uom = get_uom(element.find(nspv("swe20:uom"))) try: self.constraint = AllowedTimes(element.find(nspv("swe20:constraint/swe20:AllowedTimes"))) # AllowedTimes, min=0, max=1 except: self.constraint = None # Attributes self.localFrame = testXMLAttribute(element,"localFrame") # anyURI, optional try: self.referenceTime = parser.parse(testXMLAttribute(element,"referenceTime")) # dateTime, optional except (AttributeError, ValueError): self.referenceTime = None values = make_pair(testXMLValue(element.find(nspv("swe20:value")))) # TimePosition, min=0, max=1 self.value = [get_time(t, self.referenceTime, self.uom) for t in values] class DataRecord(AbstractDataComponent): def __init__(self, element): super(DataRecord, self).__init__(element) # Elements self.field = [Field(x) for x in element.findall(nspv("swe20:field"))] def get_by_name(self, name): return next((x for x in self.field if x.name == name), None) class Field(NamedObject): def __init__(self, element): super(Field, self).__init__(element) class Vector(AbstractDataComponent): def __init__(self, element): super(Vector, self).__init__(element) # Elements self.coordinate = [Coordinate(x) for x in element.findall(nspv("swe20:coordinate"))] # Attributes self.referenceFrame = testXMLAttribute(element,"referenceFrame") # anyURI, required self.localFrame = testXMLAttribute(element,"localFrame") # anyURI, optional def get_by_name(self, name): return next((x for x in self.coordinate if x.name == name), None) class Coordinate(NamedObject): def __init__(self, element): super(Coordinate, self).__init__(element) #if element[-1].tag not in AnyNumerical: # print "Coordinate does not appear to be an AnyNumerical member" class DataChoice(AbstractDataComponent): def __init__(self, element): super(DataChoice, self).__init__(element) self.item = [Item(x) for x in element.findall(nspv("swe20:item"))] def get_by_name(self, name): return next((x for x in self.item if x.name == name), None) class Item(NamedObject): def __init__(self, element): super(Item, self).__init__(element) class DataArray(AbstractDataComponent): def __init__(self, element): super(DataArray, self).__init__(element) self.elementCount = element.find(nspv("swe20:elementCount/swe20:Count")) # required self.elementType = ElementType(element.find(nspv("swe20:elementType"))) # required self.values = testXMLValue(element.find(nspv("swe20:values"))) try: self.encoding = AbstractEncoding(element.find(nspv("swe20:encoding"))) except: self.encoding = None class Matrix(AbstractDataComponent): def __init__(self, element): super(Matrix, self).__init__(element) self.elementCount = element.find(nspv("swe20:elementCount/swe20:Count")) # required self.elementType = ElementType(element.find(nspv("swe20:elementType"))) # required self.encoding = AbstractEncoding(element.find(nspv("swe20:encoding"))) self.values = testXMLValue(element.find(nspv("swe20:values"))) self.referenceFrame = testXMLAttribute(element, "referenceFrame") # anyURI, required self.localFrame = testXMLAttribute(element, "localFrame") # anyURI, optional class DataStream(AbstractSWEIdentifiable): def __init__(self, element): super(DataStream, self).__init__(element) self.elementCount = element.find(nspv("swe20:elementCount/swe20:Count")) # optional self.elementType = ElementType(element.find(nspv("swe20:elementType"))) # optional self.encoding = AbstractEncoding(element.find(nspv("swe20:encoding"))) self.values = testXMLValue(element.find(nspv("swe20:values"))) class ElementType(NamedObject): def __init__(self, element): super(ElementType, self).__init__(element) class AbstractEncoding(object): def __new__(cls, element): t = element[-1].tag.split("}")[-1] if t == "TextEncoding": return super(AbstractEncoding, cls).__new__(TextEncoding, element) elif t == "XMLEncoding": return super(AbstractEncoding, cls).__new__(XMLEncoding, element) elif t == "BinaryEncoding": return super(AbstractEncoding, cls).__new__(BinaryEncoding, element) class TextEncoding(AbstractEncoding): def __init__(self, element): self.tokenSeparator = testXMLAttribute(element[-1], "tokenSeparator") # string, required self.blockSeparator = testXMLAttribute(element[-1], "blockSeparator") # string, required self.decimalSeparator = testXMLAttribute(element[-1], "decimalSeparator") or "." # string, optional, default="." self.collapseWhiteSpaces = get_boolean(testXMLAttribute(element[-1], "collapseWhiteSpaces")) or True # boolean, optional, default=True class XMLEncoding(AbstractEncoding): def __init__(self, element): raise NotImplementedError class BinaryEncoding(AbstractEncoding): def __init__(self, element): raise NotImplementedError
{ "repo_name": "b-cube/OwsCapable", "path": "owscapable/swe/common.py", "copies": "1", "size": "17842", "license": "bsd-3-clause", "hash": 5843329340030468000, "line_mean": 42.3058252427, "line_max": 172, "alpha_frac": 0.6021185966, "autogenerated": false, "ratio": 3.9041575492341356, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9956499944670528, "avg_score": 0.009955240232721485, "num_lines": 412 }
from __future__ import (absolute_import, division, print_function) from owscapable.waterml.wml import SitesResponse, TimeSeriesResponse, VariablesResponse, namespaces from owscapable.etree import etree def ns(namespace): return namespaces.get(namespace) class WaterML_1_0(object): def __init__(self, element): if isinstance(element, str) or isinstance(element, unicode): self._root = etree.fromstring(str(element)) else: self._root = element if hasattr(self._root, 'getroot'): self._root = self._root.getroot() self._ns = 'wml1.0' @property def response(self): try: if self._root.tag == str(ns(self._ns) + 'variablesResponse'): return VariablesResponse(self._root, self._ns) elif self._root.tag == str(ns(self._ns) + 'timeSeriesResponse'): return TimeSeriesResponse(self._root, self._ns) elif self._root.tag == str(ns(self._ns) + 'sitesResponse'): return SitesResponse(self._root, self._ns) except: raise raise ValueError('Unable to determine response type from xml')
{ "repo_name": "b-cube/OwsCapable", "path": "owscapable/waterml/wml10.py", "copies": "1", "size": "1180", "license": "bsd-3-clause", "hash": -5399558890718936000, "line_mean": 33.7058823529, "line_max": 99, "alpha_frac": 0.6161016949, "autogenerated": false, "ratio": 4, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004769665176011926, "num_lines": 34 }
from __future__ import (absolute_import, division, print_function) from owslib.util import nspath_eval from owslib.namespaces import Namespaces from owslib.util import testXMLAttribute, testXMLValue, InfiniteDateTime, NegativeInfiniteDateTime from dateutil import parser from datetime import timedelta from owslib.etree import etree def get_namespaces(): ns = Namespaces() return ns.get_namespaces(["swe20", "xlink"]) namespaces = get_namespaces() def nspv(path): return nspath_eval(path, namespaces) def make_pair(string, cast=None): if string is None: return None string = string.split(" ") if cast is not None: try: string = [cast(x) for x in string] except: print("Could not cast pair to correct type. Setting to an empty tuple!") string = "" return tuple(string) def get_uom(element): uom = testXMLAttribute(element, "code") if uom is None: uom = testXMLAttribute(element, nspv("xlink:href")) return uom def get_boolean(value): if value is None: return None if value is True or value.lower() in ["yes","true"]: return True elif value is False or value.lower() in ["no","false"]: return False else: return None def get_int(value): try: return int(value) except: return None def get_float(value): try: return float(value) except: return None AnyScalar = [nspv(x) for x in ["swe20:Boolean", "swe20:Count", "swe20:Quantity", "swe20:Time", "swe20:Category", "swe20:Text"]] AnyNumerical = [nspv(x) for x in ["swe20:Count", "swe20:Quantity", "swe20:Time"]] AnyRange = [nspv(x) for x in ["swe20:QuantityRange", "swe20:TimeRange", "swe20:CountRange", "swe20:CategoryRange"]] class NamedObject(object): def __init__(self, element): # No call to super(), the type object will process that. self.name = testXMLAttribute(element, "name") try: self.content = eval(element[-1].tag.split("}")[-1])(element[-1]) except IndexError: self.content = None except BaseException: raise # Revert to the content if attribute does not exists def __getattr__(self, name): return getattr(self.content, name) class AbstractSWE(object): def __init__(self, element): # Attributes self.id = testXMLAttribute(element,"id") # string, optional # Elements self.extention = [] # anyType, min=0, max=X class AbstractSWEIdentifiable(AbstractSWE): def __init__(self, element): super(AbstractSWEIdentifiable, self).__init__(element) # Elements self.identifier = testXMLValue(element.find(nspv("swe20:identifier"))) # anyURI, min=0 self.label = testXMLValue(element.find(nspv("swe20:label"))) # string, min=0 self.description = testXMLValue(element.find(nspv("swe20:description"))) # string, min=0 class AbstractDataComponent(AbstractSWEIdentifiable): def __init__(self, element): super(AbstractDataComponent, self).__init__(element) # Attributes self.definition = testXMLAttribute(element,"definition") # anyURI, required self.updatable = get_boolean(testXMLAttribute(element,"updatable")) # boolean, optional self.optional = get_boolean(testXMLAttribute(element,"optional")) or False # boolean, default=False class AbstractSimpleComponent(AbstractDataComponent): def __init__(self, element): super(AbstractSimpleComponent, self).__init__(element) # Attributes self.referenceFrame = testXMLAttribute(element,"referenceFrame") # anyURI, optional self.axisID = testXMLAttribute(element,"axisID") # string, optional # Elements self.quality = [_f for _f in [Quality(q) for q in [e.find('*') for e in element.findall(nspv("swe20:quality"))] if q is not None] if _f] try: self.nilValues = NilValues(element.find(nspv("swe20:nilValues"))) except: self.nilValues = None class Quality(object): def __new__(cls, element): t = element.tag.split("}")[-1] if t == "Quantity": return Quantity(element) elif t == "QuantityRange": return QuantityRange(element) elif t == "Category": return Category(element) elif t == "Text": return Text(element) else: return None class NilValues(AbstractSWE): def __init__(self, element): super(NilValues, self).__init__(element) self.nilValue = [_f for _f in [nilValue(x) for x in element.findall(nspv("swe20:nilValue"))] if _f] # string, min=0, max=X class nilValue(object): def __init__(self, element): self.reason = testXMLAttribute(element, "reason") self.value = testXMLValue(element) class AllowedTokens(AbstractSWE): def __init__(self, element): super(AllowedTokens, self).__init__(element) self.value = [_f for _f in [testXMLValue(x) for x in element.findall(nspv("swe20:value"))] if _f] # string, min=0, max=X self.pattern = testXMLValue(element.find(nspv("swe20:pattern"))) # string (Unicode Technical Standard #18, Version 13), min=0 class AllowedValues(AbstractSWE): def __init__(self, element): super(AllowedValues, self).__init__(element) self.value = [_f for _f in [get_float(x) for x in [testXMLValue(x) for x in element.findall(nspv("swe20:value"))]] if _f] self.interval = [_f for _f in [make_pair(testXMLValue(x)) for x in element.findall(nspv("swe20:interval"))] if _f] self.significantFigures = get_int(testXMLValue(element.find(nspv("swe20:significantFigures")))) # integer, min=0 class AllowedTimes(AbstractSWE): def __init__(self, element): super(AllowedTimes, self).__init__(element) self.value = [_f for _f in [testXMLValue(x) for x in element.findall(nspv("swe20:value"))] if _f] self.interval = [_f for _f in [make_pair(testXMLValue(x)) for x in element.findall(nspv("swe20:interval"))] if _f] self.significantFigures = get_int(testXMLValue(element.find(nspv("swe20:significantFigures")))) # integer, min=0 class Boolean(AbstractSimpleComponent): def __init__(self, element): super(Boolean, self).__init__(element) # Elements """ 6.2.1 Boolean A Boolean representation of a proptery can take only two values that should be "true/false" or "yes/no". """ value = get_boolean(testXMLValue(element.find(nspv("swe20:value")))) # boolean, min=0, max=1 class Text(AbstractSimpleComponent): def __init__(self, element): super(Text, self).__init__(element) # Elements """ Req 6. A textual representation shall at least consist of a character string. """ self.value = testXMLValue(element.find(nspv("swe20:value"))) # string, min=0, max=1 try: self.constraint = AllowedTokens(element.find(nspv("swe20:constraint/swe20:AllowedTokens"))) # AllowedTokens, min=0, max=1 except: self.constraint = None class Category(AbstractSimpleComponent): def __init__(self, element): super(Category, self).__init__(element) # Elements self.codeSpace = testXMLAttribute(element.find(nspv("swe20:codeSpace")), nspv("xlink:href")) # Reference, min=0, max=1 self.value = testXMLValue(element.find(nspv("swe20:value"))) # string, min=0, max=1 try: self.constraint = AllowedTokens(element.find(nspv("swe20:constraint/swe20:AllowedTokens"))) # AllowedTokens, min=0, max=1 except: self.constraint = None class CategoryRange(Category): def __init__(self, element): super(CategoryRange, self).__init__(element) # Elements value = testXMLValue(element.find(nspv("swe20:value"))) self.values = make_pair(value) if value is not None else None class Count(AbstractSimpleComponent): def __init__(self, element): super(Count, self).__init__(element) # Elements self.value = get_int(testXMLValue(element.find(nspv("swe20:value")))) # integer, min=0, max=1 try: self.constraint = AllowedValues(element.find(nspv("swe20:constraint/swe20:AllowedValues"))) # AllowedValues, min=0, max=1 except: self.constraint = None class CountRange(Count): def __init__(self, element): super(CountRange, self).__init__(element) # Elements value = testXMLValue(element.find(nspv("swe20:value"))) self.value = make_pair(value,int) if value is not None else None class Quantity(AbstractSimpleComponent): def __init__(self, element): super(Quantity, self).__init__(element) # Elements self.uom = get_uom(element.find(nspv("swe20:uom"))) self.value = get_float(testXMLValue(element.find(nspv("swe20:value")))) # double, min=0, max=1 try: self.constraint = AllowedValues(element.find(nspv("swe20:constraint/swe20:AllowedValues"))) # AllowedValues, min=0, max=1 except: self.constraint = None class QuantityRange(Quantity): def __init__(self, element): super(QuantityRange, self).__init__(element) # Elements value = testXMLValue(element.find(nspv("swe20:value"))) self.value = make_pair(value,float) if value is not None else None def get_time(value, referenceTime, uom): try: value = parser.parse(value) except (AttributeError, ValueError): # Most likely an integer/float using a referenceTime try: if uom.lower() == "s": value = referenceTime + timedelta(seconds=float(value)) elif uom.lower() == "min": value = referenceTime + timedelta(minutes=float(value)) elif uom.lower() == "h": value = referenceTime + timedelta(hours=float(value)) elif uom.lower() == "d": value = referenceTime + timedelta(days=float(value)) except (AttributeError, ValueError): pass except OverflowError: # Too many numbers (> 10) or INF/-INF if value.lower() == "inf": value = InfiniteDateTime() elif value.lower() == "-inf": value = NegativeInfiniteDateTime() return value class Time(AbstractSimpleComponent): def __init__(self, element): super(Time, self).__init__(element) # Elements self.uom = get_uom(element.find(nspv("swe20:uom"))) try: self.constraint = AllowedTimes(element.find(nspv("swe20:constraint/swe20:AllowedTimes"))) # AllowedTimes, min=0, max=1 except: self.constraint = None # Attributes self.localFrame = testXMLAttribute(element,"localFrame") # anyURI, optional try: self.referenceTime = parser.parse(testXMLAttribute(element,"referenceTime")) # dateTime, optional except (AttributeError, ValueError): self.referenceTime = None value = testXMLValue(element.find(nspv("swe20:value"))) # TimePosition, min=0, max=1 self.value = get_time(value, self.referenceTime, self.uom) class TimeRange(AbstractSimpleComponent): def __init__(self, element): super(TimeRange, self).__init__(element) # Elements self.uom = get_uom(element.find(nspv("swe20:uom"))) try: self.constraint = AllowedTimes(element.find(nspv("swe20:constraint/swe20:AllowedTimes"))) # AllowedTimes, min=0, max=1 except: self.constraint = None # Attributes self.localFrame = testXMLAttribute(element,"localFrame") # anyURI, optional try: self.referenceTime = parser.parse(testXMLAttribute(element,"referenceTime")) # dateTime, optional except (AttributeError, ValueError): self.referenceTime = None values = make_pair(testXMLValue(element.find(nspv("swe20:value")))) # TimePosition, min=0, max=1 self.value = [get_time(t, self.referenceTime, self.uom) for t in values] class DataRecord(AbstractDataComponent): def __init__(self, element): super(DataRecord, self).__init__(element) # Elements self.field = [Field(x) for x in element.findall(nspv("swe20:field"))] def get_by_name(self, name): return next((x for x in self.field if x.name == name), None) class Field(NamedObject): def __init__(self, element): super(Field, self).__init__(element) class Vector(AbstractDataComponent): def __init__(self, element): super(Vector, self).__init__(element) # Elements self.coordinate = [Coordinate(x) for x in element.findall(nspv("swe20:coordinate"))] # Attributes self.referenceFrame = testXMLAttribute(element,"referenceFrame") # anyURI, required self.localFrame = testXMLAttribute(element,"localFrame") # anyURI, optional def get_by_name(self, name): return next((x for x in self.coordinate if x.name == name), None) class Coordinate(NamedObject): def __init__(self, element): super(Coordinate, self).__init__(element) #if element[-1].tag not in AnyNumerical: # print "Coordinate does not appear to be an AnyNumerical member" class DataChoice(AbstractDataComponent): def __init__(self, element): super(DataChoice, self).__init__(element) self.item = [Item(x) for x in element.findall(nspv("swe20:item"))] def get_by_name(self, name): return next((x for x in self.item if x.name == name), None) class Item(NamedObject): def __init__(self, element): super(Item, self).__init__(element) class DataArray(AbstractDataComponent): def __init__(self, element): super(DataArray, self).__init__(element) self.elementCount = element.find(nspv("swe20:elementCount/swe20:Count")) # required self.elementType = ElementType(element.find(nspv("swe20:elementType"))) # required self.values = testXMLValue(element.find(nspv("swe20:values"))) try: self.encoding = AbstractEncoding(element.find(nspv("swe20:encoding"))) except: self.encoding = None class Matrix(AbstractDataComponent): def __init__(self, element): super(Matrix, self).__init__(element) self.elementCount = element.find(nspv("swe20:elementCount/swe20:Count")) # required self.elementType = ElementType(element.find(nspv("swe20:elementType"))) # required self.encoding = AbstractEncoding(element.find(nspv("swe20:encoding"))) self.values = testXMLValue(element.find(nspv("swe20:values"))) self.referenceFrame = testXMLAttribute(element, "referenceFrame") # anyURI, required self.localFrame = testXMLAttribute(element, "localFrame") # anyURI, optional class DataStream(AbstractSWEIdentifiable): def __init__(self, element): super(DataStream, self).__init__(element) self.elementCount = element.find(nspv("swe20:elementCount/swe20:Count")) # optional self.elementType = ElementType(element.find(nspv("swe20:elementType"))) # optional self.encoding = AbstractEncoding(element.find(nspv("swe20:encoding"))) self.values = testXMLValue(element.find(nspv("swe20:values"))) class ElementType(NamedObject): def __init__(self, element): super(ElementType, self).__init__(element) class AbstractEncoding(object): def __new__(cls, element): t = element[-1].tag.split("}")[-1] if t == "TextEncoding": return super(AbstractEncoding, cls).__new__(TextEncoding) elif t == "XMLEncoding": return super(AbstractEncoding, cls).__new__(XMLEncoding) elif t == "BinaryEncoding": return super(AbstractEncoding, cls).__new__(BinaryEncoding) class TextEncoding(AbstractEncoding): def __init__(self, element): self.tokenSeparator = testXMLAttribute(element[-1], "tokenSeparator") # string, required self.blockSeparator = testXMLAttribute(element[-1], "blockSeparator") # string, required self.decimalSeparator = testXMLAttribute(element[-1], "decimalSeparator") or "." # string, optional, default="." self.collapseWhiteSpaces = get_boolean(testXMLAttribute(element[-1], "collapseWhiteSpaces")) or True # boolean, optional, default=True class XMLEncoding(AbstractEncoding): def __init__(self, element): raise NotImplementedError class BinaryEncoding(AbstractEncoding): def __init__(self, element): raise NotImplementedError
{ "repo_name": "mbertrand/OWSLib", "path": "owslib/swe/common.py", "copies": "14", "size": "17823", "license": "bsd-3-clause", "hash": 5678513000869002000, "line_mean": 42.2597087379, "line_max": 172, "alpha_frac": 0.5995623632, "autogenerated": false, "ratio": 3.8796255986068786, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009917605007842622, "num_lines": 412 }
from __future__ import (absolute_import, division, print_function) from owslib.waterml.wml import SitesResponse, TimeSeriesResponse, VariablesResponse, namespaces from owslib.etree import etree, ElementType def ns(namespace): return namespaces.get(namespace) class WaterML_1_0(object): def __init__(self, element): if isinstance(element, ElementType): self._root = element else: self._root = etree.fromstring(element) if hasattr(self._root, 'getroot'): self._root = self._root.getroot() self._ns = 'wml1.0' @property def response(self): try: if self._root.tag == str(ns(self._ns) + 'variablesResponse'): return VariablesResponse(self._root, self._ns) elif self._root.tag == str(ns(self._ns) + 'timeSeriesResponse'): return TimeSeriesResponse(self._root, self._ns) elif self._root.tag == str(ns(self._ns) + 'sitesResponse'): return SitesResponse(self._root, self._ns) except: raise raise ValueError('Unable to determine response type from xml')
{ "repo_name": "JuergenWeichand/OWSLib", "path": "owslib/waterml/wml10.py", "copies": "22", "size": "1156", "license": "bsd-3-clause", "hash": 7691620441642540000, "line_mean": 33, "line_max": 95, "alpha_frac": 0.6133217993, "autogenerated": false, "ratio": 4.013888888888889, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from pandora.compat import text_type from pandora.compat import iteritems class Undefined(object): pass class Test(object): AND = '&' OR = '|' def __init__(self, commands, mode=AND, error_or='No test has passed.'): self.commands = commands self.mode = mode self.error_or = error_or def run(self, value): if self.mode == self.AND: return self.run_and(value) elif self.mode == self.OR: return self.run_or(value) else: raise RuntimeError('Invalid mode supplied.') def run_and(self, value): for command in self.commands: value = command(value) return value def run_or(self, value): for command in self.commands: try: return command(value) except ValueError: continue raise ValueError(self.error_or) def __call__(self, value): return self.run(value) class MultiValueError(ValueError): def __init__(self, message, errors): super(MultiValueError, self).__init__(message) self.errors = errors @staticmethod def _recurse(value): if isinstance(value, MultiValueError): return value.to_dict() elif value is None: return value else: return str(value) def to_dict(self): return [self._recurse(v) for v in self.errors] class MappedValueError(MultiValueError): def to_dict(self): return {k: self._recurse(v) for k, v in iteritems(self.errors)} class Mapping(object): def __init__(self, schema): self.schema = list() for field_name in schema.keys(): if not isinstance(field_name, Field): field = Field(field_name) else: field = field_name self.schema.append([field, schema[field_name]]) def __call__(self, data, error='Validation error.', error_required='Field is required.'): result = dict() errors = dict() for field, test in self.schema: field_name = str(field) if field_name not in data: if field.optional: result[field_name] = field.default else: errors[field_name] = error_required else: try: result[field_name] = test(data[field_name]) except ValueError as exc: if field.soft and field.optional: result[field_name] = field.default elif field.soft: result[field_name] = None elif isinstance(exc, MultiValueError): errors[field_name] = exc else: errors[field_name] = str(exc) if len(errors): raise MappedValueError(error, errors) return result class Field(object): def __init__(self, name, default=Undefined, soft=False): self.name = name self.optional = default is not Undefined self.default = default self.soft = soft def __str__(self): return text_type(self.name) def __repr__(self): if self.optional: return '<Field {:s} [{:s}]>'.format(self.name, repr(self.default)) else: return '<Field {:s}>'.format(self.name) def validate(callback, error='Validation error.'): def wrapper(value): if not callback(value): raise ValueError(error) return value return wrapper def sanitize(callback, error='Validation error.'): def wrapper(value): try: return callback(value) except: raise ValueError(error) return wrapper def test_and_return(callback, return_value, error='Validation error.'): def wrapper(value): if callback(value): return return_value raise ValueError('Validation error.') return wrapper
{ "repo_name": "CorverDevelopment/Disinfect", "path": "src/disinfect/disinfect.py", "copies": "1", "size": "4137", "license": "mit", "hash": 5655380995033246000, "line_mean": 25.1835443038, "line_max": 78, "alpha_frac": 0.5496736766, "autogenerated": false, "ratio": 4.4627831715210355, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5512456848121036, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from panoptes_client.panoptes import LinkResolver, PanoptesObject class Classification(PanoptesObject): _api_slug = 'classifications' _link_slug = 'classification' _edit_attributes = ( ) @classmethod def where(cls, **kwargs): """ where(scope=None, **kwargs) Like :py:meth:`.PanoptesObject.where`, but also allows setting the query scope. - **scope** can be any of the values given in the `Classification Collection API documentation <http://docs.panoptes.apiary.io/#reference/classification/classification/list-all-classifications>`_ without the leading slash. Examples:: my_classifications = Classification.where() my_proj_123_classifications = Classification.where(project_id=123) all_proj_123_classifications = Classification.where( scope='project', project_id=123, ) """ scope = kwargs.pop('scope', None) if not scope: return super(Classification, cls).where(**kwargs) return cls.paginated_results(*cls.http_get(scope, params=kwargs)) LinkResolver.register(Classification)
{ "repo_name": "zooniverse/panoptes-python-client", "path": "panoptes_client/classification.py", "copies": "1", "size": "1265", "license": "apache-2.0", "hash": -9037249095617614000, "line_mean": 31.4358974359, "line_max": 139, "alpha_frac": 0.6434782609, "autogenerated": false, "ratio": 4.2592592592592595, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.540273752015926, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, ) from panoptes_client.workflow import Workflow class WorkflowVersion(PanoptesObject): _api_slug = 'versions' _edit_attributes = tuple() @classmethod def http_get(cls, path, params={}, headers={}): workflow = params.pop('workflow') return Panoptes.client().get( Workflow.url(workflow.id) + cls.url(path), params, headers, ) @classmethod def find(cls, _id, workflow): """ Like :py:meth:`.PanoptesObject.find` but also allows lookup by workflow. - **workflow** must be a :py:class:`.Workflow` instance. """ try: return cls.where(id=_id, workflow=workflow).next() except StopIteration: raise PanoptesAPIException( "Could not find {} with id='{}'".format(cls.__name__, _id) ) def save(self): """ Not implemented for this class. It is not possible to modify workflow versions once they are created. """ raise NotImplementedError( 'It is not possible to manually create workflow versions. ' 'Modify the workflow instead.' ) @property def workflow(self): """ The :py:class:`.Workflow` to which this version refers. """ return self.links.item
{ "repo_name": "zooniverse/panoptes-python-client", "path": "panoptes_client/workflow_version.py", "copies": "1", "size": "1518", "license": "apache-2.0", "hash": 8434464998281712000, "line_mean": 25.6315789474, "line_max": 77, "alpha_frac": 0.5816864295, "autogenerated": false, "ratio": 4.288135593220339, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5369822022720339, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from panoptes_client.panoptes import PanoptesObject, LinkResolver from panoptes_client.utils import isiterable, split BATCH_SIZE = 50 class User(PanoptesObject): _api_slug = 'users' _link_slug = 'users' _edit_attributes = ( 'valid_email', ) @classmethod def where(cls, **kwargs): email = kwargs.get('email') login = kwargs.get('login') if email and login: raise ValueError( 'Queries are supported on at most ONE of email and login' ) # This is a workaround for # https://github.com/zooniverse/Panoptes/issues/2733 kwargs['page_size'] = BATCH_SIZE if email: if not isiterable(email): email = [email] for batch in split(email, BATCH_SIZE): kwargs['email'] = ",".join(batch) for user in super(User, cls).where(**kwargs): yield user elif login: if not isiterable(login): login = [login] for batch in split(login, BATCH_SIZE): kwargs['login'] = ",".join(batch) for user in super(User, cls).where(**kwargs): yield user else: for user in super(User, cls).where(**kwargs): yield user @property def avatar(self): """ A dict containing metadata about the user's avatar. """ return User.http_get('{}/avatar'.format(self.id))[0] LinkResolver.register(User) LinkResolver.register(User, 'owner')
{ "repo_name": "zooniverse/panoptes-python-client", "path": "panoptes_client/user.py", "copies": "1", "size": "1655", "license": "apache-2.0", "hash": 7927981904614168000, "line_mean": 26.5833333333, "line_max": 73, "alpha_frac": 0.5528700906, "autogenerated": false, "ratio": 4.1375, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.51903700906, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from pennies.trading.trades import Trade, Portfolio from pennies.market.market import RatesTermStructure from multipledispatch import dispatch # TODO Refactor to remove the Calculator from pennies.calculators.payments import BulletPaymentCalculator from pennies.calculators.assets import default_calculators from pennies.calculators.swaps import present_value @dispatch(Trade, RatesTermStructure, str) def present_value(trade, market, reporting_ccy): """Present Value of Trade and RatesTermStructure""" pv = present_value(trade.contract, market, reporting_ccy) if trade.settlement is not None: pv += present_value(trade.settlement, market, reporting_ccy) return pv @dispatch(Portfolio, RatesTermStructure, str) def present_value(portfolio, market, reporting_ccy): """Present Value of Trade and RatesTermStructure""" pv = 0.0 for t in portfolio.trades: pv += present_value(t, market, reporting_ccy) for p in portfolio.subportfolios: pv += present_value(p, market, reporting_ccy) return pv class TradeCalculator(object): """Calculator for all Trades.""" def __init__(self, trade, market): self.contract = trade.contract self.market = market asset_ccr_cls = default_calculators()[str(type(self.contract))] self.asset_ccr = asset_ccr_cls(self.contract, market) if trade.settlement is None: self.settlement_ccr = None else: self.settlement_ccr = BulletPaymentCalculator(trade.settlement, market) # TODO - Is there a way to get all calculators available for trade? def present_value(self): pv = self.asset_ccr.present_value() if self.settlement_ccr is not None: pv += self.settlement_ccr.present_value() return pv
{ "repo_name": "caseyclements/pennies", "path": "pennies/calculators/trades.py", "copies": "1", "size": "1925", "license": "apache-2.0", "hash": 473865059248004740, "line_mean": 36.0192307692, "line_max": 75, "alpha_frac": 0.6867532468, "autogenerated": false, "ratio": 3.8043478260869565, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49911010728869565, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from pykit import types from pykit.ir import Function, Builder, Value, Op, Const #------------------------------------------------------------------------ # Utils #------------------------------------------------------------------------ def qualified_name(f): return ".".join([f.__module__, f.__name__]) #------------------------------------------------------------------------ # AIR construction #------------------------------------------------------------------------ def from_expr(graph, expr_context, ctx): """ Map a Blaze expression graph to blaze AIR Parameters ---------- graph: blaze.expr.Op Expression graph expr_context: ExprContext Context of the expression ctx: ExecutionContext """ inputs = expr_context.params # ------------------------------------------------- # Types argtypes = [operand.dshape for operand in inputs] signature = types.Function(graph.dshape, argtypes) # ------------------------------------------------- # Setup function name = "expr%d" % ctx.incr() argnames = ["e%d" % i for i in range(len(inputs))] f = Function(name, argnames, signature) builder = Builder(f) builder.position_at_beginning(f.new_block('entry')) # ------------------------------------------------- # Generate function values = dict((expr, f.get_arg("e%d" % i)) for i, expr in enumerate(inputs)) _from_expr(graph, f, builder, values) retval = values[graph] builder.ret(retval) return f, values def _from_expr(expr, f, builder, values): if expr.opcode == 'array': result = values[expr] else: # ------------------------------------------------- # Construct args # This is purely for IR readability name = qualified_name(expr.metadata['overload'].func) args = [_from_expr(arg, f, builder, values) for arg in expr.args] args = [Const(name)] + args # ------------------------------------------------- # Construct Op result = Op("kernel", expr.dshape, args) # Copy metadata verbatim assert 'kernel' in expr.metadata assert 'overload' in expr.metadata result.add_metadata(expr.metadata) # ------------------------------------------------- # Emit Op in code stream builder.emit(result) values[expr] = result return result #------------------------------------------------------------------------ # Execution context #------------------------------------------------------------------------ class ExecutionContext(object): def __init__(self): self.count = 0 def incr(self): count = self.count self.count += 1 return count
{ "repo_name": "zeeshanali/blaze", "path": "blaze/compute/air/ir.py", "copies": "1", "size": "2847", "license": "bsd-3-clause", "hash": -2788278017502028000, "line_mean": 27.198019802, "line_max": 73, "alpha_frac": 0.4418686336, "autogenerated": false, "ratio": 4.88336192109777, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.582523055469777, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from pymel.core import shelfButton, shelfLayout, tabLayout def toolShelf(): tab = tabLayout() shelfLayout('Tools - Copy these freely into your shelf, they will get remade when fossil is opened') shelfButton(image1='zeropose.png', annotation='Zero Controllers', command="import pdil.tool.fossil.userTools;pdil.core.alt.call('Zero Controllers')()") shelfButton(image1='skeletonTool.png', annotation='Open Fossil', command="import pdil.tool.fossil.main;pdil.core.alt.call('Rig Tool')()") shelfButton(image1='selectAllControls.png', annotation='Select All Controllers', command="import pdil.tool.fossil.userTools;pdil.core.alt.call('Select All Controllers')()") shelfButton(image1='quickHideControls.png', annotation='Similar to "Isolated Selected" but just for rig controls', command="import pdil.tool.rigControls;pdil.core.alt.call('Quick Hide Controls')()") return tab
{ "repo_name": "patcorwin/fossil", "path": "pdil/tool/fossil/ui/artistToolsTab.py", "copies": "1", "size": "1117", "license": "bsd-3-clause", "hash": -8043655064208936000, "line_mean": 40.4074074074, "line_max": 107, "alpha_frac": 0.6553267681, "autogenerated": false, "ratio": 3.8517241379310345, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5007050906031034, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from PySide import QtCore, QtGui class ConsoleInput(QtGui.QPlainTextEdit): def __init__(self, parent): super(ConsoleInput, self).__init__(parent) self.evaluate = None self.history = [] self.historyPos = 0 self.savedEntry = None return def keyPressEvent(self, ev): key = ev.key() mods = ev.modifiers() doc = self.document() if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter): text = doc.toPlainText() if (len(text.strip()) > 0 and (self.evaluate is None or self.evaluate(text))): # Command was run or had a syntax error; clear out the input doc.setPlainText("") self.history.append(text) self.historyPos = len(self.history) self.savedEntry = None return elif key == QtCore.Qt.Key_Up: text = doc.toPlainText() # Are we on the top line and not at the start of the history? # Note: This works even if len(self.history) == 0 if ("\n" not in text[:self.textCursor().position()] and self.historyPos != 0): # If we were editing something new, stash it away. if self.historyPos == len(self.history): self.savedEntry = text self.historyPos -= 1 doc.setPlainText(self.history[self.historyPos]) cur = self.textCursor() cur.movePosition(cur.End) self.setTextCursor(cur) return elif key == QtCore.Qt.Key_Down: text = doc.toPlainText() # Are we on the bottom line and not editing something new? if ("\n" not in text[self.textCursor().position():] and self.historyPos is not None): self.historyPos += 1 if self.historyPos == len(self.history): # We've moved onto the new edit area. Unstash it. doc.setPlainText(self.savedEntry) else: doc.setPlainText(self.history[self.historyPos]) cur = self.textCursor() cur.movePosition(cur.Start) self.setTextCursor(cur) return return super(ConsoleInput, self).keyPressEvent(ev)
{ "repo_name": "dacut/ret", "path": "ret/ui/qt/consoleinput.py", "copies": "1", "size": "2476", "license": "bsd-2-clause", "hash": -5959754788717777000, "line_mean": 37.6875, "line_max": 76, "alpha_frac": 0.531098546, "autogenerated": false, "ratio": 4.397868561278863, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5428967107278863, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from qtpy import compat from glue import config from glue.utils.qt import messagebox_on_error from glue.io.subset_mask import SubsetMaskImporter, SubsetMaskExporter __all__ = ['QtSubsetMaskImporter', 'QtSubsetMaskExporter'] def _make_filters_dict(registry): filters = {} for e in registry: if e.extension == '': fltr = "{0} (*)".format(e.label) else: fltr = "{0} ({1})".format(e.label, ' '.join('*.' + ext for ext in e.extension)) filters[fltr] = e.function return filters class QtSubsetMaskImporter(SubsetMaskImporter): def get_filename_and_reader(self): subset_mask_importers = _make_filters_dict(config.subset_mask_importer) filters = ';;'.join(sorted(subset_mask_importers)) filename, fltr = compat.getopenfilename(caption="Choose a subset mask file", filters=filters) filename = str(filename) if filename: return filename, subset_mask_importers[fltr] else: return None, None @messagebox_on_error('An error occurred when importing the subset mask file:', sep=' ') def run(self, data_or_subset, data_collection): super(QtSubsetMaskImporter, self).run(data_or_subset, data_collection) class QtSubsetMaskExporter(SubsetMaskExporter): def get_filename_and_writer(self): subset_mask_exporters = _make_filters_dict(config.subset_mask_exporter) filters = ';;'.join(sorted(subset_mask_exporters)) filename, fltr = compat.getsavefilename(caption="Choose a subset mask filename", filters=filters) filename = str(filename) if filename: return filename, subset_mask_exporters[fltr] else: return None, None @messagebox_on_error('An error occurred when exporting the subset mask:', sep=' ') def run(self, data_or_subset): super(QtSubsetMaskExporter, self).run(data_or_subset)
{ "repo_name": "stscieisenhamer/glue", "path": "glue/core/io/qt/subset_mask.py", "copies": "5", "size": "2095", "license": "bsd-3-clause", "hash": 8176946555022314000, "line_mean": 30.2686567164, "line_max": 91, "alpha_frac": 0.6329355609, "autogenerated": false, "ratio": 3.9678030303030303, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008393140932369932, "num_lines": 67 }
from __future__ import absolute_import, division, print_function from qtpy import QtCore from qtpy import PYQT5 from glue.icons.qt import get_icon from glue.utils import nonpartial from glue.viewers.common.qt.tool import CheckableTool, Tool from glue.viewers.common.qt.mouse_mode import MouseMode from glue.viewers.common.qt.toolbar import BasicToolbar if PYQT5: from matplotlib.backends.backend_qt5 import NavigationToolbar2QT else: from matplotlib.backends.backend_qt4 import NavigationToolbar2QT __all__ = ['HomeTool', 'SaveTool', 'BackTool', 'ForwardTool', 'PanTool', 'ZoomTool', 'MatplotlibViewerToolbar'] class HomeTool(Tool): def __init__(self, viewer, toolbar=None): super(HomeTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:home' self.icon = get_icon('glue_home') self.action_text = 'Home' self.tool_tip = 'Reset original zoom' self.shortcut = 'H' self.checkable = False self.toolbar = toolbar def activate(self): self.toolbar.home() class SaveTool(Tool): def __init__(self, viewer, toolbar=None): super(SaveTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:save' self.icon = get_icon('glue_filesave') self.action_text = 'Save' self.tool_tip = 'Save the figure' self.shortcut = 'Ctrl+Shift+S' self.toolbar = toolbar def activate(self): self.toolbar.save_figure() class BackTool(Tool): def __init__(self, viewer, toolbar=None): super(BackTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:back' self.icon = get_icon('glue_back') self.action_text = 'Back' self.tool_tip = 'Back to previous view' self.toolbar = toolbar def activate(self): self.toolbar.back() class ForwardTool(Tool): def __init__(self, viewer, toolbar=None): super(ForwardTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:forward' self.icon = get_icon('glue_forward') self.action_text = 'Forward' self.tool_tip = 'Forward to next view' self.toolbar = toolbar def activate(self): self.toolbar.forward() class PanTool(CheckableTool): def __init__(self, viewer, toolbar=None): super(PanTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:pan' self.icon = get_icon('glue_move') self.action_text = 'Pan' self.tool_tip = 'Pan axes with left mouse, zoom with right' self.shortcut = 'M' self.toolbar = toolbar def activate(self): self.toolbar.pan() def deactivate(self): self.toolbar.pan() class ZoomTool(CheckableTool): def __init__(self, viewer, toolbar=None): super(ZoomTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:zoom' self.icon = get_icon('glue_zoom_to_rect') self.action_text = 'Zoom' self.tool_tip = 'Zoom to rectangle' self.shortcut = 'Z' self.toolbar = toolbar def activate(self): self.toolbar.zoom() def deactivate(self): self.toolbar.zoom() class MatplotlibViewerToolbar(BasicToolbar): pan_begin = QtCore.Signal() pan_end = QtCore.Signal() def __init__(self, parent): self.canvas = parent.central_widget.canvas # Set up virtual Matplotlib navigation toolbar (don't show it) self._mpl_nav = NavigationToolbar2QT(self.canvas, parent) self._mpl_nav.hide() BasicToolbar.__init__(self, parent) def setup_default_modes(self): # Set up default Matplotlib Tools - this gets called by the __init__ # call to the parent class above. home_mode = HomeTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(home_mode) save_mode = SaveTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(save_mode) back_mode = BackTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(back_mode) forward_mode = ForwardTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(forward_mode) pan_mode = PanTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(pan_mode) zoom_mode = ZoomTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(zoom_mode) self._connections = [] def activate_tool(self, mode): if isinstance(mode, MouseMode): self._connections.append(self.canvas.mpl_connect('button_press_event', mode.press)) self._connections.append(self.canvas.mpl_connect('motion_notify_event', mode.move)) self._connections.append(self.canvas.mpl_connect('button_release_event', mode.release)) self._connections.append(self.canvas.mpl_connect('key_press_event', mode.key)) super(MatplotlibViewerToolbar, self).activate_tool(mode) def deactivate_tool(self, mode): for connection in self._connections: self.canvas.mpl_disconnect(connection) self._connections = [] super(MatplotlibViewerToolbar, self).deactivate_tool(mode)
{ "repo_name": "saimn/glue", "path": "glue/viewers/common/qt/mpl_toolbar.py", "copies": "2", "size": "5119", "license": "bsd-3-clause", "hash": -5870537988625900000, "line_mean": 29.4702380952, "line_max": 99, "alpha_frac": 0.6321547177, "autogenerated": false, "ratio": 3.6382373845060414, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5270392102206041, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from qtpy import QtCore from qtpy import PYQT5 from glue.icons.qt import get_icon from glue.viewers.common.qt.tool import CheckableTool, Tool from glue.viewers.common.qt.mouse_mode import MouseMode from glue.viewers.common.qt.toolbar import BasicToolbar if PYQT5: from matplotlib.backends.backend_qt5 import NavigationToolbar2QT else: from matplotlib.backends.backend_qt4 import NavigationToolbar2QT __all__ = ['HomeTool', 'SaveTool', 'BackTool', 'ForwardTool', 'PanTool', 'ZoomTool', 'MatplotlibViewerToolbar'] class HomeTool(Tool): def __init__(self, viewer, toolbar=None): super(HomeTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:home' self.icon = get_icon('glue_home') self.action_text = 'Home' self.tool_tip = 'Reset original zoom' self.shortcut = 'H' self.checkable = False self.toolbar = toolbar def activate(self): if hasattr(self.viewer, 'state') and hasattr(self.viewer.state, 'reset_limits'): self.viewer.state.reset_limits() else: self.toolbar.home() class SaveTool(Tool): def __init__(self, viewer, toolbar=None): super(SaveTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:save' self.icon = get_icon('glue_filesave') self.action_text = 'Save' self.tool_tip = 'Save the figure' self.shortcut = 'Ctrl+Shift+S' self.toolbar = toolbar def activate(self): self.toolbar.save_figure() class BackTool(Tool): def __init__(self, viewer, toolbar=None): super(BackTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:back' self.icon = get_icon('glue_back') self.action_text = 'Back' self.tool_tip = 'Back to previous view' self.toolbar = toolbar def activate(self): self.toolbar.back() class ForwardTool(Tool): def __init__(self, viewer, toolbar=None): super(ForwardTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:forward' self.icon = get_icon('glue_forward') self.action_text = 'Forward' self.tool_tip = 'Forward to next view' self.toolbar = toolbar def activate(self): self.toolbar.forward() class PanTool(CheckableTool): def __init__(self, viewer, toolbar=None): super(PanTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:pan' self.icon = get_icon('glue_move') self.action_text = 'Pan' self.tool_tip = 'Pan axes with left mouse, zoom with right' self.shortcut = 'M' self.toolbar = toolbar def activate(self): self.toolbar.pan() def deactivate(self): self.toolbar.pan() class ZoomTool(CheckableTool): def __init__(self, viewer, toolbar=None): super(ZoomTool, self).__init__(viewer=viewer) self.tool_id = 'mpl:zoom' self.icon = get_icon('glue_zoom_to_rect') self.action_text = 'Zoom' self.tool_tip = 'Zoom to rectangle' self.shortcut = 'Z' self.toolbar = toolbar def activate(self): self.toolbar.zoom() def deactivate(self): self.toolbar.zoom() class MatplotlibViewerToolbar(BasicToolbar): pan_begin = QtCore.Signal() pan_end = QtCore.Signal() def __init__(self, viewer): self.canvas = viewer.central_widget.canvas # Set up virtual Matplotlib navigation toolbar (don't show it) self._mpl_nav = NavigationToolbar2QT(self.canvas, viewer) self._mpl_nav.hide() BasicToolbar.__init__(self, viewer) viewer.window_closed.connect(self.close) def close(self, *args): self._mpl_nav.setParent(None) self._mpl_nav.parent = None def setup_default_modes(self): # Set up default Matplotlib Tools - this gets called by the __init__ # call to the parent class above. home_mode = HomeTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(home_mode) save_mode = SaveTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(save_mode) back_mode = BackTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(back_mode) forward_mode = ForwardTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(forward_mode) pan_mode = PanTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(pan_mode) zoom_mode = ZoomTool(self.parent(), toolbar=self._mpl_nav) self.add_tool(zoom_mode) self._connections = [] def activate_tool(self, mode): if isinstance(mode, MouseMode): self._connections.append(self.canvas.mpl_connect('button_press_event', mode.press)) self._connections.append(self.canvas.mpl_connect('motion_notify_event', mode.move)) self._connections.append(self.canvas.mpl_connect('button_release_event', mode.release)) self._connections.append(self.canvas.mpl_connect('key_press_event', mode.key)) super(MatplotlibViewerToolbar, self).activate_tool(mode) def deactivate_tool(self, mode): for connection in self._connections: self.canvas.mpl_disconnect(connection) self._connections = [] super(MatplotlibViewerToolbar, self).deactivate_tool(mode)
{ "repo_name": "stscieisenhamer/glue", "path": "glue/viewers/matplotlib/qt/toolbar.py", "copies": "1", "size": "5390", "license": "bsd-3-clause", "hash": 7466597451476573000, "line_mean": 29.625, "line_max": 99, "alpha_frac": 0.6289424861, "autogenerated": false, "ratio": 3.6394328156650912, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9766867963714565, "avg_score": 0.00030146761010525053, "num_lines": 176 }
from __future__ import absolute_import, division, print_function from qtpy import QtCore from qtpy.QtCore import Qt __all__ = ['PythonListModel'] class PythonListModel(QtCore.QAbstractListModel): """ A Qt Model that wraps a python list, and exposes a list-like interface This can be connected directly to multiple QListViews, which will stay in sync with the state of the container. """ def __init__(self, items, parent=None): """ Create a new model Parameters ---------- items : list The initial list to wrap parent : QObject The model parent """ super(PythonListModel, self).__init__(parent) self.items = items def rowCount(self, parent=None): """Number of rows""" return len(self.items) def headerData(self, section, orientation, role): """Column labels""" if role != Qt.DisplayRole: return None return "%i" % section def row_label(self, row): """ The textual label for the row""" return str(self.items[row]) def data(self, index, role): """Retrieve data at each index""" if not index.isValid(): return None if role == Qt.DisplayRole or role == Qt.EditRole: return self.row_label(index.row()) if role == Qt.UserRole: return self.items[index.row()] def setData(self, index, value, role): """ Update the data in-place Parameters ---------- index : QModelIndex The location of the change value : object The new value role : QEditRole Which aspect of the model to update """ if not index.isValid(): return False if role == Qt.UserRole: row = index.row() self.items[row] = value self.dataChanged.emit(index, index) return True return super(PythonListModel, self).setDdata(index, value, role) def removeRow(self, row, parent=None): """ Remove a row from the table Parameters ---------- row : int Row to remove Returns ------- successful : bool """ if row < 0 or row >= len(self.items): return False self.beginRemoveRows(QtCore.QModelIndex(), row, row) self._remove_row(row) self.endRemoveRows() return True def pop(self, row=None): """ Remove and return an item (default last item) Parameters ---------- row : int (optional) Which row to remove. Default=last Returns -------- popped : object """ if row is None: row = len(self) - 1 result = self[row] self.removeRow(row) return result def _remove_row(self, row): # actually remove data. Subclasses can override this as needed self.items.pop(row) def __getitem__(self, row): return self.items[row] def __setitem__(self, row, value): index = self.index(row) self.setData(index, value, role=Qt.UserRole) def __len__(self): return len(self.items) def insert(self, row, value): self.beginInsertRows(QtCore.QModelIndex(), row, row) self.items.insert(row, value) self.endInsertRows() self.rowsInserted.emit(self.index(row), row, row) def append(self, value): row = len(self) self.insert(row, value) def extend(self, values): for v in values: self.append(v) def set_list(self, values): """ Set the model to a new list """ self.beginResetModel() self.items = values self.endResetModel()
{ "repo_name": "saimn/glue", "path": "glue/utils/qt/python_list_model.py", "copies": "4", "size": "3883", "license": "bsd-3-clause", "hash": -3458478874038520000, "line_mean": 24.385620915, "line_max": 74, "alpha_frac": 0.5431367499, "autogenerated": false, "ratio": 4.3240534521158125, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0002334267040149393, "num_lines": 153 }
from __future__ import absolute_import, division, print_function from qtpy import QtCore __all__ = ['PyMimeData'] class PyMimeData(QtCore.QMimeData): """ A custom MimeData object that stores live python objects Associate specific objects with a mime type by passing mime type / object kev/value pairs to the __init__ method If a single object is passed to the init method, that object is associated with the PyMimeData.MIME_TYPE mime type """ MIME_TYPE = 'application/py_instance' def __init__(self, instance=None, **kwargs): """ :param instance: The python object to store kwargs: Optional mime type / objects pairs to store as objects """ super(PyMimeData, self).__init__() self._instances = {} self.setData(self.MIME_TYPE, instance) for k, v in kwargs.items(): self.setData(k, v) def formats(self): return list(set(super(PyMimeData, self).formats() + list(self._instances.keys()))) def hasFormat(self, fmt): return fmt in self._instances or super(PyMimeData, self).hasFormat(fmt) def setData(self, mime, data): super(PyMimeData, self).setData(mime, QtCore.QByteArray(1, '1')) self._instances[mime] = data def data(self, mime_type): """ Retrieve the data stored at the specified mime_type If mime_type is application/py_instance, a python object is returned. Otherwise, a QtCore.QByteArray is returned """ if str(mime_type) in self._instances: return self._instances[mime_type] return super(PyMimeData, self).data(mime_type)
{ "repo_name": "stscieisenhamer/glue", "path": "glue/utils/qt/mime.py", "copies": "4", "size": "1680", "license": "bsd-3-clause", "hash": -5854481314951249000, "line_mean": 30.1111111111, "line_max": 79, "alpha_frac": 0.6375, "autogenerated": false, "ratio": 3.9529411764705884, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6590441176470588, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from qtpy import QtCore __all__ = ['Worker'] class Worker(QtCore.QThread): result = QtCore.Signal(object) error = QtCore.Signal(object) def __init__(self, func, *args, **kwargs): """ Execute a function call on a different QThread :param func: The function object to call :param args: arguments to pass to the function :param kwargs: kwargs to pass to the function """ super(Worker, self).__init__() self.func = func self.args = args self.kwargs = kwargs def run(self): """ Invoke the function Upon successful completion, the result signal will be fired with the output of the function If an exception occurs, the error signal will be fired with the result form sys.exc_infno() """ try: result = self.func(*self.args, **self.kwargs) self.result.emit(result) except: import sys self.error.emit(sys.exc_info())
{ "repo_name": "saimn/glue", "path": "glue/utils/qt/threading.py", "copies": "4", "size": "1096", "license": "bsd-3-clause", "hash": -3953765221635027000, "line_mean": 27.8421052632, "line_max": 67, "alpha_frac": 0.5903284672, "autogenerated": false, "ratio": 4.366533864541832, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001644736842105263, "num_lines": 38 }
from __future__ import absolute_import, division, print_function from qtpy import QtCore, QtWidgets from glue.core.edit_subset_mode import (EditSubsetMode, OrMode, AndNotMode, AndMode, XorMode, ReplaceMode) from glue.app.qt.actions import action from glue.utils import nonpartial def set_mode(mode): edit_mode = EditSubsetMode() edit_mode.mode = mode class EditSubsetModeToolBar(QtWidgets.QToolBar): def __init__(self, title="Subset Update Mode", parent=None): super(EditSubsetModeToolBar, self).__init__(title, parent) spacer = QtWidgets.QWidget() spacer.setMinimumSize(20, 10) spacer.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) self.addWidget(spacer) self.addWidget(QtWidgets.QLabel("Selection Mode:")) self.setIconSize(QtCore.QSize(20, 20)) self._group = QtWidgets.QActionGroup(self) self._modes = {} self._add_actions() self._modes[EditSubsetMode().mode].trigger() self._backup_mode = None spacer = QtWidgets.QWidget() spacer.setMinimumSize(20, 10) spacer.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) self.addWidget(spacer) def _make_mode(self, name, tip, icon, mode): a = action(name, self, tip, icon) a.setCheckable(True) a.triggered.connect(nonpartial(set_mode, mode)) self._group.addAction(a) self.addAction(a) self._modes[mode] = a label = name.split()[0].lower().replace('&', '') self._modes[label] = mode def _add_actions(self): self._make_mode("&Replace Mode", "Replace selection", 'glue_replace', ReplaceMode) self._make_mode("&Or Mode", "Add to selection", 'glue_or', OrMode) self._make_mode("&And Mode", "Set selection as intersection", 'glue_and', AndMode) self._make_mode("&Xor Mode", "Set selection as exclusive intersection", 'glue_xor', XorMode) self._make_mode("&Not Mode", "Remove from selection", 'glue_andnot', AndNotMode) def set_mode(self, mode): """Temporarily set the edit mode to mode :param mode: Name of the mode (Or, Not, And, Xor, Replace) :type mode: str """ try: mode = self._modes[mode] # label to mode class except KeyError: raise KeyError("Unrecognized mode: %s" % mode) self._backup_mode = self._backup_mode or EditSubsetMode().mode self._modes[mode].trigger() # mode class to action def unset_mode(self): """Restore the mode to the state before set_mode was called""" mode = self._backup_mode self._backup_mode = None if mode: self._modes[mode].trigger()
{ "repo_name": "stscieisenhamer/glue", "path": "glue/app/qt/edit_subset_mode_toolbar.py", "copies": "2", "size": "2986", "license": "bsd-3-clause", "hash": 6737345832837329000, "line_mean": 35.4146341463, "line_max": 79, "alpha_frac": 0.5910917616, "autogenerated": false, "ratio": 4.046070460704607, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5637162222304607, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from qtpy import QtCore, QtWidgets from glue.core.qt.component_id_combo import ComponentIDCombo class RGBEdit(QtWidgets.QWidget): """A widget to set the contrast for individual layers in an RGB image Based off the ds9 RGB Frame widget :param artist: A :class:`~glue.viewers.image.layer_artist.RGBArtistLayerArtist` instance to control :param parent: Optional widget parent This widget sets the state of the artist object, such that contrast adjustments from a :class:`~glue.viewers.image.client` affect a particular RGB slice """ current_changed = QtCore.Signal(str) colors_changed = QtCore.Signal() def __init__(self, parent=None, artist=None): super(RGBEdit, self).__init__(parent) self._artist = artist l = QtWidgets.QGridLayout() current = QtWidgets.QLabel("Contrast") visible = QtWidgets.QLabel("Visible") l.addWidget(current, 0, 2, 1, 1) l.addWidget(visible, 0, 3, 1, 1) l.setColumnStretch(0, 0) l.setColumnStretch(1, 10) l.setColumnStretch(2, 0) l.setColumnStretch(3, 0) l.setRowStretch(0, 0) l.setRowStretch(1, 0) l.setRowStretch(2, 0) l.setRowStretch(3, 0) l.setRowStretch(4, 10) curr_grp = QtWidgets.QButtonGroup() self.current = {} self.vis = {} self.cid = {} for row, color in enumerate(['red', 'green', 'blue'], 1): lbl = QtWidgets.QLabel(color.title()) cid = ComponentIDCombo() curr = QtWidgets.QRadioButton() curr_grp.addButton(curr) vis = QtWidgets.QCheckBox() vis.setChecked(True) l.addWidget(lbl, row, 0, 1, 1) l.addWidget(cid, row, 1, 1, 1) l.addWidget(curr, row, 2, 1, 1) l.addWidget(vis, row, 3, 1, 1) curr.clicked.connect(self.update_current) vis.toggled.connect(self.update_visible) cid.currentIndexChanged.connect(self.update_layers) self.cid[color] = cid self.vis[color] = vis self.current[color] = curr self.setLayout(l) self.current['red'].click() @property def attributes(self): """A 3-tuple of the ComponentIDs for each RGB layer""" return tuple(self.cid[c].component for c in ['red', 'green', 'blue']) @attributes.setter def attributes(self, cids): for cid, c in zip(cids, ['red', 'green', 'blue']): if cid is None: continue self.cid[c].component = cid @property def rgb_visible(self): """ A 3-tuple of the visibility of each layer, as bools """ return tuple(self.vis[c].isChecked() for c in ['red', 'green', 'blue']) @rgb_visible.setter def rgb_visible(self, value): for v, c in zip(value, 'red green blue'.split()): self.vis[c].setChecked(v) @property def artist(self): return self._artist @artist.setter def artist(self, value): self._artist = value for cid in self.cid.values(): cid.data = value.layer self.update_layers() def update_layers(self): if self.artist is None: return r = self.cid['red'].component g = self.cid['green'].component b = self.cid['blue'].component changed = self.artist.r is not r or \ self.artist.g is not g or\ self.artist.b is not b self.artist.r = r self.artist.g = g self.artist.b = b if changed: self.colors_changed.emit() self.artist.update() self.artist.redraw() def update_current(self, *args): if self.artist is None: return for c in ['red', 'green', 'blue']: if self.current[c].isChecked(): self.artist.contrast_layer = c self.current_changed.emit(c) break else: raise RuntimeError("Could not determine which layer is current") def update_visible(self, *args): if self.artist is None: return self.artist.layer_visible['red'] = self.vis['red'].isChecked() self.artist.layer_visible['green'] = self.vis['green'].isChecked() self.artist.layer_visible['blue'] = self.vis['blue'].isChecked() self.artist.update() self.artist.redraw()
{ "repo_name": "saimn/glue", "path": "glue/viewers/image/qt/rgb_edit.py", "copies": "1", "size": "4546", "license": "bsd-3-clause", "hash": 9022242054683109000, "line_mean": 28.9078947368, "line_max": 83, "alpha_frac": 0.5736911571, "autogenerated": false, "ratio": 3.8722316865417374, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4945922843641737, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from qtpy import QtCore, QtWidgets from glue.core.simpleforms import IntOption, FloatOption, BoolOption from glue.utils import nonpartial _dispatch = {} class FormItem(QtCore.QObject): changed = QtCore.Signal() def __init__(self, instance, option): super(FormItem, self).__init__() self.option = option self.instance = instance @property def label(self): return self.option.label class NumberFormItem(FormItem): widget_cls = None def __init__(self, instance, option): super(NumberFormItem, self).__init__(instance, option) value = option.__get__(instance) w = self.widget_cls() w.setRange(option.min, option.max) w.setValue(value) w.valueChanged.connect(nonpartial(self.changed.emit)) self.widget = w @property def value(self): return self.widget.value() class IntFormItem(NumberFormItem): widget_cls = QtWidgets.QSpinBox class FloatFormItem(NumberFormItem): widget_cls = QtWidgets.QDoubleSpinBox class BoolFormItem(FormItem): def __init__(self, instance, option): super(BoolFormItem, self).__init__(instance, option) value = option.__get__(instance) self.widget = QtWidgets.QCheckBox() self.widget.setChecked(value) self.widget.clicked.connect(nonpartial(self.changed.emit)) @property def value(self): return self.widget.isChecked() def build_form_item(instance, option_name): option = getattr(type(instance), option_name) option_type = type(option) return _dispatch[option_type](instance, option) def register(option_cls, form_cls): _dispatch[option_cls] = form_cls register(IntOption, IntFormItem) register(FloatOption, FloatFormItem) register(BoolOption, BoolFormItem)
{ "repo_name": "saimn/glue", "path": "glue/core/qt/simpleforms.py", "copies": "5", "size": "1877", "license": "bsd-3-clause", "hash": -8121601823149359000, "line_mean": 23.3766233766, "line_max": 68, "alpha_frac": 0.6766116143, "autogenerated": false, "ratio": 3.830612244897959, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 77 }
from __future__ import absolute_import, division, print_function from qtpy import QtWidgets from glue.core.edit_subset_mode import (EditSubsetMode, OrMode, AndNotMode, AndMode, XorMode, ReplaceMode) from glue.app.qt.actions import action from glue.utils import nonpartial def set_mode(mode): edit_mode = EditSubsetMode() edit_mode.mode = mode class EditSubsetModeToolBar(QtWidgets.QToolBar): def __init__(self, title="Subset Update Mode", parent=None): super(EditSubsetModeToolBar, self).__init__(title, parent) self._group = QtWidgets.QActionGroup(self) self._modes = {} self._add_actions() self._modes[EditSubsetMode().mode].trigger() self._backup_mode = None def _make_mode(self, name, tip, icon, mode): a = action(name, self, tip, icon) a.setCheckable(True) a.triggered.connect(nonpartial(set_mode, mode)) self._group.addAction(a) self.addAction(a) self._modes[mode] = a label = name.split()[0].lower().replace('&', '') self._modes[label] = mode def _add_actions(self): self._make_mode("&Replace Mode", "Replace selection", 'glue_replace', ReplaceMode) self._make_mode("&Or Mode", "Add to selection", 'glue_or', OrMode) self._make_mode("&And Mode", "Set selection as intersection", 'glue_and', AndMode) self._make_mode("&Xor Mode", "Set selection as exclusive intersection", 'glue_xor', XorMode) self._make_mode("&Not Mode", "Remove from selection", 'glue_andnot', AndNotMode) def set_mode(self, mode): """Temporarily set the edit mode to mode :param mode: Name of the mode (Or, Not, And, Xor, Replace) :type mode: str """ try: mode = self._modes[mode] # label to mode class except KeyError: raise KeyError("Unrecognized mode: %s" % mode) self._backup_mode = self._backup_mode or EditSubsetMode().mode self._modes[mode].trigger() # mode class to action def unset_mode(self): """Restore the mode to the state before set_mode was called""" mode = self._backup_mode self._backup_mode = None if mode: self._modes[mode].trigger()
{ "repo_name": "saimn/glue", "path": "glue/app/qt/edit_subset_mode_toolbar.py", "copies": "2", "size": "2414", "license": "bsd-3-clause", "hash": -7171720837174376000, "line_mean": 36.1384615385, "line_max": 79, "alpha_frac": 0.5849212925, "autogenerated": false, "ratio": 3.9252032520325204, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 65 }
from __future__ import absolute_import, division, print_function from qtpy import QtWidgets from glue.core.hub import HubListener from glue.core.message import ComponentsChangedMessage class ComponentIDCombo(QtWidgets.QComboBox, HubListener): """ A widget to select among componentIDs in a dataset """ def __init__(self, data=None, parent=None, visible_only=True): QtWidgets.QComboBox.__init__(self, parent) self._data = data self._visible_only = visible_only @property def data(self): return self._data @data.setter def data(self, value): if value is None: return self._data = value if value.hub is not None: self.register_to_hub(value.hub) self.refresh_components() @property def component(self): return self.itemData(self.currentIndex()) @component.setter def component(self, value): for i in range(self.count()): if self.itemData(i) is value: self.setCurrentIndex(i) return else: raise ValueError("Unable to select %s" % value) def refresh_components(self): if self.data is None: return self.blockSignals(True) old_data = self.itemData(self.currentIndex()) self.clear() if self._visible_only: fields = self.data.visible_components else: fields = self.data.components index = 0 for i, f in enumerate(fields): self.addItem(f.label, userData=f) if f == old_data: index = i self.blockSignals(False) self.setCurrentIndex(index) def register_to_hub(self, hub): hub.subscribe(self, ComponentsChangedMessage, handler=lambda x: self.refresh_components, filter=lambda x: x.data is self._data)
{ "repo_name": "saimn/glue", "path": "glue/core/qt/component_id_combo.py", "copies": "2", "size": "1947", "license": "bsd-3-clause", "hash": 85786872202647310, "line_mean": 27.231884058, "line_max": 66, "alpha_frac": 0.5880842322, "autogenerated": false, "ratio": 4.307522123893805, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00024154589371980676, "num_lines": 69 }
from __future__ import absolute_import, division, print_function from qtpy import QtWidgets from glue.utils.qt.mime import PyMimeData __all__ = ['GlueItemWidget'] class GlueItemWidget(object): """ A mixin for QtWidgets.QListWidget/GlueTreeWidget subclasses, that provides drag+drop funtionality. """ # Implementation detail: QXXWidgetItems are unhashable in PySide, # and cannot be used as dictionary keys. we hash on IDs instead SUPPORTED_MIME_TYPE = None def __init__(self, parent=None): super(GlueItemWidget, self).__init__(parent) self._mime_data = {} self.setDragEnabled(True) def mimeTypes(self): """ Return the list of MIME Types supported for this object. """ types = [self.SUPPORTED_MIME_TYPE] return types def mimeData(self, selected_items): """ Return a list of MIME data associated with the each selected item. Parameters ---------- selected_items : list A list of ``QtWidgets.QListWidgetItems`` or ``QtWidgets.QTreeWidgetItems`` instances Returns ------- result : list A list of MIME objects """ try: data = [self.get_data(i) for i in selected_items] except KeyError: data = None result = PyMimeData(data, **{self.SUPPORTED_MIME_TYPE: data}) # apparent bug in pyside garbage collects custom mime # data, and crashes. Save result here to avoid self._mime = result return result def get_data(self, item): """ Convenience method to fetch the data associated with a ``QxxWidgetItem``. """ # return item.data(Qt.UserRole) return self._mime_data[id(item)] def set_data(self, item, data): """ Convenience method to set data associated with a ``QxxWidgetItem``. """ #item.setData(Qt.UserRole, data) self._mime_data[id(item)] = data def drop_data(self, item): self._mime_data.pop(id(item)) @property def data(self): return self._mime_data
{ "repo_name": "saimn/glue", "path": "glue/utils/qt/mixins.py", "copies": "1", "size": "2178", "license": "bsd-3-clause", "hash": -2165282928254934000, "line_mean": 26.5696202532, "line_max": 96, "alpha_frac": 0.5945821855, "autogenerated": false, "ratio": 4.196531791907514, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5291113977407513, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from qtpy import QtWidgets __all__ = ['pick_item', 'pick_class', 'get_text'] # TODO: update docstrings def pick_item(items, labels, title="Pick an item", label="Pick an item", default=None): """ Prompt the user to choose an item :param items: List of items to choose :param labels: List of strings to label items :param title: Optional widget title :param label: Optional prompt Returns the selected item, or None """ if default in items: current = items.index(default) else: current = 0 choice, isok = QtWidgets.QInputDialog.getItem(None, title, label, labels, current=current, editable=False) if isok: index = labels.index(str(choice)) return items[index] def pick_class(classes, sort=False, **kwargs): """Prompt the user to pick from a list of classes using QT :param classes: list of class objects :param title: string of the prompt Returns: The class that was selected, or None """ def _label(c): try: return c.LABEL except AttributeError: return c.__name__ if sort: classes = sorted(classes, key=lambda x: _label(x)) choices = [_label(c) for c in classes] return pick_item(classes, choices, **kwargs) def get_text(title='Enter a label', default=None): """Prompt the user to enter text using QT :param title: Name of the prompt :param default: Default text to show in prompt Returns: The text the user typed, or None """ result, isok = QtWidgets.QInputDialog.getText( None, title, title, text=default ) if isok: return str(result)
{ "repo_name": "stscieisenhamer/glue", "path": "glue/utils/qt/dialogs.py", "copies": "3", "size": "1835", "license": "bsd-3-clause", "hash": 3370254921730463000, "line_mean": 25.5942028986, "line_max": 72, "alpha_frac": 0.6076294278, "autogenerated": false, "ratio": 4.123595505617978, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0004817646121993948, "num_lines": 69 }
from __future__ import absolute_import, division, print_function from qtpy import QtWidgets from .connect import (connect_checkable_button, connect_value, connect_combo_data, connect_combo_text, connect_float_text, connect_text, connect_button, connect_combo_selection) __all__ = ['autoconnect_callbacks_to_qt'] HANDLERS = {} HANDLERS['value'] = connect_value HANDLERS['valuetext'] = connect_float_text HANDLERS['bool'] = connect_checkable_button HANDLERS['text'] = connect_text HANDLERS['combodata'] = connect_combo_data HANDLERS['combotext'] = connect_combo_text HANDLERS['button'] = connect_button HANDLERS['combosel'] = connect_combo_selection def autoconnect_callbacks_to_qt(instance, widget, connect_kwargs={}): """ Given a class instance with callback properties and a Qt widget/window, connect callback properties to Qt widgets automatically. The matching is done based on the objectName of the Qt widgets. Qt widgets that need to be connected should be named using the syntax ``type_name`` where ``type`` describes the kind of matching to be done, and ``name`` matches the name of a callback property. By default, the types can be: * ``value``: the callback property is linked to a Qt widget that has ``value`` and ``setValue`` methods. Note that for this type, two additional keyword arguments can be specified using ``connect_kwargs`` (see below): these are ``value_range``, which is used for cases where the Qt widget is e.g. a slider which has a range of values, and you want to map this range of values onto a different range for the callback property, and the second is ``log``, which can be set to `True` if this mapping should be done in log space. * ``valuetext``: the callback property is linked to a Qt widget that has ``text`` and ``setText`` methods, and the text is set to a string representation of the value. Note that for this type, an additional argument ``fmt`` can be provided, which gives either the format to use using the ``{}`` syntax, or should be a function that takes a value and returns a string. Optionally, if the Qt widget supports the ``editingFinished`` signal, this signal is connected to the callback property too. * ``bool``: the callback property is linked to a Qt widget that has ``isChecked`` and ``setChecked`` methods, such as a checkable button. * ``text``: the callback property is linked to a Qt widget that has ``text`` and ``setText`` methods. Optionally, if the Qt widget supports the ``editingFinished`` signal, this signal is connected to the callback property too. * ``combodata``: the callback property is linked to a QComboBox based on the ``userData`` of the entries in the combo box. * ``combotext``: the callback property is linked to a QComboBox based on the label of the entries in the combo box. Applications can also define additional mappings between type and auto-linking. To do this, simply add a new entry to the ``HANDLERS`` object:: >>> echo.qt.autoconnect import HANDLERS >>> HANDLERS['color'] = connect_color The handler function (``connect_color`` in the example above) should take the following arguments: the instance the callback property is attached to, the name of the callback property, the Qt widget, and optionally some keyword arguments. When calling ``autoconnect_callbacks_to_qt``, you can specify ``connect_kwargs``, where each key should be a valid callback property name, and which gives any additional keyword arguments that can be taken by the connect functions, as described above. These include for example ``value_range``, ``log``, and ``fmt``. This function is especially useful when defining ui files, since widget objectNames can be easily set during the editing process. """ if not hasattr(widget, 'children'): return for child in widget.findChildren(QtWidgets.QWidget): full_name = child.objectName() # FIXME: this is a temorary workaround to allow multiple widgets to be # connected to a state attribute. if full_name.endswith('_'): full_name = full_name[:-1] if '_' in full_name: wtype, wname = full_name.split('_', 1) if full_name in connect_kwargs: kwargs = connect_kwargs[full_name] elif wname in connect_kwargs: kwargs = connect_kwargs[wname] else: kwargs = {} if hasattr(instance, wname): if wtype in HANDLERS: HANDLERS[wtype](instance, wname, child, **kwargs)
{ "repo_name": "stscieisenhamer/glue", "path": "glue/external/echo/qt/autoconnect.py", "copies": "1", "size": "4899", "license": "bsd-3-clause", "hash": -5722079237413179000, "line_mean": 43.9449541284, "line_max": 81, "alpha_frac": 0.6617677077, "autogenerated": false, "ratio": 4.523545706371191, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5685313414071191, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from qtpy.QtCore import QModelIndex from qtpy.QtGui import QStandardItem, QStandardItemModel from qtpy.QtWidgets import QAction from addie.utilities import customtreeview as base from addie.calculate_gr import event_handler class GofRTree(base.CustomizedTreeView): """ Tree to record G(R) workspaces """ def __init__(self, parent): """ :param parent: :return: """ base.CustomizedTreeView.__init__(self, parent) self.parent = parent # define actions self._action_plot = QAction('Plot', self) self._action_plot.triggered.connect(self.do_plot) # to python self._action_ipython = QAction('To IPython', self) self._action_ipython.triggered.connect(self.do_copy_to_ipython) # remove from plot self._action_remove_plot = QAction('Remove from plot', self) self._action_remove_plot.triggered.connect(self.do_remove_from_plot) # delete workspace/data self._action_delete = QAction('Delete data', self) self._action_delete.triggered.connect(self.do_delete_selected_items) self._mainWindow = None self._workspaceNameList = None self.reset_gr_tree() # override def mousePressEvent(self, e): """ Over ride mouse press event Parameters ---------- e :: event """ button_pressed = e.button() if button_pressed == 2: # override the response for right button self.pop_up_menu() else: # keep base method for other buttons base.CustomizedTreeView.mousePressEvent(self, e) def pop_up_menu(self): """ Parameters ---------- """ selected_items = self.get_selected_items() if len(selected_items) == 0: return leaf_level = -1 for item in selected_items: if item.parent() is None and leaf_level == -1: leaf_level = 1 elif item.parent() is not None and leaf_level == -1: leaf_level = 2 elif item.parent() is None and leaf_level != 1: print('[Error] Nodes of different levels are selected.') elif item.parent() is None and leaf_level != 2: print('[Error] Nodes of different levels are selected.') if leaf_level == 1: self.addAction(self._action_plot) self.addAction(self._action_ipython) self.addAction(self._action_delete) elif leaf_level == 2: self.addAction(self._action_plot) self.addAction(self._action_ipython) self.addAction(self._action_remove_plot) self.addAction(self._action_delete) def add_gr(self, gr_parameter, gr_ws_name): """ Add a G(r) workspace with given Qmin and Qmax :param gr_parameter: the leaf name for the G(r) in the tree. :param gr_ws_name: :return: """ # Check assert isinstance(gr_parameter, str), 'G(r) parameters must be a string but not a %s.' \ '' % str(type(gr_parameter)) assert isinstance(gr_ws_name, str) # Create main leaf value if it does not exist main_leaf_value = str(gr_parameter) status, message = self.add_main_item(main_leaf_value, False, True) if status is False: print('[Log] %s' % message) # Add workspace name as a leaf child_value = gr_ws_name self.add_child_main_item(main_leaf_value, child_value) # register workspace self._workspaceNameList.append(gr_ws_name) def add_arb_gr(self, ws_name, is_gr=True): """ Add a G(r) workspace that is not belonged to any S(Q) and add it under 'workspaces' Parameters ---------- ws_name is_gr """ # check assert isinstance(ws_name, str) # add leaf if is_gr: self.add_child_main_item('workspaces', ws_name) else: self.add_child_main_item('SofQ', ws_name) # register workspace self._workspaceNameList.append(ws_name) def add_sq(self, sq_ws_name): """ Add an SofQ workspace Args: sq_ws_name: """ # check assert isinstance(sq_ws_name, str) # add self.add_child_main_item('SofQ', sq_ws_name) def reset_gr_tree(self): """ Clear the leaves of the tree only leaving the main node 'workspaces' """ # clear all if self.model() is not None: self.model().clear() # reset workspace data structures self._workspaceNameList = list() self._myHeaderList = list() self._leafDict.clear() # re-initialize the model self._myNumCols = 1 model = QStandardItemModel() model.setColumnCount(self._myNumCols) self.setModel(model) self.init_setup(['G(R) Workspaces']) self.add_main_item('workspaces', append=True, as_current_index=False) self.add_main_item('SofQ', append=False, as_current_index=False) def do_copy_to_ipython(self): """ Copy the selected item to an iPython command """ # Get current index and item current_index = self.currentIndex() if isinstance(current_index, QModelIndex) is False: return False, 'Current index is not QModelIndex instance, but %s.' % str(type(current_index)) assert (isinstance(current_index, QModelIndex)) current_item = self.model().itemFromIndex(current_index) if isinstance(current_item, QStandardItem) is False: return False, 'Current item is not QStandardItem instance, but %s.' % str(type(current_item)) assert (isinstance(current_item, QStandardItem)) # get the workspace name. if it is on main node, then use its child's value if current_item.parent() is None: # main node. access its child and use child's name only_child = current_item.child(0) ws_name = only_child.text() else: # workspace name node. ws_name = str(current_item.text()) python_cmd = "ws = mtd['%s']" % ws_name if self._mainWindow is not None: self._mainWindow.set_ipython_script(python_cmd) def is_gr_empty(self): """ Checks if there is a G(r) workspace and returns True if empty """ gr_exists = False for key in self._leafDict.keys(): if key.startswith('G(r)'): gr_exists = True return not gr_exists def is_sofq_empty(self): if self._leafDict['SofQ'] == []: return True return False def do_delete_selected_items(self): """ Delete the workspaces assigned to the selected items """ # get selected item selected_items = self.get_selected_items() if len(selected_items) == 0: return # check that all the items should be of the same level curr_level = -1 for item in selected_items: # get this level if item.parent() is None: temp_level = 0 else: temp_level = 1 if curr_level == -1: curr_level = temp_level elif curr_level != temp_level: raise RuntimeError( 'Nodes of different levels are selected. It is not supported for deletion.') # get item and delete if curr_level == 0: # delete node for item in selected_items: self._delete_main_node(item) else: # delete leaf for item in selected_items: self._delete_ws_node(item, None, check_gr_sq=True) self.check_widgets_status() def check_widgets_status(self): is_gr_empty = self.is_gr_empty() event_handler.gr_widgets_status(self.parent, not is_gr_empty) is_sofq_empty = self.is_sofq_empty() event_handler.sofq_widgets_status(self.parent, not is_sofq_empty) def _delete_main_node(self, node_item): """ Delete a main node Args: node_item: """ # Check assert node_item.parent() is None # check item item_name = str(node_item.text()) keep_main_node = False is_gr = True if item_name == 'workspaces': keep_main_node = True elif item_name == 'SofQ': keep_main_node = True is_gr = False # node workspaces and SofQ cannot be deleted sub_leaves = self.get_child_nodes(node_item, output_str=False) for leaf_node in sub_leaves: # delete a leaf self._delete_ws_node(leaf_node, is_gr, check_gr_sq=False) # delete this node if not keep_main_node: self.delete_node(node_item) def _delete_ws_node(self, ws_item, is_gr, check_gr_sq): """ Delete a level-2 item Args: ws_item: """ # check assert ws_item.parent() is not None if check_gr_sq: parent_node = ws_item.parent() if str(parent_node.text()) == 'SofQ': is_gr = False else: is_gr = True # get leaf node name leaf_node_name = str(ws_item.text()) # delete workspace self._mainWindow.get_workflow().delete_workspace(leaf_node_name) # remove from canvas try: if is_gr: event_handler.remove_gr_from_plot(self.parent, leaf_node_name) else: event_handler.remove_sq_from_plot(self.parent, leaf_node_name) except AssertionError as ass_err: print('Unable to remove %s from canvas due to %s.' % (leaf_node_name, str(ass_err))) # delete node self.delete_node(ws_item) def do_plot(self): """ Add selected runs :return: """ # get list of the items that are selected item_list = self.get_selected_items_of_level(target_item_level=2, excluded_parent=None, return_item_text=False) gr_list = list() sq_list = list() for item in item_list: leaf = str(item.text()) parent_i = item.parent() if str(parent_i.text()) == 'SofQ': sq_list.append(leaf) else: gr_list.append(leaf) # sort sq_list.sort() gr_list.sort() # FIXME/LATER - replace this by signal if self._mainWindow is None: raise NotImplementedError('Main window has not been set up!') if len(gr_list) > 0: for gr_name in gr_list: event_handler.plot_gr( self._mainWindow, gr_name, None, None, None, None, None, auto=True) for sq_name in sq_list: event_handler.plot_sq(self._mainWindow, sq_name, None, False) def do_remove_from_plot(self): """ Remove the selected item from plot if it is plotted """ # get selected items item_list = self.get_selected_items() # remove the selected items from plotting for tree_item in item_list: # get its name and its parent's name leaf_name = str(tree_item.text()) node_name = str(tree_item.parent().text()) # remove from canvas by calling parents if node_name == 'SofQ': event_handler.remove_sq_from_plot(self._mainWindow, leaf_name) else: event_handler.remove_gr_from_plot(self._mainWindow, leaf_name) def get_current_run(self): """ Get current run selected by mouse note: if multiple items are selected, (1) currentIndex() returns the first selected item (2) selectedIndexes() returns all the selected items :return: status, run number in integer """ # Get current index and item current_index = self.currentIndex() if isinstance(current_index, QModelIndex) is False: return False, 'Current index is not QModelIndex instance, but %s.' % str(type(current_index)) assert(isinstance(current_index, QModelIndex)) current_item = self.model().itemFromIndex(current_index) if isinstance(current_item, QStandardItem) is False: return False, 'Current item is not QStandardItem instance, but %s.' % str(type(current_item)) assert(isinstance(current_item, QStandardItem)) if current_item.parent() is None: # Top-level leaf, IPTS number return False, 'Top-level leaf for IPTS number' try: value_str = str(current_item.text()) run = int(value_str) except ValueError as value_error: return False, 'Unable to convert {0} to run number as integer due to {1}.' \ ''.format(current_item.text(), value_error) return True, run def get_workspaces(self): """ Get workspaces controlled by GSAS tree. Returns ------- """ return self._workspaceNameList def mouseDoubleClickEvent(self, e): """ Override event handling method """ status, current_run = self.get_current_run() print('[INFO] Status = {0}; Current run number = {1}'.format( status, current_run)) def set_main_window(self, main_window): """ :param main_window: :return: """ self._mainWindow = main_window
{ "repo_name": "neutrons/FastGR", "path": "addie/calculate_gr/gofrtree.py", "copies": "1", "size": "14023", "license": "mit", "hash": -8379975294481502000, "line_mean": 31.535962877, "line_max": 105, "alpha_frac": 0.5553733153, "autogenerated": false, "ratio": 4.074084834398605, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5129458149698605, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from qtpy.QtCore import Qt from addie.utilities.file_handler import FileHandler class ExportTable(object): current_path = '' column_label = [] data = [] output_text = [] def __init__(self, parent=None, filename=''): self.parent = parent self.filename = filename self.table_ui = self.parent.postprocessing_ui.table def run(self): self.collect_data() self.format_data() self.export_data() def collect_data(self): nbr_row = self.table_ui.rowCount() # collect current folder _path = self.parent.current_folder self.current_path = "current_folder: %s" % _path _full_column_label = [] nbr_column = self.table_ui.columnCount() for j in range(nbr_column): _column_label = str(self.table_ui.horizontalHeaderItem(j).text()) _full_column_label.append(_column_label) self.column_label = _full_column_label _data = [] for i in range(nbr_row): _row = [] # select flag _select_flag = self.retrieve_flag_state(row=i, column=0) _row.append(_select_flag) # name _name_item = self.get_item_value(i, 1) _row.append(_name_item) # runs _run_item = self.get_item_value(i, 2) _row.append(_run_item) # sample formula _sample_formula = self.get_item_value(i, 3) _row.append(_sample_formula) # mass density _mass_density = self.get_item_value(i, 4) _row.append(_mass_density) # radius _radius = self.get_item_value(i, 5) _row.append(_radius) # packing fraction _packing_fraction = self.get_item_value(i, 6) _row.append(_packing_fraction) # sample shape _sample_shape = self.retrieve_sample_shape(row=i, column=7) _row.append(_sample_shape) # do abs corr? _do_corr = self.retrieve_abs_corr_state(row=i, column=8) _row.append(_do_corr) _data.append(_row) self.data = _data def get_item_value(self, row, column): if self.table_ui.item(row, column) is None: return '' return str(self.table_ui.item(row, column).text()) def format_data(self): _current_path = self.current_path _column_label = self.column_label _data = self.data output_text = [] output_text.append("#" + _current_path) _title = "|".join(_column_label) output_text.append("#" + _title) for _row in _data: _formatted_row = "|".join(_row) output_text.append(_formatted_row) self.output_text = output_text def export_data(self): _filename = self.filename if _filename == '': return _output_text = self.output_text _o_file = FileHandler(filename=_filename) _o_file.create_ascii(contain=_output_text) def retrieve_abs_corr_state(self, row=0, column=8): if self.table_ui.cellWidget(row, 8) is None: return "False" _widget = self.table_ui.cellWidget(row, 8).children()[1] if (_widget.checkState() == Qt.Checked): return 'True' else: return 'False' def retrieve_sample_shape(self, row=0, column=7): _widget = self.table_ui.cellWidget(row, column) if _widget is None: return 'Cylinder' _selected_index = _widget.currentIndex() _sample_shape = str(_widget.itemText(_selected_index)) return _sample_shape def retrieve_flag_state(self, row=0, column=0): _widget = self.table_ui.cellWidget(row, column).children()[1] if _widget is None: return "False" if _widget.checkState() == Qt.Checked: return "True" else: return "False"
{ "repo_name": "neutrons/FastGR", "path": "addie/processing/idl/export_table.py", "copies": "1", "size": "4069", "license": "mit", "hash": 2705554287642263600, "line_mean": 28.9191176471, "line_max": 77, "alpha_frac": 0.5509953305, "autogenerated": false, "ratio": 3.7092069279854147, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9760202258485414, "avg_score": 0, "num_lines": 136 }
from __future__ import absolute_import, division, print_function from qtpy.QtCore import Qt from glue.core import DataCollection, Data from ..data_collection_model import DataCollectionModel from glue.core.qt.mime import LAYERS_MIME_TYPE class TestDataCollectionModel(object): def make_model(self, n_data=1, n_subsets=0): dc = DataCollection([Data(x=[1, 2, 3]) for _ in range(n_data)]) for _ in range(n_subsets): dc.new_subset_group() return DataCollectionModel(dc) def test_row_count_empty_index(self): model = self.make_model(1, 0) assert model.rowCount() == 2 def test_row_count_data_row(self): model = self.make_model(1, 0) assert model.rowCount(model.data_index()) == 1 model = self.make_model(2, 0) assert model.rowCount(model.data_index()) == 2 def test_row_count_subset_row(self): model = self.make_model(1, 0) assert model.rowCount(model.subsets_index()) == 0 model = self.make_model(1, 5) assert model.rowCount(model.subsets_index()) == 5 def test_row_count_single_subset1(self): model = self.make_model(2, 1) assert model.rowCount(model.subsets_index(0)) == 2 def test_row_count_single_subset2(self): model = self.make_model(2, 1) s = model.subsets_index(0) idx = model.index(0, 0, s) assert model.rowCount(idx) == 0 idx = model.index(1, 0, s) assert model.rowCount(s) == 2 def test_invalid_indices(self): model = self.make_model(1, 2) index = model.index(0, 1) assert not index.isValid() index = model.index(2, 0) assert not index.isValid() index = model.index(2, 0, model.index(0, 0)) assert not index.isValid() def test_heading_labels(self): model = self.make_model() assert model.data(model.data_index(), Qt.DisplayRole) == 'Data' assert model.data(model.subsets_index(), Qt.DisplayRole) == 'Subsets' def test_dc_labels(self): model = self.make_model(1, 2) dc = model.data_collection dc[0].label = 'test1' dc[0].subsets[0].label = 'subset1' dc[0].subsets[1].label = 'subset2' assert model.data(model.data_index(0), Qt.DisplayRole) == 'test1' assert model.data(model.subsets_index(0), Qt.DisplayRole) == 'subset1' assert model.data(model.subsets_index(1), Qt.DisplayRole) == 'subset2' assert model.data(model.index(0, 0, model.subsets_index(0)), Qt.DisplayRole) == 'subset1 (test1)' def test_column_count(self): model = self.make_model(1, 2) assert model.columnCount(model.data_index()) == 1 assert model.columnCount(model.data_index(0)) == 1 assert model.columnCount(model.subsets_index()) == 1 assert model.columnCount(model.subsets_index(0)) == 1 assert model.columnCount(model.subsets_index(1)) == 1 def test_header_data(self): model = self.make_model() assert model.headerData(0, Qt.Vertical) == '' assert model.headerData(0, Qt.Horizontal) == '' def test_font_role(self): model = self.make_model(1, 2) assert model.data(model.data_index(), Qt.FontRole).bold() assert model.data(model.subsets_index(), Qt.FontRole).bold() def test_drag_flags(self): model = self.make_model(1, 2) sg = model.subsets_index(0) subset = model.index(0, 0, sg) assert model.flags(model.data_index(0)) & Qt.ItemIsDragEnabled assert model.flags(subset) & Qt.ItemIsDragEnabled assert not model.flags(model.data_index()) & Qt.ItemIsDragEnabled assert not model.flags(model.subsets_index()) & Qt.ItemIsDragEnabled assert not model.flags(sg) & Qt.ItemIsDragEnabled def test_selectable_flags(self): model = self.make_model(1, 2) assert not model.flags(model.data_index()) & Qt.ItemIsSelectable assert not model.flags(model.subsets_index()) & Qt.ItemIsSelectable def test_layers_mime_type_data(self): model = self.make_model(1, 2) index = model.data_index(0) expected = [model.data_collection[0]] assert model.mimeData([index]).data(LAYERS_MIME_TYPE) == expected def test_layers_mime_type_multiselection(self): model = self.make_model(1, 2) idxs = [model.data_index(0), model.subsets_index(0), model.index(0, 0, model.subsets_index(0))] dc = model.data_collection expected = [dc[0], dc.subset_groups[0], dc.subset_groups[0].subsets[0]] assert model.mimeData(idxs).data(LAYERS_MIME_TYPE) == expected
{ "repo_name": "stscieisenhamer/glue", "path": "glue/core/qt/tests/test_data_collection_model.py", "copies": "3", "size": "4733", "license": "bsd-3-clause", "hash": 5835201909081928000, "line_mean": 34.3208955224, "line_max": 79, "alpha_frac": 0.6188463976, "autogenerated": false, "ratio": 3.4001436781609193, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 134 }
from __future__ import absolute_import, division, print_function from qtpy.QtCore import Qt from qtpy import QtCore, QtGui, QtWidgets from glue import core from glue.core.qt.mime import LAYER_MIME_TYPE, LAYERS_MIME_TYPE class GlueMdiArea(QtWidgets.QMdiArea): """Glue's MdiArea implementation. Drop events with :class:`~glue.core.data.Data` objects in :class:`~glue.utils.qt.PyMimeData` load these objects into new data viewers """ def __init__(self, application, parent=None): """ :param application: The Glue application to which this is attached :type application: :class:`~glue.app.qt.application.GlueApplication` """ super(GlueMdiArea, self).__init__(parent) self._application = application self.setAcceptDrops(True) self.setAttribute(Qt.WA_DeleteOnClose) self.setBackground(QtGui.QBrush(QtGui.QColor(250, 250, 250))) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) def addSubWindow(self, sub): super(GlueMdiArea, self).addSubWindow(sub) self.repaint() def dragEnterEvent(self, event): """ Accept the event if it has an application/py_instance format """ if event.mimeData().hasFormat(LAYERS_MIME_TYPE): event.accept() elif event.mimeData().hasFormat(LAYER_MIME_TYPE): event.accept() else: event.ignore() def dropEvent(self, event): """ Load a new data viewer if the event has a glue Data object """ md = event.mimeData() def new_layer(layer): if isinstance(layer, core.data.Data): self._application.choose_new_data_viewer(layer) else: assert isinstance(layer, core.subset.Subset) self._application.choose_new_data_viewer(layer.data) if md.hasFormat(LAYER_MIME_TYPE): new_layer(md.data(LAYER_MIME_TYPE)) assert md.hasFormat(LAYERS_MIME_TYPE) for layer in md.data(LAYERS_MIME_TYPE): new_layer(layer) event.accept() def close(self): self.closeAllSubWindows() super(GlueMdiArea, self).close() def paintEvent(self, event): super(GlueMdiArea, self).paintEvent(event) painter = QtGui.QPainter(self.viewport()) painter.setPen(QtGui.QColor(210, 210, 210)) font = painter.font() font.setPointSize(font.pointSize() * 4) font.setWeight(font.Black) painter.setFont(font) rect = self.contentsRect() painter.drawText(rect, Qt.AlignHCenter | Qt.AlignVCenter, "Drag Data To Plot") class GlueMdiSubWindow(QtWidgets.QMdiSubWindow): closed = QtCore.Signal() def closeEvent(self, event): super(GlueMdiSubWindow, self).closeEvent(event) self.closed.emit()
{ "repo_name": "stscieisenhamer/glue", "path": "glue/app/qt/mdi_area.py", "copies": "2", "size": "2926", "license": "bsd-3-clause", "hash": 5819651335262780000, "line_mean": 32.25, "line_max": 76, "alpha_frac": 0.6390977444, "autogenerated": false, "ratio": 3.7609254498714653, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 88 }
from __future__ import absolute_import, division, print_function from qtpy.QtCore import Qt from qtpy import QtCore, QtWidgets from glue.icons.qt import POINT_ICONS, symbol_icon from glue.utils.qt import mpl_to_qt4_color, qt4_to_mpl_color class ColorWidget(QtWidgets.QLabel): mousePressed = QtCore.Signal() def mousePressEvent(self, event): self.mousePressed.emit() event.accept() class StyleDialog(QtWidgets.QDialog): """Dialog which edits the style of a layer (Data or Subset) Use via StyleDialog.edit_style(layer) """ def __init__(self, layer, parent=None, edit_label=True): super(StyleDialog, self).__init__(parent) self.setWindowTitle("Style Editor") self.layer = layer self._edit_label = edit_label self._symbols = list(POINT_ICONS.keys()) self._setup_widgets() self._connect() def _setup_widgets(self): self.layout = QtWidgets.QFormLayout() self.size_widget = QtWidgets.QSpinBox() self.size_widget.setMinimum(1) self.size_widget.setMaximum(40) self.size_widget.setValue(self.layer.style.markersize) self.label_widget = QtWidgets.QLineEdit() self.label_widget.setText(self.layer.label) self.label_widget.selectAll() self.symbol_widget = QtWidgets.QComboBox() for idx, symbol in enumerate(self._symbols): icon = symbol_icon(symbol) self.symbol_widget.addItem(icon, '') if symbol is self.layer.style.marker: self.symbol_widget.setCurrentIndex(idx) self.symbol_widget.setIconSize(QtCore.QSize(20, 20)) self.symbol_widget.setMinimumSize(10, 32) self.color_widget = ColorWidget() self.color_widget.setStyleSheet('ColorWidget {border: 1px solid;}') color = self.layer.style.color color = mpl_to_qt4_color(color, alpha=self.layer.style.alpha) self.set_color(color) self.okcancel = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel) if self._edit_label: self.layout.addRow("Label", self.label_widget) self.layout.addRow("Symbol", self.symbol_widget) self.layout.addRow("Color", self.color_widget) self.layout.addRow("Size", self.size_widget) self.layout.addWidget(self.okcancel) self.setLayout(self.layout) self.layout.setContentsMargins(6, 6, 6, 6) def _connect(self): self.color_widget.mousePressed.connect(self.query_color) self.symbol_widget.currentIndexChanged.connect( lambda x: self.set_color(self.color())) self.okcancel.accepted.connect(self.accept) self.okcancel.rejected.connect(self.reject) self.setFocusPolicy(Qt.StrongFocus) def query_color(self, *args): color = QtWidgets.QColorDialog.getColor(self._color, self.color_widget, "", QtWidgets.QColorDialog.ShowAlphaChannel) if color.isValid(): self.set_color(color) def color(self): return self._color def set_color(self, color): self._color = color pm = symbol_icon(self.symbol(), color).pixmap(30, 30) self.color_widget.setPixmap(pm) def size(self): return self.size_widget.value() def label(self): return str(self.label_widget.text()) def symbol(self): return self._symbols[self.symbol_widget.currentIndex()] def update_style(self): if self._edit_label: self.layer.label = self.label() self.layer.style.color = qt4_to_mpl_color(self.color()) self.layer.style.alpha = self.color().alpha() / 255. self.layer.style.marker = self.symbol() self.layer.style.markersize = self.size() @classmethod def edit_style(cls, layer): self = cls(layer) result = self.exec_() if result == self.Accepted: self.update_style() @classmethod def dropdown_editor(cls, item, pos, **kwargs): """ Create a dropdown-style modal editor to edit the style of a given item :param item: Item with a .label and .style to edit :param pos: A QPoint to anchor the top-left corner of the dropdown at :param kwargs: Extra keywords to pass to StyleDialogs's constructor """ self = cls(item, **kwargs) self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint) pos = self.mapFromGlobal(pos) self.move(pos) if self.exec_() == self.Accepted: self.update_style() if __name__ == "__main__": from glue.core import Data d = Data(label='data label', x=[1, 2, 3, 4]) StyleDialog.edit_style(d) print("New layer properties") print(d.label) print('color: ', d.style.color) print('marker: ', d.style.marker) print('marker size: ', d.style.markersize) print('alpha ', d.style.alpha)
{ "repo_name": "saimn/glue", "path": "glue/core/qt/style_dialog.py", "copies": "4", "size": "5082", "license": "bsd-3-clause", "hash": 8531071601465652000, "line_mean": 32, "line_max": 84, "alpha_frac": 0.6196379378, "autogenerated": false, "ratio": 3.8210526315789473, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6440690569378946, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from qtpy.QtCore import Qt from qtpy import QtWidgets from glue.utils.qt import QMessageBoxPatched as QMessageBox, set_cursor_cm __all__ = ['data_wizard', 'GlueDataDialog'] def data_wizard(): """ QT Dialog to load a file into a new data object Returns: A list of new data objects. Returns an empty list if selection is canceled. """ def report_error(error, factory, curfile): import traceback retry = QMessageBox.Retry cancel = QMessageBox.Cancel buttons = retry | cancel detail = traceback.format_exc() msg = "\n".join(["Could not load %s (wrong load method?)" % curfile, "File load method: %s" % factory.label]) detail = "\n\n".join(["Error message: %s" % error, detail]) mb = QMessageBox(QMessageBox.Critical, "Data Load Error", msg) mb.setDetailedText(detail) mb.setDefaultButton(cancel) mb.setStandardButtons(buttons) ok = mb.exec_() return ok == retry while True: gdd = GlueDataDialog() try: result = gdd.load_data() break except Exception as e: decision = report_error(e, gdd.factory(), gdd._curfile) if not decision: return [] return result class GlueDataDialog(object): def __init__(self, parent=None): self._fd = QtWidgets.QFileDialog(parent) from glue.config import data_factory self.filters = [(f, self._filter(f)) for f in data_factory.members if not f.deprecated] self.setNameFilter() self._fd.setFileMode(QtWidgets.QFileDialog.ExistingFiles) self._curfile = '' try: self._fd.setOption( QtWidgets.QFileDialog.Option.HideNameFilterDetails, True) except AttributeError: # HideNameFilterDetails not present pass def factory(self): fltr = self._fd.selectedNameFilter() for k, v in self.filters: if v.startswith(fltr): return k def setNameFilter(self): fltr = ";;".join([flt for fac, flt in self.filters]) self._fd.setNameFilter(fltr) def _filter(self, factory): return "%s (*)" % factory.label def paths(self): """ Return all selected paths, as a list of unicode strings """ return self._fd.selectedFiles() def _get_paths_and_factory(self): """Show dialog to get a file path and data factory :rtype: tuple of (list-of-strings, func) giving the path and data factory. returns ([], None) if user cancels dialog """ result = self._fd.exec_() if result == QtWidgets.QDialog.Rejected: return [], None # path = list(map(str, self.paths())) # cast out of unicode path = list(self.paths()) factory = self.factory() return path, factory def load_data(self): """Highest level method to interactively load a data set. :rtype: A list of constructed data objects """ from glue.core.data_factories import data_label, load_data paths, fac = self._get_paths_and_factory() result = [] with set_cursor_cm(Qt.WaitCursor): for path in paths: self._curfile = path d = load_data(path, factory=fac.function) if not isinstance(d, list): d.label = data_label(path) d = [d] result.extend(d) return result
{ "repo_name": "saimn/glue", "path": "glue/dialogs/data_wizard/qt/data_wizard_dialog.py", "copies": "1", "size": "3682", "license": "bsd-3-clause", "hash": -8140276162241364000, "line_mean": 31.5840707965, "line_max": 76, "alpha_frac": 0.5730581206, "autogenerated": false, "ratio": 4.174603174603175, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5247661295203174, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from qtpy.QtCore import Qt from qtpy import QtWidgets, QtGui from glue.utils.qt import mpl_to_qt4_color, tint_pixmap from glue.icons import icon_path __all__ = ['symbol_icon', 'layer_icon', 'layer_artist_icon', 'get_icon', 'POINT_ICONS'] POINT_ICONS = {'o': 'glue_circle_point', 's': 'glue_box_point', '^': 'glue_triangle_up', '*': 'glue_star', '+': 'glue_cross'} def symbol_icon(symbol, color=None): bm = QtGui.QBitmap(icon_path(POINT_ICONS.get(symbol, 'glue_circle'))) if color is not None: return QtGui.QIcon(tint_pixmap(bm, color)) return QtGui.QIcon(bm) def layer_icon(layer): """Create a QtGui.QIcon for a Data or Subset instance :type layer: :class:`~glue.core.data.Data`, :class:`~glue.core.subset.Subset`, or object with a .style attribute :rtype: QtGui.QIcon """ icon = POINT_ICONS.get(layer.style.marker, 'circle_point') bm = QtGui.QBitmap(icon_path(icon)) color = mpl_to_qt4_color(layer.style.color) pm = tint_pixmap(bm, color) return QtGui.QIcon(pm) def layer_artist_icon(artist): """Create a QtGui.QIcon for a LayerArtist instance""" # TODO: need a test for this from glue.viewers.image.layer_artist import ImageLayerArtist if not artist.enabled: bm = QtGui.QBitmap(icon_path('glue_delete')) elif isinstance(artist, ImageLayerArtist): bm = QtGui.QBitmap(icon_path('glue_image')) else: bm = QtGui.QBitmap(icon_path(POINT_ICONS.get(artist.layer.style.marker, 'glue_circle_point'))) color = mpl_to_qt4_color(artist.layer.style.color) pm = tint_pixmap(bm, color) return QtGui.QIcon(pm) def get_icon(icon_name): """ Build a QtGui.QIcon from an image name Parameters ---------- icon_name : str Name of image file. Assumed to be a png file in glue/qt/icons Do not include the extension Returns ------- A QtGui.QIcon object """ return QtGui.QIcon(icon_path(icon_name))
{ "repo_name": "saimn/glue", "path": "glue/icons/qt/helpers.py", "copies": "2", "size": "2176", "license": "bsd-3-clause", "hash": -2450452469192890000, "line_mean": 27.2727272727, "line_max": 87, "alpha_frac": 0.6158088235, "autogenerated": false, "ratio": 3.405320813771518, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0004427390791027154, "num_lines": 77 }
from __future__ import absolute_import, division, print_function from qtpy.QtCore import Qt from qtpy import QtWidgets, QtGui from matplotlib.colors import Colormap from glue.utils.qt import mpl_to_qt4_color, tint_pixmap, cmap2pixmap from glue.icons import icon_path __all__ = ['symbol_icon', 'layer_icon', 'layer_artist_icon', 'get_icon', 'POINT_ICONS'] POINT_ICONS = {'o': 'glue_circle_point', 's': 'glue_box_point', '^': 'glue_triangle_up', '*': 'glue_star', '+': 'glue_cross'} def symbol_icon(symbol, color=None): bm = QtGui.QBitmap(icon_path(POINT_ICONS.get(symbol, 'glue_circle'))) if color is not None: return QtGui.QIcon(tint_pixmap(bm, color)) return QtGui.QIcon(bm) def layer_icon(layer): """Create a QtGui.QIcon for a Data or Subset instance :type layer: :class:`~glue.core.data.Data`, :class:`~glue.core.subset.Subset`, or object with a .style attribute :rtype: QtGui.QIcon """ icon = POINT_ICONS.get(layer.style.marker, 'circle_point') bm = QtGui.QBitmap(icon_path(icon)) color = mpl_to_qt4_color(layer.style.color) pm = tint_pixmap(bm, color) return QtGui.QIcon(pm) def layer_artist_icon(artist): """Create a QtGui.QIcon for a LayerArtist instance""" # TODO: need a test for this from glue.viewers.scatter.layer_artist import ScatterLayerArtist color = artist.get_layer_color() if isinstance(color, Colormap): pm = cmap2pixmap(color) else: if isinstance(artist, ScatterLayerArtist): bm = QtGui.QBitmap(icon_path(POINT_ICONS.get(artist.layer.style.marker, 'glue_circle_point'))) else: bm = QtGui.QBitmap(icon_path('glue_box_point')) color = mpl_to_qt4_color(color) pm = tint_pixmap(bm, color) return QtGui.QIcon(pm) def get_icon(icon_name): """ Build a QtGui.QIcon from an image name Parameters ---------- icon_name : str Name of image file. Assumed to be a png file in glue/qt/icons Do not include the extension Returns ------- A QtGui.QIcon object """ return QtGui.QIcon(icon_path(icon_name))
{ "repo_name": "stscieisenhamer/glue", "path": "glue/icons/qt/helpers.py", "copies": "2", "size": "2283", "license": "bsd-3-clause", "hash": 1903684439768301000, "line_mean": 26.8414634146, "line_max": 87, "alpha_frac": 0.6119141481, "autogenerated": false, "ratio": 3.453857791225416, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0002837609544926618, "num_lines": 82 }
from __future__ import absolute_import, division, print_function from qtpy.QtCore import Qt from glue.core import message as msg from glue.core import Data, Subset from glue.core.exceptions import IncompatibleDataException from glue.core.state import lookup_class_with_patches from glue.external import six from glue.external.echo import delay_callback from glue.utils import DeferDrawMeta, defer_draw from glue.utils.noconflict import classmaker from glue.viewers.common.qt.data_viewer import DataViewer __all__ = ['DataViewerWithState'] @six.add_metaclass(classmaker(left_metas=(DeferDrawMeta,))) class DataViewerWithState(DataViewer): allow_duplicate_data = False allow_duplicate_subset = False def __init__(self, session, parent=None, wcs=None, state=None): super(DataViewerWithState, self).__init__(session, parent) # Set up the state which will contain everything needed to represent # the current state of the viewer self.state = state or self._state_cls() self.state.data_collection = session.data_collection # Set up the options widget, which will include options that control the # viewer state self.options = self._options_cls(viewer_state=self.state, session=session) # When layer artists are removed from the layer artist container, we need # to make sure we remove matching layer states in the viewer state # layers attribute. self._layer_artist_container.on_changed(self._sync_state_layers) # And vice-versa when layer states are removed from the viewer state, we # need to keep the layer_artist_container in sync self.state.add_callback('layers', self._sync_layer_artist_container) self.statusBar().setSizeGripEnabled(False) self.setFocusPolicy(Qt.StrongFocus) def redraw(self): pass def _sync_state_layers(self, *args): # Remove layer state objects that no longer have a matching layer for layer_state in self.state.layers: if layer_state.layer not in self._layer_artist_container: self.state.layers.remove(layer_state) def _sync_layer_artist_container(self, *args): # Remove layer artists that no longer have a matching layer state layer_states = set(layer_state.layer for layer_state in self.state.layers) for layer_artist in self._layer_artist_container: if layer_artist.layer not in layer_states: self._layer_artist_container.remove(layer_artist) def add_data(self, data): # Check if data already exists in viewer if not self.allow_duplicate_data and data in self._layer_artist_container: return True if data not in self.session.data_collection: raise IncompatibleDataException("Data not in DataCollection") # Create layer artist and add to container layer = self.get_data_layer_artist(data) if layer is None: return False self._layer_artist_container.append(layer) layer.update() # Add existing subsets to viewer for subset in data.subsets: self.add_subset(subset) self.redraw() return True def remove_data(self, data): with delay_callback(self.state, 'layers'): for layer_state in self.state.layers[::-1]: if isinstance(layer_state.layer, Data): if layer_state.layer is data: self.state.layers.remove(layer_state) else: if layer_state.layer.data is data: self.state.layers.remove(layer_state) self.redraw() def get_data_layer_artist(self, layer=None, layer_state=None): return self.get_layer_artist(self._data_artist_cls, layer=layer, layer_state=layer_state) def get_subset_layer_artist(self, layer=None, layer_state=None): return self.get_layer_artist(self._subset_artist_cls, layer=layer, layer_state=layer_state) def get_layer_artist(self, cls, layer=None, layer_state=None): return cls(layer=layer, layer_state=layer_state) def add_subset(self, subset): # Check if subset already exists in viewer if not self.allow_duplicate_subset and subset in self._layer_artist_container: return True # Make sure we add the data first if it doesn't already exist in viewer. # This will then auto add the subsets so can just return. if subset.data not in self._layer_artist_container: self.add_data(subset.data) return # Create scatter layer artist and add to container layer = self.get_subset_layer_artist(subset) self._layer_artist_container.append(layer) layer.update() self.redraw() return True def remove_subset(self, subset): if subset in self._layer_artist_container: self._layer_artist_container.pop(subset) self.redraw() def _add_subset(self, message): self.add_subset(message.subset) def _update_data(self, message): if message.data in self._layer_artist_container: for layer_artist in self._layer_artist_container: if isinstance(layer_artist.layer, Subset): if layer_artist.layer.data is message.data: layer_artist.update() else: if layer_artist.layer is message.data: layer_artist.update() self.redraw() def _update_subset(self, message): if message.subset in self._layer_artist_container: for layer_artist in self._layer_artist_container[message.subset]: layer_artist.update() self.redraw() def _remove_subset(self, message): self.remove_subset(message.subset) def options_widget(self): return self.options def _subset_has_data(self, x): return x.sender.data in self._layer_artist_container.layers def _has_data_or_subset(self, x): return x.sender in self._layer_artist_container.layers def _remove_data(self, message): self.remove_data(message.data) def _is_appearance_settings(self, msg): return ('BACKGROUND_COLOR' in msg.settings or 'FOREGROUND_COLOR' in msg.settings) def register_to_hub(self, hub): super(DataViewerWithState, self).register_to_hub(hub) hub.subscribe(self, msg.SubsetCreateMessage, handler=self._add_subset, filter=self._subset_has_data) hub.subscribe(self, msg.SubsetUpdateMessage, handler=self._update_subset, filter=self._has_data_or_subset) hub.subscribe(self, msg.SubsetDeleteMessage, handler=self._remove_subset, filter=self._has_data_or_subset) hub.subscribe(self, msg.NumericalDataChangedMessage, handler=self._update_data, filter=self._has_data_or_subset) hub.subscribe(self, msg.DataCollectionDeleteMessage, handler=self._remove_data) hub.subscribe(self, msg.ComponentsChangedMessage, handler=self._update_data, filter=self._has_data_or_subset) hub.subscribe(self, msg.SettingsChangeMessage, self._update_appearance_from_settings, filter=self._is_appearance_settings) def _update_appearance_from_settings(self, message=None): pass def unregister(self, hub): super(DataViewerWithState, self).unregister(hub) hub.unsubscribe_all(self) def __gluestate__(self, context): return dict(state=self.state.__gluestate__(context), session=context.id(self._session), size=self.viewer_size, pos=self.position, layers=list(map(context.do, self.layers)), _protocol=1) def update_viewer_state(rec, context): pass @classmethod @defer_draw def __setgluestate__(cls, rec, context): if rec.get('_protocol', 0) < 1: cls.update_viewer_state(rec, context) session = context.object(rec['session']) viewer_state = cls._state_cls.__setgluestate__(rec['state'], context) viewer = cls(session, state=viewer_state) viewer.register_to_hub(session.hub) viewer.viewer_size = rec['size'] x, y = rec['pos'] viewer.move(x=x, y=y) # Restore layer artists. Ideally we would delay instead of ignoring the # callback here. with viewer._layer_artist_container.ignore_empty(): for l in rec['layers']: cls = lookup_class_with_patches(l.pop('_type')) layer_state = context.object(l['state']) layer_artist = viewer.get_layer_artist(cls, layer_state=layer_state) layer_state.viewer_state = viewer.state viewer._layer_artist_container.append(layer_artist) return viewer
{ "repo_name": "stscieisenhamer/glue", "path": "glue/viewers/common/qt/data_viewer_with_state.py", "copies": "1", "size": "9283", "license": "bsd-3-clause", "hash": 8976875362021127000, "line_mean": 35.6916996047, "line_max": 99, "alpha_frac": 0.6222126468, "autogenerated": false, "ratio": 4.14049955396967, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005714204059160958, "num_lines": 253 }
from __future__ import (absolute_import, division, print_function) from qtpy.QtCore import (Signal) from qtpy.QtGui import (QCursor) from qtpy.QtWidgets import (QAction, QMenu) from addie.plot import MplGraphicsView class SofQView(MplGraphicsView): """ Graphics view for S(Q) """ # boundary moving signal (1) int for left/right boundary indicator (2) boundaryMoveSignal = Signal(int, float) # resolution of boundary indicator to be selected IndicatorResolution = 0.01 def __init__(self, parent): """ Initialization :param parent:t """ self._myParent = parent MplGraphicsView.__init__(self, parent) # declare event handling to indicators self._myCanvas.mpl_connect('button_press_event', self.on_mouse_press_event) self._myCanvas.mpl_connect('button_release_event', self.on_mouse_release_event) self._myCanvas.mpl_connect('motion_notify_event', self.on_mouse_motion) self._mainApp = None # dictionary to record all the plots, key: (usually) SofQ's name, value: plot ID self._sqLineDict = dict() # S(Q) plot's information including color, marker and etc. self._sqPlotInfoDict = dict() # list of SofQ that are plot on the canvas self._shownSQNameList = list() # link signal # self.boundaryMoveSignal.connect(self._myParent.update_sq_boundary) # declare class variables for moving boundary self._showBoundary = False self._leftID = None self._rightID = None self._selectedBoundary = 0 self._prevCursorPos = None return def get_plot_info(self, sofq_name): """ get the information of a plot including color, marker and etc. :param sofq_name: :return: """ # check assert isinstance(sofq_name, str), 'SofQ {0} must be a string but not a {1}'.format(sofq_name, type(sofq_name)) if sofq_name not in self._sqPlotInfoDict: raise RuntimeError('SofQ-view does not have S(Q) plot {0}'.format(sofq_name)) # return return self._sqPlotInfoDict[sofq_name] def get_shown_sq_names(self): """ get the names of S(q) workspaces that are shown on the canvas Returns ------- """ return self._shownSQNameList[:] def is_boundary_shown(self): """ Returns ------- """ return self._showBoundary def is_on_canvas(self, sq_name): """ check whether an S(Q) is on canvas now Args: sq_name: Returns: boolean. True if on canvas; Otherwise False """ # check input assert isinstance(sq_name, str), 'SofQ name %s must be a string but not of type %s.' \ '' % (str(sq_name), str(type(sq_name))) # return return sq_name in self._sqLineDict def move_left_indicator(self, displacement, relative): """ Args: displacement: relative: Returns: """ # check assert isinstance(displacement, float) assert isinstance(relative, bool) if relative: self.move_indicator(self._leftID, displacement) else: self.set_indicator_position(self._leftID, displacement, 0) return def move_right_indicator(self, displacement, relative): """ Args: displacement: relative: Returns: """ # check assert isinstance(displacement, float) assert isinstance(relative, bool) if relative: self.move_indicator(self._rightID, displacement) else: self.set_indicator_position(self._rightID, displacement, 0) return def on_mouse_motion(self, event): """ Returns ------- """ # ignore if boundary is not shown if not self._showBoundary: return # ignore if no boundary is selected if self._selectedBoundary == 0: return elif self._selectedBoundary > 2: raise RuntimeError('Impossible to have selected boundary mode %d' % self._selectedBoundary) cursor_pos = event.xdata # ignore if the cursor is out of canvas if cursor_pos is None: return cursor_displace = cursor_pos - self._prevCursorPos left_bound_pos = self.get_indicator_position(self._leftID)[0] right_bound_pos = self.get_indicator_position(self._rightID)[0] x_range = self.getXLimit() resolution = (x_range[1] - x_range[0]) * self.IndicatorResolution if self._selectedBoundary == 1: # left boundary new_left_bound = left_bound_pos + cursor_displace # return if the left boundary is too close to right if new_left_bound > right_bound_pos - resolution * 5: return # move left boundary self.move_indicator(self._leftID, cursor_displace, 0) # signal main self.boundaryMoveSignal.emit(1, new_left_bound) else: # right boundary new_right_bound = right_bound_pos + cursor_displace # return if the right boundary is too close or left to the left boundary if new_right_bound < left_bound_pos + resolution * 5: return # move right boundary self.move_indicator(self._rightID, cursor_displace, 0) # emit signal to the main app self.boundaryMoveSignal.emit(2, new_right_bound) # update cursor position self._prevCursorPos = cursor_pos return def on_mouse_press_event(self, event): """ Handle mouse pressing event (1) left mouse: in show-boundary mode, check the action to select a boundary indicator (2) right mouse: pop up the menu Returns ------- """ # get the button button = event.button if button == 3: # right button: # Pop-out menu self.menu = QMenu(self) if self.get_canvas().is_legend_on: # figure has legend: remove legend action1 = QAction('Hide legend', self) action1.triggered.connect(self._myCanvas.hide_legend) action2 = QAction('Legend font larger', self) action2.triggered.connect(self._myCanvas.increase_legend_font_size) action3 = QAction('Legend font smaller', self) action3.triggered.connect(self._myCanvas.decrease_legend_font_size) self.menu.addAction(action2) self.menu.addAction(action3) else: # figure does not have legend: add legend action1 = QAction('Show legend', self) action1.triggered.connect(self._myCanvas.show_legend) self.menu.addAction(action1) # pop up menu self.menu.popup(QCursor.pos()) return # END-IF # ignore if boundary is not shown and the pressed mouse button is left or middle if not self._showBoundary: return # get mouse cursor x position mouse_x_pos = event.xdata if mouse_x_pos is None: return else: self._prevCursorPos = mouse_x_pos # get absolute resolution x_range = self.getXLimit() resolution = (x_range[1] - x_range[0]) * self.IndicatorResolution # see whether it is close enough to any boundary left_bound_pos = self.get_indicator_position(self._leftID)[0] right_bound_pos = self.get_indicator_position(self._rightID)[0] if abs(mouse_x_pos - left_bound_pos) < resolution: self._selectedBoundary = 1 elif abs(mouse_x_pos - right_bound_pos) < resolution: self._selectedBoundary = 2 else: self._selectedBoundary = 0 # END-IF-ELSE return def on_mouse_release_event(self, event): """ handling the event that mouse is released The operations include setting some flags' values :param event: :return: """ # ignore if boundary is not shown if not self._showBoundary: return # get mouse cursor position self._prevCursorPos = event.xdata self._prevCursorPos = None self._selectedBoundary = 0 return def plot_sq(self, ws_name, sq_y_label=None, reset_color_mark=None, color=None, marker=None, plotError=False): """Plot S(Q) :param sq_name: :param sq_y_label: label for Y-axis :param reset_color_mark: boolean to reset color marker :param color: :param color_marker: :return: """ # check whether it is a new plot or an update if ws_name in self._sqLineDict: # exiting S(q) workspace, do update sq_key = self._sqLineDict[ws_name] self.updateLine(ikey=sq_key, wkspname=ws_name, wkspindex=0) else: # new S(Q) plot on the canvas assert isinstance(sq_y_label, str), 'S(Q) label {0} must be a string but not a {1}.' \ ''.format(sq_y_label, type(sq_y_label)) # define color if color is None: if reset_color_mark: self.reset_line_color_marker_index() marker, color = self.getNextLineMarkerColorCombo() else: marker = None # plot plot_id = self.add_plot_1d(ws_name, wkspindex=0, color=color, x_label='Q', y_label=sq_y_label, marker=marker, label=ws_name, plotError=plotError) self._sqLineDict[ws_name] = plot_id self._sqPlotInfoDict[ws_name] = color, marker if ws_name not in self._shownSQNameList: self._shownSQNameList.append(ws_name) # auto scale self.auto_scale_y(room_percent=0.05, lower_boundary=0.) return def set_main(self, main_app): """ Returns ------- """ self._mainApp = main_app # link signal self.boundaryMoveSignal.connect(self._mainApp.update_sq_boundary) return def remove_sq(self, sq_ws_name): """ Remove 1 S(q) line from canvas Args: sq_ws_name: workspace name as plot key Returns: """ # check whether S(Q) does exist assert isinstance(sq_ws_name, str), 'S(Q) workspace name {0} must be a string but not a {1}.' \ ''.format(sq_ws_name, type(sq_ws_name)) if sq_ws_name not in self._sqLineDict: raise RuntimeError('key (SofQ name) {0} does not exist on the S(Q) canvas.'.format(sq_ws_name)) # retrieve the plot and remove it from the dictionary plot_id = self._sqLineDict[sq_ws_name] sq_color, sq_marker = self._sqPlotInfoDict[sq_ws_name] del self._sqLineDict[sq_ws_name] del self._sqPlotInfoDict[sq_ws_name] # delete from canvas self.remove_line(plot_id) # delete from on-show S(q) list self._shownSQNameList.remove(sq_ws_name) return sq_color, sq_marker def reset(self): """ Reset the canvas including removing all the 1-D plots and boundary indicators Returns: """ # clear the dictionary and on-show Sq list self._sqLineDict.clear() self._sqPlotInfoDict.clear() self._shownSQNameList = list() # clear the image and reset the marker/color scheme self.clear_all_lines() self.reset_line_color_marker_index() # clear the boundary flag self._showBoundary = False return def toggle_boundary(self, q_left, q_right): """ Turn on or off the left and right boundary to select Q-range Parameters ---------- q_left :: q_right :: Returns ------- """ # check assert isinstance(q_left, float) and isinstance(q_right, float) assert q_left < q_right if self._showBoundary: # Q-boundary indicator is on. turn off self.remove_indicator(self._leftID) self.remove_indicator(self._rightID) self._leftID = None self._rightID = None self._showBoundary = False else: self._leftID = self.add_vertical_indicator(q_left, 'red') self._rightID = self.add_vertical_indicator(q_right, 'red') self._showBoundary = True # reset the x-range x_range = self.getXLimit() if x_range[0] > q_left - 1: self.setXYLimit(xmin=q_left-1) # END-IF-ELSE (show boundary) return
{ "repo_name": "neutrons/FastGR", "path": "addie/calculate_gr/sofqview.py", "copies": "1", "size": "13207", "license": "mit", "hash": 8514436688408892000, "line_mean": 28.947845805, "line_max": 119, "alpha_frac": 0.5611418187, "autogenerated": false, "ratio": 4.119463505926388, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5180605324626388, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from qtpy.QtGui import QCursor from qtpy.QtWidgets import (QAction, QMenu) from addie.plot import MplGraphicsView class GofRView(MplGraphicsView): """ Graphics view for G(R) """ def __init__(self, parent): """ Initialization """ MplGraphicsView.__init__(self, parent) # class variable containers self._grDict = dict() self._colorList = ['black', 'red', 'blue', 'green', 'brown', 'orange'] self._colorIndex = 0 # define the event handlers to the mouse actions self._myCanvas.mpl_connect('button_press_event', self.on_mouse_press_event) # self._myCanvas.mpl_connect('button_release_event', self.on_mouse_release_event) # self._myCanvas.mpl_connect('motion_notify_event', self.on_mouse_motion) # class variable self._minY = None self._maxY = None # variable self._isLegendOn = False return def on_mouse_press_event(self, event): """ Event handling for mouse press action Args: event: Returns: """ # get the button and position information. curr_x = event.xdata curr_y = event.ydata if curr_x is None or curr_y is None: # outside of canvas return button = event.button if button == 1: # left button: no operation pass elif button == 3: # right button: # Pop-out menu self.menu = QMenu(self) if self.get_canvas().is_legend_on: # figure has legend: remove legend action1 = QAction('Hide legend', self) action1.triggered.connect(self._myCanvas.hide_legend) action2 = QAction('Legend font larger', self) action2.triggered.connect(self._myCanvas.increase_legend_font_size) action3 = QAction('Legend font smaller', self) action3.triggered.connect(self._myCanvas.decrease_legend_font_size) self.menu.addAction(action2) self.menu.addAction(action3) else: # figure does not have legend: add legend action1 = QAction('Show legend', self) action1.triggered.connect(self._myCanvas.show_legend) self.menu.addAction(action1) # pop up menu self.menu.popup(QCursor.pos()) # END-IF-ELSE return def plot_gr(self, plot_key, ws_name, plotError=False, color='black', style='.', marker=None, alpha=1., label=None): """ Plot G(r) :param plot_key: a key to the current plot :param vec_r: numpy array for R :param vec_g: numpy array for G(r) :param vec_e: numpy array for G(r) error :param plot_error: :param color: :param style: :param marker: :param alpha: :param label: label for the line to plot :return: """ # q_min = 10., q_max = 50. # alpha = 1. - (q_now - q_min)/(q_max - q_min) if not label: label = str(plot_key) line_id = self.add_plot_1d(ws_name, wkspindex=0, marker=marker, color=color, line_style=style, alpha=alpha, label=label, x_label=r'r ($\AA$)', plotError=plotError) self._colorIndex += 1 self._grDict[str(plot_key)] = line_id # check the low/max self.auto_scale_y() def _reset_y_range(self, vec_gr): """ reset the Y range :param vec_gr: :return: """ this_min = min(vec_gr) this_max = max(vec_gr) if self._minY is None or this_min < self._minY: self._minY = this_min if self._maxY is None or this_max > self._maxY: self._maxY = this_max return def _auto_rescale_y(self): """ :return: """ if self._minY is None or self._maxY is None: return delta_y = self._maxY - self._minY lower_boundary = self._minY - delta_y * 0.05 upper_boundary = self._maxY + delta_y * 0.05 self.setXYLimit(ymin=lower_boundary, ymax=upper_boundary) return def has_gr(self, gr_ws_name): """Check whether a plot of G(r) exists on the canvas :param gr_ws_name: :return: """ return gr_ws_name in self._grDict def get_current_grs(self): """ list all the G(r) plotted on the figure now :return: """ return list(self._grDict.keys()) def remove_gr(self, plot_key): """Remove a plotted G(r) from canvas :param plot_key: key to locate the 1-D plot on canvas :return: boolean, string (as error message) """ # check assert isinstance(plot_key, str), 'Key for the plot must be a string but not %s.' % str(type(plot_key)) if plot_key not in self._grDict: return False, 'Workspace %s cannot be found in GofR dictionary of canvas' % plot_key # get line ID line_id = self._grDict[plot_key] # remove from plot self.remove_line(line_id) # clean G(r) plot del self._grDict[plot_key] # reset min and max self._minY = None self._maxY = None return def reset_color(self): """Reset color scheme :return: """ self._colorIndex = 0 def reset(self): """ Reset the canvas by deleting all lines and clean the dictionary Returns: """ # remove all lines and reset marker/color default sequence self.clear_all_lines() self.reset_line_color_marker_index() self._colorIndex = 0 # clean dictionary self._grDict.clear() return def update_gr(self, plot_key, ws_name, plotError=False): """update the value of an existing G(r) :param plot_key: :param vec_r: :param vec_g: :param vec_ge: :return: """ # check existence if plot_key not in self._grDict: raise RuntimeError('Plot with key/workspace name {0} does not exist on plot. Current plots are ' '{1}'.format(plot_key, list(self._grDict.keys()))) # update line_key = self._grDict[plot_key] self.updateLine(ikey=line_key, wkspname=ws_name) # update range self.auto_scale_y() return
{ "repo_name": "neutrons/FastGR", "path": "addie/calculate_gr/gofrview.py", "copies": "1", "size": "6711", "license": "mit", "hash": 1661131225665665300, "line_mean": 27.3164556962, "line_max": 111, "alpha_frac": 0.5392638951, "autogenerated": false, "ratio": 3.8791907514450865, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4918454646545086, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from qtpy.QtWidgets import QApplication from qtpy import QtCore import copy from addie.utilities.general import remove_white_spaces from addie.processing.mantid.master_table.import_from_database.oncat_template_retriever import OncatTemplateRetriever from addie.databases.oncat.oncat import pyoncatGetNexus, pyoncatGetRunsFromIpts from addie.utilities.general import json_extractor import addie.processing.mantid.master_table.import_from_database.utilities as database_utilities class ImportTableFromOncat: def __init__(self, parent=None): self.parent = parent def from_oncat_template(self): """Using ONCat template, this method retrieves the metadata of either the IPTS or runs selected""" if self.parent.ui.run_radio_button.isChecked(): # remove white space to string to make ONCat happy str_runs = str(self.parent.ui.run_number_lineedit.text()) str_runs = remove_white_spaces(str_runs) if str_runs == "": "no runs provided. nothing to do" self.parent.nexus_json_from_template = {} return projection = OncatTemplateRetriever.create_oncat_projection_from_template(with_location=True, template=self.parent.oncat_template) nexus_json = pyoncatGetNexus(oncat=self.parent.parent.oncat, instrument=self.parent.parent.instrument['short_name'], runs=str_runs, facility=self.parent.parent.facility, projection=projection, ) else: ipts = str(self.parent.ui.ipts_combobox.currentText()) projection = OncatTemplateRetriever.create_oncat_projection_from_template(with_location=False, template=self.parent.oncat_template) nexus_json = pyoncatGetRunsFromIpts(oncat=self.parent.parent.oncat, instrument=self.parent.parent.instrument['short_name'], ipts=ipts, facility=self.parent.parent.facility, projection=projection, ) self.parent.nexus_json_from_template = nexus_json def from_oncat_config(self, insert_in_table=True): """using only the fields we are looking for (defined in the config.json file, this method retrieves the metadata of either the IPTS or the runs selected, and populate or not the Master table (if insert_in_table is True)""" QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) self.parent.list_of_runs_not_found = [] nexus_json = self.parent.nexus_json_from_template if self.parent.ui.run_radio_button.isChecked(): # remove white space to string to make ONCat happy str_runs = str(self.parent.ui.run_number_lineedit.text()) str_runs = remove_white_spaces(str_runs) # # nexus_json = pyoncatGetNexus(oncat=self.parent.parent.oncat, # instrument=self.parent.parent.instrument['short_name'], # runs=str_runs, # facility=self.parent.parent.facility, # ) result = database_utilities.get_list_of_runs_found_and_not_found(str_runs=str_runs, oncat_result=nexus_json) list_of_runs_not_found = result['not_found'] self.parent.list_of_runs_not_found = list_of_runs_not_found self.parent.list_of_runs_found = result['found'] else: # ipts = str(self.parent.ui.ipts_combobox.currentText()) # # nexus_json = pyoncatGetRunsFromIpts(oncat=self.parent.parent.oncat, # instrument=self.parent.parent.instrument['short_name'], # ipts=ipts, # facility=self.parent.parent.facility) result = database_utilities.get_list_of_runs_found_and_not_found(oncat_result=nexus_json, check_not_found=False) self.parent.list_of_runs_not_found = result['not_found'] self.parent.list_of_runs_found = result['found'] if insert_in_table: self.parent.insert_in_master_table(nexus_json=nexus_json) else: self.isolate_metadata(nexus_json) self.parent.nexus_json = nexus_json QApplication.restoreOverrideCursor() if insert_in_table: self.parent.close() def isolate_metadata(self, nexus_json): '''retrieve the metadata of interest from the json returns by ONCat''' # def _format_proton_charge(raw_proton_charge): # _proton_charge = raw_proton_charge/1e12 # return "{:.3}".format(_proton_charge) oncat_metadata_filters = self.parent.parent.oncat_metadata_filters # initialization of metadata dictionary metadata = {} for _entry in oncat_metadata_filters: metadata[_entry["title"]] = [] for _json in nexus_json: for _entry in oncat_metadata_filters: _value = json_extractor(json=copy.deepcopy(_json), list_args=copy.deepcopy(_entry['path'])) metadata[_entry["title"]].append(_value) # make sure we only have the unique element in each arrays for _item in metadata.keys(): metadata[_item] = set(metadata[_item]) self.parent.metadata = metadata
{ "repo_name": "neutrons/FastGR", "path": "addie/processing/mantid/master_table/import_from_database/import_table_from_oncat_handler.py", "copies": "1", "size": "6247", "license": "mit", "hash": 1949550841402200600, "line_mean": 44.598540146, "line_max": 122, "alpha_frac": 0.5484232432, "autogenerated": false, "ratio": 4.433640880056778, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5482064123256778, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from qtpy.QtWidgets import QCheckBox, QSpacerItem, QSizePolicy, QTableWidgetItem, QLabel, QPushButton, \ QComboBox, QFileDialog, QWidget, QGridLayout, QVBoxLayout, QHBoxLayout, QLineEdit from qtpy import QtCore import copy import numpy as np import random from addie.processing.mantid.master_table.placzek_handler import PlaczekHandler from addie.processing.mantid.master_table.selection_handler import TransferH3TableWidgetState from addie.processing.mantid.master_table.periodic_table.chemical_formula_handler import format_chemical_formula_equation from addie.processing.mantid.master_table.tree_definition import COLUMN_DEFAULT_HEIGHT, CONFIG_BUTTON_HEIGHT, CONFIG_BUTTON_WIDTH from addie.processing.mantid.master_table.tree_definition import (INDEX_OF_COLUMNS_SHAPE, INDEX_OF_ABS_CORRECTION, INDEX_OF_MULTI_SCATTERING_CORRECTION, INDEX_OF_INELASTIC_CORRECTION) class TableRowHandler: def __init__(self, main_window=None): self.main_window = main_window self.table_ui = main_window.processing_ui.h3_table def insert_blank_row(self): row = self._calculate_insert_row() self.insert_row(row=row) def transfer_widget_states(self, from_key=None, data_type='sample'): o_transfer = TransferH3TableWidgetState(parent=self.main_window) o_transfer.transfer_states(from_key=from_key, data_type=data_type) def get_column(self, data_type='sample', sample_norm_column=[]): column = sample_norm_column[0] if data_type == 'sample' else sample_norm_column[1] return column # global methods def shape_changed(self, shape_index=0, key=None, data_type='sample'): column = self.get_column(data_type=data_type, sample_norm_column=INDEX_OF_COLUMNS_SHAPE) def update_ui(ui=None, new_list=[]): '''repopulate the ui with the new list and select old item selected if this item is in the new list as well''' ui.blockSignals(True) # saving prev. item selected prev_item_selected = ui.currentText() # clean up ui.clear() # update list for _item in new_list: ui.addItem(_item) # re-select the same item (if still there) new_index_of_prev_item_selected = ui.findText(prev_item_selected) if new_index_of_prev_item_selected != -1: ui.setCurrentIndex(new_index_of_prev_item_selected) ui.blockSignals(False) # abs. correction absorption_correction_ui = self.main_window.master_table_list_ui[key][data_type]['abs_correction'] list_abs_correction = self.get_absorption_correction_list(shape=shape_index) update_ui(ui=absorption_correction_ui, new_list=list_abs_correction) # mult. scat. correction mult_scat_correction_ui = self.main_window.master_table_list_ui[key][data_type]['mult_scat_correction'] list_mult_scat_correction = self.get_multi_scat_correction_list(shape=shape_index) update_ui(ui=mult_scat_correction_ui, new_list=list_mult_scat_correction) _enabled_radius_1 = True _enabled_radius_2 = True _enabled_height = True _label_radius_1 = 'Radius' _label_radius_2 = 'Outer Radius' if shape_index == 0: # cylinder _enabled_radius_2 = False elif shape_index == 1: # sphere _enabled_height = False _enabled_radius_2 = False else: _label_radius_1 = 'Inner Radius' self.main_window.master_table_list_ui[key][data_type]['geometry']['radius']['value'].setVisible(_enabled_radius_1) self.main_window.master_table_list_ui[key][data_type]['geometry']['radius2']['value'].setVisible(_enabled_radius_2) self.main_window.master_table_list_ui[key][data_type]['geometry']['height']['value'].setVisible(_enabled_height) self.main_window.master_table_list_ui[key][data_type]['geometry']['radius']['label'].setVisible(_enabled_radius_1) self.main_window.master_table_list_ui[key][data_type]['geometry']['radius2']['label'].setVisible(_enabled_radius_2) self.main_window.master_table_list_ui[key][data_type]['geometry']['height']['label'].setVisible(_enabled_height) self.main_window.master_table_list_ui[key][data_type]['geometry']['radius']['units'].setVisible(_enabled_radius_1) self.main_window.master_table_list_ui[key][data_type]['geometry']['radius2']['units'].setVisible(_enabled_radius_2) self.main_window.master_table_list_ui[key][data_type]['geometry']['height']['units'].setVisible(_enabled_height) self.main_window.master_table_list_ui[key][data_type]['geometry']['radius']['label'].setText(_label_radius_1) self.main_window.master_table_list_ui[key][data_type]['geometry']['radius2']['label'].setText(_label_radius_2) # change state of other widgets of the same column if they are selected self.transfer_widget_states(from_key=key, data_type=data_type) self.main_window.check_master_table_column_highlighting(column=column) self.main_window.check_master_table_column_highlighting(column=column+1) def abs_correction_changed(self, value='', key=None, data_type='sample'): # change state of other widgets of the same column if they are selected self.transfer_widget_states(from_key=key, data_type=data_type) column = self.get_column(data_type=data_type, sample_norm_column=INDEX_OF_ABS_CORRECTION) self.main_window.check_master_table_column_highlighting(column=column) def inelastic_correction_changed(self, value=None, key=None, data_type='sample'): show_button = True if value == 0: show_button = False info = self.main_window.master_table_list_ui[key][data_type] _ui = info['placzek_button'] _ui.setVisible(show_button) # change state of other widgets of the same column if they are selected self.transfer_widget_states(from_key=key, data_type=data_type) column = self.get_column(data_type=data_type, sample_norm_column=INDEX_OF_INELASTIC_CORRECTION) self.main_window.check_master_table_column_highlighting(column=column) inelastic_correction = info['inelastic_correction'].currentText() if inelastic_correction not in ["None", None]: PlaczekHandler(parent=self.main_window, key=key, data_type=data_type) def multi_scattering_correction(self, value='', key=None, data_type='sample'): # change state of other widgets of the same column if they are selected self.transfer_widget_states(from_key=key, data_type=data_type) column = self.get_column(data_type=data_type, sample_norm_column=INDEX_OF_MULTI_SCATTERING_CORRECTION) self.main_window.check_master_table_column_highlighting(column=column) def placzek_button_pressed(self, key=None, data_type='sample'): PlaczekHandler(parent=self.main_window, key=key, data_type=data_type) def activated_row_changed(self, key=None, state=None): data_type = 'sample' # change state of other widgets of the same column if they are selected self.transfer_widget_states(from_key=key, data_type=data_type) def grouping_button(self, key=None, grouping_type='input'): message = "Select {} grouping".format(grouping_type) ext = 'Grouping (*.txt);;All (*.*)' file_name = QFileDialog.getOpenFileName(self.main_window, message, self.main_window.calibration_folder, ext) if file_name is None: return # utilities def generate_random_key(self): return random.randint(0, 1e8) def set_row_height(self, row, height): self.table_ui.setRowHeight(row, height) def fill_row(self, sample_runs='', sample_chemical_formula='N/A', sample_mass_density='N/A'): if dict == {}: return row = self._calculate_insert_row() self.insert_row(row=row, sample_runs=sample_runs, sample_mass_density=sample_mass_density, sample_chemical_formula=sample_chemical_formula) def insert_row(self, row=-1, title='', sample_runs='', sample_mass_density='N/A', sample_chemical_formula='N/A', packing_fraction='N/A', align_and_focus_args={}, sample_placzek_arguments={}, normalization_placzek_arguments={}): self.table_ui.insertRow(row) self.set_row_height(row, COLUMN_DEFAULT_HEIGHT) _list_ui_to_unlock = [self.table_ui] _dimension_widgets = {'label': None, 'value': 'N/A', 'units': None} _full_dimension_widgets = {'radius': copy.deepcopy(_dimension_widgets), 'radius2': copy.deepcopy(_dimension_widgets), 'height': copy.deepcopy(_dimension_widgets)} _text_button = {'text': None, 'button': None} _mass_density_options = {'value': "N/A", "selected": False} _mass_density_infos = {'number_density': copy.deepcopy(_mass_density_options), 'mass_density': copy.deepcopy(_mass_density_options), 'mass': copy.deepcopy(_mass_density_options), 'molecular_mass': np.NaN, 'total_number_of_atoms': np.NaN, } _material_infos = {'mantid_format': None, 'addie_format': None} _mass_density_infos['mass_density']["selected"] = True _master_table_row_ui = {'active': None, 'title': None, 'sample': {'runs': None, 'background': {'runs': None, 'background': None, }, 'material': copy.deepcopy(_text_button), 'material_infos': copy.deepcopy(_material_infos), 'mass_density': copy.deepcopy(_text_button), 'mass_density_infos': copy.deepcopy(_mass_density_infos), 'packing_fraction': None, 'geometry': copy.deepcopy(_full_dimension_widgets), 'shape': None, 'abs_correction': None, 'mult_scat_correction': None, 'inelastic_correction': None, 'placzek_button': None, 'placzek_infos': None, }, 'normalization': {'runs': None, 'background': {'runs': None, 'background': None, }, 'material': copy.deepcopy(_text_button), 'material_infos': copy.deepcopy(_material_infos), 'mass_density': copy.deepcopy(_text_button), 'mass_density_infos': copy.deepcopy(_mass_density_infos), 'packing_fraction': None, 'geometry': copy.deepcopy(_full_dimension_widgets), 'shape': None, 'abs_correction': None, 'mult_scat_correction': None, 'inelastic_correction': None, 'placzek_button': None, 'placzek_infos': None, }, 'align_and_focus_args_button': None, 'align_and_focus_args_infos': {}, 'align_and_focus_args_use_global': True, } random_key = self.generate_random_key() self.key = random_key # block main table events self.table_ui.blockSignals(True) # column 0 (active or not checkBox) _layout = QHBoxLayout() _widget = QCheckBox() _widget.setCheckState(QtCore.Qt.Checked) _widget.setEnabled(True) _master_table_row_ui['active'] = _widget _spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) _layout.addItem(_spacer) _layout.addWidget(_widget) _spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) _layout.addItem(_spacer) _layout.addStretch() _new_widget = QWidget() _new_widget.setLayout(_layout) _widget.stateChanged.connect(lambda state=0, key=random_key: self.main_window.master_table_select_state_changed(state, key)) column = 0 self.table_ui.setCellWidget(row, column, _new_widget) # sample column += 1 # column 1 - title _item = QTableWidgetItem(title) _master_table_row_ui['title'] = _item self.table_ui.setItem(row, column, _item) # column 2 - sample runs column += 1 _item = QTableWidgetItem(sample_runs) _master_table_row_ui['sample']['runs'] = _item self.table_ui.setItem(row, column, _item) # column 3 - background runs column += 1 _item = QTableWidgetItem("") _master_table_row_ui['sample']['background']['runs'] = _item self.table_ui.setItem(row, column, _item) # column 4 - background background column += 1 _item = QTableWidgetItem("") _master_table_row_ui['sample']['background']['background'] = _item self.table_ui.setItem(row, column, _item) # column 5 - material (chemical formula) column += 1 clean_sample_chemical_formula = format_chemical_formula_equation(sample_chemical_formula) _material_text = QLineEdit(clean_sample_chemical_formula) _material_text = QLabel(clean_sample_chemical_formula) _material_button = QPushButton("...") _material_button.setFixedHeight(CONFIG_BUTTON_HEIGHT) _material_button.setFixedWidth(CONFIG_BUTTON_WIDTH) _material_button.pressed.connect(lambda key=random_key: self.main_window.master_table_sample_material_button_pressed(key)) _verti_layout = QVBoxLayout() _verti_layout.addWidget(_material_text) _verti_layout.addWidget(_material_button) _material_widget = QWidget() _material_widget.setLayout(_verti_layout) self.table_ui.setCellWidget(row, column, _material_widget) _master_table_row_ui['sample']['material']['text'] = _material_text _master_table_row_ui['sample']['material']['button'] = _material_button # column 6 - mass density column += 1 _mass_text = QLineEdit(sample_mass_density) _mass_text.returnPressed.connect(lambda key=random_key: self.main_window.master_table_sample_mass_density_line_edit_entered(key)) _mass_units = QLabel("g/cc") _top_widget = QWidget() _top_layout = QHBoxLayout() _top_layout.addWidget(_mass_text) _top_layout.addWidget(_mass_units) _top_widget.setLayout(_top_layout) _mass_button = QPushButton("...") _mass_button.setFixedHeight(CONFIG_BUTTON_HEIGHT) _mass_button.setFixedWidth(CONFIG_BUTTON_WIDTH) _mass_button.pressed.connect(lambda key=random_key: self.main_window.master_table_sample_mass_density_button_pressed(key)) _verti_layout = QVBoxLayout() _verti_layout.addWidget(_top_widget) _verti_layout.addWidget(_mass_button) _mass_widget = QWidget() _mass_widget.setLayout(_verti_layout) self.table_ui.setCellWidget(row, column, _mass_widget) _master_table_row_ui['sample']['mass_density']['text'] = _mass_text _master_table_row_ui['sample']['mass_density']['button'] = _mass_button # column 7 - packing fraction column += 1 if packing_fraction == "N/A": packing_fraction = "{}".format(self.main_window.packing_fraction) _item = QTableWidgetItem(packing_fraction) _master_table_row_ui['sample']['packing_fraction'] = _item self.table_ui.setItem(row, column, _item) # column 8 - shape (cylinder or sphere) column += 1 _layout = QHBoxLayout() _layout.setContentsMargins(0, 0, 0, 0) _widget = QComboBox() _shape_default_index = 0 _widget.currentIndexChanged.connect(lambda index=_shape_default_index, key=random_key: self.main_window.master_table_sample_shape_changed(index, key)) _list_ui_to_unlock.append(_widget) _widget.blockSignals(True) _widget.addItem("Cylinder") _widget.addItem("Sphere") _widget.addItem("Hollow Cylinder") _master_table_row_ui['sample']['shape'] = _widget _layout.addWidget(_widget) _w = QWidget() _w.setLayout(_layout) self.table_ui.setCellWidget(row, column, _w) # column 9 - dimensions column += 1 # layout 1 _grid_layout = QGridLayout() _label1 = QLabel("Radius:") _grid_layout.addWidget(_label1, 1, 0) _value1 = QLabel("N/A") _grid_layout.addWidget(_value1, 1, 1) _dim1 = QLabel("cm") _grid_layout.addWidget(_dim1, 1, 2) _label2 = QLabel("Radius:") _label2.setVisible(False) _grid_layout.addWidget(_label2, 2, 0) _value2 = QLabel("N/A") _value2.setVisible(False) _grid_layout.addWidget(_value2, 2, 1) _dim2 = QLabel("cm") _dim2.setVisible(False) _grid_layout.addWidget(_dim2, 2, 2) _label3 = QLabel("Height:") _grid_layout.addWidget(_label3, 3, 0) _value3 = QLabel("N/A") _grid_layout.addWidget(_value3, 3, 1) _dim3 = QLabel("cm") _grid_layout.addWidget(_dim3, 3, 2) _master_table_row_ui['sample']['geometry']['radius']['value'] = _value1 _master_table_row_ui['sample']['geometry']['radius2']['value'] = _value2 _master_table_row_ui['sample']['geometry']['height']['value'] = _value3 _master_table_row_ui['sample']['geometry']['radius']['label'] = _label1 _master_table_row_ui['sample']['geometry']['radius2']['label'] = _label2 _master_table_row_ui['sample']['geometry']['height']['label'] = _label3 _master_table_row_ui['sample']['geometry']['radius']['units'] = _dim1 _master_table_row_ui['sample']['geometry']['radius2']['units'] = _dim2 _master_table_row_ui['sample']['geometry']['height']['units'] = _dim3 _geometry_widget = QWidget() _geometry_widget.setLayout(_grid_layout) _set_dimensions_button = QPushButton("...") _set_dimensions_button.setFixedHeight(CONFIG_BUTTON_HEIGHT) _set_dimensions_button.setFixedWidth(CONFIG_BUTTON_WIDTH) _verti_layout = QVBoxLayout() _verti_layout.addWidget(_geometry_widget) _verti_layout.addWidget(_set_dimensions_button) _verti_widget = QWidget() _verti_widget.setLayout(_verti_layout) _set_dimensions_button.pressed.connect(lambda key=random_key: self.main_window.master_table_sample_dimensions_setter_button_pressed(key)) self.table_ui.setCellWidget(row, column, _verti_widget) # column 10 - abs. correction column += 1 _layout = QHBoxLayout() _layout.setContentsMargins(0, 0, 0, 0) _widget = QComboBox() _shape_default_value = 0 list_abs_correction = self.get_absorption_correction_list(shape=_shape_default_value) _widget.currentIndexChanged.connect(lambda value=list_abs_correction[0], key = random_key: self.main_window.master_table_sample_abs_correction_changed(value, key)) _widget.blockSignals(True) _list_ui_to_unlock.append(_widget) for _item in list_abs_correction: _widget.addItem(_item) _master_table_row_ui['sample']['abs_correction'] = _widget _layout.addWidget(_widget) _w = QWidget() _w.setLayout(_layout) self.table_ui.setCellWidget(row, column, _w) # column 11 - multi. scattering correction column += 1 _layout = QHBoxLayout() _layout.setContentsMargins(0, 0, 0, 0) _widget = QComboBox() list_multi_scat_correction = self.get_multi_scat_correction_list(shape=_shape_default_value) _widget.currentIndexChanged.connect(lambda value=list_multi_scat_correction[0], key=random_key: self.main_window.master_table_sample_multi_scattering_correction_changed(value, key)) _widget.blockSignals(True) _list_ui_to_unlock.append(_widget) for _item in list_multi_scat_correction: _widget.addItem(_item) _master_table_row_ui['sample']['mult_scat_correction'] = _widget _layout.addWidget(_widget) _w = QWidget() _w.setLayout(_layout) self.table_ui.setCellWidget(row, column, _w) # column 12 - inelastic correction column += 1 _layout = QHBoxLayout() _layout.setContentsMargins(0, 0, 0, 0) _widget1 = QComboBox() _widget1.setMinimumHeight(20) list_inelastic_correction = self.get_inelastic_scattering_list(shape=_shape_default_value) for _item in list_inelastic_correction: _widget1.addItem(_item) _master_table_row_ui['sample']['inelastic_correction'] = _widget1 _button = QPushButton("...") _button.setFixedHeight(CONFIG_BUTTON_HEIGHT) _button.setFixedWidth(CONFIG_BUTTON_WIDTH) _button.pressed.connect(lambda key=random_key: self.main_window.master_table_sample_placzek_button_pressed(key)) _master_table_row_ui['sample']['placzek_button'] = _button _button.setVisible(False) _master_table_row_ui['sample']['placzek_button'] = _button _layout.addWidget(_widget1) _layout.addWidget(_button) _widget = QWidget() _widget.setLayout(_layout) _default_value = 'None' _widget1.currentIndexChanged.connect(lambda value=_default_value, key=random_key: self.main_window.master_table_sample_inelastic_correction_changed(value, key)) _widget.blockSignals(True) _list_ui_to_unlock.append(_widget) self.table_ui.setCellWidget(row, column, _widget) # save default placzek settings _sample_formated_placzek_default = self.formated_placzek_default(sample_placzek_arguments) _master_table_row_ui['sample']['placzek_infos'] = _sample_formated_placzek_default ## normalization # column 13 - sample runs column += 1 _item = QTableWidgetItem("") self.table_ui.setItem(row, column, _item) # column 14 - background runs column += 1 _item = QTableWidgetItem("") self.table_ui.setItem(row, column, _item) # column 15 - background background column += 1 _item = QTableWidgetItem("") self.table_ui.setItem(row, column, _item) # column 16 - material (chemical formula) column += 1 #_material_text = QLineEdit("") _material_text = QLabel("N/A") _material_button = QPushButton("...") _material_button.setFixedHeight(CONFIG_BUTTON_HEIGHT) _material_button.setFixedWidth(CONFIG_BUTTON_WIDTH) _material_button.pressed.connect(lambda key=random_key: self.main_window.master_table_normalization_material_button_pressed(key)) _verti_layout = QVBoxLayout() _verti_layout.addWidget(_material_text) _verti_layout.addWidget(_material_button) _material_widget = QWidget() _material_widget.setLayout(_verti_layout) self.table_ui.setCellWidget(row, column, _material_widget) _master_table_row_ui['normalization']['material']['text'] = _material_text _master_table_row_ui['normalization']['material']['button'] = _material_button # column 17 - mass density column += 1 _mass_text = QLineEdit("N/A") _mass_text.returnPressed.connect(lambda key=random_key: self.main_window.master_table_normalization_mass_density_line_edit_entered(key)) _mass_units = QLabel("g/cc") _top_widget = QWidget() _top_layout = QHBoxLayout() _top_layout.addWidget(_mass_text) _top_layout.addWidget(_mass_units) _top_widget.setLayout(_top_layout) _mass_button = QPushButton("...") _mass_button.setFixedWidth(CONFIG_BUTTON_WIDTH) _mass_button.setFixedHeight(CONFIG_BUTTON_HEIGHT) _mass_button.pressed.connect(lambda key=random_key: self.main_window.master_table_normalization_mass_density_button_pressed(key)) _verti_layout = QVBoxLayout() _verti_layout.addWidget(_top_widget) _verti_layout.addWidget(_mass_button) _mass_widget = QWidget() _mass_widget.setLayout(_verti_layout) self.table_ui.setCellWidget(row, column, _mass_widget) _master_table_row_ui['normalization']['mass_density']['text'] = _mass_text _master_table_row_ui['normalization']['mass_density']['button'] = _mass_button # column 18 - packing fraction column += 1 _item = QTableWidgetItem("") self.table_ui.setItem(row, column, _item) # column 19 - shape (cylinder or sphere) column += 1 _layout = QHBoxLayout() _layout.setContentsMargins(0, 0, 0, 0) _widget = QComboBox() _widget.currentIndexChanged.connect(lambda value=_shape_default_value, key=random_key: self.main_window.master_table_normalization_shape_changed(value, key)) _widget.blockSignals(True) _list_ui_to_unlock.append(_widget) _widget.addItem("Cylinder") _widget.addItem("Sphere") _widget.addItem("Hollow Cylinder") _master_table_row_ui['normalization']['shape'] = _widget _layout.addWidget(_widget) _w = QWidget() _w.setLayout(_layout) self.table_ui.setCellWidget(row, column, _w) # column 20 - dimensions column += 1 # layout 1 _grid_layout = QGridLayout() _label1 = QLabel("Radius:") _grid_layout.addWidget(_label1, 1, 0) _value1 = QLabel("N/A") _grid_layout.addWidget(_value1, 1, 1) _dim1 = QLabel("cm") _grid_layout.addWidget(_dim1, 1, 2) _label2 = QLabel("Radius:") _label2.setVisible(False) _grid_layout.addWidget(_label2, 2, 0) _value2 = QLabel("N/A") _value2.setVisible(False) _grid_layout.addWidget(_value2, 2, 1) _dim2 = QLabel("cm") _dim2.setVisible(False) _grid_layout.addWidget(_dim2, 2, 2) _label3 = QLabel("Height:") _grid_layout.addWidget(_label3, 3, 0) _value3 = QLabel("N/A") _grid_layout.addWidget(_value3, 3, 1) _dim3 = QLabel("cm") _grid_layout.addWidget(_dim3, 3, 2) _master_table_row_ui['normalization']['geometry']['radius']['value'] = _value1 _master_table_row_ui['normalization']['geometry']['radius2']['value'] = _value2 _master_table_row_ui['normalization']['geometry']['height']['value'] = _value3 _master_table_row_ui['normalization']['geometry']['radius']['label'] = _label1 _master_table_row_ui['normalization']['geometry']['radius2']['label'] = _label2 _master_table_row_ui['normalization']['geometry']['height']['label'] = _label3 _master_table_row_ui['normalization']['geometry']['radius']['units'] = _dim1 _master_table_row_ui['normalization']['geometry']['radius2']['units'] = _dim2 _master_table_row_ui['normalization']['geometry']['height']['units'] = _dim3 _geometry_widget = QWidget() _geometry_widget.setLayout(_grid_layout) _set_dimensions_button = QPushButton("...") _set_dimensions_button.setFixedHeight(CONFIG_BUTTON_HEIGHT) _set_dimensions_button.setFixedWidth(CONFIG_BUTTON_WIDTH) _verti_layout = QVBoxLayout() _verti_layout.addWidget(_geometry_widget) _verti_layout.addWidget(_set_dimensions_button) _verti_widget = QWidget() _verti_widget.setLayout(_verti_layout) _set_dimensions_button.pressed.connect(lambda key=random_key: self.main_window.master_table_normalization_dimensions_setter_button_pressed(key)) # noqa self.table_ui.setCellWidget(row, column, _verti_widget) # column 21 - abs. correction column += 1 _layout = QHBoxLayout() _layout.setContentsMargins(0, 0, 0, 0) _widget = QComboBox() _widget.currentIndexChanged.connect(lambda value=list_abs_correction[0], key=random_key: self.main_window.master_table_normalization_abs_correction_changed(value, key)) # noqa _widget.blockSignals(True) _list_ui_to_unlock.append(_widget) for _item in list_abs_correction: _widget.addItem(_item) _widget.setCurrentIndex(0) _master_table_row_ui['normalization']['abs_correction'] = _widget _layout.addWidget(_widget) _w = QWidget() _w.setLayout(_layout) self.table_ui.setCellWidget(row, column, _w) # column 24 - multi. scattering correction column += 1 _layout = QHBoxLayout() _layout.setContentsMargins(0, 0, 0, 0) _widget = QComboBox() _widget.currentIndexChanged.connect(lambda value=list_multi_scat_correction[0], key=random_key: self.main_window.master_table_normalization_multi_scattering_correction_changed(value, key)) # noqa _widget.blockSignals(True) _list_ui_to_unlock.append(_widget) for _item in list_multi_scat_correction: _widget.addItem(_item) _widget.setCurrentIndex(0) _master_table_row_ui['normalization']['mult_scat_correction'] = _widget _layout.addWidget(_widget) _w = QWidget() _w.setLayout(_layout) self.table_ui.setCellWidget(row, column, _w) # column 22 - inelastic correction column += 1 _layout = QHBoxLayout() _layout.setContentsMargins(0, 0, 0, 0) _widget1 = QComboBox() _widget1.setMinimumHeight(20) list_inelastic_correction = self.get_inelastic_scattering_list(shape=_shape_default_value) for _item in list_inelastic_correction: _widget1.addItem(_item) _widget1.setCurrentIndex(0) _master_table_row_ui['normalization']['inelastic_correction'] = _widget1 _button = QPushButton("...") _button.setFixedWidth(CONFIG_BUTTON_WIDTH) _button.setFixedHeight(CONFIG_BUTTON_HEIGHT) _button.pressed.connect(lambda key=random_key: self.main_window.master_table_normalization_placzek_button_pressed(key)) _master_table_row_ui['normalization']['placzek_button'] = _button _button.setVisible(False) _layout.addWidget(_widget1) _layout.addWidget(_button) _widget = QWidget() _widget.setLayout(_layout) _default_value = 'None' _widget1.currentIndexChanged.connect( lambda value=_default_value, key=random_key: self.main_window.master_table_normalization_inelastic_correction_changed(value, key)) # noqa _widget.blockSignals(True) _list_ui_to_unlock.append(_widget) self.table_ui.setCellWidget(row, column, _widget) # automatically populate placzek infos with default values _norm_formated_placzek_default = self.formated_placzek_default(normalization_placzek_arguments) _master_table_row_ui['normalization']['placzek_infos'] = _norm_formated_placzek_default # column 23 - key/value pair column += 1 _layout = QHBoxLayout() _spacer_kv1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) _layout.addItem(_spacer_kv1) _button = QPushButton("...") _layout.addWidget(_button) _button.setFixedWidth(CONFIG_BUTTON_WIDTH) _button.setFixedHeight(CONFIG_BUTTON_HEIGHT) _button.pressed.connect(lambda key=random_key: self.main_window.master_table_keyvalue_button_pressed(key)) _new_widget = QWidget() _new_widget.setLayout(_layout) self.table_ui.setCellWidget(row, column, _new_widget) _master_table_row_ui['align_and_focus_args_button'] = _button _spacer_kv2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) _layout.addItem(_spacer_kv2) _layout.addStretch() align_and_focus_args = self.add_global_key_value_to_local_key_value(align_and_focus_args) _master_table_row_ui['align_and_focus_args_infos'] = align_and_focus_args # Recap. self.main_window.master_table_list_ui[random_key] = _master_table_row_ui self.unlock_signals_ui(list_ui=_list_ui_to_unlock) self.main_window.check_status_of_right_click_buttons() def add_global_key_value_to_local_key_value(self, local_align_and_focus_args): global_list_key_value = self.main_window.global_key_value current_local_key_value = local_align_and_focus_args if current_local_key_value == {}: return global_list_key_value else: list_local_keys = current_local_key_value.keys() list_global_keys = global_list_key_value.keys() new_local_key_value = {} for _key in list_local_keys: if _key in list_global_keys: new_local_key_value[_key] = global_list_key_value[_key] else: new_local_key_value[_key] = current_local_key_value[_key] return new_local_key_value def formated_placzek_default(self, placzek={}): config_placzek = self.main_window.placzek_default if placzek == {}: _dict = config_placzek else: _dict = placzek order_index = _dict['order']['index_selected'] is_self = _dict['is_self'] is_interference = _dict['is_interference'] fit_spectrum_index = _dict['fit_spectrum_with']['index_selected'] lambda_fit_min = _dict['lambda_binning_for_fit']['min'] lambda_fit_max = _dict['lambda_binning_for_fit']['max'] lambda_fit_delta = _dict['lambda_binning_for_fit']['delta'] lambda_calc_min = _dict['lambda_binning_for_calc']['min'] lambda_calc_max = _dict['lambda_binning_for_calc']['max'] lambda_calc_delta = _dict['lambda_binning_for_calc']['delta'] new_format = {'order_index': order_index, 'is_self': is_self, 'is_interference': is_interference, 'fit_spectrum_index': fit_spectrum_index, 'lambda_fit_min': lambda_fit_min, 'lambda_fit_max': lambda_fit_max, 'lambda_fit_delta': lambda_fit_delta, 'lambda_calc_min': lambda_calc_min, 'lambda_calc_max': lambda_calc_max, 'lambda_calc_delta': lambda_calc_delta, } return new_format def _get_list_ui_from_master_table_row_ui(self, master_table_row_ui): list_ui = [] if master_table_row_ui['active']: list_ui.append(master_table_row_ui['active']) for _root in ['sample', 'normalization']: _sub_root = master_table_row_ui[_root] for _key in _sub_root.keys(): _ui = _sub_root[_key] if _ui: list_ui.append(_ui) return list_ui def unlock_signals_ui(self, list_ui=[]): if list_ui == []: return for _ui in list_ui: _ui.blockSignals(False) def get_multi_scat_correction_list(self, shape=0): if shape == 0: # cylinder return ['None', 'Carpenter', 'Mayers'] elif shape == 1: # sphere return ['None'] elif shape == 2: # hollow cylinder return ['None'] return ['None'] def get_inelastic_scattering_list(self, shape='Cylinder'): return ['None', 'Placzek', ] def get_absorption_correction_list(self, shape=0): if shape == 0: # cylinder return ['None', 'Carpenter', 'Mayers', 'Podman & Pings', 'Monte Carlo', 'Numerical', ] elif shape == 1: # sphere return ['None', 'Monte Carlo', ] elif shape== 2: # hollow cylinder return ['None', 'Monte Carlo'] return ['None'] def _calculate_insert_row(self): selection = self.main_window.processing_ui.h3_table.selectedRanges() # no row selected, new row will be the first row if selection == []: return 0 first_selection = selection[0] return first_selection.topRow()
{ "repo_name": "neutrons/FastGR", "path": "addie/processing/mantid/master_table/table_row_handler.py", "copies": "1", "size": "40007", "license": "mit", "hash": -7964366070701274000, "line_mean": 44.4108967083, "line_max": 144, "alpha_frac": 0.5630764616, "autogenerated": false, "ratio": 3.9642290923503767, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0015438219472925267, "num_lines": 881 }
from __future__ import (absolute_import, division, print_function) from qtpy.QtWidgets import QDialog from addie.utilities import load_ui from qtpy import QtGui from addie.processing.mantid.master_table.table_row_handler import TableRowHandler from addie.utilities.math_tools import is_number from addie.processing.mantid.master_table.tree_definition import INDEX_OF_COLUMNS_WITH_GEOMETRY_INFOS def _sphere_csg_radius(value): value = 0.01 * value # converts from cm -> m for CSG sphere_xml = " \ <sphere id='some-sphere'> \ <centre x='0.0' y='0.0' z='0.0' /> \ <radius val={radius} /> \ </sphere> \ <algebra val='some-sphere' /> \ ".format(radius=value) return sphere_xml _table2mantid_cylinder = { "Shape": {"Key": "Shape"}, "Radius": {"Key": "Radius"}, "Height": {"Key": "Height"} } _table2mantid_hollow_cylinder = { "Shape": {"Key": "Shape", "ValueProcessor": lambda x: "HollowCylinder"}, "Radius": {"Key": "InnerRadius"}, "Radius2": {"Key": "OuterRadius"}, "Height": {"Key": "Height"} } _table2mantid_sphere = { "Shape": {"Key": "Shape", "ValueProcessor": lambda x: "CSG"}, "Radius": {"Key": "Value", "ValueProcessor": _sphere_csg_radius} } table2mantid = { "Cylinder": _table2mantid_cylinder, "Hollow Cylinder": _table2mantid_hollow_cylinder, "Sphere": _table2mantid_sphere } class DimensionsSetter(QDialog): shape_selected = 'Cylinder' column = 0 def __init__(self, parent=None, key=None, data_type='sample'): self.parent = parent self.key = key self.data_type = data_type QDialog.__init__(self, parent=parent) self.ui = load_ui('dimensions_setter.ui', baseinstance=self) self.group_widgets() self.init_widgets_layout() self.init_widgets_content() if parent.geometry_ui_position: self.move(parent.geometry_ui_position) self.check_save_button() self.set_column_index() def set_column_index(self): self.column = INDEX_OF_COLUMNS_WITH_GEOMETRY_INFOS[0] if self.data_type == 'sample' else \ INDEX_OF_COLUMNS_WITH_GEOMETRY_INFOS[1] def group_widgets(self): self.group = {'radius': [self.ui.radius_label, self.ui.radius_value, self.ui.radius_units], 'radius2': [self.ui.radius2_label, self.ui.radius2_value, self.ui.radius2_units], 'height': [self.ui.height_label, self.ui.height_value, self.ui.height_units]} def __get_label_value(self, geometry_type): '''helper function to retrieve value of labels from master table. :argument: geometry_type being 'radius', 'radius2' or 'height' ''' return str(self.parent.master_table_list_ui[self.key] [self.data_type]['geometry'][geometry_type]['value'].text()) def __set_label_value(self, geometry_type, value): '''helper function to set value of label in master table. :argument: geometry_type being 'radius', 'radius2' or 'height' value: value to set ''' self.parent.master_table_list_ui[self.key][self.data_type]['geometry'][geometry_type]['value'].setText( value) def init_widgets_content(self): '''populate the widgets using the value from the master table''' height = 'N/A' radius2 = 'N/A' if self.shape_selected.lower() == 'cylinder': radius = self.__get_label_value('radius') height = self.__get_label_value('height') elif self.shape_selected.lower() == 'sphere': radius = self.__get_label_value('radius') else: radius = self.__get_label_value('radius') radius2 = self.__get_label_value('radius2') height = self.__get_label_value('height') self.ui.radius_value.setText(radius) self.ui.radius2_value.setText(radius2) self.ui.height_value.setText(height) def init_widgets_layout(self): '''using the shape defined for this row, will display the right widgets and will populate them with the right values''' # which shape are we working on table_row_ui = self.parent.master_table_list_ui[self.key][self.data_type] shape_ui = table_row_ui['shape'] self.shape_selected = shape_ui.currentText() # hide/show widgets according to shape selected if self.shape_selected.lower() == 'cylinder': # change label of first label self.ui.radius_label.setText("Radius") # hide radius 2 widgets for _widget in self.group['radius2']: _widget.setVisible(False) # display right image label self.ui.preview.setPixmap(QtGui.QPixmap( ":/preview/cylinder_reference.png")) self.ui.preview.setScaledContents(True) elif self.shape_selected.lower() == 'sphere': # change label of first label self.ui.radius_label.setText("Radius") # hide radius widgets for _widget in self.group['radius2']: _widget.setVisible(False) # hide radius 2 widgets for _widget in self.group['height']: _widget.setVisible(False) # display the right image label self.ui.preview.setPixmap(QtGui.QPixmap( ":/preview/sphere_reference.png")) self.ui.preview.setScaledContents(True) elif self.shape_selected.lower() == 'hollow cylinder': # display the right image label self.ui.preview.setPixmap(QtGui.QPixmap( ":/preview/hollow_cylinder_reference.png")) self.ui.preview.setScaledContents(True) # display value of radius1,2,height for this row return def value_changed(self, text): self.check_save_button() def check_save_button(self): save_button_status = False radius = str(self.ui.radius_value.text()) radius2 = str(self.ui.radius2_value.text()) height = str(self.ui.height_value.text()) if self.shape_selected.lower() == 'cylinder': if is_number(radius) and is_number(height): save_button_status = True elif self.shape_selected.lower() == 'sphere': if is_number(radius): save_button_status = True else: if is_number(radius) and is_number(radius2) and is_number(height): save_button_status = True self.ui.ok.setEnabled(save_button_status) def accept(self): radius = str(self.ui.radius_value.text()) radius2 = 'N/A' height = 'N/A' if self.shape_selected.lower() == 'cylinder': height = str(self.ui.height_value.text()) elif self.shape_selected.lower() == 'sphere': pass else: radius2 = str(self.ui.radius2_value.text()) height = str(self.ui.height_value.text()) self.__set_label_value('radius', radius) self.__set_label_value('radius2', radius2) self.__set_label_value('height', height) o_table = TableRowHandler(main_window=self.parent) o_table.transfer_widget_states( from_key=self.key, data_type=self.data_type) self.parent.check_master_table_column_highlighting(column=self.column) self.close() def closeEvent(self, c): self.parent.geometry_ui_position = self.pos()
{ "repo_name": "neutrons/FastGR", "path": "addie/processing/mantid/master_table/geometry_handler.py", "copies": "1", "size": "7756", "license": "mit", "hash": -8907388346463121000, "line_mean": 34.0950226244, "line_max": 111, "alpha_frac": 0.5847086127, "autogenerated": false, "ratio": 3.7889594528578407, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48736680655578407, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from qtpy.QtWidgets import QDialog from addie.utilities import load_ui class ImportFromRunNumberHandler: def __init__(self, parent=None): if parent.import_from_run_number_ui is None: o_import = ImportFromRunNumberWindow(parent=parent) parent.import_from_run_number_ui = o_import if parent.import_from_run_number_ui_position: parent.import_from_run_number_ui.move(parent.import_from_run_number_ui_position) o_import.show() else: parent.import_from_run_number_ui.setFocus() parent.import_from_run_number_ui.activateWindow() class ImportFromRunNumberWindow(QDialog): def __init__(self, parent=None): self.parent = parent QDialog.__init__(self, parent=parent) self.ui = load_ui('import_from_run_number.ui', baseinstance=self) self.init_widgets() def init_widgets(self): pass def change_user_clicked(self): pass def run_number_return_pressed(self): pass def run_number_text_changed(self, run_number_string): self.check_widgets(run_number_string=run_number_string) def run_number_format_is_correct(self, run_number_string): #FIXME # make sure the format of the string is correct and that we can retrieve a correct list of runs return True def check_widgets(self, run_number_string=""): enabled_import_button = True if run_number_string.strip() == "": if not self.run_number_format_is_correct(run_number_string.strip()): enabled_import_button = False self.ui.import_button.setEnabled(enabled_import_button) def import_button_clicked(self): pass def cancel_button_clicked(self): self.close() def closeEvent(self, c): self.parent.import_from_run_number_ui = None self.parent.import_from_run_number_ui_position = self.pos()
{ "repo_name": "neutrons/FastGR", "path": "addie/processing/mantid/master_table/import_from_run_number_handler.py", "copies": "1", "size": "2018", "license": "mit", "hash": -86003323304852350, "line_mean": 31.5483870968, "line_max": 103, "alpha_frac": 0.6486620416, "autogenerated": false, "ratio": 3.7579143389199254, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9898597589500174, "avg_score": 0.0015957582039502006, "num_lines": 62 }
from __future__ import (absolute_import, division, print_function) from qtpy.QtWidgets import QDialog from addie.utilities import load_ui # Create token store class InMemoryTokenStore(object): def __init__(self): self._token = None def set_token(self, token): pass def get_token(self): return self._token def pyoncatGetNexus(oncat=None, instrument='', runs=-1, facility='SNS', projection=[]): if projection == []: projection = ['location', 'indexed.run_number', 'metadata.entry.sample.chemical_formula', 'metadata.entry.sample.mass_density', 'metadata.entry.title', 'metadata.entry.proton_charge', 'metadata.entry.daslogs.bl1b:se:sampletemp.device_name' ] datafiles = oncat.Datafile.list( facility=facility, instrument=instrument, projection=projection, tags=['type/raw'], exts=['.nxs.h5', '.nxs'], ranges_q='indexed.run_number:%s' % runs ) return datafiles def pyoncatGetTemplate(oncat=None, instrument='', facility='SNS'): all_templates = oncat.Template.list(facility=facility, instrument=instrument, ) return all_templates def pyoncatGetRunsFromIpts(oncat=None, instrument='', ipts='', facility='SNS', projection=[]): if projection == []: projection = ['indexed.run_number', 'metadata.entry.sample.chemical_formula', 'metadata.entry.sample.mass_density', 'metadata.entry.title', 'metadata.entry.proton_charge', 'metadata.entry.daslogs.bl1b:se:sampletemp.device_name' ] run_list = oncat.Datafile.list(facility=facility, instrument=instrument, experiment=ipts, projection=projection, tags=['type/raw'], exts=['.nxs.h5', '.nxs']) return run_list def pyoncatGetIptsList(oncat=None, instrument='', facility='SNS'): ipts_list = oncat.Experiment.list( facility=facility, instrument=instrument, projection=['id'] ) return [ipts.name for ipts in ipts_list] # if __name__ == "__main__": # useRcFile = True # dashes = 35 # oncat = pyoncatForADDIE(useRcFile=useRcFile) # # print("-" * dashes) # print("NOMAD file 11000") # print("-" * dashes) # datafiles = pyoncatGetRuns(oncat, 'NOM', 111000) # for datafile in datafiles: # print(datafile.location) # # print("-" * dashes) # print("ARCS file 11000") # print("-" * dashes) # datafiles = pyoncatGetRuns(oncat, 'ARCS', 11000) # for datafile in datafiles: # print(datafile.location) # # print("-" * dashes) # print("NOMAD IPTSs") # print("-" * dashes) # print(pyoncatGetIptsList(oncat, 'NOM')) # # print("-" * dashes) # print("VISION IPTSs") # print("-" * dashes) # print(pyoncatGetIptsList(oncat, 'VIS')) class OncatErrorMessageWindow(QDialog): def __init__(self, parent=None, list_of_runs=[], message=''): QDialog.__init__(self, parent=parent) self.ui = load_ui('oncat_error_message.ui', baseinstance=self) self.init_widgets(list_of_runs=list_of_runs) self.ui.message.setText(message) def init_widgets(self, list_of_runs=[]): str_list_of_runs = "\n".join(list_of_runs) self.ui.list_of_runs.setText(str_list_of_runs)
{ "repo_name": "neutrons/FastGR", "path": "addie/databases/oncat/oncat.py", "copies": "1", "size": "4027", "license": "mit", "hash": -2590342275542607000, "line_mean": 30.2170542636, "line_max": 77, "alpha_frac": 0.5147752669, "autogenerated": false, "ratio": 3.9557956777996073, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9970570944699607, "avg_score": 0, "num_lines": 129 }
from __future__ import (absolute_import, division, print_function) from qtpy.QtWidgets import QMainWindow, QLineEdit, QApplication from addie.utilities import load_ui try: import pyoncat except ImportError: print('failed to import pyoncat') pyoncat = None # Create token store class InMemoryTokenStore(object): def __init__(self): self._token = None def set_token(self, token): self._token = token def get_token(self): return self._token class OncatAuthenticationHandler: def __init__(self, parent=None, next_ui='from_database_ui', next_function=None): o_oncat = OncatAuthenticationWindow(parent=parent, next_ui=next_ui, next_function=next_function) parent.oncat_authentication_ui = o_oncat if parent.oncat_authentication_ui_position: o_oncat.move(parent.oncat_authentication_ui_position) o_oncat.show() parent.oncat_authentication_ui.activateWindow() parent.oncat_authentication_ui.setFocus() class OncatAuthenticationWindow(QMainWindow): def __init__(self, parent=None, next_ui='from_database_ui', next_function=None): QMainWindow.__init__(self, parent=parent) self.parent = parent self.next_ui = next_ui self.next_function = next_function self.ui = load_ui('oncat_authentication.ui', baseinstance=self) self.center() self.init_widgets() self.ui.password.setFocus() def center(self): frameGm = self.frameGeometry() screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos()) centerPoint = QApplication.desktop().screenGeometry(screen).center() frameGm.moveCenter(centerPoint) self.move(frameGm.topLeft()) def init_widgets(self): self.ui.ucams.setText(self.parent.ucams) self.ui.password.setEchoMode(QLineEdit.Password) self.ui.password.setFocus() self.ui.authentication_message.setVisible(False) self.ui.authentication_message.setStyleSheet("color: red") def is_valid_password(self): userid = str(self.ui.ucams.text()).strip() password = str(self.ui.password.text()) # Initialize token store token_store = InMemoryTokenStore() # # Setup ONcat object # oncat = pyoncat.ONCat( # 'https://oncat.ornl.gov', # client_id='cf46da72-9279-4466-bc59-329aea56bafe', # client_secret=None, # token_getter=token_store.get_token, # token_setter=token_store.set_token, # flow=pyoncat.RESOURCE_OWNER_CREDENTIALS_FLOW # ) # pyoncat is not available if pyoncat is None: return False # Setup ONcat object oncat = pyoncat.ONCat( 'https://oncat.ornl.gov', client_id='cf46da72-9279-4466-bc59-329aea56bafe', scopes = ['api:read', 'settings:read'], client_secret=None, token_getter=token_store.get_token, token_setter=token_store.set_token, flow=pyoncat.RESOURCE_OWNER_CREDENTIALS_FLOW ) try: oncat.login(userid, password) self.parent.ucams = userid self.parent.oncat = oncat except: return False return True def ok_clicked(self): # do something if self.is_valid_password(): self.close() self.next_function() # if self.next_ui == 'from_database_ui': # self.parent.launch_import_from_database_handler() # elif self.next_ui == 'from_run_number_ui': # self.parent.launch_import_from_run_number_handler() else: self.ui.password.setText("") self.ui.authentication_message.setVisible(True) def password_changed(self, password): self.ui.authentication_message.setVisible(False) def cancel_clicked(self): self.close() def closeEvent(self, c): self.parent.oncat_authentication_ui_position = self.pos()
{ "repo_name": "neutrons/FastGR", "path": "addie/processing/mantid/master_table/import_from_database/oncat_authentication_handler.py", "copies": "1", "size": "4185", "license": "mit", "hash": 7482614199176354000, "line_mean": 31.6953125, "line_max": 91, "alpha_frac": 0.6088410992, "autogenerated": false, "ratio": 3.835930339138405, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4944771438338405, "avg_score": null, "num_lines": null }
from __future__ import (absolute_import, division, print_function) from qtpy.QtWidgets import QTableWidgetItem import copy import numpy as np from addie.utilities.gui_handler import TableHandler from addie.utilities.general import json_extractor class FilterTableHandler: """Class to work with the table filter (top table of second tab)""" def __init__(self, table_ui=None): self.table_ui = table_ui def return_first_row_for_this_item_value( self, string_to_find="", column_to_look_for=-1): """return the first row found where the item value matches the string passed. If the string can not be found, return -1 """ nbr_rows = self.table_ui.rowCount() for _row in np.arange(nbr_rows): item_value = str( self.table_ui.item( _row, column_to_look_for).text()) if string_to_find == item_value: return _row return -1 def get_combobox_value(self, row=-1, column=-1): combobox = self.table_ui.cellWidget(row, column) return str(combobox.currentText()) def get_keyword_name(self, row=-1): """this method returns the value of the keyword selected for the given row""" return self.get_combobox_value(row=row, column=2) def get_criteria(self, row=-1): """this method returns the value of the criteria (is or contains) selected for the given row""" return self.get_combobox_value(row=row, column=3) def get_string_to_look_for(self, row=-1): """this method returns the value of the string to look for in all the metadata for the given keyword""" return self.get_combobox_value(row=row, column=4) class FilterResultTableHandler: """class to work with the table listing the rows that match the rules""" def __init__(self, table_ui=None): self.table_ui = table_ui def get_column_of_given_keyword(self, keyword=''): """looking through all the columns headers to find the one that match the keyword argument. If it does, return the column index. If this keyword can not be found, return -1""" nbr_columns = self.table_ui.columnCount() for _col in np.arange(nbr_columns): column_header = str( self.table_ui.horizontalHeaderItem(_col).text()) if column_header == keyword: return _col return -1 def get_rows_of_matching_string( self, column_to_look_for=-1, string_to_find='', criteria='is'): nbr_row = self.table_ui.rowCount() list_matching_rows = [] for _row in np.arange(nbr_row): string_at_this_row = str( self.table_ui.item( _row, column_to_look_for).text()) if criteria == 'is': if string_at_this_row == string_to_find: list_matching_rows.append(_row) elif criteria == 'contains': if string_to_find in string_at_this_row: list_matching_rows.append(_row) return list_matching_rows def get_number_of_visible_rows(self): nbr_row = self.table_ui.rowCount() nbr_visible_row = 0 for _row in np.arange(nbr_row): if not self.table_ui.isRowHidden(_row): nbr_visible_row += 1 return nbr_visible_row class GuiHandler: @staticmethod def preview_widget_status(window_ui, enabled_widgets=False): """enable or not all the widgets related to the preview tab""" window_ui.search_logo_label.setEnabled(enabled_widgets) window_ui.name_search.setEnabled(enabled_widgets) window_ui.clear_search_button.setEnabled(enabled_widgets) window_ui.list_of_runs_label.setEnabled(enabled_widgets) @staticmethod def filter_widget_status(window_ui, enabled_widgets=False): """enable or not all the widgets related to the filter tab""" window_ui.tableWidget.setEnabled(enabled_widgets) window_ui.add_criteria_button.setEnabled(enabled_widgets) window_ui.filter_result_label.setEnabled(enabled_widgets) window_ui.tableWidget_filter_result.setEnabled(enabled_widgets) @staticmethod def check_import_button(parent): window_ui = parent.ui enable_import = False if window_ui.toolBox.currentIndex() == 0: # import everything nbr_row = window_ui.tableWidget_all_runs.rowCount() if nbr_row > 0: enable_import = True else: # rule tab o_gui = FilterResultTableHandler( table_ui=window_ui.tableWidget_filter_result) nbr_row_visible = o_gui.get_number_of_visible_rows() if nbr_row_visible > 0: enable_import = True window_ui.import_button.setEnabled(enable_import) class ImportFromDatabaseTableHandler: def __init__(self, table_ui=None, parent=None): self.table_ui = table_ui self.parent = parent self.parent_parent = parent.parent def refresh_table(self, nexus_json={}): """This function takes the nexus_json returns by ONCat and fill the filter table with only the metadata of interests. Those are defined in the oncat_metadata_filters dictionary (coming from the json config) ex: title, chemical formula, mass density, Sample Env. Device and proton charge """ oncat_metadata_filters = self.parent_parent.oncat_metadata_filters TableHandler.clear_table(self.table_ui) for _row, _json in enumerate(nexus_json): self.table_ui.insertRow(_row) for _column, metadata_filter in enumerate(oncat_metadata_filters): self._set_table_item(json=copy.deepcopy(_json), metadata_filter=metadata_filter, row=_row, col=_column) self.parent.first_time_filling_table = False def _set_table_item(self, json=None, metadata_filter={}, row=-1, col=-1): """Populate the filter metadada table from the oncat json file of only the arguments specified in the config.json file (oncat_metadata_filters)""" table_ui = self.table_ui def _format_proton_charge(raw_proton_charge): _proton_charge = raw_proton_charge / 1e12 return "{:.3}".format(_proton_charge) title = metadata_filter['title'] list_args = metadata_filter["path"] argument_value = json_extractor(json=json, list_args=copy.deepcopy(list_args)) # if title is "Proton Charge" change format of value displayed if title == "Proton Charge (C)": argument_value = _format_proton_charge(argument_value) if table_ui is None: table_ui = self.ui.tableWidget_filter_result if self.parent.first_time_filling_table: table_ui.insertColumn(col) _item_title = QTableWidgetItem(title) table_ui.setHorizontalHeaderItem(col, _item_title) width = metadata_filter["column_width"] table_ui.setColumnWidth(col, width) _item = QTableWidgetItem("{}".format(argument_value)) table_ui.setItem(row, col, _item) def refresh_preview_table(self, nexus_json=[]): """This function takes the nexus_json returns by ONCat using the ONCat template. It will then fill the Preview table to just inform the users of what are the infos of all the runs he is about to import or filter. """ table_ui = self.table_ui TableHandler.clear_table(table_ui) oncat_template = self.parent.oncat_template for _row, json in enumerate(nexus_json): table_ui.insertRow(_row) for _col in oncat_template.keys(): if self.parent.first_time_filling_preview_table: title = oncat_template[_col]['title'] units = oncat_template[_col]['units'] if units: title = "{} ({})".format(title, units) table_ui.insertColumn(_col) _item_title = QTableWidgetItem(title) table_ui.setHorizontalHeaderItem(_col, _item_title) path = oncat_template[_col]['path'] list_path = path.split(".") argument_value = json_extractor( json=json, list_args=copy.deepcopy(list_path)) # used to evaluate expression returned by ONCat if oncat_template[_col]['formula']: # the expression will look like '{value/10e11}' # so value will be replaced by argument_value and the # expression will be evaluated using eval value = argument_value # noqa: F841 argument_value = eval(oncat_template[_col]['formula']) argument_value = argument_value.pop() _item = QTableWidgetItem("{}".format(argument_value)) table_ui.setItem(_row, _col, _item) self.parent.first_time_filling_preview_table = False
{ "repo_name": "neutrons/FastGR", "path": "addie/processing/mantid/master_table/import_from_database/gui_handler.py", "copies": "1", "size": "9368", "license": "mit", "hash": -3790388372458057000, "line_mean": 38.3613445378, "line_max": 111, "alpha_frac": 0.596498719, "autogenerated": false, "ratio": 4.0836965998256325, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0004884194901843659, "num_lines": 238 }
from __future__ import absolute_import, division, print_function from ..qtutil import (mpl_to_qt4_color, symbol_icon, POINT_ICONS, qt4_to_mpl_color) from ...external.qt.QtGui import (QFormLayout, QDialogButtonBox, QColorDialog, QWidget, QLineEdit, QListWidget, QListWidgetItem, QPixmap, QDialog, QLabel, QSpinBox, QComboBox) from ...external.qt.QtCore import QSize, Signal, Qt class ColorWidget(QLabel): mousePressed = Signal() def mousePressEvent(self, event): self.mousePressed.emit() event.accept() class StyleDialog(QDialog): """Dialog which edits the style of a layer (Data or Subset) Use via StyleDialog.edit_style(layer) """ def __init__(self, layer, parent=None, edit_label=True): super(StyleDialog, self).__init__(parent) self.setWindowTitle("Style Editor") self.layer = layer self._edit_label = edit_label self._symbols = list(POINT_ICONS.keys()) self._setup_widgets() self._connect() def _setup_widgets(self): self.layout = QFormLayout() self.size_widget = QSpinBox() self.size_widget.setMinimum(1) self.size_widget.setMaximum(40) self.size_widget.setValue(self.layer.style.markersize) self.label_widget = QLineEdit() self.label_widget.setText(self.layer.label) self.label_widget.selectAll() self.symbol_widget = QComboBox() for idx, symbol in enumerate(self._symbols): icon = symbol_icon(symbol) self.symbol_widget.addItem(icon, '') if symbol is self.layer.style.marker: self.symbol_widget.setCurrentIndex(idx) self.symbol_widget.setIconSize(QSize(20, 20)) self.symbol_widget.setMinimumSize(10, 32) self.color_widget = ColorWidget() self.color_widget.setStyleSheet('ColorWidget {border: 1px solid;}') color = self.layer.style.color color = mpl_to_qt4_color(color, alpha=self.layer.style.alpha) self.set_color(color) self.okcancel = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) if self._edit_label: self.layout.addRow("Label", self.label_widget) self.layout.addRow("Symbol", self.symbol_widget) self.layout.addRow("Color", self.color_widget) self.layout.addRow("Size", self.size_widget) self.layout.addWidget(self.okcancel) self.setLayout(self.layout) self.layout.setContentsMargins(6, 6, 6, 6) def _connect(self): self.color_widget.mousePressed.connect(self.query_color) self.symbol_widget.currentIndexChanged.connect( lambda x: self.set_color(self.color())) self.okcancel.accepted.connect(self.accept) self.okcancel.rejected.connect(self.reject) self.setFocusPolicy(Qt.StrongFocus) def query_color(self, *args): color = QColorDialog.getColor(self._color, self.color_widget, "", QColorDialog.ShowAlphaChannel) if color.isValid(): self.set_color(color) def color(self): return self._color def set_color(self, color): self._color = color pm = symbol_icon(self.symbol(), color).pixmap(30, 30) self.color_widget.setPixmap(pm) def size(self): return self.size_widget.value() def label(self): return str(self.label_widget.text()) def symbol(self): return self._symbols[self.symbol_widget.currentIndex()] def update_style(self): if self._edit_label: self.layer.label = self.label() self.layer.style.color = qt4_to_mpl_color(self.color()) self.layer.style.alpha = self.color().alpha() / 255. self.layer.style.marker = self.symbol() self.layer.style.markersize = self.size() @classmethod def edit_style(cls, layer): self = cls(layer) result = self.exec_() if result == self.Accepted: self.update_style() @classmethod def dropdown_editor(cls, item, pos, **kwargs): """ Create a dropdown-style modal editor to edit the style of a given item :param item: Item with a .label and .style to edit :param pos: A QPoint to anchor the top-left corner of the dropdown at :param kwargs: Extra keywords to pass to StyleDialogs's constructor """ self = cls(item, **kwargs) self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint) pos = self.mapFromGlobal(pos) self.move(pos) if self.exec_() == self.Accepted: self.update_style() if __name__ == "__main__": from glue.core import Data d = Data(label='data label', x=[1, 2, 3, 4]) StyleDialog.edit_style(d) print("New layer properties") print(d.label) print('color: ', d.style.color) print('marker: ', d.style.marker) print('marker size: ', d.style.markersize) print('alpha ', d.style.alpha)
{ "repo_name": "JudoWill/glue", "path": "glue/qt/widgets/style_dialog.py", "copies": "1", "size": "5203", "license": "bsd-3-clause", "hash": -1374483894387904500, "line_mean": 31.9303797468, "line_max": 78, "alpha_frac": 0.6040745724, "autogenerated": false, "ratio": 3.845528455284553, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4949603027684553, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from .regex import RegexDispatcher from .dispatch import dispatch from .compatibility import basestring __all__ = 'resource', 'create_index', 'drop' resource = RegexDispatcher('resource') @resource.register('.*', priority=1) def resource_all(uri, *args, **kwargs): raise NotImplementedError("Unable to parse uri to data resource: " + uri) @resource.register('.+::.+', priority=15) def resource_split(uri, *args, **kwargs): uri, other = uri.rsplit('::', 1) return resource(uri, other, *args, **kwargs) @dispatch(object, (basestring, list, tuple)) def create_index(t, column_name_or_names, name=None): """Create an index on a column. Parameters ---------- o : table-like index_name : str The name of the index to create column_name_or_names : string, list, tuple A column name to index on, or a list or tuple for a composite index Examples -------- >>> # Using SQLite >>> from blaze import SQL >>> # create a table called 'tb', in memory >>> sql = SQL('sqlite:///:memory:', 'tb', ... schema='{id: int64, value: float64, categ: string}') >>> data = [(1, 2.0, 'a'), (2, 3.0, 'b'), (3, 4.0, 'c')] >>> sql.extend(data) >>> # create an index on the 'id' column (for SQL we must provide a name) >>> sql.table.indexes set() >>> create_index(sql, 'id', name='id_index') >>> sql.table.indexes {Index('id_index', Column('id', BigInteger(), table=<tb>, nullable=False))} """ raise NotImplementedError("create_index not implemented for type %r" % type(t).__name__) @dispatch(basestring, (basestring, list, tuple)) def create_index(uri, column_name_or_names, name=None, **kwargs): data = resource(uri, **kwargs) create_index(data, column_name_or_names, name=name) return data @dispatch(object) def drop(rsrc): """Remove a resource. Parameters ---------- rsrc : CSV, SQL, tables.Table, pymongo.Collection A resource that will be removed. For example, calling ``drop(csv)`` will delete the CSV file. Examples -------- >>> # Using SQLite >>> from blaze import SQL, into >>> # create a table called 'tb', in memory >>> sql = SQL('sqlite:///:memory:', 'tb', ... schema='{id: int64, value: float64, categ: string}') >>> data = [(1, 2.0, 'a'), (2, 3.0, 'b'), (3, 4.0, 'c')] >>> sql.extend(data) >>> into(list, sql) [(1, 2.0, 'a'), (2, 3.0, 'b'), (3, 4.0, 'c')] >>> sql.table.exists(sql.engine) True >>> drop(sql) >>> sql.table.exists(sql.engine) False """ raise NotImplementedError("drop not implemented for type %r" % type(rsrc).__name__) @dispatch(basestring) def drop(uri, **kwargs): data = resource(uri, **kwargs) drop(data)
{ "repo_name": "vitan/blaze", "path": "blaze/resource.py", "copies": "1", "size": "2914", "license": "bsd-3-clause", "hash": 9042609296049213000, "line_mean": 29.6736842105, "line_max": 80, "alpha_frac": 0.5837336994, "autogenerated": false, "ratio": 3.5278450363196128, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.960950648803333, "avg_score": 0.0004144495372565548, "num_lines": 95 }
from __future__ import absolute_import, division, print_function from .requests import create_remote_session, close_remote_session, \ add_computed_fields, make_computed_fields, sort, groupby from .rarray import rarray class session: def __init__(self, root_url): """ Creates a remote Blaze compute session with the requested Blaze remote array as the root. """ self.root_url = root_url j = create_remote_session(root_url) self.session_url = j['session'] self.server_version = j['version'] print('Remote Blaze session created at %s' % root_url) print('Remote DyND-Python version: %s' % j['dynd_python_version']) print('Remote DyND version: %s' % j['dynd_version']) def __repr__(self): return 'Blaze Remote Compute Session\n' + \ ' root url: ' + self.root_url + '\n' \ ' session url: ' + self.session_url + '\n' + \ ' server version: ' + self.server_version + '\n' def add_computed_fields(self, arr, fields, rm_fields=[], fnname=None): """ Adds one or more new fields to a struct array. Each field_expr in 'fields' is a string/ast fragment which is called using eval, with the input fields in the locals and numpy/scipy in the globals. arr : rarray A remote array on the server. fields : list of (field_name, field_type, field_expr) These are the fields which are added to 'n'. rm_fields : list of string, optional For fields that are in the input, but have no expression, this removes them from the output struct instead of keeping the value. fnname : string, optional The function name, which affects how the resulting deferred expression dtype is printed. """ j = add_computed_fields(self.session_url, arr.url, fields, rm_fields, fnname) return rarray(j['output'], j['dshape']) def make_computed_fields(self, arr, replace_undim, fields, fnname=None): """ Creates an array with the requested computed fields. If replace_undim is positive, that many uniform dimensions are provided into the field expressions, so the result has fewer dimensions. arr : rarray A remote array on the server. replace_undim : integer The number of uniform dimensions to leave in the input going to the fields. For example if the input has shape (3,4,2) and replace_undim is 1, the result will have shape (3,4), and each operand provided to the field expression will have shape (2). fields : list of (field_name, field_type, field_expr) These are the fields which are added to 'n'. fnname : string, optional The function name, which affects how the resulting deferred expression dtype is printed. """ j = make_computed_fields(self.session_url, arr.url, replace_undim, fields, fnname) return rarray(j['output'], j['dshape']) def sort(self, arr, field): j = sort(self.session_url, arr.url, field) return rarray(j['output'], j['dshape']) def groupby(self, arr, fields): """ Applies a groupby to a struct array based on selected fields. arr : rarray A remote array on the server. fields : list of field names These are the fields which are used for grouping. Returns a tuple of the groupby result and the groups. """ j = groupby(self.session_url, arr.url, fields) return ( rarray(j['output_gb'], j['dshape_gb']), rarray(j['output_groups'], j['dshape_groups'])) def close(self): close_remote_session(self.session_url) self.session_url = None
{ "repo_name": "mwiebe/blaze", "path": "blaze/io/client/session.py", "copies": "6", "size": "4101", "license": "bsd-3-clause", "hash": 6863411319337956000, "line_mean": 39.2058823529, "line_max": 76, "alpha_frac": 0.5798585711, "autogenerated": false, "ratio": 4.312302839116719, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7892161410216719, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from rest_framework import serializers from tests.models import User, Organisation, Membership class UserRegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'full_name', 'password',) extra_kwargs = {'password': {'write_only': True}} class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'full_name', 'password', 'is_active') extra_kwargs = { 'password': {'write_only': True} } read_only_fields = ('is_active',) class ResetPasswordSerializer(serializers.ModelSerializer): id = serializers.CharField() token = serializers.CharField() class Meta: model = User fields = ('id', 'token', 'password',) extra_kwargs = {'password': {'write_only': True}} class MembershipSerializer(serializers.ModelSerializer): class Meta: model = Membership fields = ('joined', 'is_owner', 'role') class CreateOrganisationSerializer(serializers.ModelSerializer): membership_set = MembershipSerializer(many=True) class Meta: model = Organisation fields = ('name', 'slug', 'membership_set') class RetrieveOrganisationSerializer(serializers.ModelSerializer): membership_set = MembershipSerializer() class Meta: model = Organisation fields = ('name', 'slug', 'is_active', 'membership_set') class OrganisationMembersSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() class Meta: model = Membership fields = ('joined', 'user', 'is_owner', 'role') def get_user(self, obj): serializer = UserProfileSerializer(obj.user) return serializer.data class OrganisationErroredSerializer(serializers.ModelSerializer): class Meta: model = Organisation fields = ('name', 'slug', 'is_active') def __init__(self, *args, **kwargs): super(OrganisationErroredSerializer, self).__init__(*args, **kwargs) # Should raise a KeyError self.context["test_value"]
{ "repo_name": "ekonstantinidis/django-rest-framework-docs", "path": "tests/serializers.py", "copies": "2", "size": "2205", "license": "bsd-2-clause", "hash": -8450874022754096000, "line_mean": 26.2222222222, "line_max": 76, "alpha_frac": 0.6557823129, "autogenerated": false, "ratio": 4.427710843373494, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6083493156273494, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from scipy.spatial.distance import pdist, squareform import scipy.sparse as sps from scipy import linalg from scipy.sparse.linalg import eigsh, eigs from nilearn import datasets, plotting from nilearn.input_data import NiftiLabelsMasker, NiftiMapsMasker from nilearn.connectome import ConnectivityMeasure from sklearn.metrics import pairwise_distances import numpy as np import h5py import os def get_atlas(name): if name == "destrieux_2009": atlas = datasets.fetch_atlas_destrieux_2009() atlas_filename = atlas['maps'] elif name == "harvard_oxford": atlas = datasets.fetch_atlas_harvard_oxford("cort-maxprob-thr25-2mm") atlas_filename = atlas['maps'] elif name == "aal": atlas = datasets.fetch_atlas_aal() atlas_filename = atlas['maps'] elif name == "smith_2009": atlas = datasets.fetch_atlas_smith_2009() atlas_filename = atlas['rsn70'] else: raise ValueError('Atlas name unkown') return atlas_filename def extract_correlation_matrix(data_filename, confounds_filename, atlas_name = "destrieux_2009", correlation_type = 'correlation'): atlas_filename = get_atlas(atlas_name) #labels = atlas['labels'] masker = NiftiLabelsMasker(labels_img=atlas_filename, standardize=True) time_series = masker.fit_transform(data_filename, confounds= confounds_filename) correlation_measure = ConnectivityMeasure(kind=correlation_type) correlation_matrix = correlation_measure.fit_transform([time_series])[0] return correlation_matrix def compute_nearest_neighbor_graph(K, n_neighbors=50): idx = np.argsort(K, axis=1) col = idx[:, -n_neighbors:].flatten() row = (np.array(range(K.shape[0]))[:, None] * np.ones((1, n_neighbors))).flatten().astype(int) A1 = sps.csr_matrix((np.ones((len(row))), (row, col)), shape=K.shape) A1 = (A1 + A1.transpose()) > 0 idx1 = A1.nonzero() K = sps.csr_matrix((K.flat[idx1[0]*A1.shape[1] + idx1[1]], A1.indices, A1.indptr)) return K def compute_affinity(X, method='markov', eps=None): D = pairwise_distances(X, metric='euclidean') if eps is None: k = int(max(2, np.round(D.shape[0] * 0.01))) eps = 2 * np.median(np.sort(D, axis=0)[k+1, :])**2 if method == 'markov': affinity_matrix = np.exp(-(D * D) / eps) elif method == 'cauchy': affinity_matrix = 1./(D * D + eps) return affinity_matrix """Generate a diffusion map embedding """ def compute_markov_matrix(L, alpha=0.5, diffusion_time=0, skip_checks=False, overwrite=False): """ Computes a markov transition matrix from the affinity matrix. Code written by Satra Ghosh (https://github.com/satra/mapalign) """ use_sparse = False if sps.issparse(L): use_sparse = True if not skip_checks: from sklearn.manifold.spectral_embedding_ import _graph_is_connected if not _graph_is_connected(L): raise ValueError('Graph is disconnected') ndim = L.shape[0] if overwrite: L_alpha = L else: L_alpha = L.copy() if alpha > 0: # Step 2 d = np.array(L_alpha.sum(axis=1)).flatten() d_alpha = np.power(d, -alpha) if use_sparse: L_alpha.data *= d_alpha[L_alpha.indices] L_alpha = sps.csr_matrix(L_alpha.transpose().toarray()) L_alpha.data *= d_alpha[L_alpha.indices] L_alpha = sps.csr_matrix(L_alpha.transpose().toarray()) else: L_alpha = d_alpha[:, np.newaxis] * L_alpha L_alpha = L_alpha * d_alpha[np.newaxis, :] # Step 3 d_alpha = np.power(np.array(L_alpha.sum(axis=1)).flatten(), -1) if use_sparse: L_alpha.data *= d_alpha[L_alpha.indices] else: L_alpha = d_alpha[:, np.newaxis] * L_alpha return L_alpha def compute_diffusion_map(L, alpha=0.5, n_components=20, diffusion_time=0, skip_checks=False, overwrite=False): """ Code by Satra Ghosh (github.com/satra/mapalign) Compute the diffusion maps of a symmetric similarity matrix L : matrix N x N L is symmetric and L(x, y) >= 0 alpha: float [0, 1] Setting alpha=1 and the diffusion operator approximates the Laplace-Beltrami operator. We then recover the Riemannian geometry of the data set regardless of the distribution of the points. To describe the long-term behavior of the point distribution of a system of stochastic differential equations, we can use alpha=0.5 and the resulting Markov chain approximates the Fokker-Planck diffusion. With alpha=0, it reduces to the classical graph Laplacian normalization. n_components: int The number of diffusion map components to return. Due to the spectrum decay of the eigenvalues, only a few terms are necessary to achieve a given relative accuracy in the sum M^t. diffusion_time: float >= 0 use the diffusion_time (t) step transition matrix M^t t not only serves as a time parameter, but also has the dual role of scale parameter. One of the main ideas of diffusion framework is that running the chain forward in time (taking larger and larger powers of M) reveals the geometric structure of X at larger and larger scales (the diffusion process). t = 0 empirically provides a reasonable balance from a clustering perspective. Specifically, the notion of a cluster in the data set is quantified as a region in which the probability of escaping this region is low (within a certain time t). skip_checks: bool Avoid expensive pre-checks on input data. The caller has to make sure that input data is valid or results will be undefined. overwrite: bool Optimize memory usage by re-using input matrix L as scratch space. References ---------- [1] https://en.wikipedia.org/wiki/Diffusion_map [2] Coifman, R.R.; S. Lafon. (2006). "Diffusion maps". Applied and Computational Harmonic Analysis 21: 5-30. doi:10.1016/j.acha.2006.04.006 """ M = compute_markov_matrix(L, alpha, diffusion_time, skip_checks, overwrite) ndim = L.shape[0] # Step 4 func = eigs if n_components is not None: lambdas, vectors = func(M, k=n_components + 1) else: lambdas, vectors = func(M, k=max(2, int(np.sqrt(ndim)))) del M if func == eigsh: lambdas = lambdas[::-1] vectors = vectors[:, ::-1] else: lambdas = np.real(lambdas) vectors = np.real(vectors) lambda_idx = np.argsort(lambdas)[::-1] lambdas = lambdas[lambda_idx] vectors = vectors[:, lambda_idx] # Step 5 psi = vectors/vectors[:, [0]] olambdas = lambdas.copy() if diffusion_time == 0: lambdas = lambdas[1:] / (1 - lambdas[1:]) else: lambdas = lambdas[1:] ** float(diffusion_time) lambda_ratio = lambdas/lambdas[0] threshold = max(0.05, lambda_ratio[-1]) n_components_auto = np.amax(np.nonzero(lambda_ratio > threshold)[0]) n_components_auto = min(n_components_auto, ndim) if n_components is None: n_components = n_components_auto embedding = psi[:, 1:(n_components + 1)] * lambdas[:n_components][None, :] result = dict(lambdas=lambdas, orig_lambdas = olambdas, vectors=vectors, n_components=n_components, diffusion_time=diffusion_time, n_components_auto=n_components_auto) return embedding, result def save_create_dataset(path_to_node, dset_name, dset_data, f,overwrite): if not(path_to_node+dset_name in f): dset = f[path_to_node].create_dataset(dset_name, dset_data.shape, dtype=dset_data.dtype, data = dset_data) elif overwrite==True: f[path_to_node+dset_name][...]=dset_data else: print("Data " + path_to_node+ dset_name +" exists. Skipping...") def compute_matrices(data_volumes, confounds, subject_ids, runs, output_file = "embeddings.hdf5", overwrite=False): """ Main function to compute low-dimensional representations from preprocessed fMRI volumes """ f = h5py.File(output_file, "a") for i in xrange(len(data_volumes)): subject = subject_ids[i] print("Subject %s" % subject) run = runs[i] print("Run %s" % run) data_name = data_volumes[i] confounds_name = confounds[i] for atlas in ["destrieux_2009", "harvard_oxford", "aal"]: print("Atlas: %s" % atlas) for correlation_measure in ["correlation", "partial correlation", "precision"]: print("Affinity measure: %s" % correlation_measure) path_to_node = str(subject+"/"+run+"/"+atlas+"/"+correlation_measure+"/") if not(path_to_node in f): print("Creating group...") f.create_group(path_to_node) if (overwrite == True) or not(path_to_node+"correlation" in f): correlation_matrix = extract_correlation_matrix(data_name, confounds_name, atlas_name = atlas, correlation_type=correlation_measure) print("Saving...") save_create_dataset(path_to_node, "correlation", correlation_matrix, f, overwrite) if (overwrite == True) or not(path_to_node+"affinity" in f): try: nn = int(round(correlation_matrix.shape[0]*0.1)) print("knn: %d" % nn) nn_mat = compute_nearest_neighbor_graph(correlation_matrix, n_neighbors = nn) nn_mat = np.around(nn_mat.todense(), decimals = 5) E,V = linalg.eigh(nn_mat) except ValueError: E = np.asarray([-1,-1,-1]) if not(any(E < 0)) and (np.all(nn_mat.transpose() == nn_mat)): method='nearest-neighbor' affinity_matrix = nn_mat else: method='affinity' affinity_matrix = compute_affinity(correlation_matrix) print("Saving...") save_create_dataset(path_to_node, "affinity", affinity_matrix, f, overwrite) if not(path_to_node+"affinity_matrix_type" in f): dset= f[path_to_node].create_dataset("affinity_matrix_type", data = method) elif overwrite == True: f[path_to_node+"affinity_matrix_type"][...]=method else: print("Node " + path_to_node+ " affinity_matrix_type exists. Skipping...") if (overwrite == True) or not(path_to_node+"S"): embedding, res = compute_diffusion_map(affinity_matrix) v=res['vectors'] lambdas = res['orig_lambdas'] print("Saving...") save_create_dataset(path_to_node, "S", lambdas, f, overwrite) #dset = sgrp.create_dataset("lambdas", lambdas.shape, dtype=lambdas.dtype) #dset[...]=lambdas #dset = sgrp.create_dataset("v", v.shape, dtype=v.dtype) #dset[...]=v #dset= sgrp.create_dataset("affinity_matrix_type", data = method) f.close()
{ "repo_name": "mfalkiewicz/diffusion_embed", "path": "diffusion_embed/diffusion_embed.py", "copies": "1", "size": "11647", "license": "mit", "hash": -6894142738191903000, "line_mean": 41.3527272727, "line_max": 152, "alpha_frac": 0.5967201855, "autogenerated": false, "ratio": 3.6431029089771663, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4739823094477166, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from sentry.constants import STATUS_CHOICES from sentry.models import EventUser, User from sentry.utils.auth import find_users def get_user_tag(project, key, value): if key == 'id': lookup = 'ident' elif key == 'ip': lookup = 'ip_address' else: lookup = key # TODO(dcramer): do something with case of multiple matches try: euser = EventUser.objects.filter( project=project, **{lookup: value} )[0] except IndexError: return '{}:{}'.format(key, value) return euser.tag_value def parse_query(project, query, user): # TODO(dcramer): handle query being wrapped in quotes tokens = query.split(' ') results = {'tags': {}, 'query': []} tokens_iter = iter(tokens) for token in tokens_iter: # ignore empty tokens if not token: continue if ':' not in token: results['query'].append(token) continue key, value = token.split(':', 1) if not value: results['query'].append(token) continue if value[0] == '"': nvalue = value while nvalue[-1] != '"': try: nvalue = tokens_iter.next() except StopIteration: break value = '%s %s' % (value, nvalue) if value.endswith('"'): value = value[1:-1] else: value = value[1:] if key == 'is': try: results['status'] = STATUS_CHOICES[value] except KeyError: pass elif key == 'assigned': if value == 'me': results['assigned_to'] = user else: try: results['assigned_to'] = find_users(value)[0] except IndexError: # XXX(dcramer): hacky way to avoid showing any results when # an invalid user is entered results['assigned_to'] = User(id=0) elif key == 'first-release': results['first_release'] = value elif key == 'release': results['tags']['sentry:release'] = value elif key == 'user': if ':' in value: comp, value = value.split(':', 1) else: comp = 'id' results['tags']['sentry:user'] = get_user_tag( project, comp, value) elif key.startswith('user.'): results['tags']['sentry:user'] = get_user_tag( project, key.split('.', 1)[1], value) else: results['tags'][key] = value results['query'] = ' '.join(results['query']) return results
{ "repo_name": "Natim/sentry", "path": "src/sentry/search/utils.py", "copies": "1", "size": "2848", "license": "bsd-3-clause", "hash": -619302346856395400, "line_mean": 28.3608247423, "line_max": 79, "alpha_frac": 0.4880617978, "autogenerated": false, "ratio": 4.463949843260188, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5452011641060188, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from sentry.constants import STATUS_CHOICES from sentry.models import User from sentry.utils.auth import find_users def parse_query(query, user): # TODO(dcramer): handle query being wrapped in quotes tokens = query.split(' ') results = {'tags': {}, 'query': []} tokens_iter = iter(tokens) for token in tokens_iter: # ignore empty tokens if not token: continue if ':' not in token: results['query'].append(token) continue key, value = token.split(':', 1) if not value: results['query'].append(token) continue if value[0] == '"': nvalue = value while nvalue[-1] != '"': try: nvalue = tokens_iter.next() except StopIteration: break value = '%s %s' % (value, nvalue) if value.endswith('"'): value = value[1:-1] else: value = value[1:] if key == 'is': try: results['status'] = STATUS_CHOICES[value] except KeyError: pass elif key == 'assigned': if value == 'me': results['assigned_to'] = user else: try: results['assigned_to'] = find_users(value)[0] except IndexError: # XXX(dcramer): hacky way to avoid showing any results when # an invalid user is entered results['assigned_to'] = User(id=0) elif key == 'first-release': results['first_release'] = value elif key == 'release': results['tags']['sentry:release'] = value elif key == 'user': results['tags']['sentry:user'] = value else: results['tags'][key] = value results['query'] = ' '.join(results['query']) return results
{ "repo_name": "felixbuenemann/sentry", "path": "src/sentry/search/utils.py", "copies": "5", "size": "2056", "license": "bsd-3-clause", "hash": 7159864205500770000, "line_mean": 28.7971014493, "line_max": 79, "alpha_frac": 0.4858949416, "autogenerated": false, "ratio": 4.662131519274377, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7648026460874378, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from setuptools import find_packages try: from buildbot_pkg import setup_www_plugin except ImportError: import sys print("Please install buildbot_pkg module in order to install that package, or use the pre-build .whl modules available on pypi", file=sys.stderr) sys.exit(1) setup_www_plugin( name='buildbot_travis', description="Travis CI implemented in Buildbot", long_description=open("README.rst").read(), keywords="buildbot travis ci", url="http://github.com/buildbot/buildbot_travis", author="Buildbot community", author_email="buildbot-devel@lists.sourceforge.net", license="MIT", packages=find_packages(exclude=['ez_setup']), include_package_data=True, zip_safe=False, entry_points={ 'buildbot.travis': [ 'git+poller = buildbot_travis.vcs.git:GitPoller', 'gerrit = buildbot_travis.vcs.gerrit:Gerrit', 'github = buildbot_travis.vcs.github:GitHub', 'gitpb = buildbot_travis.vcs.git:GitPb', # untested 'svn+poller = buildbot_travis.vcs.svn:SVNPoller', ], 'buildbot.www': [ 'buildbot_travis = buildbot_travis.ep:ep' ], 'console_scripts': [ 'bbtravis=buildbot_travis.cmdline:bbtravis', ] }, install_requires=[ 'setuptools', 'buildbot>=0.9.6', # for virtual builders features 'buildbot-www', 'buildbot-console-view', 'buildbot-waterfall-view', 'buildbot-worker', 'klein', 'urwid', 'PyYAML', 'txrequests', 'pyjade', 'txgithub', 'ldap3', 'hyper_sh', 'future' ], )
{ "repo_name": "isotoma/buildbot_travis", "path": "setup.py", "copies": "2", "size": "1764", "license": "apache-2.0", "hash": 753770614715236600, "line_mean": 30.5, "line_max": 150, "alpha_frac": 0.6060090703, "autogenerated": false, "ratio": 3.7136842105263157, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00011825922421948912, "num_lines": 56 }
from __future__ import absolute_import, division, print_function from six import string_types import functools import logging import warnings try: import arrow except ImportError: arrow = None log = logging.getLogger(__name__) def clean_username(username): if not username: return username return username.replace('.', '-') def deprecated(message): def wrap(func): @functools.wraps(func) def wrapped(self, *args, **kwargs): warnings.warn(message, DeprecationWarning, stacklevel=2) return func(self, *args, **kwargs) return wrapped return wrap def dictfilter(d, **kwargs): result = {} if 'get' in kwargs: for key in kwargs['get']: value = d.get(key, None) if value is not None: result[key] = value if 'pop' in kwargs: for key in kwargs['pop']: value = d.pop(key, None) if value is not None: result[key] = value return result def synchronized(f_lock, mode='full'): if mode == 'full': mode = ['acquire', 'release'] elif isinstance(mode, string_types): mode = [mode] def wrap(func): @functools.wraps(func) def wrapped(self, *args, **kwargs): lock = f_lock(self) def acquire(): if 'acquire' not in mode: return lock.acquire() def release(): if 'release' not in mode: return lock.release() # Acquire the lock acquire() try: # Execute wrapped function result = func(self, *args, **kwargs) finally: # Release the lock release() # Return the result return result return wrapped return wrap def try_convert(value, value_type, default=None): try: return value_type(value) except (ValueError, TypeError): return default # # Date/Time Conversion # @deprecated('`from_iso8601(value)` has been renamed to `from_iso8601_datetime(value)`') def from_iso8601(value): return from_iso8601_datetime(value) def from_iso8601_date(value): if value is None: return None if arrow is None: raise Exception('"arrow" module is not available') # Parse ISO8601 datetime dt = arrow.get(value, 'YYYY-MM-DD') # Return date object return dt.date() def from_iso8601_datetime(value): if value is None: return None if arrow is None: raise Exception('"arrow" module is not available') # Parse ISO8601 datetime dt = arrow.get(value, 'YYYY-MM-DDTHH:mm:ss.SZZ') # Convert to UTC dt = dt.to('UTC') # Return datetime object return dt.datetime @deprecated('`to_iso8601(value)` has been renamed to `to_iso8601_datetime(value)`') def to_iso8601(value): return to_iso8601_datetime(value) def to_iso8601_date(value): if value is None: return None return value.strftime('%Y-%m-%d') def to_iso8601_datetime(value): if value is None: return None return value.strftime('%Y-%m-%dT%H:%M:%S') + '.000-00:00'
{ "repo_name": "fuzeman/trakt.py", "path": "trakt/core/helpers.py", "copies": "2", "size": "3281", "license": "mit", "hash": 4145772322449733600, "line_mean": 19.50625, "line_max": 87, "alpha_frac": 0.571167327, "autogenerated": false, "ratio": 4.045622688039457, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00014542748917748918, "num_lines": 160 }
from __future__ import absolute_import, division, print_function from six import with_metaclass from functools import partial from google.protobuf.message import Message from .protobuf import dict_to_protobuf, protobuf_to_dict class Map(dict): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) @classmethod def cast(cls, v): if isinstance(v, Map): return v elif isinstance(v, dict): return Map(**v) # elif hasattr(v, '__iter__'): elif isinstance(v, (list, tuple)): return list(map(cls.cast, v)) else: return v def __setitem__(self, k, v): super(Map, self).__setitem__(k, self.cast(v)) def __setattr__(self, k, v): prop = getattr(self.__class__, k, None) if isinstance(prop, property): # property binding prop.fset(self, v) elif hasattr(v, '__call__'): # method binding self.__dict__[k] = v else: self[k] = v def __getattr__(self, k): try: return self[k] except KeyError: raise AttributeError def __delattr__(self, k): del self[k] def __hash__(self): return hash(tuple(self.items())) class RegisterProxies(type): def __init__(cls, name, bases, nmspc): super(RegisterProxies, cls).__init__(name, bases, nmspc) if not hasattr(cls, 'registry'): cls.registry = [] cls.registry.insert(0, (cls.proto, cls)) # cls.registry -= set(bases) # Remove base classes # Metamethods, called on class objects: def __iter__(cls): return iter(cls.registry) class MessageProxy(with_metaclass(RegisterProxies, Map)): proto = Message decode = partial(protobuf_to_dict, containers=MessageProxy.registry) encode = partial(dict_to_protobuf, containers=MessageProxy.registry, strict=False)
{ "repo_name": "kszucs/proxo", "path": "proxo/messages.py", "copies": "1", "size": "1968", "license": "apache-2.0", "hash": -5771007126150231000, "line_mean": 25.9589041096, "line_max": 68, "alpha_frac": 0.5767276423, "autogenerated": false, "ratio": 3.889328063241107, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4966055705541107, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from spectral_cube import SpectralCube, StokesSpectralCube from glue.core import Data from glue.config import data_factory, qglue_parser from glue.core.data_factories.fits import is_fits from glue.core.coordinates import coordinates_from_wcs __all__ = ['read_spectral_cube', 'parse_spectral_cube'] def is_spectral_cube(filename, **kwargs): """ Check that the file is a 3D or 4D FITS spectral cube """ if not is_fits(filename): return False try: StokesSpectralCube.read(filename) except Exception: return False else: return True def spectral_cube_to_data(cube, label=None): if isinstance(cube, SpectralCube): cube = StokesSpectralCube({'I': cube}) result = Data(label=label) result.coords = coordinates_from_wcs(cube.wcs) for component in cube.components: data = getattr(cube, component).unmasked_data[...] result.add_component(data, label='STOKES {0}'.format(component)) return result @data_factory(label='FITS Spectral Cube', identifier=is_spectral_cube) def read_spectral_cube(filename, **kwargs): """ Read in a FITS spectral cube. If multiple Stokes components are present, these are split into separate glue components. """ cube = StokesSpectralCube.read(filename) return spectral_cube_to_data(cube) @qglue_parser((SpectralCube, StokesSpectralCube)) def parse_spectral_cube(cube, label): return [spectral_cube_to_data(cube, label=label)]
{ "repo_name": "saimn/glue", "path": "glue/plugins/data_factories/spectral_cube/spectral_cube.py", "copies": "5", "size": "1556", "license": "bsd-3-clause", "hash": 6725113911947074000, "line_mean": 26.7857142857, "line_max": 76, "alpha_frac": 0.7030848329, "autogenerated": false, "ratio": 3.6186046511627907, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6821689484062792, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import api_requestor, connect_api_base, error from stripe.six.moves.urllib.parse import urlencode class OAuth(object): @staticmethod def _set_client_id(params): if "client_id" in params: return from stripe import client_id if client_id: params["client_id"] = client_id return raise error.AuthenticationError( "No client_id provided. (HINT: set your client_id using " '"stripe.client_id = <CLIENT-ID>"). You can find your client_ids ' "in your Stripe dashboard at " "https://dashboard.stripe.com/account/applications/settings, " "after registering your account as a platform. See " "https://stripe.com/docs/connect/standalone-accounts for details, " "or email support@stripe.com if you have any questions." ) @staticmethod def authorize_url(express=False, **params): if express is False: path = "/oauth/authorize" else: path = "/express/oauth/authorize" OAuth._set_client_id(params) if "response_type" not in params: params["response_type"] = "code" query = urlencode(list(api_requestor._api_encode(params))) url = connect_api_base + path + "?" + query return url @staticmethod def token(api_key=None, **params): requestor = api_requestor.APIRequestor( api_key, api_base=connect_api_base ) response, _ = requestor.request("post", "/oauth/token", params, None) return response.data @staticmethod def deauthorize(api_key=None, **params): requestor = api_requestor.APIRequestor( api_key, api_base=connect_api_base ) OAuth._set_client_id(params) response, _ = requestor.request( "post", "/oauth/deauthorize", params, None ) return response.data
{ "repo_name": "stripe/stripe-python", "path": "stripe/oauth.py", "copies": "1", "size": "2027", "license": "mit", "hash": -156206948917122400, "line_mean": 32.7833333333, "line_max": 79, "alpha_frac": 0.6008880118, "autogenerated": false, "ratio": 4.062124248496994, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5163012260296994, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import api_requestor, error, util, six from stripe.stripe_object import StripeObject from stripe.six.moves.urllib.parse import quote_plus class APIResource(StripeObject): @classmethod def retrieve(cls, id, api_key=None, **params): instance = cls(id, api_key, **params) instance.refresh() return instance def refresh(self): self.refresh_from(self.request("get", self.instance_url())) return self @classmethod def class_url(cls): if cls == APIResource: raise NotImplementedError( "APIResource is an abstract class. You should perform " "actions on its subclasses (e.g. Charge, Customer)" ) # Namespaces are separated in object names with periods (.) and in URLs # with forward slashes (/), so replace the former with the latter. base = cls.OBJECT_NAME.replace(".", "/") return "/v1/%ss" % (base,) def instance_url(self): id = self.get("id") if not isinstance(id, six.string_types): raise error.InvalidRequestError( "Could not determine which URL to request: %s instance " "has invalid ID: %r, %s. ID should be of type `str` (or" " `unicode`)" % (type(self).__name__, id, type(id)), "id", ) id = util.utf8(id) base = self.class_url() extn = quote_plus(id) return "%s/%s" % (base, extn) # The `method_` and `url_` arguments are suffixed with an underscore to # avoid conflicting with actual request parameters in `params`. @classmethod def _static_request( cls, method_, url_, api_key=None, idempotency_key=None, stripe_version=None, stripe_account=None, **params ): requestor = api_requestor.APIRequestor( api_key, api_version=stripe_version, account=stripe_account ) headers = util.populate_headers(idempotency_key) response, api_key = requestor.request(method_, url_, params, headers) return util.convert_to_stripe_object( response, api_key, stripe_version, stripe_account ) # The `method_` and `url_` arguments are suffixed with an underscore to # avoid conflicting with actual request parameters in `params`. @classmethod def _static_request_stream( cls, method_, url_, api_key=None, idempotency_key=None, stripe_version=None, stripe_account=None, **params ): requestor = api_requestor.APIRequestor( api_key, api_version=stripe_version, account=stripe_account ) headers = util.populate_headers(idempotency_key) response, _ = requestor.request_stream(method_, url_, params, headers) return response
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/abstract/api_resource.py", "copies": "1", "size": "2975", "license": "mit", "hash": -4651945846926117000, "line_mean": 33.1954022989, "line_max": 79, "alpha_frac": 0.5959663866, "autogenerated": false, "ratio": 4.0476190476190474, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 87 }
from __future__ import absolute_import, division, print_function from stripe import api_requestor from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import ListableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import custom_method from stripe.api_resources.abstract import nested_resource_class_methods @custom_method("delete_discount", http_verb="delete", http_path="discount") @nested_resource_class_methods( "balance_transaction", operations=["create", "retrieve", "update", "list"], ) @nested_resource_class_methods( "source", operations=["create", "retrieve", "update", "delete", "list"], ) @nested_resource_class_methods( "tax_id", operations=["create", "retrieve", "delete", "list"], ) class Customer( CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource, ): OBJECT_NAME = "customer" def delete_discount(self, **params): requestor = api_requestor.APIRequestor( self.api_key, api_version=self.stripe_version, account=self.stripe_account, ) url = self.instance_url() + "/discount" _, api_key = requestor.request("delete", url, params) self.refresh_from({"discount": None}, api_key, True)
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/customer.py", "copies": "1", "size": "1432", "license": "mit", "hash": -1734775154573042000, "line_mean": 33.9268292683, "line_max": 75, "alpha_frac": 0.7108938547, "autogenerated": false, "ratio": 3.8085106382978724, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5019404492997872, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import api_requestor from stripe import util from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import ListableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import custom_method @custom_method("finalize_invoice", http_verb="post", http_path="finalize") @custom_method("mark_uncollectible", http_verb="post") @custom_method("pay", http_verb="post") @custom_method("send_invoice", http_verb="post", http_path="send") @custom_method("void_invoice", http_verb="post", http_path="void") class Invoice( CreateableAPIResource, DeletableAPIResource, ListableAPIResource, UpdateableAPIResource, ): OBJECT_NAME = "invoice" def finalize_invoice(self, idempotency_key=None, **params): url = self.instance_url() + "/finalize" headers = util.populate_headers(idempotency_key) self.refresh_from(self.request("post", url, params, headers)) return self def mark_uncollectible(self, idempotency_key=None, **params): url = self.instance_url() + "/mark_uncollectible" headers = util.populate_headers(idempotency_key) self.refresh_from(self.request("post", url, params, headers)) return self def pay(self, idempotency_key=None, **params): url = self.instance_url() + "/pay" headers = util.populate_headers(idempotency_key) self.refresh_from(self.request("post", url, params, headers)) return self def send_invoice(self, idempotency_key=None, **params): url = self.instance_url() + "/send" headers = util.populate_headers(idempotency_key) self.refresh_from(self.request("post", url, params, headers)) return self def void_invoice(self, idempotency_key=None, **params): url = self.instance_url() + "/void" headers = util.populate_headers(idempotency_key) self.refresh_from(self.request("post", url, params, headers)) return self @classmethod def upcoming( cls, api_key=None, stripe_version=None, stripe_account=None, **params ): requestor = api_requestor.APIRequestor( api_key, api_version=stripe_version, account=stripe_account ) url = cls.class_url() + "/upcoming" response, api_key = requestor.request("get", url, params) return util.convert_to_stripe_object( response, api_key, stripe_version, stripe_account )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/invoice.py", "copies": "1", "size": "2646", "license": "mit", "hash": 4288284793918003000, "line_mean": 39.0909090909, "line_max": 77, "alpha_frac": 0.6836734694, "autogenerated": false, "ratio": 3.649655172413793, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9833328641813793, "avg_score": 0, "num_lines": 66 }
from __future__ import absolute_import, division, print_function from stripe import api_requestor from stripe import util from stripe.api_resources.abstract import DeletableAPIResource class EphemeralKey(DeletableAPIResource): OBJECT_NAME = "ephemeral_key" @classmethod def create( cls, api_key=None, idempotency_key=None, stripe_version=None, stripe_account=None, **params ): if stripe_version is None: raise ValueError( "stripe_version must be specified to create an ephemeral " "key" ) requestor = api_requestor.APIRequestor( api_key, api_version=stripe_version, account=stripe_account ) url = cls.class_url() headers = util.populate_headers(idempotency_key) response, api_key = requestor.request("post", url, params, headers) return util.convert_to_stripe_object( response, api_key, stripe_version, stripe_account )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/ephemeral_key.py", "copies": "1", "size": "1034", "license": "mit", "hash": -8593430235595291000, "line_mean": 28.5428571429, "line_max": 75, "alpha_frac": 0.6266924565, "autogenerated": false, "ratio": 4.0549019607843135, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5181594417284313, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import api_requestor, six, util from stripe.stripe_object import StripeObject from stripe.six.moves.urllib.parse import quote_plus class ListObject(StripeObject): OBJECT_NAME = "list" def list( self, api_key=None, stripe_version=None, stripe_account=None, **params ): stripe_object = self._request( "get", self.get("url"), api_key=api_key, stripe_version=stripe_version, stripe_account=stripe_account, **params ) stripe_object._retrieve_params = params return stripe_object def create( self, api_key=None, idempotency_key=None, stripe_version=None, stripe_account=None, **params ): return self._request( "post", self.get("url"), api_key=api_key, idempotency_key=idempotency_key, stripe_version=stripe_version, stripe_account=stripe_account, **params ) def retrieve( self, id, api_key=None, stripe_version=None, stripe_account=None, **params ): url = "%s/%s" % (self.get("url"), quote_plus(util.utf8(id))) return self._request( "get", url, api_key=api_key, stripe_version=stripe_version, stripe_account=stripe_account, **params ) def _request( self, method_, url_, api_key=None, idempotency_key=None, stripe_version=None, stripe_account=None, **params ): api_key = api_key or self.api_key stripe_version = stripe_version or self.stripe_version stripe_account = stripe_account or self.stripe_account requestor = api_requestor.APIRequestor( api_key, api_version=stripe_version, account=stripe_account ) headers = util.populate_headers(idempotency_key) response, api_key = requestor.request(method_, url_, params, headers) stripe_object = util.convert_to_stripe_object( response, api_key, stripe_version, stripe_account ) return stripe_object def __getitem__(self, k): if isinstance(k, six.string_types): return super(ListObject, self).__getitem__(k) else: raise KeyError( "You tried to access the %s index, but ListObject types only " "support string keys. (HINT: List calls return an object with " "a 'data' (which is the data array). You likely want to call " ".data[%s])" % (repr(k), repr(k)) ) def __iter__(self): return getattr(self, "data", []).__iter__() def __len__(self): return getattr(self, "data", []).__len__() def __reversed__(self): return getattr(self, "data", []).__reversed__() def auto_paging_iter(self): page = self while True: if ( "ending_before" in self._retrieve_params and "starting_after" not in self._retrieve_params ): for item in reversed(page): yield item page = page.previous_page() else: for item in page: yield item page = page.next_page() if page.is_empty: break @classmethod def empty_list( cls, api_key=None, stripe_version=None, stripe_account=None ): return cls.construct_from( {"data": []}, key=api_key, stripe_version=stripe_version, stripe_account=stripe_account, last_response=None, ) @property def is_empty(self): return not self.data def next_page( self, api_key=None, stripe_version=None, stripe_account=None, **params ): if not self.has_more: return self.empty_list( api_key=api_key, stripe_version=stripe_version, stripe_account=stripe_account, ) last_id = self.data[-1].id params_with_filters = self._retrieve_params.copy() params_with_filters.update({"starting_after": last_id}) params_with_filters.update(params) return self.list( api_key=api_key, stripe_version=stripe_version, stripe_account=stripe_account, **params_with_filters ) def previous_page( self, api_key=None, stripe_version=None, stripe_account=None, **params ): if not self.has_more: return self.empty_list( api_key=api_key, stripe_version=stripe_version, stripe_account=stripe_account, ) first_id = self.data[0].id params_with_filters = self._retrieve_params.copy() params_with_filters.update({"ending_before": first_id}) params_with_filters.update(params) return self.list( api_key=api_key, stripe_version=stripe_version, stripe_account=stripe_account, **params_with_filters )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/list_object.py", "copies": "1", "size": "5374", "license": "mit", "hash": 494737141300167550, "line_mean": 28.0486486486, "line_max": 79, "alpha_frac": 0.5349832527, "autogenerated": false, "ratio": 4.022455089820359, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.505743834252036, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import api_requestor, util from stripe.api_resources.abstract.api_resource import APIResource class UsageRecord(APIResource): OBJECT_NAME = "usage_record" @classmethod def create( cls, api_key=None, idempotency_key=None, stripe_version=None, stripe_account=None, **params ): if "subscription_item" not in params: raise ValueError("Params must have a subscription_item key") subscription_item = params.pop("subscription_item") requestor = api_requestor.APIRequestor( api_key, api_version=stripe_version, account=stripe_account ) url = "/v1/subscription_items/%s/usage_records" % subscription_item headers = util.populate_headers(idempotency_key) response, api_key = requestor.request("post", url, params, headers) return util.convert_to_stripe_object( response, api_key, stripe_version, stripe_account )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/usage_record.py", "copies": "1", "size": "1059", "license": "mit", "hash": -3674553377394932000, "line_mean": 31.0909090909, "line_max": 75, "alpha_frac": 0.6543909348, "autogenerated": false, "ratio": 3.966292134831461, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5120683069631461, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import api_requestor, util from stripe.six.moves.urllib.parse import quote_plus def nested_resource_class_methods( resource, path=None, operations=None, resource_plural=None ): if resource_plural is None: resource_plural = "%ss" % resource if path is None: path = resource_plural if operations is None: raise ValueError("operations list required") def wrapper(cls): def nested_resource_url(cls, id, nested_id=None): url = "%s/%s/%s" % ( cls.class_url(), quote_plus(id), quote_plus(path), ) if nested_id is not None: url += "/%s" % quote_plus(nested_id) return url resource_url_method = "%ss_url" % resource setattr(cls, resource_url_method, classmethod(nested_resource_url)) def nested_resource_request( cls, method, url, api_key=None, idempotency_key=None, stripe_version=None, stripe_account=None, **params ): requestor = api_requestor.APIRequestor( api_key, api_version=stripe_version, account=stripe_account ) headers = util.populate_headers(idempotency_key) response, api_key = requestor.request(method, url, params, headers) return util.convert_to_stripe_object( response, api_key, stripe_version, stripe_account ) resource_request_method = "%ss_request" % resource setattr( cls, resource_request_method, classmethod(nested_resource_request) ) for operation in operations: if operation == "create": def create_nested_resource(cls, id, **params): url = getattr(cls, resource_url_method)(id) return getattr(cls, resource_request_method)( "post", url, **params ) create_method = "create_%s" % resource setattr( cls, create_method, classmethod(create_nested_resource) ) elif operation == "retrieve": def retrieve_nested_resource(cls, id, nested_id, **params): url = getattr(cls, resource_url_method)(id, nested_id) return getattr(cls, resource_request_method)( "get", url, **params ) retrieve_method = "retrieve_%s" % resource setattr( cls, retrieve_method, classmethod(retrieve_nested_resource) ) elif operation == "update": def modify_nested_resource(cls, id, nested_id, **params): url = getattr(cls, resource_url_method)(id, nested_id) return getattr(cls, resource_request_method)( "post", url, **params ) modify_method = "modify_%s" % resource setattr( cls, modify_method, classmethod(modify_nested_resource) ) elif operation == "delete": def delete_nested_resource(cls, id, nested_id, **params): url = getattr(cls, resource_url_method)(id, nested_id) return getattr(cls, resource_request_method)( "delete", url, **params ) delete_method = "delete_%s" % resource setattr( cls, delete_method, classmethod(delete_nested_resource) ) elif operation == "list": def list_nested_resources(cls, id, **params): url = getattr(cls, resource_url_method)(id) return getattr(cls, resource_request_method)( "get", url, **params ) list_method = "list_%s" % resource_plural setattr(cls, list_method, classmethod(list_nested_resources)) else: raise ValueError("Unknown operation: %s" % operation) return cls return wrapper
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/abstract/nested_resource_class_methods.py", "copies": "1", "size": "4357", "license": "mit", "hash": -1348931905863878000, "line_mean": 34.1370967742, "line_max": 79, "alpha_frac": 0.5118200597, "autogenerated": false, "ratio": 4.684946236559139, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 124 }
from __future__ import absolute_import, division, print_function from stripe import error from stripe import util from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import VerifyMixin from stripe.api_resources.account import Account from stripe.api_resources.customer import Customer from stripe.six.moves.urllib.parse import quote_plus class BankAccount(DeletableAPIResource, UpdateableAPIResource, VerifyMixin): OBJECT_NAME = "bank_account" def instance_url(self): token = util.utf8(self.id) extn = quote_plus(token) if hasattr(self, "customer"): customer = util.utf8(self.customer) base = Customer.class_url() owner_extn = quote_plus(customer) class_base = "sources" elif hasattr(self, "account"): account = util.utf8(self.account) base = Account.class_url() owner_extn = quote_plus(account) class_base = "external_accounts" else: raise error.InvalidRequestError( "Could not determine whether bank_account_id %s is " "attached to a customer or an account." % token, "id", ) return "%s/%s/%s/%s" % (base, owner_extn, class_base, extn) @classmethod def modify(cls, sid, **params): raise NotImplementedError( "Can't modify a bank account without a customer or account ID. " "Call save on customer.sources.retrieve('bank_account_id') or " "account.external_accounts.retrieve('bank_account_id') instead." ) @classmethod def retrieve( cls, id, api_key=None, stripe_version=None, stripe_account=None, **params ): raise NotImplementedError( "Can't retrieve a bank account without a customer or account ID. " "Use customer.sources.retrieve('bank_account_id') or " "account.external_accounts.retrieve('bank_account_id') instead." )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/bank_account.py", "copies": "1", "size": "2143", "license": "mit", "hash": 1363179753098697000, "line_mean": 33.0158730159, "line_max": 78, "alpha_frac": 0.6290247317, "autogenerated": false, "ratio": 4.169260700389105, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 63 }
from __future__ import absolute_import, division, print_function from stripe import error from stripe import util from stripe.api_resources import Customer from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import VerifyMixin from stripe.api_resources.abstract import nested_resource_class_methods from stripe.six.moves.urllib.parse import quote_plus @nested_resource_class_methods("source_transaction", operations=["list"]) class Source(CreateableAPIResource, UpdateableAPIResource, VerifyMixin): OBJECT_NAME = "source" def detach(self, idempotency_key=None, **params): token = util.utf8(self.id) if hasattr(self, "customer") and self.customer: extn = quote_plus(token) customer = util.utf8(self.customer) base = Customer.class_url() owner_extn = quote_plus(customer) url = "%s/%s/sources/%s" % (base, owner_extn, extn) headers = util.populate_headers(idempotency_key) self.refresh_from(self.request("delete", url, params, headers)) return self else: raise error.InvalidRequestError( "Source %s does not appear to be currently attached " "to a customer object." % token, "id", ) def source_transactions(self, **params): """source_transactions is deprecated, use Source.list_source_transactions instead.""" return self.request( "get", self.instance_url() + "/source_transactions", params )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/source.py", "copies": "1", "size": "1650", "license": "mit", "hash": 6010186626070241000, "line_mean": 38.2857142857, "line_max": 93, "alpha_frac": 0.6666666667, "autogenerated": false, "ratio": 4.135338345864661, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5302005012564661, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import ListableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import custom_method @custom_method("attach", http_verb="post") @custom_method("detach", http_verb="post") class PaymentMethod( CreateableAPIResource, ListableAPIResource, UpdateableAPIResource, ): OBJECT_NAME = "payment_method" def attach(self, idempotency_key=None, **params): url = self.instance_url() + "/attach" headers = util.populate_headers(idempotency_key) self.refresh_from(self.request("post", url, params, headers)) return self def detach(self, idempotency_key=None, **params): url = self.instance_url() + "/detach" headers = util.populate_headers(idempotency_key) self.refresh_from(self.request("post", url, params, headers)) return self
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/payment_method.py", "copies": "1", "size": "1058", "license": "mit", "hash": -5878034319708689000, "line_mean": 35.4827586207, "line_max": 69, "alpha_frac": 0.7221172023, "autogenerated": false, "ratio": 3.7785714285714285, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5000688630871428, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.customer import Customer from stripe.six.moves.urllib.parse import quote_plus class AlipayAccount(DeletableAPIResource, UpdateableAPIResource): OBJECT_NAME = "alipay_account" @classmethod def _build_instance_url(cls, customer, sid): token = util.utf8(sid) extn = quote_plus(token) customer = util.utf8(customer) base = Customer.class_url() owner_extn = quote_plus(customer) return "%s/%s/sources/%s" % (base, owner_extn, extn) def instance_url(self): return self._build_instance_url(self.customer, self.id) @classmethod def modify(cls, customer, id, **params): url = cls._build_instance_url(customer, id) return cls._static_request("post", url, **params) @classmethod def retrieve( cls, id, api_key=None, stripe_version=None, stripe_account=None, **params ): raise NotImplementedError( "Can't retrieve an Alipay account without a customer ID. " "Use customer.sources.retrieve('alipay_account_id') instead." )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/alipay_account.py", "copies": "1", "size": "1356", "license": "mit", "hash": -3297844570801561000, "line_mean": 29.8181818182, "line_max": 73, "alpha_frac": 0.6615044248, "autogenerated": false, "ratio": 3.8413597733711047, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5002864198171104, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.account import Account from stripe.six.moves.urllib.parse import quote_plus class Person(UpdateableAPIResource): OBJECT_NAME = "person" def instance_url(self): token = util.utf8(self.id) account = util.utf8(self.account) base = Account.class_url() acct_extn = quote_plus(account) extn = quote_plus(token) return "%s/%s/persons/%s" % (base, acct_extn, extn) @classmethod def modify(cls, sid, **params): raise NotImplementedError( "Can't modify a person without an account" "ID. Call save on account.persons.retrieve('person_id')" ) @classmethod def retrieve(cls, id, api_key=None, **params): raise NotImplementedError( "Can't retrieve a person without an account" "ID. Use account.persons.retrieve('person_id')" )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/person.py", "copies": "1", "size": "1050", "license": "mit", "hash": 1521282207184414500, "line_mean": 31.8125, "line_max": 68, "alpha_frac": 0.6533333333, "autogenerated": false, "ratio": 3.888888888888889, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5042222222188889, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.transfer import Transfer from stripe.six.moves.urllib.parse import quote_plus class Reversal(UpdateableAPIResource): OBJECT_NAME = "transfer_reversal" def instance_url(self): token = util.utf8(self.id) transfer = util.utf8(self.transfer) base = Transfer.class_url() cust_extn = quote_plus(transfer) extn = quote_plus(token) return "%s/%s/reversals/%s" % (base, cust_extn, extn) @classmethod def modify(cls, sid, **params): raise NotImplementedError( "Can't modify a reversal without a transfer" "ID. Call save on transfer.reversals.retrieve('reversal_id')" ) @classmethod def retrieve(cls, id, api_key=None, **params): raise NotImplementedError( "Can't retrieve a reversal without a transfer" "ID. Use transfer.reversals.retrieve('reversal_id')" )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/reversal.py", "copies": "1", "size": "1085", "license": "mit", "hash": 4915966306517254000, "line_mean": 32.90625, "line_max": 73, "alpha_frac": 0.66359447, "autogenerated": false, "ratio": 3.7937062937062938, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9957300763706294, "avg_score": 0, "num_lines": 32 }
from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources.account import Account from stripe.api_resources.abstract import UpdateableAPIResource from stripe.six.moves.urllib.parse import quote_plus class Capability(UpdateableAPIResource): OBJECT_NAME = "capability" def instance_url(self): token = util.utf8(self.id) account = util.utf8(self.account) base = Account.class_url() acct_extn = quote_plus(account) extn = quote_plus(token) return "%s/%s/capabilities/%s" % (base, acct_extn, extn) @classmethod def modify(cls, sid, **params): raise NotImplementedError( "Can't update a capability without an account ID. Update a capability using " "account.modify_capability('acct_123', 'acap_123', params)" ) @classmethod def retrieve(cls, id, api_key=None, **params): raise NotImplementedError( "Can't retrieve a capability without an account ID. Retrieve a capability using " "account.retrieve_capability('acct_123', 'acap_123')" )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/capability.py", "copies": "1", "size": "1144", "license": "mit", "hash": -1339937430737975300, "line_mean": 34.75, "line_max": 93, "alpha_frac": 0.6660839161, "autogenerated": false, "ratio": 3.958477508650519, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5124561424750519, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources import ApplicationFee from stripe.api_resources.abstract import UpdateableAPIResource from stripe.six.moves.urllib.parse import quote_plus class ApplicationFeeRefund(UpdateableAPIResource): OBJECT_NAME = "fee_refund" @classmethod def _build_instance_url(cls, fee, sid): fee = util.utf8(fee) sid = util.utf8(sid) base = ApplicationFee.class_url() cust_extn = quote_plus(fee) extn = quote_plus(sid) return "%s/%s/refunds/%s" % (base, cust_extn, extn) @classmethod def modify(cls, fee, sid, **params): url = cls._build_instance_url(fee, sid) return cls._static_request("post", url, **params) def instance_url(self): return self._build_instance_url(self.fee, self.id) @classmethod def retrieve(cls, id, api_key=None, **params): raise NotImplementedError( "Can't retrieve a refund without an application fee ID. " "Use application_fee.refunds.retrieve('refund_id') instead." )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/application_fee_refund.py", "copies": "1", "size": "1138", "license": "mit", "hash": 1133513525815358000, "line_mean": 32.4705882353, "line_max": 72, "alpha_frac": 0.6616871705, "autogenerated": false, "ratio": 3.624203821656051, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.978589099215605, "avg_score": 0, "num_lines": 34 }
from __future__ import absolute_import, division, print_function from stripe import util from stripe.six.moves.urllib.parse import quote_plus def custom_method(name, http_verb, http_path=None, is_streaming=False): if http_verb not in ["get", "post", "delete"]: raise ValueError( "Invalid http_verb: %s. Must be one of 'get', 'post' or 'delete'" % http_verb ) if http_path is None: http_path = name def wrapper(cls): def custom_method_request(cls, sid, **params): url = "%s/%s/%s" % ( cls.class_url(), quote_plus(util.utf8(sid)), http_path, ) return cls._static_request(http_verb, url, **params) def custom_method_request_stream(cls, sid, **params): url = "%s/%s/%s" % ( cls.class_url(), quote_plus(util.utf8(sid)), http_path, ) return cls._static_request_stream(http_verb, url, **params) if is_streaming: class_method_impl = classmethod(custom_method_request_stream) else: class_method_impl = classmethod(custom_method_request) existing_method = getattr(cls, name, None) if existing_method is None: setattr(cls, name, class_method_impl) else: # If a method with the same name we want to use already exists on # the class, we assume it's an instance method. In this case, the # new class method is prefixed with `_cls_`, and the original # instance method is decorated with `util.class_method_variant` so # that the new class method is called when the original method is # called as a class method. setattr(cls, "_cls_" + name, class_method_impl) instance_method = util.class_method_variant("_cls_" + name)( existing_method ) setattr(cls, name, instance_method) return cls return wrapper
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/abstract/custom_method.py", "copies": "1", "size": "2064", "license": "mit", "hash": 1667774437511122700, "line_mean": 35.8571428571, "line_max": 78, "alpha_frac": 0.5615310078, "autogenerated": false, "ratio": 4.111553784860558, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5173084792660557, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe.six.moves.urllib.parse import parse_qs, urlparse import stripe class TestOAuth(object): def test_authorize_url(self, request_mock): url = stripe.OAuth.authorize_url( scope="read_write", state="csrf_token", stripe_user={ "email": "test@example.com", "url": "https://example.com/profile/test", "country": "US", }, ) o = urlparse(url) params = parse_qs(o.query) url_express = stripe.OAuth.authorize_url( express=True, scope="read_write", state="csrf_token" ) o_express = urlparse(url_express) assert o.scheme == "https" assert o.netloc == "connect.stripe.com" assert o.path == "/oauth/authorize" assert o_express.path == "/express/oauth/authorize" assert params["client_id"] == ["ca_123"] assert params["scope"] == ["read_write"] assert params["stripe_user[email]"] == ["test@example.com"] assert params["stripe_user[url]"] == [ "https://example.com/profile/test" ] assert params["stripe_user[country]"] == ["US"] def test_token(self, request_mock): request_mock.stub_request( "post", "/oauth/token", { "access_token": "sk_access_token", "scope": "read_only", "livemode": "false", "token_type": "bearer", "refresh_token": "sk_refresh_token", "stripe_user_id": "acct_test", "stripe_publishable_key": "pk_test", }, ) resp = stripe.OAuth.token( grant_type="authorization_code", code="this_is_an_authorization_code", ) request_mock.assert_requested( "post", "/oauth/token", { "grant_type": "authorization_code", "code": "this_is_an_authorization_code", }, ) assert resp["access_token"] == "sk_access_token" def test_deauthorize(self, request_mock): request_mock.stub_request( "post", "/oauth/deauthorize", {"stripe_user_id": "acct_test_deauth"}, ) resp = stripe.OAuth.deauthorize(stripe_user_id="acct_test_deauth") request_mock.assert_requested( "post", "/oauth/deauthorize", {"client_id": "ca_123", "stripe_user_id": "acct_test_deauth"}, ) assert resp["stripe_user_id"] == "acct_test_deauth"
{ "repo_name": "stripe/stripe-python", "path": "tests/test_oauth.py", "copies": "1", "size": "2682", "license": "mit", "hash": -7411726626742459000, "line_mean": 31.7073170732, "line_max": 74, "alpha_frac": 0.514541387, "autogenerated": false, "ratio": 3.8757225433526012, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4890263930352601, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from stripe.util import merge_dicts from stripe.stripe_object import StripeObject class ErrorObject(StripeObject): def refresh_from( self, values, api_key=None, partial=False, stripe_version=None, stripe_account=None, last_response=None, ): # Unlike most other API resources, the API will omit attributes in # error objects when they have a null value. We manually set default # values here to facilitate generic error handling. values = merge_dicts( { "charge": None, "code": None, "decline_code": None, "doc_url": None, "message": None, "param": None, "payment_intent": None, "payment_method": None, "setup_intent": None, "source": None, "type": None, }, values, ) return super(ErrorObject, self).refresh_from( values, api_key, partial, stripe_version, stripe_account, last_response, ) class OAuthErrorObject(StripeObject): def refresh_from( self, values, api_key=None, partial=False, stripe_version=None, stripe_account=None, last_response=None, ): # Unlike most other API resources, the API will omit attributes in # error objects when they have a null value. We manually set default # values here to facilitate generic error handling. values = merge_dicts( {"error": None, "error_description": None}, values ) return super(OAuthErrorObject, self).refresh_from( values, api_key, partial, stripe_version, stripe_account, last_response, )
{ "repo_name": "stripe/stripe-python", "path": "stripe/api_resources/error_object.py", "copies": "1", "size": "2019", "license": "mit", "hash": 5452032578480393000, "line_mean": 28.2608695652, "line_max": 76, "alpha_frac": 0.52897474, "autogenerated": false, "ratio": 4.567873303167421, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5596848043167421, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from subprocess import check_call from graphviz import Digraph from .core import istask, get_dependencies, ishashable def task_label(task): """Label for a task on a dot graph. Examples -------- >>> from operator import add >>> task_label((add, 1, 2)) 'add' >>> task_label((add, (add, 1, 2), 3)) 'add(...)' """ func = task[0] if hasattr(func, 'funcs'): if len(func.funcs) > 1: return '{0}(...)'.format(funcname(func.funcs[0])) else: head = funcname(func.funcs[0]) else: head = funcname(task[0]) if any(has_sub_tasks(i) for i in task[1:]): return '{0}(...)'.format(head) else: return head def has_sub_tasks(task): """Returns True if the task has sub tasks""" if istask(task): return True elif isinstance(task, list): return any(has_sub_tasks(i) for i in task) else: return False def funcname(func): """Get the name of a function.""" while hasattr(func, 'func'): func = func.func return func.__name__ def name(x): try: return str(hash(x)) except TypeError: return str(hash(str(x))) def to_graphviz(dsk, data_attributes=None, function_attributes=None): if data_attributes is None: data_attributes = {} if function_attributes is None: function_attributes = {} g = Digraph(graph_attr={'rankdir': 'BT'}) seen = set() for k, v in dsk.items(): k_name = name(k) if k_name not in seen: seen.add(k_name) g.node(k_name, label=str(k), shape='box', **data_attributes.get(k, {})) if istask(v): func_name = name((k, 'function')) if func_name not in seen: seen.add(func_name) g.node(func_name, label=task_label(v), shape='circle', **function_attributes.get(k, {})) g.edge(func_name, k_name) for dep in get_dependencies(dsk, k): dep_name = name(dep) if dep_name not in seen: seen.add(dep_name) g.node(dep_name, label=str(dep), shape='box', **data_attributes.get(dep, {})) g.edge(dep_name, func_name) elif ishashable(v) and v in dsk: g.edge(name(v), k_name) return g def dot_graph(dsk, filename='mydask', **kwargs): g = to_graphviz(dsk, **kwargs) g.save(filename + '.dot') check_call('dot -Tpdf {0}.dot -o {0}.pdf'.format(filename), shell=True) check_call('dot -Tpng {0}.dot -o {0}.png'.format(filename), shell=True) try: from IPython.display import Image return Image(filename + '.png') except ImportError: pass
{ "repo_name": "simudream/dask", "path": "dask/dot.py", "copies": "4", "size": "2877", "license": "bsd-3-clause", "hash": 5247927080170826000, "line_mean": 26.141509434, "line_max": 75, "alpha_frac": 0.5404935697, "autogenerated": false, "ratio": 3.5300613496932516, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6070554919393252, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from sunpy.image.transform import affine_transform import numpy as np from skimage import transform as tf import skimage.data as images import pytest from sunpy.extern.six.moves import range, zip # Define test image first so it's accessible to all functions. original = images.camera().astype('float') # Tolerance for tests rtol = 1.0e-15 @pytest.fixture def identity(): return np.array([[1, 0], [0, 1]]) def compare_results(expect, result, allclose=True): """ Function to check that the obtained results are what was expected, to within the relative tolerance defined above. """ # Outermost pixels can contain artefacts which will be ignored. exp = expect[1:-1, 1:-1] res = result[1:-1, 1:-1] t1 = abs(exp.mean() - res.mean()) <= rtol*exp.mean() #Don't do the allclose test for scipy as the bicubic algorithm has edge effects if allclose: t2 = np.allclose(exp, res, rtol=rtol) #TODO: Develop a better way of testing this else: t2 = True return t1 and t2 @pytest.mark.parametrize("angle, k", [(90.0, 1), (-90.0, -1), (-270.0, 1), (-90.0, 3), (360.0, 0), (-360.0, 0)]) def test_rotation(angle, k): # Test rotation against expected outcome angle = np.radians(angle) c = np.cos(angle); s = np.sin(angle) rmatrix = np.array([[c, -s], [s, c]]) expected = np.rot90(original, k=k) #Run the tests at order 4 as it produces more accurate 90 deg rotations rot = affine_transform(original, order=4, rmatrix=rmatrix) assert compare_results(expected, rot) # TODO: Check incremental 360 degree rotation against original image # Check derotated image against original derot_matrix = np.array([[c, s], [-s, c]]) derot = affine_transform(rot, order=4, rmatrix=derot_matrix) assert compare_results(original, derot) @pytest.mark.parametrize("angle, k", [(90.0, 1), (-90.0, -1), (-270.0, 1), (-90.0, 3), (360.0, 0), (-360.0, 0)]) def test_scipy_rotation(angle, k): # Test rotation against expected outcome angle = np.radians(angle) c = np.cos(angle); s = np.sin(angle) rmatrix = np.array([[c, -s], [s, c]]) expected = np.rot90(original, k=k) rot = affine_transform(original, rmatrix=rmatrix, use_scipy=True) assert compare_results(expected, rot, allclose=False) # TODO: Check incremental 360 degree rotation against original image # Check derotated image against original derot_matrix = np.array([[c, s], [-s, c]]) derot = affine_transform(rot, rmatrix=derot_matrix, use_scipy=True) assert compare_results(original, derot, allclose=False) dx_values, dy_values = list(range(-100, 101, 100))*3, list(range(-100, 101, 100))*3 dy_values.sort() @pytest.mark.parametrize("dx, dy", list(zip(dx_values, dy_values))) def test_shift(dx, dy): # Rotation center for all translation tests. image_center = np.array(original.shape)/2.0 - 0.5 # No rotation for all translation tests. rmatrix = np.array([[1.0, 0.0], [0.0, 1.0]]) # Check a shifted shape against expected outcome expected = np.roll(np.roll(original, dx, axis=1), dy, axis=0) rcen = image_center + np.array([dx, dy]) shift = affine_transform(original, rmatrix=rmatrix, recenter=True, image_center=rcen) ymin, ymax = max([0, dy]), min([original.shape[1], original.shape[1]+dy]) xmin, xmax = max([0, dx]), min([original.shape[0], original.shape[0]+dx]) compare_results(expected[ymin:ymax, xmin:xmax], shift[ymin:ymax, xmin:xmax]) # Check shifted and unshifted shape against original image rcen = image_center - np.array([dx, dy]) unshift = affine_transform(shift, rmatrix=rmatrix, recenter=True, image_center=rcen) # Need to ignore the portion of the image cut off by the first shift ymin, ymax = max([0, -dy]), min([original.shape[1], original.shape[1]-dy]) xmin, xmax = max([0, -dx]), min([original.shape[0], original.shape[0]-dx]) compare_results(original[ymin:ymax, xmin:xmax], unshift[ymin:ymax, xmin:xmax]) @pytest.mark.parametrize("scale_factor", [0.25, 0.5, 0.75, 1.0, 1.25, 1.5]) def test_scale(scale_factor): # No rotation for all scaling tests. rmatrix = np.array([[1.0, 0.0], [0.0, 1.0]]) # Check a scaled image against the expected outcome newim = tf.rescale(original/original.max(), scale_factor, order=4, mode='constant') * original.max() # Old width and new center of image w = original.shape[0]/2.0 - 0.5 new_c = (newim.shape[0]/2.0) - 0.5 expected = np.zeros(original.shape) upper = w+new_c+1 if scale_factor > 1: lower = new_c-w expected = newim[lower:upper, lower:upper] else: lower = w-new_c expected[lower:upper, lower:upper] = newim scale = affine_transform(original, rmatrix=rmatrix, scale=scale_factor) compare_results(expected, scale) @pytest.mark.parametrize("angle, dx, dy, scale_factor", [(90, -100, 50, 0.25), (-90, 50, -100, 0.75), (180, 100, 50, 1.5)]) def test_all(angle, dx, dy, scale_factor): """ Tests to make sure that combinations of scaling, shifting and rotation produce the expected output. """ k = int(angle/90) angle = np.radians(angle) image_center = np.array(original.shape)/2.0 - 0.5 # Check a shifted, rotated and scaled shape against expected outcome c = np.cos(angle); s = np.sin(angle) rmatrix = np.array([[c, -s], [s, c]]) scale = tf.rescale(original/original.max(), scale_factor, order=4, mode='constant') * original.max() new = np.zeros(original.shape) # Old width and new center of image w = np.array(original.shape[0])/2.0 - 0.5 new_c = (np.array(scale.shape[0])/2.0 - 0.5) upper = w+new_c+1 if scale_factor > 1: lower = new_c-w new = scale[lower:upper, lower:upper] else: lower = w-new_c new[lower:upper, lower:upper] = scale disp = np.array([dx, dy]) rcen = image_center + disp rot = np.rot90(new, k=k) shift = np.roll(np.roll(rot, dx, axis=1), dy, axis=0) expected = shift rotscaleshift = affine_transform(original, rmatrix=rmatrix, scale=scale_factor, recenter=True, image_center=rcen) w = np.array(expected.shape[0])/2.0 - 0.5 new_c = (np.array(rotscaleshift.shape[0])/2.0 - 0.5) upper = w+new_c+1 if scale_factor > 1: lower = new_c-w expected = rotscaleshift[lower:upper, lower:upper] else: lower = w-new_c expected[lower:upper, lower:upper] = rotscaleshift compare_results(expected, rotscaleshift) # Check a rotated/shifted and restored image against original transformed = affine_transform(original, rmatrix=rmatrix, scale=1.0, recenter=True, image_center=rcen) rcen = image_center - np.dot(rmatrix, np.array([dx, dy])) dx, dy = np.dot(rmatrix, disp) rmatrix = np.array([[c, s], [-s, c]]) inverse = affine_transform(transformed, rmatrix=rmatrix, scale=1.0, recenter=True, image_center=rcen) # Need to ignore the portion of the image cut off by the first shift # (which isn't the portion you'd expect, because of the rotation) ymin, ymax = max([0, -dy]), min([original.shape[1], original.shape[1]-dy]) xmin, xmax = max([0, -dx]), min([original.shape[0], original.shape[0]-dx]) compare_results(original[ymin:ymax, xmin:xmax], inverse[ymin:ymax, xmin:xmax]) def test_flat(identity): # Test that a flat array can be rotated using scikit-image in_arr = np.array([[100]]) out_arr = affine_transform(in_arr, rmatrix=identity) assert np.allclose(in_arr, out_arr, rtol=rtol) def test_nan_skimage_low(identity): # Test non-replacement of NaN values for scikit-image rotation with order <= 3 in_arr = np.array([[np.nan]]) out_arr = affine_transform(in_arr, rmatrix=identity, order=3) assert np.all(np.isnan(out_arr)) def test_nan_skimage_high(identity): # Test replacement of NaN values for scikit-image rotation with order >=4 in_arr = np.array([[np.nan]]) out_arr = affine_transform(in_arr, rmatrix=identity, order=4) assert not np.all(np.isnan(out_arr)) def test_nan_scipy(identity): # Test replacement of NaN values for scipy rotation in_arr = np.array([[np.nan]]) out_arr = affine_transform(in_arr, rmatrix=identity, use_scipy=True) assert not np.all(np.isnan(out_arr)) def test_int(identity): # Test casting of integer array to float array in_arr = np.array([[100]], dtype=int) out_arr = affine_transform(in_arr, rmatrix=identity) assert np.issubdtype(out_arr.dtype, np.float)
{ "repo_name": "Alex-Ian-Hamilton/sunpy", "path": "sunpy/image/tests/test_transform.py", "copies": "1", "size": "8900", "license": "bsd-2-clause", "hash": 8657544459010295000, "line_mean": 38.9103139013, "line_max": 90, "alpha_frac": 0.636741573, "autogenerated": false, "ratio": 3.2648569332355097, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.440159850623551, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from symantecssl import utils from symantecssl.models import OrderContacts class OrderDetails(list): def __init__(self, details_to_add=[]): self.extend(details_to_add) @classmethod def deserialize(cls, xml_node): """ Deserializes order details section in response. :param xml_node: XML node to be parsed. Expected to explicitly be Order Details XML node. :return: details in order detail section. """ details = [OrderDetail.deserialize(node) for node in xml_node.findall('.//m:OrderDetail', utils.NS)] return OrderDetails(details) class OrderDetail(object): def __init__(self): self.status_code = '' self.status_message = '' self.certificates = None self.organization_info = OrganizationInfo() self.organization_contacts = OrderContacts() self.modified_events = ModificationEvents() self.vulnerabilities = Vulnerabilities() self.approver_email = '' @classmethod def deserialize(cls, xml_node): """Deserializes the order detail section in response. :param xml_node: XML node to be parsed. Expected to explicitly be Order Detail XML node. :return: parsed order detail response. """ od = OrderDetail() od.status_code = utils.get_element_text( xml_node.find('.//m:OrderStatusMinorCode', utils.NS) ) od.status_name = utils.get_element_text( xml_node.find('.//m:OrderStatusMinorName', utils.NS) ) od.approver_email = utils.get_element_text( xml_node.find('.//m:ApproverEmailAddress', utils.NS) ) # Deserialize Child nodes org_info_node = xml_node.find('.//m:OrganizationInfo', utils.NS) org_contacts_node = xml_node.find('.//m:OrderContacts', utils.NS) od.organization_info = OrganizationInfo.deserialize(org_info_node) od.organization_contacts = OrderContacts.deserialize(org_contacts_node) mod_events_node = xml_node.find('.//m:ModificationEvents', utils.NS) if mod_events_node is not None: od.modified_events = ( ModificationEvents.deserialize(mod_events_node) ) vulnerability_node = xml_node.find('.//m:Vulnerabilities', utils.NS) if vulnerability_node is not None: od.vulnerabilities = ( Vulnerabilities.deserialize(vulnerability_node) ) fulfillment_node = xml_node.find('.//m:Fulfillment', utils.NS) if fulfillment_node is not None: od.certificates = Certificate.deserialize(fulfillment_node) return od class OrganizationInfo(object): def __init__(self): self.name = '' self.city = '' # Region is also state self.region = '' self.country = '' @classmethod def deserialize(cls, xml_node): """Deserializes the organization information section in response. :param xml_node: XML node to be parsed. Expected to explicitly be Organization Information XML node. :return: parsed organization information response. """ org_info = OrganizationInfo() org_info.name = utils.get_element_text( xml_node.find('.//m:OrganizationName', utils.NS) ) org_info.city = utils.get_element_text( xml_node.find('.//m:City', utils.NS) ) org_info.region = utils.get_element_text( xml_node.find('.//m:Region', utils.NS) ) org_info.country = utils.get_element_text( xml_node.find('.//m:Country', utils.NS) ) return org_info class CertificateInfo(object): def __init__(self): self.common_name = '' self.status = '' self.hash_algorithm = '' self.encryption_algorithm = '' @classmethod def deserialize(cls, xml_node): """Deserializes the certificate information section in the response. :param xml_node: XML node to be parsed. Expected to explicitly be Certificate Information XML node. :return: parsed certificate information response. """ cert_info = CertificateInfo() cert_info.common_name = utils.get_element_text( xml_node.find('.//m:CommonName', utils.NS) ) cert_info.status = utils.get_element_text( xml_node.find('.//m:CertificateStatus', utils.NS) ) cert_info.hash_algorithm = utils.get_element_text( xml_node.find('.//m:SignatureHashAlgorithm', utils.NS) ) cert_info.encryption_algorithm = utils.get_element_text( xml_node.find('.//m:SignatureEncryptionAlgorithm', utils.NS) ) return cert_info class Certificate(object): def __init__(self): self.server_cert = '' self.intermediates = [] @classmethod def deserialize(cls, xml_node): """Deserializes the certificate section in the response. :param xml_node:XML node to be parsed. Expected to explicitly be Certificates XML node. :return: parsed certificate response. """ cert = Certificate() cert.server_cert = utils.get_element_text( xml_node.find('.//m:ServerCertificate', utils.NS) ) ca_certs = xml_node.find('.//m:CACertificates', utils.NS) for x in ca_certs: cert.intermediates.append(IntermediateCertificate.deserialize(x)) return cert class IntermediateCertificate(object): def __init__(self): self.type = '' self.cert = '' @classmethod def deserialize(cls, xml_node): """Deserializes the intermediate certificates section in the response. :param xml_node: XML node to be parsed. Expected to explicitly be Intermediate Certificate XML node. :return: parsed intermediate certificate response. """ inter_info = IntermediateCertificate() inter_info.type = utils.get_element_text( xml_node.find('.//m:Type', utils.NS) ) inter_info.cert = utils.get_element_text( xml_node.find('.//m:CACert', utils.NS) ) return inter_info class ModificationEvents(list): def __init__(self, details_to_add=[]): self.extend(details_to_add) @classmethod def deserialize(cls, xml_node): """Deserializes the modification events section in the response. This is the section which holds multiple modification events. It will loop through each node found within it and initialize deserialization. :param xml_node: XML node to be parsed. Expected to explicitly be Modification Events XML node. :return: parsed modification events response. """ details = [ModificationEvent.deserialize(node) for node in xml_node.findall('.//m:ModificationEvent', utils.NS)] return ModificationEvents(details) class ModificationEvent(object): def __init__(self): self.event_name = '' self.time_stamp = '' self.mod_id = '' @classmethod def deserialize(cls, xml_node): """ Deserializes the modification event section in the response. :param xml_node: XML node to be parsed. Expected to explicitly be Modification Event XML node. :return: parsed modification event response. """ me = ModificationEvent() me.mod_id = utils.get_element_text( xml_node.find('.//m:ModificationEventID', utils.NS) ) me.event_name = utils.get_element_text( xml_node.find('.//m:ModificationEventName', utils.NS) ) me.time_stamp = utils.get_element_text( xml_node.find('.//m:ModificationTimestamp', utils.NS) ) return me class Vulnerabilities(list): def __init__(self, details_to_add=[]): self.extend(details_to_add) @classmethod def deserialize(cls, xml_node): """Deserializes the Vulnerabilities section in the response. :param xml_node: XML node to be parsed. Expected to explicitly be Vulnerabilities XML node. :return: parsed vulnerabilities response. """ details = [Vulnerability.deserialize(node) for node in xml_node.findall('.//m:Vulnerability', utils.NS)] return Vulnerabilities(details) class Vulnerability(object): def __init__(self): self.severity = '' self.number_found = '' @classmethod def deserialize(cls, xml_node): """ Deserializes the vulnerability section in the response. :param xml_node: XML node to be parsed. Expected to explicitly be Vulnerability XML node. :return: parsed vulnerability response. """ vuln = Vulnerability() vuln.mod_id = utils.get_element_text( xml_node.find('.//m:Severity', utils.NS) ) vuln.event_name = utils.get_element_text( xml_node.find('.//m:NumberFound', utils.NS) ) return vuln class QuickOrderResponse(object): def __init__(self): self.result = QuickOrderResult() @classmethod def deserialize(cls, xml_node): response = QuickOrderResponse() response.result = QuickOrderResult.deserialize(xml_node) return response class QuickOrderResult(object): def __init__(self): self.order_id = '' self.order_response = OrderResponseHeader() @classmethod def deserialize(cls, xml_node): result = QuickOrderResult() result.order_id = utils.get_element_text( xml_node.find('.//m:GeoTrustOrderID', utils.ONS) ) result.order_response = OrderResponseHeader.deserialize(xml_node) return result class OrderResponseHeader(object): def __init__(self): self.partner_order_id = '' self.success_code = '' self.timestamp = '' @classmethod def deserialize(cls, xml_node): order_response = OrderResponseHeader() order_response.partner_order_id = utils.get_element_text( xml_node.find('.//m:PartnerOrderID', utils.ONS) ) order_response.success_code = utils.get_element_text( xml_node.find('.//m:SuccessCode', utils.ONS) ) order_response.timestamp = utils.get_element_text( xml_node.find('.//m:Timestamp', utils.ONS) ) return order_response class ReissueResponse(object): def __init__(self): self.result = ReissueResult() @classmethod def deserialize(cls, xml_node): """Deserializes the reissue section in the response. :param xml_node: XML node to be parsed. Expected to explicitly be Reissue Response XML node. :return: response. Parsed reissue response. """ response = ReissueResponse() response.result = ReissueResult.deserialize(xml_node) return response class ReissueResult(object): def __init__(self): self.order_response = OrderResponseHeader() @classmethod def deserialize(cls, xml_node): """Deserializes the reissue result section in the response. :param xml_node: XML node to be parsed. Expected to explicitly be ReissueResult XML node. :return: result. Parsed reissue response. """ result = ReissueResult() result.order_response = OrderResponseHeader.deserialize(xml_node) return result
{ "repo_name": "glyph/symantecssl", "path": "symantecssl/response_models.py", "copies": "2", "size": "11690", "license": "apache-2.0", "hash": 8757605748314829000, "line_mean": 30.1733333333, "line_max": 79, "alpha_frac": 0.6141146279, "autogenerated": false, "ratio": 4.214131218457101, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 375 }
from __future__ import (absolute_import, division, print_function) from sympy import And, Gt, Lt, Abs, Dummy, oo, Tuple, Symbol from sympy.codegen.ast import ( Assignment, AddAugmentedAssignment, CodeBlock, Declaration, FunctionDefinition, Print, Return, Scope, While, Variable, Pointer, real ) """ This module collects functions for constructing ASTs representing algorithms. """ def newtons_method(expr, wrt, atol=1e-12, delta=None, debug=False, itermax=None, counter=None): """ Generates an AST for Newton-Raphson method (a root-finding algorithm). Returns an abstract syntax tree (AST) based on ``sympy.codegen.ast`` for Netwon's method of root-finding. Parameters ========== expr : expression wrt : Symbol With respect to, i.e. what is the variable. atol : number or expr Absolute tolerance (stopping criterion) delta : Symbol Will be a ``Dummy`` if ``None``. debug : bool Whether to print convergence information during iterations itermax : number or expr Maximum number of iterations. counter : Symbol Will be a ``Dummy`` if ``None``. Examples ======== >>> from sympy import symbols, cos >>> from sympy.codegen.ast import Assignment >>> from sympy.codegen.algorithms import newtons_method >>> x, dx, atol = symbols('x dx atol') >>> expr = cos(x) - x**3 >>> algo = newtons_method(expr, x, atol, dx) >>> algo.has(Assignment(dx, -expr/expr.diff(x))) True References ========== .. [1] https://en.wikipedia.org/wiki/Newton%27s_method """ if delta is None: delta = Dummy() Wrapper = Scope name_d = 'delta' else: Wrapper = lambda x: x name_d = delta.name delta_expr = -expr/expr.diff(wrt) whl_bdy = [Assignment(delta, delta_expr), AddAugmentedAssignment(wrt, delta)] if debug: prnt = Print([wrt, delta], r"{0}=%12.5g {1}=%12.5g\n".format(wrt.name, name_d)) whl_bdy = [whl_bdy[0], prnt] + whl_bdy[1:] req = Gt(Abs(delta), atol) declars = [Declaration(Variable(delta, type=real, value=oo))] if itermax is not None: counter = counter or Dummy(integer=True) v_counter = Variable.deduced(counter, 0) declars.append(Declaration(v_counter)) whl_bdy.append(AddAugmentedAssignment(counter, 1)) req = And(req, Lt(counter, itermax)) whl = While(req, CodeBlock(*whl_bdy)) blck = declars + [whl] return Wrapper(CodeBlock(*blck)) def _symbol_of(arg): if isinstance(arg, Declaration): arg = arg.variable.symbol elif isinstance(arg, Variable): arg = arg.symbol return arg def newtons_method_function(expr, wrt, params=None, func_name="newton", attrs=Tuple(), **kwargs): """ Generates an AST for a function implementing the Newton-Raphson method. Parameters ========== expr : expression wrt : Symbol With respect to, i.e. what is the variable params : iterable of symbols Symbols appearing in expr that are taken as constants during the iterations (these will be accepted as parameters to the generated function). func_name : str Name of the generated function. attrs : Tuple Attribute instances passed as ``attrs`` to ``FunctionDefinition``. \\*\\*kwargs : Keyword arguments passed to :func:`sympy.codegen.algorithms.newtons_method`. Examples ======== >>> from sympy import symbols, cos >>> from sympy.codegen.algorithms import newtons_method_function >>> from sympy.codegen.pyutils import render_as_module >>> from sympy.core.compatibility import exec_ >>> x = symbols('x') >>> expr = cos(x) - x**3 >>> func = newtons_method_function(expr, x) >>> py_mod = render_as_module(func) # source code as string >>> namespace = {} >>> exec_(py_mod, namespace, namespace) >>> res = eval('newton(0.5)', namespace) >>> abs(res - 0.865474033102) < 1e-12 True See Also ======== sympy.codegen.algorithms.newtons_method """ if params is None: params = (wrt,) pointer_subs = {p.symbol: Symbol('(*%s)' % p.symbol.name) for p in params if isinstance(p, Pointer)} delta = kwargs.pop('delta', None) if delta is None: delta = Symbol('d_' + wrt.name) if expr.has(delta): delta = None # will use Dummy algo = newtons_method(expr, wrt, delta=delta, **kwargs).xreplace(pointer_subs) if isinstance(algo, Scope): algo = algo.body not_in_params = expr.free_symbols.difference(set(_symbol_of(p) for p in params)) if not_in_params: raise ValueError("Missing symbols in params: %s" % ', '.join(map(str, not_in_params))) declars = tuple(Variable(p, real) for p in params) body = CodeBlock(algo, Return(wrt)) return FunctionDefinition(real, func_name, declars, body, attrs=attrs)
{ "repo_name": "kaushik94/sympy", "path": "sympy/codegen/algorithms.py", "copies": "1", "size": "4980", "license": "bsd-3-clause", "hash": 2191923240224348700, "line_mean": 32.8775510204, "line_max": 97, "alpha_frac": 0.6246987952, "autogenerated": false, "ratio": 3.6456808199121524, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47703796151121525, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from tabulate import tabulate from appr.utils import colorize, get_media_type def print_packages(packages, registry_host=""): header = ['app', 'release', 'downloads', 'manifests'] table = [] for package in packages: release = package["default"] manifests = ", ".join(package['manifests']) table.append([ registry_host + "/" + package['name'], release, str(package.get('downloads', '-')), manifests]) return tabulate(table, header) def print_package_info(packages, extended=False): header = ["release", "manifest", "digest"] if extended: header = header + ["created_at", "size", "downloads"] table = [] for package in packages: row = [ package['release'], get_media_type(package['content']['mediaType']), package['content']['digest'], ] if extended: row = row + [ package['created_at'], package['content']['size'], package.get('downloads', '-'), ] table.append(row) return tabulate(table, header) def print_channels(channels): header = ['channel', 'release'] table = [] for channel in channels: table.append([channel['name'], channel['current']]) return tabulate(table, header) def print_deploy_result(table): header = ["package", "release", "type", "name", "namespace", "status"] for r in table: status = r.pop() r.append(colorize(status)) return tabulate(table, header)
{ "repo_name": "cn-app-registry/cnr-server", "path": "appr/display.py", "copies": "2", "size": "1611", "license": "apache-2.0", "hash": 5336134582049589000, "line_mean": 29.3962264151, "line_max": 74, "alpha_frac": 0.582867784, "autogenerated": false, "ratio": 4.130769230769231, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5713637014769231, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from tensorflow.python.keras import Sequential from tensorflow.python.keras.layers import (Activation, BatchNormalization, Dense, Layer) from tensorflow.python.util.tf_export import keras_export __all__ = ['Identity', 'Parallel', 'BatchRenormalization'] class BatchRenormalization(BatchNormalization): """ Shortcut for batch renormalization References ---------- [1] S. Ioffe, “Batch Renormalization: Towards Reducing Minibatch Dependence in Batch-Normalized Models,” arXiv:1702.03275 [cs], Feb. 2017. """ def __init__(self, axis=-1, momentum=0.99, epsilon=1e-3, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None, renorm_clipping=None, renorm_momentum=0.99, fused=None, trainable=True, virtual_batch_size=None, adjustment=None, name=None, **kwargs): super(BatchRenormalization, self).__init__( name=name, axis=axis, momentum=momentum, epsilon=epsilon, center=center, scale=scale, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, moving_mean_initializer=moving_mean_initializer, moving_variance_initializer=moving_variance_initializer, beta_regularizer=beta_regularizer, gamma_regularizer=gamma_regularizer, beta_constraint=beta_constraint, gamma_constraint=gamma_constraint, renorm=True, renorm_clipping=renorm_clipping, renorm_momentum=renorm_momentum, fused=fused, trainable=trainable, virtual_batch_size=virtual_batch_size, adjustment=adjustment, **kwargs) class Identity(Layer): def __init__(self, name=None): super(Identity, self).__init__(name=name) self.supports_masking = True def call(self, inputs, training=None): return inputs def compute_output_shape(self, input_shape): return input_shape @keras_export('keras.models.Sequential', 'keras.Sequential') class Parallel(Sequential): """ Similar design to keras `Sequential` but simultanously applying all the layer on the input and return all the results. This layer is important for implementing multitask learning. """ def call(self, inputs, training=None, mask=None, **kwargs): # pylint: disable=redefined-outer-name if self._is_graph_network: if not self.built: self._init_graph_network(self.inputs, self.outputs, name=self.name) return super(Parallel, self).call(inputs, training=training, mask=mask) outputs = [] for layer in self.layers: # During each iteration, `inputs` are the inputs to `layer`, and `outputs` # are the outputs of `layer` applied to `inputs`. At the end of each # iteration `inputs` is set to `outputs` to prepare for the next layer. kw = {} argspec = self._layer_call_argspecs[layer].args if 'mask' in argspec: kw['mask'] = mask if 'training' in argspec: kw['training'] = training # support custom keyword argument also for k, v in kwargs.items(): if k in argspec: kw[k] = v o = layer(inputs, **kw) outputs.append(o) return tuple(outputs) def compute_output_shape(self, input_shape): shape = [] for layer in self.layers: shape.append(layer.compute_output_shape(input_shape)) return tuple(shape) def compute_mask(self, inputs, mask): outputs = self.call(inputs, mask=mask) return [o._keras_mask for o in outputs]
{ "repo_name": "imito/odin", "path": "odin/networks/util_layers.py", "copies": "1", "size": "4050", "license": "mit", "hash": 6239411273191407000, "line_mean": 31.6290322581, "line_max": 101, "alpha_frac": 0.6240731587, "autogenerated": false, "ratio": 4.124362895005097, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5248436053705097, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from tests.core import mock from trakt import Trakt from hamcrest import assert_that, has_entries from httmock import HTTMock def test_progress_watched(): with HTTMock(mock.fixtures, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): progress = Trakt['shows'].progress_watched(1390) assert progress is not None assert progress.reset_at is not None assert progress.last_progress_change is not None assert progress.aired == 10 assert progress.completed == 6 assert len(progress.seasons) == 1 assert progress.seasons[1].aired == 8 assert progress.seasons[1].completed == 6 assert len(progress.seasons[1].episodes) == 10 assert progress.seasons[1].episodes[1].progress_timestamp is not None assert len(progress.hidden_seasons) == 0 # Next Episode assert progress.next_episode is not None assert progress.next_episode.pk == (1, 7) assert progress.next_episode.keys == [ (1, 7), ('tvdb', '3436461'), ('tmdb', '63062'), ('imdb', 'tt1837863'), ('tvrage', '1065036404'), ('trakt', '73646') ] assert_that(progress.next_episode.to_dict(), has_entries({ 'number': 7, 'title': 'You Win or You Die', 'ids': { 'trakt': '73646', 'tvrage': '1065036404', 'tvdb': '3436461', 'tmdb': '63062', 'imdb': 'tt1837863' } })) # Last Episode assert progress.last_episode is not None assert progress.last_episode.pk == (1, 5) assert progress.last_episode.keys == [ (1, 5), ('tvdb', '3436461'), ('tmdb', '63062'), ('imdb', 'tt1837863'), ('tvrage', '1065036404'), ('trakt', '73646') ] assert_that(progress.last_episode.to_dict(), has_entries({ 'number': 5, 'title': 'You Die and You Win', 'ids': { 'trakt': '73646', 'tvrage': '1065036404', 'tvdb': '3436461', 'tmdb': '63062', 'imdb': 'tt1837863' } })) def test_progress_watched_plus_hidden(): with HTTMock(mock.fixtures, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): progress = Trakt['shows'].progress_watched('game-of-thrones', hidden=True) assert progress is not None assert progress.reset_at is None assert len(progress.hidden_seasons) == 1 assert_that(progress.to_dict(), has_entries({ 'aired': 10, 'completed': 6, 'last_watched_at': '2015-03-21T19:03:58.000-00:00', 'reset_at': None, 'seasons': [ { 'number': 1, 'aired': 8, 'completed': 6, 'episodes': [ { 'number': 1, 'completed': True, 'last_watched_at': '2015-03-21T19:03:58.000-00:00' }, { 'number': 2, 'completed': True, 'last_watched_at': '2015-03-21T19:03:58.000-00:00' }, { 'number': 3, 'completed': True, 'last_watched_at': '2015-03-21T19:03:58.000-00:00' }, { 'number': 4, 'completed': True, 'last_watched_at': '2015-03-21T19:03:58.000-00:00' }, { 'number': 5, 'completed': True, 'last_watched_at': '2015-03-21T19:03:58.000-00:00' }, { 'number': 6, 'completed': True, 'last_watched_at': '2015-03-21T19:03:58.000-00:00' }, { 'number': 7, 'completed': False, 'last_watched_at': None }, { 'number': 8, 'completed': False, 'last_watched_at': None }, { 'number': 9, 'completed': False, 'last_watched_at': None }, { 'number': 10, 'completed': False, 'last_watched_at': None } ] } ], 'hidden_seasons': [ { 'number': 2, 'ids': { 'trakt': '3051', 'tvdb': '498968', 'tmdb': '53334' } } ], 'next_episode': { 'season': 1, 'number': 7, 'title': 'You Win or You Die', 'ids': { 'trakt': '73646', 'tvdb': '3436461', 'imdb': 'tt1837863', 'tmdb': '63062', 'tvrage': '1065036404' } } })) def test_progress_collection(): with HTTMock(mock.fixtures, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): progress = Trakt['shows'].progress_collection(1390) assert progress is not None assert progress.reset_at is None assert progress.last_progress_change is not None assert progress.seasons[1].episodes[1].progress_timestamp is not None # Next Episode assert progress.next_episode is not None assert progress.next_episode.pk == (1, 7) assert progress.next_episode.keys == [ (1, 7), ('tvdb', '3436461'), ('tmdb', '63062'), ('imdb', 'tt1837863'), ('tvrage', '1065036404'), ('trakt', '73646') ] assert_that(progress.next_episode.to_dict(), has_entries({ 'number': 7, 'title': 'You Win or You Die', 'ids': { 'trakt': '73646', 'tvrage': '1065036404', 'tvdb': '3436461', 'tmdb': '63062', 'imdb': 'tt1837863' } }))
{ "repo_name": "fuzeman/trakt.py", "path": "tests/test_progress.py", "copies": "1", "size": "6427", "license": "mit", "hash": -4203908284075866000, "line_mean": 28.6175115207, "line_max": 86, "alpha_frac": 0.4379959546, "autogenerated": false, "ratio": 3.9919254658385093, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9929656575902253, "avg_score": 0.000052968907251443404, "num_lines": 217 }
from __future__ import absolute_import, division, print_function from tests.core import mock from trakt import Trakt from httmock import HTTMock import pytest def test_likes(): with HTTMock(mock.fixtures, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): likes = Trakt['users'].likes() assert likes is not None likes = list(likes) assert len(likes) == 3 assert likes[0].keys == [ ('trakt', 1519) ] assert likes[1].keys == [ ('trakt', '1238362'), ('slug', 'star-wars-machete') ] assert likes[2].keys == [ ('trakt', '840781'), ('slug', 'star-wars-timeline') ] def test_likes_invalid_response(): with HTTMock(mock.fixtures, mock.unknown): likes = Trakt['users'].likes() assert likes is None def test_likes_invalid_type(): with HTTMock(mock.fixtures, mock.unknown): with pytest.raises(ValueError): likes = Trakt['users'].likes('invalid') assert likes is not None likes = list(likes)
{ "repo_name": "fuzeman/trakt.py", "path": "tests/test_user.py", "copies": "1", "size": "1086", "license": "mit", "hash": 2084474598217265700, "line_mean": 21.625, "line_max": 64, "alpha_frac": 0.5893186004, "autogenerated": false, "ratio": 3.62, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47093186004, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from tests.core import mock from trakt import Trakt from httmock import HTTMock def test_delete(): with HTTMock(mock.list_delete, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): success = Trakt['users/sean/lists/star-wars-in-machete-order'].delete() assert success is True def test_update_data(): with HTTMock(mock.list_update, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): result = Trakt['users/sean/lists/star-wars-in-machete-order'].update( name='Shows (2)', return_type='data' ) assert result is not None def test_update_object(): with HTTMock(mock.list_update, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): result = Trakt['users/sean/lists/star-wars-in-machete-order'].update( name='Shows (2)' ) assert result is not None def test_like(): with HTTMock(mock.list_like, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): success = Trakt['users/sean/lists/star-wars-in-machete-order'].like() assert success is True def test_unlike(): with HTTMock(mock.list_unlike, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): success = Trakt['users/sean/lists/star-wars-in-machete-order'].unlike() assert success is True def test_item_add(): with HTTMock(mock.list_item_add, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): result = Trakt['users/sean/lists/star-wars-in-machete-order'].add({ 'shows': [ {'ids': {'tvdb': 121361}} ] }) assert result is not None def test_item_remove(): with HTTMock(mock.list_item_remove, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): result = Trakt['users/sean/lists/star-wars-in-machete-order'].remove({ 'shows': [ {'ids': {'tvdb': 121361}} ] }) assert result is not None
{ "repo_name": "fuzeman/trakt.py", "path": "tests/users/lists/test_actions.py", "copies": "1", "size": "2178", "license": "mit", "hash": -7597224094298817000, "line_mean": 28.04, "line_max": 83, "alpha_frac": 0.5945821855, "autogenerated": false, "ratio": 3.547231270358306, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4641813455858306, "avg_score": null, "num_lines": null }
from __future__ import absolute_import, division, print_function from tests.core import mock from trakt import Trakt from httmock import HTTMock def test_start(): with HTTMock(mock.scrobble_start, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): result = Trakt['scrobble'].start( movie={'ids': {'tmdb': 76341}}, progress=0.35 ) assert result is not None assert result.get('action') == 'start' assert result.get('id') == 9832 assert result.get('progress') == 0.35 def test_pause(): with HTTMock(mock.scrobble_pause, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): result = Trakt['scrobble'].pause( movie={'ids': {'tmdb': 76341}}, progress=35.86 ) assert result is not None assert result.get('action') == 'pause' assert result.get('id') == 9832 assert result.get('progress') == 35.86 def test_stop(): with HTTMock(mock.scrobble_stop, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): result = Trakt['scrobble'].stop( movie={'ids': {'tmdb': 76341}}, progress=97.45 ) assert result is not None assert result.get('action') == 'stop' assert result.get('id') == 9832 assert result.get('progress') == 97.45
{ "repo_name": "fuzeman/trakt.py", "path": "tests/test_scrobble.py", "copies": "1", "size": "1407", "license": "mit", "hash": -7293573760489764000, "line_mean": 25.0555555556, "line_max": 64, "alpha_frac": 0.5764036958, "autogenerated": false, "ratio": 3.7620320855614975, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48384357813614975, "avg_score": null, "num_lines": null }