Validation and typcasting
543400
def check_patch_size(patch_size):
    """"""

    patch_size = np.array(patch_size)
    if patch_size.size == 1:
        patch_size = np.repeat(patch_size, 2).astype('int16')

    return patch_size
471256
function validateLiteral( node ) {
		var token = context.getTokens( node )[ 0 ];
		if (
			token.type === 'RegularExpression' &&
			!safe( token.value )
		) {
			context.report( node, 'Unsafe regular expression' );
		}
	}
1368726
def validate_all_types(kwargs):
        
        for key in kwargs:
            assert isinstance(kwargs[key], type), """\n
    Typedtuple needs its arguments to be types. Argument "{k:}" was {type_name:}({val_repr}).
    You might want to try:
        {k:} = {type_name:}\n\n""".format(k=key, type_name=type(kwargs[key]).__name__, val_repr=kwargs[key].__repr__())
234772
def validate(self, value):
        """"""
        value = self.pre_validate(value)
        if not self._typecheck(value):
            raise ValueError('%r failed type check' % value)
        return value
311567
def validate(self):
        
        log.info("{}\nValidating against {}"
                 .format("-" * 100, self.schema_def.__class__.__name__))

        if not self.schema_def:
            raise ValueError("No schema definition supplied.")

        self.checked_attributes = []

        # TODO - this should maybe choose the actually used namespace, not just
        # the first one in the list
        result = ValidationResult(self.allowed_namespaces[0],
                                  self.schema_def.__class__.__name__)
        for subject, predicate, object_ in self.graph:
            log.info("\nsubj: {subj}\npred: {pred}\n obj: {obj}"
                     .format(subj=subject, pred=predicate,
                             obj=object_.encode('utf-8')))
            result.add_error(self._check_triple((subject, predicate, object_)))
        return result
792973
function validateBaseIndent(line, actualText, expectedIndent) {
                const expectedBaseIndentText = expectedIndent.baseIndentText
                if (
                    expectedBaseIndentText &&
                    (actualText.length < expectedBaseIndentText.length ||
                        !actualText.startsWith(expectedBaseIndentText))
                ) {
                    context.report({
                        loc: {
                            start: { line, column: 0 },
                            end: {
                                line,
                                column: actualText.length,
                            },
                        },
                        messageId: actualText
                            ? "unexpectedBaseIndentation"
                            : "missingBaseIndentation",
                        data: {
                            expected: JSON.stringify(expectedBaseIndentText),
                            actual: actualText
                                ? JSON.stringify(
                                      actualText.slice(
                                          0,
                                          expectedBaseIndentText.length
                                      )
                                  )
                                : "",
                        },
                        fix: defineFix(line, actualText, expectedIndent),
                    })
                    return false
                }
                return true
            }
42751
function prepValidations(validations) {
  validations = _.cloneDeep(validations);
  for (var key in validations) {
    var validation = validations[key];
    if (!_.isArray(validation)) validations[key] = validation = [validation];
    for (var i = 0, l = validation.length; i < l; i++) {
      validation[i] = assembleValidation(validation[i]);
    }
  }
  return validations;
}
921736
def _validated(self, data):
        """"""
        try:
            return self.convert(data)
        except (TypeError, ValueError) as ex:
            raise NotValid(*ex.args)
976333
def validate(self):
        """"""
        # Literals representing boolean values or None are correctly representable and supported.
        if self.value is None or self.value is True or self.value is False:
            return

        # Literal safe strings are correctly representable and supported.
        if isinstance(self.value, six.string_types):
            validate_safe_string(self.value)
            return

        # Literal ints are correctly representable and supported.
        if isinstance(self.value, int):
            return

        # Literal empty lists, and non-empty lists of safe strings, are
        # correctly representable and supported.
        if isinstance(self.value, list):
            if len(self.value) > 0:
                for x in self.value:
                    validate_safe_string(x)
            return

        raise GraphQLCompilationError(u'Cannot represent literal: {}'.format(self.value))
853800
def validate(self):
        
        if getattr(self, '_getting_validated', False):
            return True
        self._getting_validated = True
        self._validation_error_tuples = []
        self._non_validation_error = None
        try:
            for val in itervalues(self._class_validators):
                try:
                    if isinstance(val.func, string_types):
                        valid = getattr(self, val.func)()
                    else:
                        valid = val.func(self)
                    if valid is False:
                        raise utils.ValidationError(
                            'Validation failed', None, None, self
                        )
                except utils.ValidationError as val_err:
                    self._validation_error_tuples += val_err.error_tuples
                except GENERIC_ERRORS as err:
                    if not self._non_validation_error:
                        self._non_validation_error = err
            if self._validation_error_tuples:
                self._error_hook(self._validation_error_tuples)
                msgs = ['Validation failed:']
                msgs += [val.message for val in self._validation_error_tuples]
                raise utils.ValidationError(
                    message='\n- '.join(msgs),
                    _error_tuples=self._validation_error_tuples,
                )
            if self._non_validation_error:
                raise self._non_validation_error                               #pylint: disable=raising-bad-type
            return True
        finally:
            self._getting_validated = False
            self._validation_error_tuples = None
            self._non_validation_error = None
509166
def validate(self):
        
        for key, val in self.grammar.items():
            try:
                setattr(self, key, val)
            except ValueError as e:
                raise ValidationError('invalid contents: ' + e.args[0])
922590
function validateTokenIndent(token, desiredIndentLevel) {
            const indentation = tokenInfo.getTokenIndent(token);
            const expectedChar = indentType === "space" ? " " : "\t";

            return indentation === expectedChar.repeat(desiredIndentLevel * indentSize) ||

                // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
                indentation.includes(" ") && indentation.includes("\t");
        }
586859
def _validate(self):
        
        checker = (self._check0, self._check1, self._check2, self._check3,
                   self._check4, self._check5)
        if not 0 <= self.field_type <= 5:
            raise NotImplementedError("unsupported widget type")
        if type(self.rect) is not Rect:
            raise ValueError("invalid rect")
        if self.rect.isInfinite or self.rect.isEmpty:
            raise ValueError("rect must be finite and not empty")
        if not self.field_name:
            raise ValueError("field name missing")

        if self.border_color:
            if not len(self.border_color) in range(1,5) or \
               type(self.border_color) not in (list, tuple):
               raise ValueError("border_color must be 1 - 4 floats")

        if self.fill_color:
            if not len(self.fill_color) in range(1,5) or \
               type(self.fill_color) not in (list, tuple):
               raise ValueError("fill_color must be 1 - 4 floats")

        if not self.text_color:
            self.text_color = (0, 0, 0)
        if not len(self.text_color) in range(1,5) or \
            type(self.text_color) not in (list, tuple):
            raise ValueError("text_color must be 1 - 4 floats")

        if not self.border_width:
            self.border_width = 0

        if not self.text_fontsize:
            self.text_fontsize = 0

        checker[self.field_type]()
398394
def validate(self):
        """"""
        if not isinstance(self.fields, dict):
            raise TypeError(u'Expected dict fields, got: {} {}'.format(
                type(self.fields).__name__, self.fields))

        for key, value in six.iteritems(self.fields):
            validate_safe_string(key)
            if not isinstance(value, Expression):
                raise TypeError(
                    u'Expected Expression values in the fields dict, got: '
                    u'{} -> {}'.format(key, value))
1257631
def _validate(self, writing=False):
        """"""
        if self.colorspace is not None and self.icc_profile is not None:
            msg = ("Colorspace and icc_profile cannot both be set when "
                   "creating a ColourSpecificationBox.")
            self._dispatch_validation_error(msg, writing=writing)

        if self.method not in _COLORSPACE_METHODS.keys():
            msg = "Invalid colorspace method value ({method})."
            msg = msg.format(method=self.method)
            if writing:
                raise IOError(msg)
            else:
                warnings.warn(msg, UserWarning)

        if self.approximation not in _APPROXIMATION_MEASURES.keys():
            msg = "Invalid colr approximation value ({approx})."
            msg = msg.format(approx=self.approximation)
            if not writing:
                # Don't bother to check this for the case of writing=True
                # because it's already handles in the wrapping code.
                warnings.warn(msg, UserWarning)
975150
function assembleValidation(validation) {
  if (!_.isPlainObject(validation)) {
    validation = {rule: validation, params: []};
  }
  if (_.isString(validation.rule)) {
    var splitRule = validation.rule.split(':');
    validation.rule = splitRule[0];
    if (_.isEmpty(validation.params)) {
      validation.params = _.tail(splitRule);
    }
  } else if (!_.isFunction(validation.rule)) {
    throw new TypeError('Invalid validation');
  }
  return validation;
}
893174
function (validation) {

            validation = validation.toString().replace(/\s/g, '');

            if (validation.charAt(0) === "[" && validation.charAt(validation.length - 1) === "]") {
                validation = validation.replace(/^\[|]$/g, '');
            }

            return validation;

        }