我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用operator.index()。
def test_simple(self): arr = np.ones((5, 4, 3)) index = np.array([True]) #self.assert_deprecated(arr.__getitem__, args=(index,)) assert_warns(np.VisibleDeprecationWarning, arr.__getitem__, index) index = np.array([False] * 6) #self.assert_deprecated(arr.__getitem__, args=(index,)) assert_warns(np.VisibleDeprecationWarning, arr.__getitem__, index) index = np.zeros((4, 4), dtype=bool) #self.assert_deprecated(arr.__getitem__, args=(index,)) assert_warns(np.VisibleDeprecationWarning, arr.__getitem__, index) #self.assert_deprecated(arr.__getitem__, args=((slice(None), index),)) assert_warns(np.VisibleDeprecationWarning, arr.__getitem__, (slice(None), index))
def receive_some(self, max_bytes): async with self._receive_conflict_detector: # Argument validation max_bytes = operator.index(max_bytes) if max_bytes < 1: raise ValueError("max_bytes must be >= 1") # State validation if self._receiver_closed: raise ClosedStreamError # Wake wait_send_all_might_not_block and wait for data self._receiver_waiting = True self._something_happened() try: await self._wait_for(lambda: self._data or self._sender_closed) finally: self._receiver_waiting = False # Get data, possibly waking send_all if self._data: got = self._data[:max_bytes] del self._data[:max_bytes] self._something_happened() return got else: assert self._sender_closed return b""
def _create_daily_stats(self, perfs): # create daily and cumulative stats dataframe daily_perfs = [] # TODO: the loop here could overwrite expected properties # of daily_perf. Could potentially raise or log a # warning. for perf in perfs: if 'daily_perf' in perf: perf['daily_perf'].update( perf['daily_perf'].pop('recorded_vars') ) perf['daily_perf'].update(perf['cumulative_risk_metrics']) daily_perfs.append(perf['daily_perf']) else: self.risk_report = perf daily_dts = pd.DatetimeIndex( [p['period_close'] for p in daily_perfs], tz='UTC' ) daily_stats = pd.DataFrame(daily_perfs, index=daily_dts) return daily_stats
def number_of_args(fn): """Return the number of positional arguments for a function, or None if the number is variable. Looks inside any decorated functions.""" try: if hasattr(fn, '__wrapped__'): return number_of_args(fn.__wrapped__) if any(p.kind == p.VAR_POSITIONAL for p in signature(fn).parameters.values()): return None else: return sum(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in signature(fn).parameters.values()) except ValueError: # signatures don't work for built-in operators, so check for a few explicitly UNARY_OPS = [len, op.not_, op.truth, op.abs, op.index, op.inv, op.invert, op.neg, op.pos] BINARY_OPS = [op.lt, op.le, op.gt, op.ge, op.eq, op.ne, op.is_, op.is_not, op.add, op.and_, op.floordiv, op.lshift, op.mod, op.mul, op.or_, op.pow, op.rshift, op.sub, op.truediv, op.xor, op.concat, op.contains, op.countOf, op.delitem, op.getitem, op.indexOf] TERNARY_OPS = [op.setitem] if fn in UNARY_OPS: return 1 elif fn in BINARY_OPS: return 2 elif fn in TERNARY_OPS: return 3 else: raise NotImplementedError("Bult-in operator {} not supported".format(fn))
def test_index_returns_int_subclass(self): class BadInt: def __index__(self): return True class BadInt2(int): def __index__(self): return True bad_int = BadInt() with self.assertWarns(DeprecationWarning): n = operator.index(bad_int) self.assertEqual(n, 1) bad_int = BadInt2() n = operator.index(bad_int) self.assertEqual(n, 0)
def test_same_kind_index_casting(self): # Indexes should be cast with same-kind and not safe, even if that # is somewhat unsafe. So test various different code paths. index = np.arange(5) u_index = index.astype(np.uintp) arr = np.arange(10) assert_array_equal(arr[index], arr[u_index]) arr[u_index] = np.arange(5) assert_array_equal(arr, np.arange(10)) arr = np.arange(10).reshape(5, 2) assert_array_equal(arr[index], arr[u_index]) arr[u_index] = np.arange(5)[:,None] assert_array_equal(arr, np.arange(5)[:,None].repeat(2, axis=1)) arr = np.arange(25).reshape(5, 5) assert_array_equal(arr[u_index, u_index], arr[index, index])
def test_ellipsis_index(self): # Ellipsis index does not create a view a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert_equal(a[...], a) # `a[...]` was `a` in numpy <1.9. assert_(a[...].base is a) # Slicing with ellipsis can skip an # arbitrary number of dimensions assert_equal(a[0, ...], a[0]) assert_equal(a[0, ...], a[0,:]) assert_equal(a[..., 0], a[:, 0]) # Slicing with ellipsis always results # in an array, not a scalar assert_equal(a[0, ..., 1], np.array(2)) # Assignment with `(Ellipsis,)` on 0-d arrays b = np.array(1) b[(Ellipsis,)] = 2 assert_equal(b, 2)
def test_single_bool_index(self): # Single boolean index a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Python boolean converts to integer # These are being deprecated (and test in test_deprecations) #assert_equal(a[True], a[1]) #assert_equal(a[False], a[0]) # Same with NumPy boolean scalar # Before DEPRECATE, this is an error (as always, but telling about # future change): assert_raises(IndexError, a.__getitem__, np.array(True)) assert_raises(IndexError, a.__getitem__, np.array(False)) # After DEPRECATE, this behaviour can be enabled: #assert_equal(a[np.array(True)], a[None]) #assert_equal(a[np.array(False), a[None][0:0]])
def test_unaligned(self): v = (np.zeros(64, dtype=np.int8) + ord('a'))[1:-7] d = v.view(np.dtype("S8")) # unaligned source x = (np.zeros(16, dtype=np.int8) + ord('a'))[1:-7] x = x.view(np.dtype("S8")) x[...] = np.array("b" * 8, dtype="S") b = np.arange(d.size) #trivial assert_equal(d[b], d) d[b] = x # nontrivial # unaligned index array b = np.zeros(d.size + 1).view(np.int8)[1:-(np.intp(0).itemsize - 1)] b = b.view(np.intp)[:d.size] b[...] = np.arange(d.size) assert_equal(d[b.astype(np.int16)], d) d[b.astype(np.int16)] = x # boolean d[b % 2 == 0] d[b % 2 == 0] = x[::2]
def test_boolean_index_cast_assign(self): # Setup the boolean index and float arrays. shape = (8, 63) bool_index = np.zeros(shape).astype(bool) bool_index[0, 1] = True zero_array = np.zeros(shape) # Assigning float is fine. zero_array[bool_index] = np.array([1]) assert_equal(zero_array[0, 1], 1) # Fancy indexing works, although we get a cast warning. assert_warns(np.ComplexWarning, zero_array.__setitem__, ([0], [1]), np.array([2 + 1j])) assert_equal(zero_array[0, 1], 2) # No complex part # Cast complex to float, throwing away the imaginary portion. assert_warns(np.ComplexWarning, zero_array.__setitem__, bool_index, np.array([1j])) assert_equal(zero_array[0, 1], 0)
def _check_multi_index(self, arr, index): """Check a multi index item getting and simple setting. Parameters ---------- arr : ndarray Array to be indexed, must be a reshaped arange. index : tuple of indexing objects Index being tested. """ # Test item getting try: mimic_get, no_copy = self._get_multi_index(arr, index) except Exception: if HAS_REFCOUNT: prev_refcount = sys.getrefcount(arr) assert_raises(Exception, arr.__getitem__, index) assert_raises(Exception, arr.__setitem__, index, 0) if HAS_REFCOUNT: assert_equal(prev_refcount, sys.getrefcount(arr)) return self._compare_index_result(arr, index, mimic_get, no_copy)
def _check_single_index(self, arr, index): """Check a single index item getting and simple setting. Parameters ---------- arr : ndarray Array to be indexed, must be an arange. index : indexing object Index being tested. Must be a single index and not a tuple of indexing objects (see also `_check_multi_index`). """ try: mimic_get, no_copy = self._get_multi_index(arr, (index,)) except Exception: if HAS_REFCOUNT: prev_refcount = sys.getrefcount(arr) assert_raises(Exception, arr.__getitem__, index) assert_raises(Exception, arr.__setitem__, index, 0) if HAS_REFCOUNT: assert_equal(prev_refcount, sys.getrefcount(arr)) return self._compare_index_result(arr, index, mimic_get, no_copy)
def test_boolean(self): a = np.array(5) assert_equal(a[np.array(True)], 5) a[np.array(True)] = 1 assert_equal(a, 1) # NOTE: This is different from normal broadcasting, as # arr[boolean_array] works like in a multi index. Which means # it is aligned to the left. This is probably correct for # consistency with arr[boolean_array,] also no broadcasting # is done at all self._check_multi_index( self.a, (np.zeros_like(self.a, dtype=bool),)) self._check_multi_index( self.a, (np.zeros_like(self.a, dtype=bool)[..., 0],)) self._check_multi_index( self.a, (np.zeros_like(self.a, dtype=bool)[None, ...],))
def __getitem__(self, idx): if isinstance(idx, slice): start, stop, step = idx.indices(len(self)) return [self._revoked_cert(i) for i in range(start, stop, step)] else: idx = operator.index(idx) if idx < 0: idx += len(self) if not 0 <= idx < len(self): raise IndexError return self._revoked_cert(idx)
def test_indexing(self): a = np.array([[[5]]]) def assert_deprecated(*args, **kwargs): self.assert_deprecated(*args, exceptions=(IndexError,), **kwargs) assert_deprecated(lambda: a[0.0]) assert_deprecated(lambda: a[0, 0.0]) assert_deprecated(lambda: a[0.0, 0]) assert_deprecated(lambda: a[0.0,:]) assert_deprecated(lambda: a[:, 0.0]) assert_deprecated(lambda: a[:, 0.0,:]) assert_deprecated(lambda: a[0.0,:,:]) assert_deprecated(lambda: a[0, 0, 0.0]) assert_deprecated(lambda: a[0.0, 0, 0]) assert_deprecated(lambda: a[0, 0.0, 0]) assert_deprecated(lambda: a[-1.4]) assert_deprecated(lambda: a[0, -1.4]) assert_deprecated(lambda: a[-1.4, 0]) assert_deprecated(lambda: a[-1.4,:]) assert_deprecated(lambda: a[:, -1.4]) assert_deprecated(lambda: a[:, -1.4,:]) assert_deprecated(lambda: a[-1.4,:,:]) assert_deprecated(lambda: a[0, 0, -1.4]) assert_deprecated(lambda: a[-1.4, 0, 0]) assert_deprecated(lambda: a[0, -1.4, 0]) # Test that the slice parameter deprecation warning doesn't mask # the scalar index warning. assert_deprecated(lambda: a[0.0:, 0.0], num=2) assert_deprecated(lambda: a[0.0:, 0.0,:], num=2)
def test_bool_as_int_argument(self): a = np.array([[[1]]]) self.assert_deprecated(np.reshape, args=(a, (True, -1))) self.assert_deprecated(np.reshape, args=(a, (np.bool_(True), -1))) # Note that operator.index(np.array(True)) does not work, a boolean # array is thus also deprecated, but not with the same message: assert_raises(TypeError, operator.index, np.array(True)) self.assert_deprecated(np.take, args=(a, [0], False)) self.assert_deprecated(lambda: a[False:True:True], exceptions=IndexError, num=3) self.assert_deprecated(lambda: a[False, 0], exceptions=IndexError) self.assert_deprecated(lambda: a[False, 0, 0], exceptions=IndexError)
def test_array_to_index_deprecation(self): # This drops into the non-integer deprecation, which is ignored here, # so no exception is expected. The raising is effectively tested above. a = np.array([[[1]]]) self.assert_deprecated(operator.index, args=(np.array([1]),)) self.assert_deprecated(np.reshape, args=(a, (a, -1)), exceptions=()) self.assert_deprecated(np.take, args=(a, [0], a), exceptions=()) # Check slicing. Normal indexing checks arrays specifically. self.assert_deprecated(lambda: a[a:a:a], exceptions=(), num=3)
def _validate_axis(axis, ndim, argname): try: axis = [operator.index(axis)] except TypeError: axis = list(axis) axis = [a + ndim if a < 0 else a for a in axis] if not builtins.all(0 <= a < ndim for a in axis): raise ValueError('invalid axis for this array in `%s` argument' % argname) if len(set(axis)) != len(axis): raise ValueError('repeated axis in `%s` argument' % argname) return axis
def __index__(self): return operator.index(self.__wrapped__)
def __init__(self, capacity): if not isinstance(capacity, int): raise TypeError("capacity must be an integer") if capacity < 1: raise ValueError("capacity must be >= 1") # Invariants: # get_semaphore.value() == len(self._data) # put_semaphore.value() + get_semaphore.value() = capacity self.capacity = operator.index(capacity) self._put_semaphore = Semaphore(capacity, max_value=capacity) self._get_semaphore = Semaphore(0, max_value=capacity) self._data = deque() self._join_lot = _core.ParkingLot() self._unprocessed = 0
def _check_max_bytes(self, max_bytes): if max_bytes is None: return max_bytes = operator.index(max_bytes) if max_bytes < 1: raise ValueError("max_bytes must be >= 1")
def test_basic(self): self.o.ind = -2 self.n.ind = 2 self.assertEqual(operator.index(self.o), -2) self.assertEqual(operator.index(self.n), 2)
def test_error(self): self.o.ind = 'dumb' self.n.ind = 'bad' self.assertRaises(TypeError, operator.index, self.o) self.assertRaises(TypeError, operator.index, self.n) self.assertRaises(TypeError, slice(self.o).indices, 0) self.assertRaises(TypeError, slice(self.n).indices, 0)
def __getitem__(self, index): return self._list[index]
def test_proxy_index(self): class C: def __index__(self): return 10 o = C() p = weakref.proxy(o) self.assertEqual(operator.index(p), 10)