我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用operator.mod()。
def __iadd__(self, other): if not isinstance(other, (PyPtxt, int)): raise TypeError("PyPtxt '+=' error: lhs must be of type PyPtxt or int instead of type " + str(type(other))) from operator import add, mod if isinstance(other, PyPtxt): self = PyPtxt([mod(elt, self.__pyfhel.getModulus()) for elt in list(map(add, self.getPtxt(), other.getPtxt()))], self.getPyfhel()) else: constPtxt = [other for _ in range(self.__length)] self = PyPtxt([mod(elt, self.__pyfhel.getModulus()) for elt in list(map(add, self.getPtxt(), constPtxt))], self.getPyfhel()) del constPtxt return self # SUBSTRACT: # '-' operator
def test_modulus_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): if sg1 == -1 and dt1 in np.typecodes['UnsignedInteger']: continue if sg2 == -1 and dt2 in np.typecodes['UnsignedInteger']: continue fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (dt1, dt2, sg1, sg2) a = np.array(sg1*71, dtype=dt1)[()] b = np.array(sg2*19, dtype=dt2)[()] div = self.floordiv(a, b) rem = self.mod(a, b) assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg)
def test_float_modulus_roundoff(self): # gh-6127 dt = np.typecodes['Float'] for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (dt1, dt2, sg1, sg2) a = np.array(sg1*78*6e-8, dtype=dt1)[()] b = np.array(sg2*6e-8, dtype=dt2)[()] div = self.floordiv(a, b) rem = self.mod(a, b) # Equal assertion should hold when fmod is used assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg)
def check_mod(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) assert_poly_almost_equal(p4 % p2, p3) assert_poly_almost_equal(p4 % c2, p3) assert_poly_almost_equal(c4 % p2, p3) assert_poly_almost_equal(p4 % tuple(c2), p3) assert_poly_almost_equal(tuple(c4) % p2, p3) assert_poly_almost_equal(p4 % np.array(c2), p3) assert_poly_almost_equal(np.array(c4) % p2, p3) assert_poly_almost_equal(2 % p2, Poly([2])) assert_poly_almost_equal(p2 % 2, Poly([0])) assert_raises(TypeError, op.mod, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.mod, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.mod, p1, Chebyshev([0])) else: assert_raises(TypeError, op.mod, p1, Polynomial([0]))
def test_float_mod(self): # Check behaviour of % operator for IEEE 754 special cases. # In particular, check signs of zeros. mod = operator.mod self.assertEqualAndEqualSign(mod(-1.0, 1.0), 0.0) self.assertEqualAndEqualSign(mod(-1e-100, 1.0), 1.0) self.assertEqualAndEqualSign(mod(-0.0, 1.0), 0.0) self.assertEqualAndEqualSign(mod(0.0, 1.0), 0.0) self.assertEqualAndEqualSign(mod(1e-100, 1.0), 1e-100) self.assertEqualAndEqualSign(mod(1.0, 1.0), 0.0) self.assertEqualAndEqualSign(mod(-1.0, -1.0), -0.0) self.assertEqualAndEqualSign(mod(-1e-100, -1.0), -1e-100) self.assertEqualAndEqualSign(mod(-0.0, -1.0), -0.0) self.assertEqualAndEqualSign(mod(0.0, -1.0), -0.0) self.assertEqualAndEqualSign(mod(1e-100, -1.0), -1.0) self.assertEqualAndEqualSign(mod(1.0, -1.0), -0.0)
def getSymbolikImport(vw, impname): """ Resolve (hopefully) and return a symbolik import emulation function for the given import by name. """ modbase = vw.getMeta('SymbolikImportEmulation') if modbase is None: return None nameparts = impname.split('.') # FIXME *.malloc! # FIXME cache mod = vw.loadModule(modbase) return vstruct.resolve(mod, nameparts)
def __init__(self, code, objects=None): self._OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.mod), ('/', operator.truediv), ('*', operator.mul), ] self._ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in self._OPERATORS] self._ASSIGN_OPERATORS.append(('=', lambda cur, right: right)) self._VARNAME_PATTERN = r'[a-zA-Z_$][a-zA-Z_$0-9]*' if objects is None: objects = {} self.code = code self._functions = {} self._objects = objects
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_valueholder_integer_operations(x, y, operation, inplace_operation): v = ValueHolder(x) is_supported = operation not in unsupported_operations.get(type(x), set()) isdiv = ('div' in operation.__name__) or ('mod' in operation.__name__) # forward... with optional_contextmanager(pytest.raises(TypeError), ignore=is_supported): with optional_contextmanager(pytest.raises(ZeroDivisionError), ignore=y or not isdiv): assert operation(x, y) == operation(v, y) # backward... with optional_contextmanager(pytest.raises(TypeError), ignore=is_supported): with optional_contextmanager(pytest.raises(ZeroDivisionError), ignore=x or not isdiv): assert operation(y, x) == operation(y, v) # in place... if inplace_operation is not None: with optional_contextmanager(pytest.raises(TypeError), ignore=is_supported): with optional_contextmanager(pytest.raises(ZeroDivisionError), ignore=y or not isdiv): inplace_operation(v, y) assert v == operation(x, y)
def execute(self, context): x = 0 y = 0 for v in range(0, self.county): if operator.mod(v, 2) == 0: x = 0 else: x = self.radius for u in range(0, self.countx): if self.mesh: bpy.ops.mesh.primitive_cylinder_add( vertices=self.segments, radius=self.radius + self.radsup, depth=self.height, location=(x, y, 0)) else: bpy.ops.curve.primitive_bezier_circle_add( radius=self.radius + self.radsup, location=(x, y, 0)) obj = bpy.context.active_object obj.data.extrude = self.height obj.data.dimensions = '2D' obj.data.fill_mode = 'BOTH' x += 2 * self.radius y += 2 * self.radius * math.sqrt(0.75) return {'FINISHED'}
def execute(self, context): x = 0 y = 0 obj = bpy.context.active_object if obj: for v in range(0, self.county): if self.trisq: if operator.mod(v, 2) == 0: x = 0 else: x = self.radius else: x = 0 for u in range(0, self.countx): if not (u == 0 and v == 0): bpy.ops.object.duplicate(linked=self.linkedcopy) obj = bpy.context.active_object obj.location = (x, y, 0) x += 2 * self.radius if self.trisq: y += 2 * self.radius * math.sqrt(0.75) else: y += 2 * self.radius return {'FINISHED'}
def add_globals(self): "Add some Scheme standard procedures." import math, cmath, operator as op from functools import reduce self.update(vars(math)) self.update(vars(cmath)) self.update({ '+':op.add, '-':op.sub, '*':op.mul, '/':op.itruediv, 'níl':op.not_, 'agus':op.and_, '>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq, 'mod':op.mod, 'frmh':cmath.sqrt, 'dearbhluach':abs, 'uas':max, 'íos':min, 'cothrom_le?':op.eq, 'ionann?':op.is_, 'fad':len, 'cons':cons, 'ceann':lambda x:x[0], 'tóin':lambda x:x[1:], 'iarcheangail':op.add, 'liosta':lambda *x:list(x), 'liosta?': lambda x:isa(x,list), 'folamh?':lambda x: x == [], 'adamh?':lambda x: not((isa(x, list)) or (x == None)), 'boole?':lambda x: isa(x, bool), 'scag':lambda f, x: list(filter(f, x)), 'cuir_le':lambda proc,l: proc(*l), 'mapáil':lambda p, x: list(map(p, x)), 'lódáil':lambda fn: load(fn), 'léigh':lambda f: f.read(), 'oscail_comhad_ionchuir':open,'dún_comhad_ionchuir':lambda p: p.file.close(), 'oscail_comhad_aschur':lambda f:open(f,'w'), 'dún_comhad_aschur':lambda p: p.close(), 'dac?':lambda x:x is eof_object, 'luacháil':lambda x: evaluate(x), 'scríobh':lambda x,port=sys.stdout:port.write(to_string(x) + '\n')}) return self
def __isub__(self, other): if not isinstance(other, (PyPtxt, int)): raise TypeError("PyPtxt '-=' error: lhs must be of type PyPtxt or int instead of type " + str(type(other))) from operator import sub, mod if isinstance(other, PyPtxt): self = PyPtxt([mod(elt, self.__pyfhel.getModulus()) for elt in list(map(sub, self.getPtxt(), other.getPtxt()))], self.getPyfhel()) else: constPtxt = [other for _ in range(self.__length)] self = PyPtxt([mod(elt, self.__pyfhel.getModulus()) for elt in list(map(sub, self.getPtxt(), constPtxt))], self.getPyfhel()) del constPtxt return self # MULTIPLY: # '*' operator
def __imul__(self, other): if not isinstance(other, (PyPtxt, int)): raise TypeError("PyPtxt '*=' error: lhs must be of type PyPtxt or int instead of type " + str(type(other))) from operator import mul, mod if isinstance(other, PyPtxt): self = PyPtxt([mod(elt, self.__pyfhel.getModulus()) for elt in list(map(mul, self.getPtxt(), other.getPtxt()))], self.getPyfhel()) else: constPtxt = [other for _ in range(self.__length)] self = PyPtxt([mod(elt, self.__pyfhel.getModulus()) for elt in list(map(mul, self.getPtxt(), constPtxt))], self.getPyfhel()) del constPtxt return self # SCALAR PRODUCT: # '%' operator
def easter(g_year): """Return fixed date of Easter in Gregorian year g_year.""" century = quotient(g_year, 100) + 1 shifted_epact = mod(14 + 11 * mod(g_year, 19) - quotient(3 * century, 4) + quotient(5 + (8 * century), 25), 30) adjusted_epact = ((shifted_epact + 1) if ((shifted_epact == 0) or ((shifted_epact == 1) and (10 < mod(g_year, 19)))) else shifted_epact) paschal_moon = (fixed_from_gregorian(gregorian_date(g_year, APRIL, 19)) - adjusted_epact) return kday_after(SUNDAY, paschal_moon) # see lines 1429-1431 in calendrica-3.0.cl
def standard_from_sundial(tee, location): """Return standard time of temporal moment, tee, at location, location. Return BOGUS if temporal hour is undefined that day.""" date = fixed_from_moment(tee) hour = 24 * mod(tee, 1) if (6 <= hour <= 18): h = daytime_temporal_hour(date, location) elif (hour < 6): h = nighttime_temporal_hour(date - 1, location) else: h = nighttime_temporal_hour(date, location) # return if (h == BOGUS): return BOGUS elif (6 <= hour <= 18): return sunrise(date, location) + ((hour - 6) * h) elif (hour < 6): return sunset(date - 1, location) + ((hour + 6) * h) else: return sunset(date, location) + ((hour - 18) * h) # see lines 3075-3079 in calendrica-3.0.cl
def lunar_phase(tee): """Return the lunar phase, as an angle in degrees, at moment tee. An angle of 0 means a new moon, 90 degrees means the first quarter, 180 means a full moon, and 270 degrees means the last quarter.""" phi = mod(lunar_longitude(tee) - solar_longitude(tee), 360) t0 = nth_new_moon(0) n = iround((tee - t0) / MEAN_SYNODIC_MONTH) phi_prime = (deg(360) * mod((tee - nth_new_moon(n)) / MEAN_SYNODIC_MONTH, 1)) if abs(phi - phi_prime) > deg(180): return phi_prime else: return phi # see lines 3615-3625 in calendrica-3.0.cl
def fixed_from_arithmetic_persian(p_date): """Return fixed date equivalent to Persian date p_date.""" day = standard_day(p_date) month = standard_month(p_date) p_year = standard_year(p_date) y = (p_year - 474) if (0 < p_year) else (p_year - 473) year = mod(y, 2820) + 474 temp = (31 * (month - 1)) if (month <= 7) else ((30 * (month - 1)) + 6) return ((PERSIAN_EPOCH - 1) + (1029983 * quotient(y, 2820)) + (365 * (year - 1)) + quotient((31 * year) - 5, 128) + temp + day) # see lines 3960-3986 in calendrica-3.0.cl
def fixed_from_tibetan(t_date): """Return the fixed date corresponding to Tibetan lunar date, t_date.""" year = tibetan_year(t_date) month = tibetan_month(t_date) leap_month = tibetan_leap_month(t_date) day = tibetan_day(t_date) leap_day = tibetan_leap_day(t_date) months = ifloor((804/65 * (year - 1)) + (67/65 * month) + (-1 if leap_month else 0) + 64/65) days = (30 * months) + day mean = ((days * 11135/11312) -30 + (0 if leap_day else -1) + 1071/1616) solar_anomaly = mod((days * 13/4824) + 2117/4824, 1) lunar_anomaly = mod((days * 3781/105840) + 2837/15120, 1) sun = -tibetan_sun_equation(12 * solar_anomaly) moon = tibetan_moon_equation(28 * lunar_anomaly) return ifloor(TIBETAN_EPOCH + mean + sun + moon) # see lines 5757-5796 in calendrica-3.0.cl
def __mod__(self, trc): return self.apply_op2(trc, operator.mod)
def test_mod (self): c1 = pygame.Color (0xFFFFFFFF) self.assertEquals (c1.r, 255) self.assertEquals (c1.g, 255) self.assertEquals (c1.b, 255) self.assertEquals (c1.a, 255) c2 = pygame.Color (2, 4, 8, 16) self.assertEquals (c2.r, 2) self.assertEquals (c2.g, 4) self.assertEquals (c2.b, 8) self.assertEquals (c2.a, 16) c3 = c1 % c2 self.assertEquals (c3.r, 1) self.assertEquals (c3.g, 3) self.assertEquals (c3.b, 7) self.assertEquals (c3.a, 15) # Issue #286: Is type checking done for Python 3.x? self.assertRaises (TypeError, operator.mod, c1, None) self.assertRaises (TypeError, operator.mod, None, c1) # Division by zero check dividend = pygame.Color (255, 255, 255, 255) for i in range (4): divisor = pygame.Color (64, 64, 64, 64) divisor[i] = 0 quotient = pygame.Color (63, 63, 63, 63) quotient[i] = 0 self.assertEqual (dividend % divisor, quotient)
def module(self, *args): if not len(args) > 1: raise EvaluateException('% requires at least 2 parameters!' + ' (' + str(len(args)) + ' given).') elif False in [isinstance(x, NumberType) for x in args]: raise EvaluateException('% requires all parameters to be numbers!') elif 0 in [x.content for x in args[1:]]: raise EvaluateException('module by zero!') return reduce(op.mod, args[1:], args[0])
def _test_quantity_mod(self, unit, func): a = self.Q_('10*meter') b = self.Q_('3*second') self.assertRaises(DimensionalityError, op.mod, a, b) self.assertRaises(DimensionalityError, op.mod, 3, b) self.assertRaises(DimensionalityError, op.mod, a, 3) self.assertRaises(DimensionalityError, op.imod, a, b) self.assertRaises(DimensionalityError, op.imod, 3, b) self.assertRaises(DimensionalityError, op.imod, a, 3) func(op.mod, unit * 10.0, '4.2*meter/meter', 1.6, unit)
def test_float_modulus_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for dt in np.typecodes['Float']: msg = 'dtype: %s' % (dt,) fa = a.astype(dt) fb = b.astype(dt) # use list comprehension so a_ and b_ are scalars div = [self.floordiv(a_, b_) for a_, b_ in zip(fa, fb)] rem = [self.mod(a_, b_) for a_, b_ in zip(fa, fb)] assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg)
def test_float_modulus_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = self.mod(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = self.mod(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with warnings.catch_warnings(): warnings.simplefilter('always') warnings.simplefilter('ignore', RuntimeWarning) for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = self.mod(fone, fzer) assert_(np.isnan(rem), 'dt: %s' % dt) # MSVC 2008 returns NaN here, so disable the check. #rem = self.mod(fone, finf) #assert_(rem == fone, 'dt: %s' % dt) rem = self.mod(fone, fnan) assert_(np.isnan(rem), 'dt: %s' % dt) rem = self.mod(finf, fone) assert_(np.isnan(rem), 'dt: %s' % dt)
def test_mod_scalar(self): with testing.NumpyError(divide='ignore', invalid='ignore'): self.check_array_scalar_op(operator.mod)
def test_rmod_scalar(self): with testing.NumpyError(divide='ignore', invalid='ignore'): self.check_array_scalar_op(operator.mod, swap=True)
def test_mod_scalarzero(self): with testing.NumpyError(divide='ignore', invalid='ignore'): self.check_array_scalarzero_op(operator.mod)