Perform tag matching/error reporting for invalid HTML.
342236
private void visit(
      HtmlMatcherTagNode tagNode,
      Map<Equivalence.Wrapper<ExprNode>, Boolean> exprValueMap,
      HtmlStack stack) {
    HtmlTagNode tag = (HtmlTagNode) tagNode.getSoyNode().get();
    TagName openTagName = tag.getTagName();
    HtmlStack prev = stack;
    switch (tagNode.getTagKind()) {
      case VOID_TAG:
        HtmlOpenTagNode voidTag = (HtmlOpenTagNode) tag;
        // Report errors for non-void tags that are self-closing.
        // For void tags, we don't care if they are self-closing or not. But when we visit
        // a HtmlCloseTagNode we will throw an error if it is a void tag.
        // Ignore this check if we are currently in a foreign content (svg).
        if (!stack.inForeignContent
            && !openTagName.isDefinitelyVoid()
            && voidTag.isSelfClosing()
            && openTagName.isStatic()) {
          errorReporter.report(
              voidTag.getSourceLocation(),
              INVALID_SELF_CLOSING_TAG,
              openTagName.getStaticTagName());
        }
        break;
      case OPEN_TAG:
        HtmlOpenTagNode openTag = (HtmlOpenTagNode) tag;
        if (openTagName.isForeignContent() && stack.inForeignContent) {
          errorReporter.report(openTag.getSourceLocation(), makeSoyErrorKind(NESTED_SVG));
        }
        // In a case where an open tag can close another open tag (ie <p><p> or <li><li>),
        // check if this is possible by peeking the stack and inject a tag before the open tag.
        if (!prev.isEmpty()) {
          HtmlOpenTagNode optionalTag = stack.tagNode;
          if (optionalTag.getTagName().isDefinitelyOptional()) {
            if (TagName.checkOpenTagClosesOptional(
                openTag.getTagName(), optionalTag.getTagName())) {
              injectCloseTag(optionalTag, openTag, idGenerator);
              prev = prev.pop();
            }
          }
        }
        prev =
            prev.push(openTag, stack.inForeignContent || openTag.getTagName().isForeignContent());
        break;
      case CLOSE_TAG:
        HtmlCloseTagNode closeTag = (HtmlCloseTagNode) tag;
        // Report an error if this node is a void tag. Void tag should never be closed.
        if (closeTag.getTagName().isDefinitelyVoid()) {
          errorReporter.report(
              closeTag.getTagName().getTagLocation(),
              INVALID_CLOSE_TAG,
              closeTag.getTagName().getStaticTagName());
          break;
        }
        // This is for cases similar to {block}</p>{/block}
        if (stack.isEmpty()) {
          errorReporter.report(
              closeTag.getSourceLocation(), makeSoyErrorKind(UNEXPECTED_CLOSE_TAG));
          break;
        }
        prev = stack;
        while (!prev.isEmpty()) {
          HtmlOpenTagNode nextOpenTag = prev.tagNode;
          if (nextOpenTag.getTagName().equals(closeTag.getTagName())) {
            annotationMap.put(nextOpenTag, Optional.of(closeTag));
            annotationMap.put(closeTag, Optional.of(nextOpenTag));
            prev = prev.pop();
            break;
          } else if (nextOpenTag.getTagName().isDefinitelyOptional()
              && TagName.checkCloseTagClosesOptional(
                  closeTag.getTagName(), nextOpenTag.getTagName())) {
            // Close tag closes an optional open tag (e.g. <li> ... </ul>). Inject a synthetic
            // close tag that matches `openTag`.
            injectCloseTag(nextOpenTag, closeTag, idGenerator);
            prev = prev.pop();
          } else {
            annotationMap.put(nextOpenTag, INVALID_NODE);
            errorReporter.report(
                closeTag.getSourceLocation(),
                makeSoyErrorKind(UNEXPECTED_CLOSE_TAG_KNOWN),
                nextOpenTag.getTagName(),
                nextOpenTag.getSourceLocation());
            prev = prev.pop();
          }
        }
        break;
    }
    Optional<HtmlMatcherGraphNode> nextNode = tagNode.getNodeForEdgeKind(EdgeKind.TRUE_EDGE);
    if (nextNode.isPresent()) {
      visit(nextNode.get(), exprValueMap, prev);
    } else {
      checkUnusedTags(prev);
    }
  }
350074
def match_selectors(self, el, selectors):
        """"""

        match = False
        is_not = selectors.is_not
        is_html = selectors.is_html

        # Internal selector lists that use the HTML flag, will automatically get the `html` namespace.
        if is_html:
            namespaces = self.namespaces
            iframe_restrict = self.iframe_restrict
            self.namespaces = {'html': NS_XHTML}
            self.iframe_restrict = True

        if not is_html or self.is_html:
            for selector in selectors:
                match = is_not
                # We have a un-matchable situation (like `:focus` as you can focus an element in this environment)
                if isinstance(selector, ct.SelectorNull):
                    continue
                # Verify tag matches
                if not self.match_tag(el, selector.tag):
                    continue
                # Verify tag is defined
                if selector.flags & ct.SEL_DEFINED and not self.match_defined(el):
                    continue
                # Verify element is root
                if selector.flags & ct.SEL_ROOT and not self.match_root(el):
                    continue
                # Verify element is scope
                if selector.flags & ct.SEL_SCOPE and not self.match_scope(el):
                    continue
                # Verify `nth` matches
                if not self.match_nth(el, selector.nth):
                    continue
                if selector.flags & ct.SEL_EMPTY and not self.match_empty(el):
                    continue
                # Verify id matches
                if selector.ids and not self.match_id(el, selector.ids):
                    continue
                # Verify classes match
                if selector.classes and not self.match_classes(el, selector.classes):
                    continue
                # Verify attribute(s) match
                if not self.match_attributes(el, selector.attributes):
                    continue
                # Verify ranges
                if selector.flags & RANGES and not self.match_range(el, selector.flags & RANGES):
                    continue
                # Verify language patterns
                if selector.lang and not self.match_lang(el, selector.lang):
                    continue
                # Verify pseudo selector patterns
                if selector.selectors and not self.match_subselectors(el, selector.selectors):
                    continue
                # Verify relationship selectors
                if selector.relation and not self.match_relations(el, selector.relation):
                    continue
                # Validate that the current default selector match corresponds to the first submit button in the form
                if selector.flags & ct.SEL_DEFAULT and not self.match_default(el):
                    continue
                # Validate that the unset radio button is among radio buttons with the same name in a form that are
                # also not set.
                if selector.flags & ct.SEL_INDETERMINATE and not self.match_indeterminate(el):
                    continue
                # Validate element directionality
                if selector.flags & DIR_FLAGS and not self.match_dir(el, selector.flags & DIR_FLAGS):
                    continue
                # Validate that the tag contains the specified text.
                if not self.match_contains(el, selector.contains):
                    continue
                match = not is_not
                break

        # Restore actual namespaces being used for external selector lists
        if is_html:
            self.namespaces = namespaces
            self.iframe_restrict = iframe_restrict

        return match
1306465
private void checkForbiddenTag(IfdTags metadata, String tagName, String ext) {
    int tagid = TiffTags.getTagId(tagName);
    if (metadata.containsTagId(tagid)) {
      validation.addErrorLoc("Forbidden tag for TiffEP found " + tagName, ext);
    }
  }
809656
def html_for_check(self, check) -> str:
        """"""
        check["logs"].sort(key=lambda c: LOGLEVELS.index(c["status"]))
        logs = "<ul>" + "".join([self.log_html(log) for log in check["logs"]]) + "</ul>"
        return logs
240991
def report_errors
      begin
        yield
        true
      rescue Exception => error
        say 'massimo had a problem', :red
        indent do
          say error.message, :magenta
          say error.backtrace.first, :magenta
        end
        growl "#{error.message}\n#{error.backtrace.first}", 'massimo problem'
        false
      end
    end
300471
def sanitize_html(value, valid_tags=VALID_TAGS, strip=True):
    
    return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip)
554528
public static void checkIfMatch(final String ifMatch, final EntityTag etag) {
        if (ifMatch == null) {
            return;
        }
        final Set<String> items = stream(ifMatch.split(",")).map(String::trim).collect(toSet());
        if (items.contains("*")) {
            return;
        }
        try {
            if (etag.isWeak() || items.stream().map(EntityTag::valueOf).noneMatch(isEqual(etag))) {
                    throw new ClientErrorException(status(PRECONDITION_FAILED).build());
            }
        } catch (final IllegalArgumentException ex) {
            throw new BadRequestException(ex);
        }
    }
1106662
def render_error_debug(request, exception, is_html):
    '''
    '''
    error = Html('div', cn='well well-lg') if is_html else []
    for trace in format_traceback(exception):
        counter = 0
        for line in trace.split('\n'):
            if line.startswith('  '):
                counter += 1
                line = line[2:]
            if line:
                if is_html:
                    line = Html('p', escape(line), cn='text-danger')
                    if counter:
                        line.css({'margin-left': '%spx' % (20*counter)})
                error.append(line)
    if is_html:
        error = Html('div', Html('h1', request.response.status), error)
    return error
1319871
public void validateElementTag() {

		String errorMsg = String.format(
				ErrorMessages.ERROR_INVALID_TAG_TO_CLASS, getElement()
						.getTagName());

		if (!isValidElementTag()) {
			throw new IllegalArgumentException(errorMsg);
		}
	}
857768
def valid(cls, data, context=None):
        """"""
        return cls(cls.TagType.VALID, data, context)
409843
def _is_missing_tags_strict(self):
        
        val = self.missing_tags

        if val == MissingTags.strict:
            return True
        elif val == MissingTags.ignore:
            return False

        raise Exception("Unsupported 'missing_tags' value: %s" % repr(val))
50083
def render_html(self):
        """"""
        return self._template.safe_substitute(
            report_type=self._report_type,
            results=self.render_json()
        )
468450
def get_tag_value(resource, tag, utf_8=False):
        """"""

        tags = {k.lower(): v for k, v in resource.get('tags', {}).items()}
        value = tags.get(tag, False)

        if value is not False:
            if utf_8:
                value = value.encode('utf8').decode('utf8')
        return value
1246302
private void MungeInput() {
        int srci = 0;
        int dsti = 0;
        byte b;
        boolean  inMarkup = false;
        int      openTags = 0;
        int      badTags  = 0;
        
        //
        //  html / xml markup stripping.
        //     quick and dirty, not 100% accurate, but hopefully good enough, statistically.
        //     discard everything within < brackets >
        //     Count how many total '<' and illegal (nested) '<' occur, so we can make some
        //     guess as to whether the input was actually marked up at all.
        if (fStripTags) {
            for (srci = 0; srci < fRawLength && dsti < fInputBytes.length; srci++) {
                b = fRawInput[srci];
                if (b == (byte)'<') {
                    if (inMarkup) {
                        badTags++;
                    }
                    inMarkup = true;
                    openTags++;
                }
                
                if (! inMarkup) {
                    fInputBytes[dsti++] = b;
                }
                
                if (b == (byte)'>') {
                    inMarkup = false;
                }        
            }
            
            fInputLen = dsti;
        }
        
        //
        //  If it looks like this input wasn't marked up, or if it looks like it's
        //    essentially nothing but markup abandon the markup stripping.
        //    Detection will have to work on the unstripped input.
        //
        if (openTags<5 || openTags/5 < badTags || 
                (fInputLen < 100 && fRawLength>600)) {
            int limit = fRawLength;
            
            if (limit > kBufSize) {
                limit = kBufSize;
            }
            
            for (srci=0; srci<limit; srci++) {
                fInputBytes[srci] = fRawInput[srci];
            }
            fInputLen = srci;
        }
        
        //
        // Tally up the byte occurence statistics.
        //   These are available for use by the various detectors.
        //
        Arrays.fill(fByteStats, (short)0);
        for (srci=0; srci<fInputLen; srci++) {
            int val = fInputBytes[srci] & 0x00ff;
            fByteStats[val]++;
        }
        
        fC1Bytes = false;
        for (int i = 0x80; i <= 0x9F; i += 1) {
            if (fByteStats[i] != 0) {
                fC1Bytes = true;
                break;
            }
        }
     }
342156
def error(request, message, extra_tags='', fail_silently=False):
    """"""
    add_message(request, constants.ERROR, message, extra_tags=extra_tags,
                fail_silently=fail_silently)
243417
public void validate(String html) throws ParserException {

        m_unbalancedClosedTags = 0;
        m_unbalancedOpenedTags = 0;
        m_rootElementCount = 0;
        m_stack.clear();
        m_messages.clear();
        Parser parser = new Parser();
        Lexer lexer = new Lexer();
        Page page = new Page(html, "UTF-8");
        lexer.setPage(page);
        parser.setLexer(lexer);
        // override built in composite tags to skip automatic tag closing
        PrototypicalNodeFactory factory = configureNoAutoCorrectionTags();
        lexer.setNodeFactory(factory);

        parser.visitAllNodesWith(this);
    }
1164045
public void doTag()
            throws JspException
    {
        // report any errors...
        if (hasErrors()) {
            reportErrors();
            return;
        }

        // calculate the output value...
        String text;
        if (_value != null) {
            text = _value.toString();
        }
        else {
            if (_defaultValue != null) {
                text = _defaultValue;
            }
            else {
                logger.warn(Bundle.getString("Tags_ContentExpressionNull", _value));
                text = DEFAULT_NULL_TEXT;
            }
        }

        write(text);
    }