Validate all `service_checks.json` files.
7486
def service_checks():
    """"""
    root = get_root()
    echo_info("Validating all service_checks.json files...")
    failed_checks = 0
    ok_checks = 0
    for check_name in sorted(os.listdir(root)):
        service_checks_file = os.path.join(root, check_name, 'service_checks.json')

        if file_exists(service_checks_file):
            file_failed = False
            display_queue = []

            try:
                decoded = json.loads(read_file(service_checks_file).strip(), object_pairs_hook=OrderedDict)
            except JSONDecodeError as e:
                failed_checks += 1
                echo_info("{}/service_checks.json... ".format(check_name), nl=False)
                echo_failure("FAILED")
                echo_failure('  invalid json: {}'.format(e))
                continue

            unique_names = set()
            unique_checks = set()
            for service_check in decoded:
                # attributes are valid
                attrs = set(service_check)
                for attr in sorted(attrs - REQUIRED_ATTRIBUTES):
                    file_failed = True
                    display_queue.append((echo_failure, '  Attribute `{}` is invalid'.format(attr)))
                for attr in sorted(REQUIRED_ATTRIBUTES - attrs):
                    file_failed = True
                    display_queue.append((echo_failure, '  Attribute `{}` is required'.format(attr)))

                # agent_version
                agent_version = service_check.get('agent_version')
                version_parts = parse_version_parts(agent_version)
                if len(version_parts) != 3:
                    file_failed = True

                    if not agent_version:
                        output = '  required non-null string: agent_version'
                    else:
                        output = '  invalid `agent_version`: {}'.format(agent_version)

                    display_queue.append((echo_failure, output))

                # check
                check = service_check.get('check')
                if not check or not isinstance(check, string_types):
                    file_failed = True
                    display_queue.append((echo_failure, '  required non-null string: check'))
                else:
                    if check in unique_checks:
                        file_failed = True
                        display_queue.append((echo_failure, '  {} is not a unique check'.format(check)))
                    else:
                        unique_checks.add(check)

                # description
                description = service_check.get('description')
                if not description or not isinstance(description, string_types):
                    file_failed = True
                    display_queue.append((echo_failure, '  required non-null string: description'))

                # groups
                groups = service_check.get('groups')
                if groups is None or not isinstance(groups, list):
                    file_failed = True
                    display_queue.append((echo_failure, '  required list: groups'))

                # integration
                integration = service_check.get('integration')
                if integration is None or not isinstance(integration, string_types):
                    file_failed = True
                    display_queue.append((echo_failure, '  required non-null string: integration'))

                # name
                name = service_check.get('name')
                if not name or not isinstance(name, string_types):
                    file_failed = True
                    display_queue.append((echo_failure, '  required non-null string: name'))
                else:
                    if name in unique_names:
                        file_failed = True
                        display_queue.append((echo_failure, '  {} is not a unique name'.format(name)))
                    else:
                        unique_names.add(name)

                # statuses
                statuses = service_check.get('statuses')
                if not statuses or not isinstance(statuses, list):
                    file_failed = True
                    display_queue.append((echo_failure, '  required non empty list: statuses'))

            if file_failed:
                failed_checks += 1
                # Display detailed info if file invalid
                echo_info("{}/service_checks.json... ".format(check_name), nl=False)
                echo_failure("FAILED")
                for display_func, message in display_queue:
                    display_func(message)
            else:
                ok_checks += 1

    if ok_checks:
        echo_success("{} valid files".format(ok_checks))
    if failed_checks:
        echo_failure("{} invalid files".format(failed_checks))
        abort()
969359
def validate(cls, data):
        """"""
        try:
            jsonschema.validate(
                data, cls.SCHEMA,
                # See: https://github.com/Julian/jsonschema/issues/148
                types={'array': (list, tuple)})
        except jsonschema.ValidationError as e:
            raise InvalidFormat("Failure data not of the"
                                " expected format: %s" % (e.message))
        else:
            # Ensure that all 'exc_type_names' originate from one of
            # base exceptions, because those are the root exceptions that
            # python mandates/provides and anything else is invalid...
            causes = collections.deque([data])
            while causes:
                cause = causes.popleft()
                try:
                    generated_on = cause['generated_on']
                    ok_bases = cls.BASE_EXCEPTIONS[generated_on[0]]
                except (KeyError, IndexError):
                    ok_bases = []
                root_exc_type = cause['exc_type_names'][-1]
                if root_exc_type not in ok_bases:
                    raise InvalidFormat(
                        "Failure data 'exc_type_names' must"
                        " have an initial exception type that is one"
                        " of %s types: '%s' is not one of those"
                        " types" % (ok_bases, root_exc_type))
                sub_cause = cause.get('cause')
                if sub_cause is not None:
                    causes.append(sub_cause)
789102
def _filter_validate(filepath, location, values, validate):
    
    for value in values:
        if not isinstance(value, dict):
            warn_invalid(filepath, location, value, '(expected a dict)')
            continue
        try:
            yield validate(**value)
        except dbt.exceptions.JSONValidationException as exc:
            # we don't want to fail the full run, but we do want to fail
            # parsing this file
            warn_invalid(filepath, location, value, '- ' + exc.msg)
            continue
1342514
def validate(self):
        
        errors = []
        for param in self.required_params:
            if (not hasattr(self, param) or getattr(self, param) is None):
                errors.append("missing %s parameter" % (param))
        if (len(errors) > 0):
            raise IIIFInfoError("Bad data for info.json: " + ", ".join(errors))
        return True
424899
def validate(self, path):
        """"""
        # Exclude hidden files and folders with '.' prefix
        if os.path.basename(path).startswith('.'):
            return False

        # Check that current path level is more than min path and less than max path
        if not self.check_level(path):
            return False

        if self.filters:
            if not self._level_filters(path):
                return False

        # Force include and exclude iterations to be strings in case of integer filters
        # Handle exclusions
        if self.to_exclude:
            if any(str(ex).lower() in path.lower() for ex in self.to_exclude):
                return False

        # Handle inclusions
        if self.to_include:
            if not any(str(inc).lower() in path.lower() for inc in self.to_include):
                return False

        return True
742702
function _validate_files(&$files) {
        global $CFG, $COURSE;

        $files = array();

        if (empty($_FILES)) {
            // we do not need to do any checks because no files were submitted
            // note: server side rules do not work for files - use custom verification in validate() instead
            return true;
        }

        $errors = array();
        $filenames = array();

        // now check that we really want each file
        foreach ($_FILES as $elname=>$file) {
            $required = $this->_form->isElementRequired($elname);

            if ($file['error'] == 4 and $file['size'] == 0) {
                if ($required) {
                    $errors[$elname] = get_string('required');
                }
                unset($_FILES[$elname]);
                continue;
            }

            if (!empty($file['error'])) {
                $errors[$elname] = file_get_upload_error($file['error']);
                unset($_FILES[$elname]);
                continue;
            }

            if (!is_uploaded_file($file['tmp_name'])) {
                // TODO: improve error message
                $errors[$elname] = get_string('error');
                unset($_FILES[$elname]);
                continue;
            }

            if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
                // hmm, this file was not requested
                unset($_FILES[$elname]);
                continue;
            }

            // NOTE: the viruses are scanned in file picker, no need to deal with them here.

            $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
            if ($filename === '') {
                // TODO: improve error message - wrong chars
                $errors[$elname] = get_string('error');
                unset($_FILES[$elname]);
                continue;
            }
            if (in_array($filename, $filenames)) {
                // TODO: improve error message - duplicate name
                $errors[$elname] = get_string('error');
                unset($_FILES[$elname]);
                continue;
            }
            $filenames[] = $filename;
            $_FILES[$elname]['name'] = $filename;

            $files[$elname] = $_FILES[$elname]['tmp_name'];
        }

        // return errors if found
        if (count($errors) == 0){
            return true;

        } else {
            $files = array();
            return $errors;
        }
    }
1211984
def check_files(files)
      files.each { |file| check_file(file) if file.is_a? String }
    end
106381
def validate(filename, verbose=False):
    
    # is_css = filename.endswith(".css")

    is_remote = filename.startswith("http://") or filename.startswith(
        "https://")
    with tempfile.TemporaryFile() if is_remote else open(
            filename, "rb") as f:

        if is_remote:
            r = requests.get(filename, verify=False)
            f.write(r.content)
            f.seek(0)

        # if is_css:
        #     cmd = (
        #         "curl -sF \"file=@%s;type=text/css\" -F output=json -F warning=0 %s"
        #         % (quoted_filename, CSS_VALIDATOR_URL))
        #     _ = cmd
        # else:
        r = requests.post(
            HTML_VALIDATOR_URL,
            files={"file": (filename, f, "text/html")},
            data={
                "out": "json",
                "showsource": "yes",
            },
            verify=False)

    return r.json()
995685
def register_checkers(linter):
    """"""
    linter.register_checker(ModelChecker(linter))
    linter.register_checker(DjangoInstalledChecker(linter))
    linter.register_checker(JsonResponseChecker(linter))
    linter.register_checker(FormChecker(linter))
781174
def _CheckInstallSuccess(self):
    """"""
    if not os.path.exists(self.install_path):
      raise RuntimeError("Install failed, no files at: %s" % self.install_path)

    try:
      output = subprocess.check_output(["sc", "query", self.service_name])
      service_running = "RUNNING" in output
    except subprocess.CalledProcessError as e:
      if e.returncode == 1060:
        # 1060 means: The specified service does not exist as an installed
        # service.
        service_running = False
      else:
        raise

    if self.expect_service_running:
      if not service_running:
        raise RuntimeError(
            "GRR service not running after install, sc query output: %s" %
            output)
    else:
      if service_running:
        raise RuntimeError(
            "GRR service running after install with expect_service_running == "
            "False, sc query output: %s" % output)
25918
function validateMetadata(metadataPath, cb) {
  validateJSonStructure(metadataPath, function(err, metadataObject) {
    if (err) {
      cb(err, null);
    } else {
      cb(null, metadataObject.files);
    }
  });
}
1097015
async def validate(self, request: web.Request):
        
        parameters = {}
        files = {}
        errors = self.errors_factory()
        body = None

        if request.method in request.POST_METHODS:
            try:
                body = await self._content_receiver.receive(request)
            except ValueError as e:
                errors[request.content_type].add(str(e))
            except TypeError:
                errors[request.content_type].add('Not supported content type')

        for name, param in self._parameters.items():
            where = param['in']
            schema = param.get('schema', param)
            vtype = schema['type']
            is_array = vtype == 'array'

            if where == 'query':
                source = request.query
            elif where == 'header':
                source = request.headers
            elif where == 'path':
                source = request.match_info
            elif body is None:
                source = ()
            elif where == 'formData':
                source = body
            elif where == 'body':
                if isinstance(body, BaseException):
                    errors[name].add(str(body))
                else:
                    parameters[name] = body
                continue
            else:
                raise ValueError(where)

            if is_array and hasattr(source, 'getall'):
                collection_format = param.get('collectionFormat')
                default = param.get('default', [])
                value = get_collection(source, name,
                                       collection_format, default)
                if param.get('minItems') and not value \
                        and name not in self._required:
                    continue
            elif isinstance(source, Mapping) and name in source and (
                vtype not in ('number', 'integer') or source[name] != ''
            ):
                value = source[name]
            elif 'default' in param:
                parameters[name] = param['default']
                continue
            elif name in self._required:
                errors[name].add('Required')
                if isinstance(source, BaseException):
                    errors[name].add(str(body))
                continue
            else:
                continue

            if is_array:
                vtype = schema['items']['type']
                vformat = schema['items'].get('format')
            else:
                vformat = schema.get('format')

            if source is body and isinstance(body, dict):
                pass
            elif vtype not in ('string', 'file'):
                value = convert(name, value, vtype, vformat, errors)

            if vtype == 'file':
                files[name] = value
            else:
                parameters[name] = value

        parameters = self._validate(parameters, errors)
        parameters.update(files)
        return parameters, errors
394913
def validateAllServers(self):
        
        url = self._url + "/servers/validate"
        params = {"f" : "json"}
        return self._get(url=url,
                         param_dict=params,
                         proxy_port=self._proxy_port,
                         proxy_url=self._proxy_ur)
1314603
function validate(json, done) {
  var log = []
  var err

  try {
    json = JSON.parse(JSON.stringify(json))
  }
  catch (e) {
    err = e
    json = {}
  }

  Object.keys(json).forEach(function (selector) {
    var declarations = json[selector]

    Object.keys(declarations).forEach(function (name) {
      var value = declarations[name]
      var result = validateItem(name, value)

      if (typeof result.value === 'number' || typeof result.value === 'string') {
        declarations[name] = result.value
      }
      else {
        delete declarations[name]
      }

      if (result.log) {
        log.push(result.log)
      }
    })
  })

  done(err, {
    jsonStyle: json,
    log: log
  })
}
232117
def _validate_source_data(self):
        

        try:
            jsonschema.validate(self._buffer, self._schema)
        except jsonschema.ValidationError as e:
            raise ValidationError(e)
1342997
def validate(self):
        """"""
        passed = True
        for data in self.profile.get('validations') or []:
            data_type = data.get('data_type', 'redis')  # default to redis for older data files
            if data_type == 'redis':
                user_data = data.get('data')
                user_data_path = data.get('data_path')  # jmespath expression
                if isinstance(user_data, string_types) and re.match(self._vars_match, user_data):
                    # if user_data reference a redis variable retrieve the data
                    if user_data.endswith('Binary'):
                        # call specific method and do not decode data
                        user_data = self.tcex.playbook.read_binary(user_data, False, False)
                    elif user_data.endswith('BinaryArray'):
                        # call specific method and do not decode data
                        user_data = self.tcex.playbook.read_binary_array(user_data, False, False)
                    else:
                        user_data = self.tcex.playbook.read(user_data)

                if user_data_path is not None:
                    user_data = self.path_data(user_data, user_data_path)

                # get db variable/data
                variable = data.get('variable')
                if variable.endswith('Binary'):
                    # call specific method and do not decode data
                    db_data = self.tcex.playbook.read_binary(variable, False, False)
                elif variable.endswith('BinaryArray'):
                    # call specific method and do not decode data
                    db_data = self.tcex.playbook.read_binary_array(variable, False, False)
                else:
                    db_data = self.tcex.playbook.read(variable)
                db_data_path = data.get('variable_path')
                if db_data_path is not None:
                    db_data = self.path_data(db_data, db_data_path)

                # operator
                oper = data.get('operator', 'eq')

                # validate if possible
                sep = '-' * 10
                self.log.info('{0} {1} {0}'.format(sep, variable))
                # self.log.info('[validate] Variable  : {}'.format(variable))
                if not self.validate_redis(db_data, user_data, oper):
                    passed = False
                    self.exit_code = 1  # if any validation fails everything fails
        return passed
604785
def validate_request_file_upload(owner, repo, filepath, md5_checksum=None):
    """"""
    client = get_files_api()
    md5_checksum = md5_checksum or calculate_file_md5(filepath)

    with catch_raise_api_exception():
        _, _, headers = client.files_validate_with_http_info(
            owner=owner,
            repo=repo,
            data={"filename": os.path.basename(filepath), "md5_checksum": md5_checksum},
        )

    ratelimits.maybe_rate_limit(client, headers)
    return md5_checksum