FIXME: Optimise, perhaps moving the validator to a __set function.
18195
public function update(array $data, $isAtomic = true)
    {
        $validationStatus = array();
        // Check all values before modifying the object.
        foreach ($data as $name => $value) {
            $fieldValidationStatus = $this->validate($name, $value);
            if ($fieldValidationStatus) {
                $validationStatus[$name] = $fieldValidationStatus;
            } elseif (!$isAtomic) {
                // If the field is valid and the operation does not need
                // to be atomic, keep the value.
                $this->$name = $value;
            }
        }

        if (empty($validationStatus)) {
            // If the operation is not atomic, the valid values have
            // already been set. Otherwise, all the values can now
            // be safely assigned.
            if ($isAtomic) {
                // The fields' values are valid, the object can be updated.
                foreach ($data as $name => $value) {
                    // Check each value before modifying the object.
                    $this->$name = $value;
                }
            }
        } else {
            // If there is something in the validation status, the validation
            // failed. Load the validation status into an exception.
            $exception = new Validators\Exception;
            $exception->setValidationStatus($validationStatus);
            throw $exception;
        }

        // If the entity has an now an ID, register it with its Factory.
        $id = @$data['id'];
        if ($id && !$this->getFactory()->getEntity($id)) {
            $this->getFactory()->registerEntity($this);
        }
    }
93004
def validate(self, validators, resp_obj):
        
        self.validation_results = []
        if not validators:
            return

        logger.log_debug("start to validate.")

        validate_pass = True
        failures = []

        for validator in validators:
            # validator should be LazyFunction object
            if not isinstance(validator, parser.LazyFunction):
                raise exceptions.ValidationFailure(
                    "validator should be parsed first: {}".format(validators))

            # evaluate validator args with context variable mapping.
            validator_args = validator.get_args()
            check_item, expect_item = validator_args
            check_value = self.__eval_validator_check(
                check_item,
                resp_obj
            )
            expect_value = self.__eval_validator_expect(expect_item)
            validator.update_args([check_value, expect_value])

            comparator = validator.func_name
            validator_dict = {
                "comparator": comparator,
                "check": check_item,
                "check_value": check_value,
                "expect": expect_item,
                "expect_value": expect_value
            }
            validate_msg = "\nvalidate: {} {} {}({})".format(
                check_item,
                comparator,
                expect_value,
                type(expect_value).__name__
            )

            try:
                validator.to_value(self.test_variables_mapping)
                validator_dict["check_result"] = "pass"
                validate_msg += "\t==> pass"
                logger.log_debug(validate_msg)
            except (AssertionError, TypeError):
                validate_pass = False
                validator_dict["check_result"] = "fail"
                validate_msg += "\t==> fail"
                validate_msg += "\n{}({}) {} {}({})".format(
                    check_value,
                    type(check_value).__name__,
                    comparator,
                    expect_value,
                    type(expect_value).__name__
                )
                logger.log_error(validate_msg)
                failures.append(validate_msg)

            self.validation_results.append(validator_dict)

            # restore validator args, in case of running multiple times
            validator.update_args(validator_args)

        if not validate_pass:
            failures_string = "\n".join([failure for failure in failures])
            raise exceptions.ValidationFailure(failures_string)
348783
async def set(self, *args, **kwargs):
        

        return await self._makeApiCall(self.funcinfo["set"], *args, **kwargs)
1373443
function addSetOperator(update) {
  var operatorRegexp = /^\$.*/;
  update.$set = {};
  _.each(update, function (v, k) {
    if (!operatorRegexp.test(k)) {
      update.$set[k] = v;
      delete update[k];
    }
  });
  if (_.isEmpty(update.$set)) {
    delete update.$set;
  }
}
1063895
def _build_iterable_validator(iterable):
    """"""
    sub_schemas = [parse_schema(s) for s in iterable]

    def item_validator(value):
        """Validate items in an iterable."""
        for sub in sub_schemas:
            try:
                return sub(value)

            except NotValid:
                pass

        raise NotValid('%r invalidated by anything in %s.' % (value, iterable))

    def iterable_validator(data):
        """Validate an iterable."""
        if not type(data) is type(iterable):
            raise NotValid('%r is not of type %s' % (data, type(iterable)))

        return type(iterable)(item_validator(value) for value in data)

    return iterable_validator
500113
def _apply_validator_chain(chain, value, handler):
    """"""

    if hasattr(chain, 'validate'):  # not a list
        chain = [chain, ]

    for validator in chain:
        if hasattr(validator, 'validate'):
            value = validator.validate(value, handler)
        else:
            raise web.HTTPError(500)
    return value
347433
def validate(option, value):
    
    lower = option.lower()
    validator = VALIDATORS.get(lower, raise_config_error)
    value = validator(option, value)
    return lower, value
323786
function(value, context, argCount) {
                if (value == null) return _.identity;
                if (_.isFunction(value)) return optimizeCb(value, context, argCount);
                if (_.isObject(value)) return _.matcher(value);
                return _.property(value);
              }
863622
def store_validator_set(self, height, validators):
        
        return backend.query.store_validator_set(self.connection, {'height': height,
                                                                   'validators': validators})
76555
def with_validator(self, validator):
    """"""
    if not callable(validator):
      raise ValueError('Validator must be callable', validator)
    self.validators.append(validator)
    self._cached = None
    return self
993730
def field2range(self, field, **kwargs):
        
        validators = [
            validator
            for validator in field.validators
            if (
                hasattr(validator, "min")
                and hasattr(validator, "max")
                and not hasattr(validator, "equal")
            )
        ]

        attributes = {}
        for validator in validators:
            if validator.min is not None:
                if hasattr(attributes, "minimum"):
                    attributes["minimum"] = max(attributes["minimum"], validator.min)
                else:
                    attributes["minimum"] = validator.min
            if validator.max is not None:
                if hasattr(attributes, "maximum"):
                    attributes["maximum"] = min(attributes["maximum"], validator.max)
                else:
                    attributes["maximum"] = validator.max
        return attributes
617452
def validate(self):
        """"""
        if self.error:
            return False

        for v in self.validators:
            self.error = v(self.value)
            if self.error:
                return False

        return True
758422
function normalizeValidator(validator) {
	        if (validator.validate !== undefined) {
	            return function (c) { return validator.validate(c); };
	        }
	        else {
	            return validator;
	        }
	    }
742545
def optimize(self):
        """"""

        def te(weights, r, proxies):
            """Helper func.  `pyfinance.tracking_error` doesn't work here."""
            if isinstance(weights, list):
                weights = np.array(weights)
            proxy = np.sum(proxies * weights, axis=1)
            te = np.std(proxy - r)  # not anlzd...
            return te

        ew = utils.equal_weights(n=self.n, sumto=self.sumto)
        bnds = tuple((0, 1) for x in range(self.n))
        cons = {"type": "eq", "fun": lambda x: np.sum(x) - self.sumto}

        xs = []
        funs = []
        for i, j in zip(self._r, self._proxies):
            opt = sco.minimize(
                te,
                x0=ew,
                args=(i, j),
                method="SLSQP",
                bounds=bnds,
                constraints=cons,
            )
            x, fun = opt["x"], opt["fun"]
            xs.append(x)
            funs.append(fun)
        self._xs = np.array(xs)
        self._funs = np.array(funs)

        return self
1323257
def _validate_min(self, min_value, field, value):
        
        try:
            if value < min_value:
                self._error(field, errors.MIN_VALUE)
        except TypeError:
            pass
1239127
def _wrap_set_op(self, fun, arg):
        """"""
        result = fun(self, arg)
        result._autostep = self._autostep
        result.padding = self.padding
        return result
89432
def as_set(self, include_weak=False):
        """"""
        rv = set(self._strong)
        if include_weak:
            rv.update(self._weak)
        return rv