validation checks for price argument
512481
def validate_price(price):
	
	if isinstance(price, str):
		try:
			price = int(price)
		except ValueError: # fallback if convert to int failed
			price = float(price)
	if not isinstance(price, (int, float)):
		raise TypeError('Price should be a number: ' + repr(price))
	return price
1072088
def validate_arg(arg, argdef):
        
        datatype = argdef['datatype']
        reasons = set()
        ranges = {
            'ui1': (int, 0, 255),
            'ui2': (int, 0, 65535),
            'ui4': (int, 0, 4294967295),
            'i1': (int, -128, 127),
            'i2': (int, -32768, 32767),
            'i4': (int, -2147483648, 2147483647),
            'r4': (Decimal, Decimal('3.40282347E+38'), Decimal('1.17549435E-38'))
        }
        try:
            if datatype in set(ranges.keys()):
                v_type, v_min, v_max = ranges[datatype]
                if not v_min <= v_type(arg) <= v_max:
                    reasons.add('%r datatype must be a number in the range %s to %s' % (
                        datatype, v_min, v_max))

            elif datatype in {'r8', 'number', 'float', 'fixed.14.4'}:
                v = Decimal(arg)
                if v < 0:
                    assert Decimal('-1.79769313486232E308') <= v <= Decimal('4.94065645841247E-324')
                else:
                    assert Decimal('4.94065645841247E-324') <= v <= Decimal('1.79769313486232E308')

            elif datatype == 'char':
                v = arg.decode('utf8') if six.PY2 or isinstance(arg, bytes) else arg
                assert len(v) == 1

            elif datatype == 'string':
                v = arg.decode("utf8") if six.PY2 or isinstance(arg, bytes) else arg
                if argdef['allowed_values'] and v not in argdef['allowed_values']:
                    reasons.add('Value %r not in allowed values list' % arg)

            elif datatype == 'date':
                v = parse_date(arg)
                if any((v.hour, v.minute, v.second)):
                    reasons.add("'date' datatype must not contain a time")

            elif datatype in ('dateTime', 'dateTime.tz'):
                v = parse_date(arg)
                if datatype == 'dateTime' and v.tzinfo is not None:
                    reasons.add("'dateTime' datatype must not contain a timezone")

            elif datatype in ('time', 'time.tz'):
                now = datetime.datetime.utcnow()
                v = parse_date(arg, default=now)
                if v.tzinfo is not None:
                    now += v.utcoffset()
                if not all((
                        v.day == now.day,
                        v.month == now.month,
                        v.year == now.year)):
                    reasons.add('%r datatype must not contain a date' % datatype)
                if datatype == 'time' and v.tzinfo is not None:
                    reasons.add('%r datatype must not have timezone information' % datatype)

            elif datatype == 'boolean':
                valid = {'true', 'yes', '1', 'false', 'no', '0'}
                if arg.lower() not in valid:
                    reasons.add('%r datatype must be one of %s' % (datatype, ','.join(valid)))

            elif datatype == 'bin.base64':
                b64decode(arg)

            elif datatype == 'bin.hex':
                unhexlify(arg)

            elif datatype == 'uri':
                urlparse(arg)

            elif datatype == 'uuid':
                if not re.match(
                        r'^[0-9a-f]{8}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{12}$',
                        arg, re.I):
                    reasons.add('%r datatype must contain a valid UUID')

            else:
                reasons.add("%r datatype is unrecognised." % datatype)

        except ValueError as exc:
            reasons.add(str(exc))

        return not bool(len(reasons)), reasons
1210580
function validate(cmd, args, info) {
  AbstractCommand.prototype.validate.apply(this, arguments);
  var op = ('' + args[0]).toLowerCase();
  if(op !== BITOP.AND && op !== BITOP.OR
    && op !== BITOP.XOR && op !== BITOP.NOT) {
    throw CommandSyntax;
  }
  if(op === BITOP.NOT && args.length !== 3) {
    throw BitopNot;
  }
  args[0] = op;
}
234772
def validate(self, value):
        """"""
        value = self.pre_validate(value)
        if not self._typecheck(value):
            raise ValueError('%r failed type check' % value)
        return value
895732
def check_stoplimit_prices(price, label):
    
    try:
        if not isfinite(price):
            raise BadOrderParameters(
                msg="Attempted to place an order with a {} price "
                    "of {}.".format(label, price)
            )
    # This catches arbitrary objects
    except TypeError:
        raise BadOrderParameters(
            msg="Attempted to place an order with a {} price "
                "of {}.".format(label, type(price))
        )

    if price < 0:
        raise BadOrderParameters(
            msg="Can't place a {} order with a negative price.".format(label)
        )
629961
function validPPValue(value) {

  // Get PPValue from string (all `/s` were already removed)
  function string2PPValue(inString) {
    var matches = /^(.+?)(%)?$/.exec(inString);
    var value = void 0,
        isRatio = void 0;
    return matches && isFinite(value = parseFloat(matches[1])) ? { value: (isRatio = !!(matches[2] && value)) ? value / 100 : value, isRatio: isRatio } : null; // 0% -> 0
  }

  return isFinite(value) ? { value: value, isRatio: false } : typeof value === 'string' ? string2PPValue(value.replace(/\s/g, '')) : null;
}
621436
def valid?
      pricing_type_validator = EnumAttributeValidator.new('String', ["FIXED_PRICING", "VARIABLE_PRICING"])
      return false unless pricing_type_validator.valid?(@pricing_type)
      inventory_alert_type_validator = EnumAttributeValidator.new('String', ["NONE", "LOW_QUANTITY"])
      return false unless inventory_alert_type_validator.valid?(@inventory_alert_type)
      return true
    end
1374183
def _check_required(self, value):
        '''
        
        '''
        if value is None and self._required:
            err_msg = self._errors['required'].format(self.__class__.__name__, self.name)
            if self.container_model:
                err_msg += self._errors['required_extra'].format(self.container_model.__name__)
            raise ValueError(err_msg)
758071
def validate_SUMTO(in_value, restriction):
    
    #Sometimes restriction values can accidentally be put in the template <item>100</items>,
    #Making them a list, not a number. Rather than blowing up, just get value 1 from the list.
    if type(restriction) is list:
        restriction = restriction[0]

    value = _get_val(in_value, full=True)

    if len(value) == 0:
        return

    flat_list = _flatten_value(value)

    try:
        sum(flat_list)
    except:
        raise ValidationError("List cannot be summed: %s"%(flat_list,))

    if sum(flat_list) != restriction:
        raise ValidationError("SUMTO: %s"%(restriction))
1165450
def validate(self, instance, value):
        """"""
        if isinstance(value, string_types):
            value = COLORS_NAMED.get(value, value)
            if value.upper() == 'RANDOM':
                value = random.choice(COLORS_20)
            value = value.upper().lstrip('#')
            if len(value) == 3:
                value = ''.join(v*2 for v in value)
            if len(value) != 6:
                self.error(instance, value, extra='Color must be known name '
                           'or a hex with 6 digits. e.g. "#FF0000"')
            try:
                value = [
                    int(value[i:i + 6 // 3], 16) for i in range(0, 6, 6 // 3)
                ]
            except ValueError:
                self.error(instance, value,
                           extra='Hex color must be base 16 (0-F)')
        if not isinstance(value, (list, tuple)):
            self.error(instance, value,
                       extra='Color must be a list or tuple of length 3')
        if len(value) != 3:
            self.error(instance, value, extra='Color must be length 3')
        for val in value:
            if not isinstance(val, integer_types) or not 0 <= val <= 255:
                self.error(instance, value,
                           extra='Color values must be ints 0-255.')
        return tuple(value)
347433
def validate(option, value):
    
    lower = option.lower()
    validator = VALIDATORS.get(lower, raise_config_error)
    value = validator(option, value)
    return lower, value
811144
def value_check(arg_name, pos, allowed_values):
    

    def decorator(fn):

        # brevity compromised in favour of readability
        def logic(*args, **kwargs):
            arg_count = len(args)
            if arg_count:
                if pos < arg_count:
                    if args[pos] in allowed_values:
                        return fn(*args, **kwargs)
                    else:
                        raise ValueError(
                            "'{0}' at position {1} not in allowed values {2}".format(args[pos], pos, allowed_values))
                else:
                    if arg_name in kwargs:
                        value = kwargs[arg_name]
                        if value in allowed_values:
                            return fn(*args, **kwargs)
                        else:
                            raise ValueError("'{0}' is not an allowed kwarg".format(arg_name))
                    else:
                        # partially applied functions because of incomplete args, let python handle this
                        return fn(*args, **kwargs)
            else:
                if arg_name in kwargs:
                    value = kwargs[arg_name]
                    if value in allowed_values:
                        return fn(*args, **kwargs)
                else:
                    raise ValueError("'{0}' is not an allowed kwarg".format(arg_name))

        return logic

    return decorator
477998
def validate_range_values(request, label, kwargs):
    """"""
    value = kwargs.get(label, request.query.get(label))
    if value:
        kwargs[label] = int(value)
        if kwargs[label] < 0 or kwargs[label] > MAX_PAGE_SIZE:
            raise ValueError
1270380
def __args_check(self, valid, args=None, kwargs=None):
        '''
        
        '''
        if not isinstance(valid, list):
            valid = [valid]
        for cond in valid:
            if not isinstance(cond, dict):
                # Invalid argument
                continue
            # whitelist args, kwargs
            cond_args = cond.get('args', [])
            good = True
            for i, cond_arg in enumerate(cond_args):
                if args is None or len(args) <= i:
                    good = False
                    break
                if cond_arg is None:  # None == '.*' i.e. allow any
                    continue
                if not self.match_check(cond_arg, six.text_type(args[i])):
                    good = False
                    break
            if not good:
                continue
            # Check kwargs
            cond_kwargs = cond.get('kwargs', {})
            for k, v in six.iteritems(cond_kwargs):
                if kwargs is None or k not in kwargs:
                    good = False
                    break
                if v is None:  # None == '.*' i.e. allow any
                    continue
                if not self.match_check(v, six.text_type(kwargs[k])):
                    good = False
                    break
            if good:
                return True
        return False
110864
def validate(self, **kwargs):
        
        self.check_crossrefs()
        for value in self.values():
            value.validate(**kwargs)
846493
def validate(self, instance, value):
        """"""
        value = super(URL, self).validate(instance, value)
        parsed_url = urlparse(value)
        if not parsed_url.scheme or not parsed_url.netloc:
            self.error(instance, value, extra='URL needs scheme and netloc.')
        parse_result = ParseResult(
            scheme=parsed_url.scheme,
            netloc=parsed_url.netloc,
            path=parsed_url.path,
            params='' if self.remove_parameters else parsed_url.params,
            query='' if self.remove_parameters else parsed_url.query,
            fragment='' if self.remove_fragment else parsed_url.fragment,
        )
        parse_result = parse_result.geturl()
        return parse_result
831478
def validate(self, value, messages=None):
        
        valid     = True
        primitive = value

        def log(msg):
            if messages is not None:
                messages.append(msg)

        if self.enum:
            if value not in self.enum.keys():
                valid = False
                args  = (self.name, str(value))
                log("%s value '%s' not in allowed enumerated values." % args)
            else:
                primitive = int(self.enum[value])

        if self.type:
            if self.type.validate(primitive, messages, self.name) is False:
                valid = False

        if self.range:
            if primitive < self.range[0] or primitive > self.range[1]:
                valid = False
                args  = (self.name, str(primitive), self.range[0], self.range[1])
                log("%s value '%s' out of range [%d, %d]." % args)

        return valid