我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用operator.abs()。
def __init__(self): Module.__init__(self) self.add_method('+', self.addition) self.add_method('-', self.subtraction) self.add_method('*', self.multiplication) self.add_method('/', self.division) self.add_method('%', self.module) self.add_method('**', self.power) self.add_method('abs', self.abs) self.add_method('min', self.minimum) self.add_method('max', self.maximum) self.add_method('strcat', self.strcat) self.add_method('substr', self.substr) self.add_method('strlen', self.strlen) self.add_method('strindex', self.strindex) self.add_method('symcat', self.symcat) self.add_method('randint', self.randint) random.seed(time.time())
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 __abs__(self): return self.apply_op1(operator.abs)
def __abs__(self): return abs(self.trace)
def foo2(): return map(o.abs, [1, 2, 3])
def abs(self, *args): if not len(args) is 1: raise EvaluateException('Abs requires 1 parameter!') elif not isinstance(args[0], NumberType): raise EvaluateException('Abs requires all parameters to be numbers!') return op.abs(args[0])
def test_abs_array(self): self.check_array_op(operator.abs)
def test_abs_zerodim(self): self.check_zerodim_op(operator.abs)
def test_abs(self): self.assertRaises(TypeError, operator.abs) self.assertRaises(TypeError, operator.abs, None) self.assertEqual(operator.abs(-1), 1) self.assertEqual(operator.abs(1), 1)
def __abs__(self): return NonStandardInteger(operator.abs(self.val))
def test_registry_association(): ds = fake_random_ds(64, nprocs=1, length_unit=10) a = ds.quan(3, 'cm') b = YTQuantity(4, 'm') c = ds.quan(6, '') d = 5 assert_equal(id(a.units.registry), id(ds.unit_registry)) def binary_op_registry_comparison(op): e = op(a, b) f = op(b, a) g = op(c, d) h = op(d, c) assert_equal(id(e.units.registry), id(ds.unit_registry)) assert_equal(id(f.units.registry), id(b.units.registry)) assert_equal(id(g.units.registry), id(h.units.registry)) assert_equal(id(g.units.registry), id(ds.unit_registry)) def unary_op_registry_comparison(op): c = op(a) d = op(b) assert_equal(id(c.units.registry), id(ds.unit_registry)) assert_equal(id(d.units.registry), id(b.units.registry)) binary_ops = [operator.add, operator.sub, operator.mul, operator.truediv] if hasattr(operator, "div"): binary_ops.append(operator.div) for op in binary_ops: binary_op_registry_comparison(op) for op in [operator.abs, operator.neg, operator.pos]: unary_op_registry_comparison(op)
def test_abs(self): self.assertRaises(TypeError, operator.abs) self.assertRaises(TypeError, operator.abs, None) self.assertTrue(operator.abs(-1) == 1) self.assertTrue(operator.abs(1) == 1)
def round_significant(x, n=1): """Round x to n significant digits.""" return 0 if x==0 else round(x, -int(floor(log10(abs(x)))) + (n-1))
def floor_significant(x, n=1): """Floor x to n significant digits.""" return 0 if x==0 else floor_digits(x, -int(floor(log10(abs(x)))) + (n-1))
def ceil_significant(x, n=1): """Ceil x to n significant digits.""" return 0 if x==0 else ceil_digits(x, -int(floor(log10(abs(x)))) + (n-1))
def setUp(self): super(CoreUnaryOpsTest, self).setUp() self.ops = [ ('abs', operator.abs, tf.abs, core.abs_function), ('neg', operator.neg, tf.neg, core.neg), # TODO(shoyer): add unary + to core TensorFlow ('pos', None, None, None), ('sign', None, tf.sign, core.sign), ('reciprocal', None, tf.reciprocal, core.reciprocal), ('square', None, tf.square, core.square), ('round', None, tf.round, core.round_function), ('sqrt', None, tf.sqrt, core.sqrt), ('rsqrt', None, tf.rsqrt, core.rsqrt), ('log', None, tf.log, core.log), ('exp', None, tf.exp, core.exp), ('log', None, tf.log, core.log), ('ceil', None, tf.ceil, core.ceil), ('floor', None, tf.floor, core.floor), ('cos', None, tf.cos, core.cos), ('sin', None, tf.sin, core.sin), ('tan', None, tf.tan, core.tan), ('acos', None, tf.acos, core.acos), ('asin', None, tf.asin, core.asin), ('atan', None, tf.atan, core.atan), ('lgamma', None, tf.lgamma, core.lgamma), ('digamma', None, tf.digamma, core.digamma), ('erf', None, tf.erf, core.erf), ('erfc', None, tf.erfc, core.erfc), ('lgamma', None, tf.lgamma, core.lgamma), ] total_size = np.prod([v.size for v in self.original_lt.axes.values()]) self.test_lt = core.LabeledTensor( tf.cast(self.original_lt, tf.float32) / total_size, self.original_lt.axes)
def __abs__(self): return _op1(self, operator.abs)
def __init__(self, start=0.0, end=1.0): super(UniformNode, self).__init__() self._shift = min(start, end) self._scale = abs(end - start) self._describe = 'uniform(%f, %f)' % (start, end)
def norm_cdf(x, mu=0, sigma=1): """ Parameters ---------- x : mu : float distribution's mean sigma : float distribution's standard deviation Returns ------- float pdf or cdf value, depending on input flag ``f`` Notes ----- http://stackoverflow.com/questions/809362/how-to-calculate-cumulative-normal-distribution-in-python Examples -------- Compares total absolute error for 100 values >>> from scipy.stats import norm >>> sum( [abs(Util.norm_cdf(x) - norm.cdf(x)) for x in range(100)]) 3.3306690738754696e-16 """ y = 0.5 * (1 - math.erf(-(x - mu)/(sigma * math.sqrt(2.0)))) if y > 1: y = 1 return y
def norm_pdf(x, mu=0, sigma=1): u = (x - mu)/abs(sigma) y = (1/(math.sqrt(2 * math.pi) * abs(sigma))) * math.exp(-u*u/2) return y
def __abs__(self): return Vec(map(op.abs, self))
def setUp(self): super(CoreUnaryOpsTest, self).setUp() self.ops = [ ('abs', operator.abs, math_ops.abs, core.abs_function), ('neg', operator.neg, math_ops.negative, core.neg), # TODO(shoyer): add unary + to core TensorFlow ('pos', None, None, None), ('sign', None, math_ops.sign, core.sign), ('reciprocal', None, math_ops.reciprocal, core.reciprocal), ('square', None, math_ops.square, core.square), ('round', None, math_ops.round, core.round_function), ('sqrt', None, math_ops.sqrt, core.sqrt), ('rsqrt', None, math_ops.rsqrt, core.rsqrt), ('log', None, math_ops.log, core.log), ('exp', None, math_ops.exp, core.exp), ('log', None, math_ops.log, core.log), ('ceil', None, math_ops.ceil, core.ceil), ('floor', None, math_ops.floor, core.floor), ('cos', None, math_ops.cos, core.cos), ('sin', None, math_ops.sin, core.sin), ('tan', None, math_ops.tan, core.tan), ('acos', None, math_ops.acos, core.acos), ('asin', None, math_ops.asin, core.asin), ('atan', None, math_ops.atan, core.atan), ('lgamma', None, math_ops.lgamma, core.lgamma), ('digamma', None, math_ops.digamma, core.digamma), ('erf', None, math_ops.erf, core.erf), ('erfc', None, math_ops.erfc, core.erfc), ('lgamma', None, math_ops.lgamma, core.lgamma), ] total_size = np.prod([v.size for v in self.original_lt.axes.values()]) self.test_lt = core.LabeledTensor( math_ops.cast(self.original_lt, dtypes.float32) / total_size, self.original_lt.axes)
def parse_file(self, filename): """ Parses input file into FollowJointTrajectoryGoal format @param filename: input filename """ #open recorded file with open(filename, 'r') as f: lines = f.readlines() #read joint names specified in file joint_names = lines[0].rstrip().split(',') #parse joint names for right limb for name in joint_names: if self.limb == name[:-3]: self.goal.trajectory.joint_names.append(name) def find_start_offset(pos): #create empty lists cur = [] cmd = [] dflt_vel = [] vel_param = self._param_ns + "%s_default_velocity" #for all joints find our current and first commanded position #reading default velocities from the parameter server if specified for name in joint_names: if self.limb == name[:-3]: cmd.append(pos[name]) cur.append(self.arm.joint_angle(name)) prm = rospy.get_param(vel_param % name, 0.25) dflt_vel.append(prm) diffs = map(operator.sub, cmd, cur) diffs = map(operator.abs, diffs) #determine the largest time offset necessary across all joints offset = max(map(operator.div, diffs, dflt_vel)) return offset for idx, values in enumerate(lines[1:]): #clean each line of file cmd, values = self._clean_line(values, joint_names) #find allowable time offset for move to start position if idx == 0: # Set the initial position to be the current pose. # This ensures we move slowly to the starting point of the # trajectory from the current pose - The user may have moved # arm since recording cur_cmd = [self.arm.joint_angle(jnt) for jnt in self.goal.trajectory.joint_names] self._add_point(cur_cmd, self.limb, 0.0) start_offset = find_start_offset(cmd) # Gripper playback won't start until the starting movement's # duration has passed, and the actual trajectory playback begins self._slow_move_offset = start_offset self._trajectory_start_offset = rospy.Duration(start_offset + values[0]) #add a point for this set of commands with recorded time cur_cmd = [cmd[jnt] for jnt in self.goal.trajectory.joint_names] self._add_point(cur_cmd, self.limb, values[0] + start_offset) if self.gripper: cur_cmd = [cmd[self.gripper_name]] self._add_point(cur_cmd, self.gripper_name, values[0] + start_offset)