Checks item type uniqueness, field applicability and multiplicity.
439426
def check_save(sender, **kwargs):
    
    tag = kwargs['instance']
    obj = Tag.get_object(tag)
    previous_tags = Tag.get_tags(obj)
    
    err_uniq = check_item_type_uniqueness(tag, previous_tags)
    err_appl = check_field_applicability(tag)
    err_mult = check_field_multiplicity(tag, previous_tags)
    err_msg = generate_error_message(tag, err_uniq, err_appl, err_mult)
    if err_uniq or err_appl or err_mult:
        raise TypeError(err_msg)
1192326
def validate_items(self):
        
        logger.debug(fmt("Validating {}", self))
        from python_jsonschema_objects import classbuilder

        if self.__itemtype__ is None:
            return

        type_checks = self.__itemtype__
        if not isinstance(type_checks, (tuple, list)):
            # we were given items = {'type': 'blah'} ; thus ensure the type for all data.
            type_checks = [type_checks] * len(self.data)
        elif len(type_checks) > len(self.data):
            raise ValidationError(
                "{1} does not have sufficient elements to validate against {0}"
                .format(self.__itemtype__, self.data))

        typed_elems = []
        for elem, typ in zip(self.data, type_checks):
            if isinstance(typ, dict):
                for param, paramval in six.iteritems(typ):
                    validator = registry(param)
                    if validator is not None:
                        validator(paramval, elem, typ)
                typed_elems.append(elem)

            elif util.safe_issubclass(typ, classbuilder.LiteralValue):
                val = typ(elem)
                val.validate()
                typed_elems.append(val)
            elif util.safe_issubclass(typ, classbuilder.ProtocolBase):
                if not isinstance(elem, typ):
                    try:
                        if isinstance(elem, (six.string_types, six.integer_types, float)):
                            val = typ(elem)
                        else:
                            val = typ(**util.coerce_for_expansion(elem))
                    except TypeError as e:
                        raise ValidationError("'{0}' is not a valid value for '{1}': {2}"
                                              .format(elem, typ, e))
                else:
                    val = elem
                val.validate()
                typed_elems.append(val)

            elif util.safe_issubclass(typ, ArrayWrapper):
                val = typ(elem)
                val.validate()
                typed_elems.append(val)

            elif isinstance(typ, (classbuilder.TypeProxy, classbuilder.TypeRef)):
                try:
                    if isinstance(elem, (six.string_types, six.integer_types, float)):
                        val = typ(elem)
                    else:
                        val = typ(**util.coerce_for_expansion(elem))
                except TypeError as e:
                    raise ValidationError("'{0}' is not a valid value for '{1}': {2}"
                                          .format(elem, typ, e))
                else:
                    val.validate()
                    typed_elems.append(val)

        self._dirty = False
        self._typed = typed_elems
        return typed_elems
53452
def check_unique(self):
        """"""
        result = yield views.repository_name.values(key=self.name)
        repo_id = getattr(self, 'id', None)
        repos = {x for x in result if x != repo_id and x}

        if repos:
            raise exceptions.ValidationError(
                "Repository with name '{}' already exists".format(self.name))
457469
def build_list_type_validator(item_validator):
    
    def validate_list_of_type(value):
        return [item_validator(item) for item in validate_list(value)]
    return validate_list_of_type
375974
def _verify_type(self, spec, path):
        """"""
        field_type = spec['type']

        if isinstance(field_type, Schema):
            # Nested documents cannot have validation
            if not set(spec.keys()).issubset(set(['type', 'required', 'nullable', 'default'])):
                raise SchemaFormatException("Unsupported field spec item at {}. Items: "+repr(spec.keys()), path)
            return

        elif isinstance(field_type, Array):
            if not isinstance(field_type.contained_type, (type, Schema, Array, types.FunctionType)):
                raise SchemaFormatException("Unsupported field type contained by Array at {}.", path)

        elif not isinstance(field_type, type) and not isinstance(field_type, types.FunctionType):
            raise SchemaFormatException("Unsupported field type at {}. Type must be a type, a function, an Array or another Schema", path)
1117659
def check_uniqe(self, obj_class, error_msg=_('Must be unique'), **kwargs):
        
        if obj_class.objects.filter(**kwargs).exclude(pk=self.instance.pk):
            raise forms.ValidationError(error_msg)
550417
@PostConstruct
    public void checkUniqueSchemes() {
        Multimap<String, ConfigFileLoaderPlugin> schemeToPluginMap = HashMultimap.create();

        for (ConfigFileLoaderPlugin plugin: getLoaderPlugins()) {
            schemeToPluginMap.put(plugin.getUriScheme(), plugin);
        }

        StringBuilder violations = new StringBuilder();
        for (String scheme: schemeToPluginMap.keySet()) {
            final Collection<ConfigFileLoaderPlugin> plugins = schemeToPluginMap.get(scheme);
            if (plugins.size() > 1) {
                violations.append("\n\n* ").append("There are  has multiple ")
                        .append(ConfigFileLoaderPlugin.class.getSimpleName())
                        .append(" plugins that support the scheme: '").append(scheme).append('\'')
                        .append(":\n\t").append(plugins);
            }
        }

        if (violations.length() > 0) {
            throw new IllegalStateException(violations.toString());
        }
    }
1374787
def make_valid_avro(items,          # type: Avro
                    alltypes,       # type: Dict[Text, Dict[Text, Any]]
                    found,          # type: Set[Text]
                    union=False     # type: bool
                    ):
    # type: (...) -> Union[Avro, Dict, Text]
    """"""
    # Possibly could be integrated into our fork of avro/schema.py?
    if isinstance(items, MutableMapping):
        items = copy.copy(items)
        if items.get("name") and items.get("inVocab", True):
            items["name"] = avro_name(items["name"])

        if "type" in items and items["type"] in (
                "https://w3id.org/cwl/salad#record",
                "https://w3id.org/cwl/salad#enum", "record", "enum"):
            if (hasattr(items, "get") and items.get("abstract")) or ("abstract"
                                                                     in items):
                return items
            if items["name"] in found:
                return cast(Text, items["name"])
            found.add(items["name"])
        for field in ("type", "items", "values", "fields"):
            if field in items:
                items[field] = make_valid_avro(
                    items[field], alltypes, found, union=True)
        if "symbols" in items:
            items["symbols"] = [avro_name(sym) for sym in items["symbols"]]
        return items
    if isinstance(items, MutableSequence):
        ret = []
        for i in items:
            ret.append(make_valid_avro(i, alltypes, found, union=union))  # type: ignore
        return ret
    if union and isinstance(items, string_types):
        if items in alltypes and avro_name(items) not in found:
            return cast(Dict, make_valid_avro(alltypes[items], alltypes, found,
                                              union=union))
        items = avro_name(items)
    return items
1265839
def validate_items(self, input_list):
        """"""
        output_list = []
        for item in input_list:
            valid = self.list_item_type.validate(item, self.item_name)
            output_list.append(valid)

            # this might lead to confusing error messages.  tbh, we need to
            # figure out a better way to do validation and error handling here,
            # but i'm brute forcing this a bit so that we have something
            # workable
        return output_list
1229206
def _check_existence_by_collection(self, container, item_name):
        '''
        '''

        coll = container.get_collection()
        for item in coll:
            if item.name == item_name:
                return True
        return False
1109424
def _val_is_unique(val, field):
        
        if val is None:
            return False

        if not field.unique:
            return True

        field_name = field.name
        return field.model.objects.filter(**{field_name: val}).count() == 0
4756
function validateArrayTypeItemsExistence (api, response, schema, path) {
  if (schema.type === 'array' && _.isUndefined(schema.items)) {
    response.errors.push({
      code: 'OBJECT_MISSING_REQUIRED_PROPERTY',
      message: 'Missing required property: items',
      path: path
    });
  }
}
245065
private void checkListMapType(Field field) {
        Class<?> cls = field.getType();
        boolean needCheckGenericType = false;
        if (List.class.isAssignableFrom(cls)) {
            // if check is list ignore check
            isList = true;
            needCheckGenericType = true;
        }
        if (Map.class.isAssignableFrom(cls)) {
            // if check is list ignore check
            isMap = true;
            needCheckGenericType = true;
        }

        if (!needCheckGenericType) {
            return;
        }

        Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;

            Type[] actualTypeArguments = ptype.getActualTypeArguments();

            if (actualTypeArguments != null) {

                int length = actualTypeArguments.length;
                // validate
                if (isList) {
                    if (length != 1) {
                        throw new RuntimeException(
                                "List must use generic definiation like List<String>, please check  field name '"
                                        + field.getName() + " at class " + field.getDeclaringClass().getName());
                    }
                } else if (isMap) {
                    if (length != 2) {
                        throw new RuntimeException(
                                "Map must use generic definiation like Map<String, String>, please check  field name '"
                                        + field.getName() + " at class " + field.getDeclaringClass().getName());
                    }
                }

                Type targetType = actualTypeArguments[0];
                if (targetType instanceof Class) {
                    genericKeyType = (Class) targetType;
                }

                if (actualTypeArguments.length > 1) {
                    targetType = actualTypeArguments[1];
                    if (targetType instanceof Class) {
                        genericeValueType = (Class) targetType;
                    }
                }

            }
        }

    }
1172799
function uniqueCountLegacy(arr) {
  const seen = [];
  arr.forEach((item) => {
    if (seen.indexOf(item) === -1) {
      seen.push(item);
    }
  });
  return seen.length;
}
582881
def _checkMissingParamsFromWorkitem(self, copied_from, keep=False,
                                        **kwargs):
        

        parameters = self.listFieldsFromWorkitem(copied_from,
                                                 keep=keep)
        self._findMissingParams(parameters, **kwargs)
692755
def verify_identifiers(identifiers, n_items):
    """"""
    if identifiers is None:
        return identifiers

    identifiers = np.array(identifiers, copy=False)

    # Check length for consistency
    if len(identifiers) != n_items:
        raise ValueError("identifiers has inconsistent dimension.")

    # Check that identifiers are unique
    if len(np.unique(identifiers)) != n_items:
        raise ValueError("identifiers contains duplicate values.")

    return identifiers
1280054
def _verify_default(self, spec, path):
        """"""
        field_type = spec['type']
        default = spec['default']

        # If it's a function there's nothing we can really do except assume its valid
        if callable(default):
            return

        if isinstance(field_type, Array):
            # Verify we'd got a list as our default
            if not isinstance(default, list):
                raise SchemaFormatException("Default value for Array at {} is not a list of values.", path)

            # Ensure the contents are of the correct type
            for i, item in enumerate(default):
                if isinstance(field_type.contained_type, Schema):
                    if not self._valid_schema_default(item):
                        raise SchemaFormatException("Default value for Schema is not valid.", path)
                elif not isinstance(item, field_type.contained_type):
                        raise SchemaFormatException("Not all items in the default list for the Array field at {} are of the correct type.", path)

        elif isinstance(field_type, Schema):
            if not self._valid_schema_default(default):
                raise SchemaFormatException("Default value for Schema is not valid.", path)

        else:
            if not isinstance(default, field_type):
                raise SchemaFormatException("Default value for {} is not of the nominated type.", path)