Factory function for making binary operator methods on a Factor.

    Returns a function, "reflected_binary_operator" suitable for implementing
    functions like __radd__.
494066
def reflected_binary_operator(op):
    
    assert not is_comparison(op)

    @with_name(method_name_for_op(op, commute=True))
    @coerce_numbers_to_my_dtype
    def reflected_binary_operator(self, other):

        if isinstance(self, NumericalExpression):
            self_expr, other_expr, new_inputs = self.build_binary_op(
                op, other
            )
            return NumExprFactor(
                "({left}) {op} ({right})".format(
                    left=other_expr,
                    right=self_expr,
                    op=op,
                ),
                new_inputs,
                dtype=binop_return_dtype(op, other.dtype, self.dtype)
            )

        # Only have to handle the numeric case because in all other valid cases
        # the corresponding left-binding method will be called.
        elif isinstance(other, Number):
            return NumExprFactor(
                "{constant} {op} x_0".format(op=op, constant=other),
                binds=(self,),
                dtype=binop_return_dtype(op, other.dtype, self.dtype),
            )
        raise BadBinaryOperator(op, other, self)
    return reflected_binary_operator
880414
def derivative_factory(name):
    """"""

    if name == 'sin':
        def derivative(self, point):
            """Return the derivative operator."""
            return MultiplyOperator(cos(self.domain)(point))
    elif name == 'cos':
        def derivative(self, point):
            """Return the derivative operator."""
            point = self.domain.element(point)
            return MultiplyOperator(-sin(self.domain)(point))
    elif name == 'tan':
        def derivative(self, point):
            """Return the derivative operator."""
            return MultiplyOperator(1 + self(point) ** 2)
    elif name == 'sqrt':
        def derivative(self, point):
            """Return the derivative operator."""
            return MultiplyOperator(0.5 / self(point))
    elif name == 'square':
        def derivative(self, point):
            """Return the derivative operator."""
            point = self.domain.element(point)
            return MultiplyOperator(2.0 * point)
    elif name == 'log':
        def derivative(self, point):
            """Return the derivative operator."""
            point = self.domain.element(point)
            return MultiplyOperator(1.0 / point)
    elif name == 'exp':
        def derivative(self, point):
            """Return the derivative operator."""
            return MultiplyOperator(self(point))
    elif name == 'reciprocal':
        def derivative(self, point):
            """Return the derivative operator."""
            point = self.domain.element(point)
            return MultiplyOperator(-self(point) ** 2)
    elif name == 'sinh':
        def derivative(self, point):
            """Return the derivative operator."""
            point = self.domain.element(point)
            return MultiplyOperator(cosh(self.domain)(point))
    elif name == 'cosh':
        def derivative(self, point):
            """Return the derivative operator."""
            return MultiplyOperator(sinh(self.domain)(point))
    else:
        # Fallback to default
        derivative = Operator.derivative

    return derivative
1282775
def binary_op(data, op, other, blen=None, storage=None, create='array',
              **kwargs):
    """"""

    # normalise scalars
    if hasattr(other, 'shape') and len(other.shape) == 0:
        other = other[()]

    if np.isscalar(other):
        def f(block):
            return op(block, other)
        return map_blocks(data, f, blen=blen, storage=storage, create=create, **kwargs)

    elif len(data) == len(other):
        def f(a, b):
            return op(a, b)
        return map_blocks((data, other), f, blen=blen, storage=storage, create=create,
                          **kwargs)

    else:
        raise NotImplementedError('argument type not supported')
1317568
private static void reflect(Tuple2d p, Tuple2d base, double a, double b) {
        double x = a * (p.x - base.x) + b * (p.y - base.y) + base.x;
        double y = b * (p.x - base.x) - a * (p.y - base.y) + base.y;
        p.x = x;
        p.y = y;
    }
812560
public Factor getBinaryRuleExpectations() {
    Tensor binaryRuleWeights = binaryRuleDistribution.coerceToDiscrete().getWeights();
    SparseTensor tensor = SparseTensor.copyRemovingZeros(binaryRuleWeights,
        binaryRuleExpectations);

    return new TableFactor(binaryRuleDistribution.getVars(), tensor);
  }
645373
def unary_operator(op):
    
    # Only negate is currently supported.
    valid_ops = {'-'}
    if op not in valid_ops:
        raise ValueError("Invalid unary operator %s." % op)

    @with_doc("Unary Operator: '%s'" % op)
    @with_name(unary_op_name(op))
    def unary_operator(self):
        if self.dtype != float64_dtype:
            raise TypeError(
                "Can't apply unary operator {op!r} to instance of "
                "{typename!r} with dtype {dtypename!r}.\n"
                "{op!r} is only supported for Factors of dtype "
                "'float64'.".format(
                    op=op,
                    typename=type(self).__name__,
                    dtypename=self.dtype.name,
                )
            )

        # This can't be hoisted up a scope because the types returned by
        # unary_op_return_type aren't defined when the top-level function is
        # invoked.
        if isinstance(self, NumericalExpression):
            return NumExprFactor(
                "{op}({expr})".format(op=op, expr=self._expr),
                self.inputs,
                dtype=float64_dtype,
            )
        else:
            return NumExprFactor(
                "{op}x_0".format(op=op),
                (self,),
                dtype=float64_dtype,
            )
    return unary_operator
1073742
def construct_func_expr(n):
    
    op = n[0]
    if op.startswith('_') and op.endswith('_'):
        op = op.strip('_')
        if op == 'var':
            return Var(str(n[1]))
        elif op == 'literal':
            if isinstance(n[1], basestring):
                raise "not implemented"
            return Constant(n[1])
        elif op == 'cast':
            raise "not implemented"
    elif op in '+-/*':
        return ArithErrFunc(op, *map(construct_func_expr,n[1:]))
    else:
        klass = __agg2f__.get(op, None)
        if klass:
            return klass(map(construct_func_expr, n[1:]))
        raise "no klass"
1119985
def rewrite_binary_composition_inside_ternary_conditional(ir_blocks):
    """"""
    def visitor_fn(expression):
        """Expression visitor function."""
        # MATCH queries do not allow BinaryComposition inside a TernaryConditional's true/false
        # value blocks, since OrientDB cannot produce boolean values for comparisons inside them.
        # We transform any structures that resemble the following:
        #    TernaryConditional(predicate, X, Y), with X or Y of type BinaryComposition
        # into the following:
        # - if X is of type BinaryComposition, and Y is not,
        #    BinaryComposition(
        #        u'=',
        #        TernaryConditional(
        #            predicate,
        #            TernaryConditional(X, true, false),
        #            Y
        #        ),
        #        true
        #    )
        # - if Y is of type BinaryComposition, and X is not,
        #    BinaryComposition(
        #        u'=',
        #        TernaryConditional(
        #            predicate,
        #            X,
        #            TernaryConditional(Y, true, false),
        #        ),
        #        true
        #    )
        # - if both X and Y are of type BinaryComposition,
        #    BinaryComposition(
        #        u'=',
        #        TernaryConditional(
        #            predicate,
        #            TernaryConditional(X, true, false),
        #            TernaryConditional(Y, true, false)
        #        ),
        #        true
        #    )
        if not isinstance(expression, TernaryConditional):
            return expression

        if_true = expression.if_true
        if_false = expression.if_false

        true_branch_rewriting_necessary = isinstance(if_true, BinaryComposition)
        false_branch_rewriting_necessary = isinstance(if_false, BinaryComposition)

        if not (true_branch_rewriting_necessary or false_branch_rewriting_necessary):
            # No rewriting is necessary.
            return expression

        if true_branch_rewriting_necessary:
            if_true = TernaryConditional(if_true, TrueLiteral, FalseLiteral)

        if false_branch_rewriting_necessary:
            if_false = TernaryConditional(if_false, TrueLiteral, FalseLiteral)

        ternary = TernaryConditional(expression.predicate, if_true, if_false)
        return BinaryComposition(u'=', ternary, TrueLiteral)

    new_ir_blocks = [
        block.visit_and_update_expressions(visitor_fn)
        for block in ir_blocks
    ]

    return new_ir_blocks
1074995
def makeHashFunction(self, originalHashFunction, syntheticMemberList):
        
        if originalHashFunction is None:
            return None

        for member in syntheticMemberList:
            if not member.readOnly():
                return None

        # All synthetic members are read-only: generate a hash function.
        def hash_function(instance):
            values = [getattr(instance, m.privateMemberName()) for m in syntheticMemberList]
            if inspect.isfunction(originalHashFunction) or inspect.ismethod(originalHashFunction):
                values.append(originalHashFunction(instance))
            return hash(tuple(values))

        return hash_function
702658
def gradient_factory(name):
    """"""

    if name == 'sin':
        def gradient(self):
            """Return the gradient operator."""
            return cos(self.domain)
    elif name == 'cos':
        def gradient(self):
            """Return the gradient operator."""
            return -sin(self.domain)
    elif name == 'tan':
        def gradient(self):
            """Return the gradient operator."""
            return 1 + square(self.domain) * self
    elif name == 'sqrt':
        def gradient(self):
            """Return the gradient operator."""
            return FunctionalQuotient(ConstantFunctional(self.domain, 0.5),
                                      self)
    elif name == 'square':
        def gradient(self):
            """Return the gradient operator."""
            return ScalingFunctional(self.domain, 2.0)
    elif name == 'log':
        def gradient(self):
            """Return the gradient operator."""
            return reciprocal(self.domain)
    elif name == 'exp':
        def gradient(self):
            """Return the gradient operator."""
            return self
    elif name == 'reciprocal':
        def gradient(self):
            """Return the gradient operator."""
            return FunctionalQuotient(ConstantFunctional(self.domain, -1.0),
                                      square(self.domain))
    elif name == 'sinh':
        def gradient(self):
            """Return the gradient operator."""
            return cosh(self.domain)
    elif name == 'cosh':
        def gradient(self):
            """Return the gradient operator."""
            return sinh(self.domain)
    else:
        # Fallback to default
        gradient = Functional.gradient

    return gradient
603162
def _make_operator(method_name):
        """"""
        def operator(self, other):
            """Operator delegating to the :class:`float` method `method_name`"""
            float_operator = getattr(float, method_name)
            try:
                float_other = float(other)
            except (ValueError, TypeError):
                return False
            return float_operator(float(self), float_other)
        return operator
680569
def _create_binary_trigger(trigger):
    """"""

    ops = {
        0: ">",
        1: "<",
        2: ">=",
        3: "<=",
        4: "==",
        5: 'always'
    }

    op_codes = {y: x for x, y in ops.items()}
    source = 0

    if isinstance(trigger, TrueTrigger):
        op_code = op_codes['always']
    elif isinstance(trigger, FalseTrigger):
        raise ArgumentError("Cannot express a never trigger in binary descriptor", trigger=trigger)
    else:
        op_code = op_codes[trigger.comp_string]

        if trigger.use_count:
            source = 1

    return (op_code << 1) | source
751650
private RandomVariable[] getBasisFunctions(RandomVariable underlying) {
		double min = underlying.getMin();
		double max = underlying.getMax();

		ArrayList<RandomVariable> basisFunctionList = new ArrayList<>();
		double[] discretization = (new TimeDiscretizationFromArray(min, numberOfBins, (max-min)/numberOfBins)).getAsDoubleArray();
		for(double discretizationStep : discretization) {
			RandomVariable indicator = underlying.sub(discretizationStep).choose(new RandomVariableFromDoubleArray(1.0), new RandomVariableFromDoubleArray(0.0));
			basisFunctionList.add(indicator);
		}

		return basisFunctionList.toArray(new RandomVariable[0]);
	}
757805
function baseCreateWrapper(bindData) {
    var func = bindData[0],
        bitmask = bindData[1],
        partialArgs = bindData[2],
        partialRightArgs = bindData[3],
        thisArg = bindData[4],
        arity = bindData[5];

    var isBind = bitmask & 1,
        isBindKey = bitmask & 2,
        isCurry = bitmask & 4,
        isCurryBound = bitmask & 8,
        key = func;

    function bound() {
      var thisBinding = isBind ? thisArg : this;
      if (partialArgs) {
        var args = slice(partialArgs);
        push.apply(args, arguments);
      }
      if (partialRightArgs || isCurry) {
        args || (args = slice(arguments));
        if (partialRightArgs) {
          push.apply(args, partialRightArgs);
        }
        if (isCurry && args.length < arity) {
          bitmask |= 16 & ~32;
          return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
        }
      }
      args || (args = arguments);
      if (isBindKey) {
        func = thisBinding[key];
      }
      if (this instanceof bound) {
        thisBinding = baseCreate(func.prototype);
        var result = func.apply(thisBinding, args);
        return isObject(result) ? result : thisBinding;
      }
      return func.apply(thisBinding, args);
    }
    return bound;
  }
852764
def Compile(self, filter_implementation):
    """"""
    operator = self.operator.lower()
    if operator in ('and', '&&'):
      method = 'AndFilter'
    elif operator in ('or', '||'):
      method = 'OrFilter'
    else:
      raise errors.ParseError(
          'Invalid binary operator {0:s}'.format(operator))

    args = [x.Compile(filter_implementation) for x in self.args]
    return getattr(filter_implementation, method)(*args)
859149
def func_factory(p, method: str) -> callable:
    

    def callback(pretty: bool = False):
        res = getattr(p, method)
        dump = partial(json.dumps, indent=4) if pretty else partial(json.dumps)
        click.echo(dump(res))

    return callback
547387
def make_binary(lineno, operator, left, right, func=None, type_=None):
    
    return symbols.BINARY.make_node(operator, left, right, lineno, func, type_)