this method is ugly, and does a lot. but other breakups cause rescanning and stringbuilder generations
966540
static void escape(Appendable accum, String string, Document.OutputSettings out,
                       boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) throws IOException {

        boolean lastWasWhite = false;
        boolean reachedNonWhite = false;
        final EscapeMode escapeMode = out.escapeMode();
        final CharsetEncoder encoder = out.encoder();
        final CoreCharset coreCharset = out.coreCharset; // init in out.prepareEncoder()
        final int length = string.length();

        int codePoint;
        for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) {
            codePoint = string.codePointAt(offset);

            if (normaliseWhite) {
                if (StringUtil.isWhitespace(codePoint)) {
                    if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)
                        continue;
                    accum.append(' ');
                    lastWasWhite = true;
                    continue;
                } else {
                    lastWasWhite = false;
                    reachedNonWhite = true;
                }
            }
            // surrogate pairs, split implementation for efficiency on single char common case (saves creating strings, char[]):
            if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
                final char c = (char) codePoint;
                // html specific and required escapes:
                switch (c) {
                    case '&':
                        accum.append("&amp;");
                        break;
                    case 0xA0:
                        if (escapeMode != EscapeMode.xhtml)
                            accum.append("&nbsp;");
                        else
                            accum.append("&#xa0;");
                        break;
                    case '<':
                        // escape when in character data or when in a xml attribue val; not needed in html attr val
                        if (!inAttribute || escapeMode == EscapeMode.xhtml)
                            accum.append("&lt;");
                        else
                            accum.append(c);
                        break;
                    case '>':
                        if (!inAttribute)
                            accum.append("&gt;");
                        else
                            accum.append(c);
                        break;
                    case '"':
                        if (inAttribute)
                            accum.append("&quot;");
                        else
                            accum.append(c);
                        break;
                    default:
                        if (canEncode(coreCharset, c, encoder))
                            accum.append(c);
                        else
                            appendEncoded(accum, escapeMode, codePoint);
                }
            } else {
                final String c = new String(Character.toChars(codePoint));
                if (encoder.canEncode(c)) // uses fallback encoder for simplicity
                    accum.append(c);
                else
                    appendEncoded(accum, escapeMode, codePoint);
            }
        }
    }
237396
function generateSourceMappings(removedNodes) {
  var mappings = '';
  if (!removedNodes || removedNodes.length === '') {
    return mappings;
  }

  var end = {line: 1, column: 0};

  for (var i = 0; i < removedNodes.length; i++) {
    var start = removedNodes[i].loc.start;
    var lineDiff = start.line - end.line;
    var columnDiff = start.column - end.column;
    if (lineDiff) {
      for (var l = 0; l !== lineDiff; l++) {
        mappings += ';';
      }
      mappings += vlq.encode([start.column, 0, lineDiff, columnDiff]);
    } else if (columnDiff) {
      if (i) {
        mappings += ',';
      }
      mappings += vlq.encode([columnDiff, 0, lineDiff, columnDiff]);
    }

    end = removedNodes[i].loc.end;
    mappings += ',';
    mappings += vlq.encode([
      0,
      0,
      end.line - start.line,
      end.column - start.column,
    ]);
  }

  return mappings;
}
1157864
static Matcher removeMatchAnyFollowedByIndexOf(Matcher matcher) {
    if (matcher instanceof ZeroOrMoreMatcher) {
      ZeroOrMoreMatcher zm = matcher.as();
      if (zm.repeated() instanceof AnyMatcher
          && PatternUtils.getPrefix(zm.next()) instanceof IndexOfMatcher) {
        return zm.next();
      }
    }
    return matcher;
  }
472226
function processUncached( $tpl, $functionChildren, $rootNamespace, $currentNamespace )
    {
        $children = $functionChildren;

        $childTextElements = array();
        if ( is_array( $children ) )
        {
            foreach ( array_keys( $children ) as $childKey )
            {
                $child =& $children[$childKey];
                $tpl->processNode( $child, $childTextElements, $rootNamespace, $currentNamespace );
            }
        }
        $text = implode( '', $childTextElements );
        return $text;
    }
1084937
public void removeTrailingWhitespaces()
    {
        int last = -1;
        for (int i = text.length() - 1; i >= 0; i--)
        {
            if (isWhitespace(text.charAt(i)))
                last = i;
            else
                break;
        }
        if (last != -1)
        {
            text = text.substring(0, last);
            textStart = 0;
            textEnd = last;
        }
    }
156902
private static String decodeLineString(LineString lineString) {
		if (lineString == null || lineString.isEmpty()) {
			return "";
		}
		StringBuilder buffer = new StringBuilder();
		Coordinate[] coordinates = lineString.getCoordinates();
		for (int i = 0; i < coordinates.length; i++) {
			buffer.append(getX(coordinates[i]));
			buffer.append(" ");
			buffer.append(getY(coordinates[i]));
			if (i < (coordinates.length - 1)) {
				buffer.append(", ");
			}
		}
		return "M" + buffer.toString();
	}
450989
function trimStringEnds(keyValueString, unwantedCharArray) {
    var unwantedBegCharIndex = 0;
    var unwantedEndCharIndex = keyValueString.length - 1;
    var charIsUnwanted;
    var keepGoing = true; //keep traversing the string
    //starting from the beginning of the string
    while (keepGoing) {
        charIsUnwanted = false;
        for (var x = 0; x < unwantedCharArray.length; x++) {
            if (keyValueString.charAt(unwantedBegCharIndex) === unwantedCharArray[x]) {
                charIsUnwanted = true;
            }
        }
        if (!charIsUnwanted) {
            keepGoing = false;
        } else {
            unwantedBegCharIndex++;
        }
    }
    //now start at the end
    keepGoing = true;
    while (keepGoing) {
        charIsUnwanted = false;
        for (var y = 0; y < unwantedCharArray.length; y++) {
            if (keyValueString.charAt(unwantedEndCharIndex) === unwantedCharArray[y]) {
                charIsUnwanted = true;
            }
        }
        if (!charIsUnwanted) {
            keepGoing = false;
        } else {
            unwantedEndCharIndex--;
        }
    }
    keyValueString = keyValueString.slice(unwantedBegCharIndex, unwantedEndCharIndex + 1);
    return keyValueString;
}
44545
function (str) {
            return _(str).chain()
                .unescapeHTML()
                .stripTags()
                .clean()
                .value()
                .replace( matchJunk, '' )
                .toLowerCase();
        }
43924
function trimTrailingWhitespace(index, nextTag) {
    for (var endTag = null; index >= 0 && _canTrimWhitespace(endTag); index--) {
      var str = buffer[index];
      var match = str.match(/^<\/([\w:-]+)>$/);
      if (match) {
        endTag = match[1];
      }
      else if (/>$/.test(str) || (buffer[index] = collapseWhitespaceSmart(str, null, nextTag, options))) {
        break;
      }
    }
  }
1044542
function prune(code) {
  var ast = esprima.parse(code);

  estraverse.replace(ast, {
    leave: function leave(node, parent) {
      var ret;

      if ('IfStatement' === node.type) {
        if ('BinaryExpression' !== node.test.type) return;

        if ('self' === node.test.left.argument.name) {
          node.alternate = null;
        } else if ('global' === node.test.left.argument.name) {
          ret = node.alternate;
        }

        return ret;
      }

      if (
          'BlockStatement' === node.type
        && 'FunctionExpression' === parent.type
      ) {
        return node.body[0].alternate.alternate;
      }
    }
  });

  return escodegen.generate(ast, {
    format: {
      indent: { style: '  ' },
      semicolons: false,
      compact: true
    }
  });
}
1007318
function clean(obj) {
  var ret = {};

  // Remove traits/properties that are already represented
  // outside of the data container
  // TODO: Refactor into `omit` call
  var excludeKeys = ['id', 'name', 'firstName', 'lastName'];
  each(excludeKeys, function(omitKey) {
    clear(obj, omitKey);
  });

  // Flatten nested hierarchy, preserving arrays
  obj = flatten(obj);

  // Discard nulls, represent arrays as comma-separated strings
  // FIXME: This also discards `undefined`s. Is that OK?
  for (var key in obj) {
    if (has.call(obj, key)) {
      var val = obj[key];
      if (val == null) {
        continue;
      }

      if (is.array(val)) {
        ret[key] = val.toString();
        continue;
      }

      ret[key] = val;
    }
  }

  return ret;
}
1245419
function deepSplitString (input, separators) {
  if (input === null || typeof input === 'undefined') {
    return input
  }
  if (separators.length === 0) {
    return input
  }

  const sep = separators.shift()
  let output = input

  if (typeof input === 'string') {
    output = splitString(input, sep)
  } else if (Array.isArray(input)) {
    output = input.map(i => splitString(i, sep))
  } else if (typeof input === 'object') {
    output = {}
    Object.keys(input).forEach(key => {
      output[key] = splitString(input[key], sep)
    })
  }

  if (separators.length > 0) {
    return deepSplitString(output, separators)
  } else {
    return output
  }
}
953903
function destroyCircular(from, seen) {
	var to = Array.isArray(from) ? [] : {};

	seen.push(from);

	for (var _iterator = Object.keys(from), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
		var _ref;

		if (_isArray) {
			if (_i >= _iterator.length) break;
			_ref = _iterator[_i++];
		} else {
			_i = _iterator.next();
			if (_i.done) break;
			_ref = _i.value;
		}

		var key = _ref;

		var value = from[key];

		if (typeof value === 'function') {
			continue;
		}

		if (!value || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') {
			to[key] = value;
			continue;
		}

		if (seen.indexOf(from[key]) === -1) {
			to[key] = destroyCircular(from[key], seen.slice(0));
			continue;
		}

		to[key] = '[Circular]';
	}

	if (typeof from.name === 'string') {
		to.name = from.name;
	}

	if (typeof from.message === 'string') {
		to.message = from.message;
	}

	if (typeof from.stack === 'string') {
		to.stack = from.stack;
	}

	return to;
}
610260
public void removeTextSymbolizersWrapper() {
        List<SymbolizerWrapper> removeSW = new ArrayList<SymbolizerWrapper>();
        List<Symbolizer> removeS = new ArrayList<Symbolizer>();

        List<Symbolizer> symbolizers = rule.symbolizers();
        for( SymbolizerWrapper symbolizerWrapper : symbolizersWrapperList ) {
            if (symbolizerWrapper.isTextSymbolizer()) {
                Symbolizer symbolizer = symbolizerWrapper.getSymbolizer();
                removeSW.add(symbolizerWrapper);
                removeS.add(symbolizer);
            }
        }

        symbolizersWrapperList.removeAll(removeSW);
        symbolizers.removeAll(removeS);
    }
636568
function extractWhitespaces(ast /*, options*/) {
  const TYPE_WHITESPACE = "whitespace";
  return ast.map(node => {
    if (!node.children) {
      return node;
    }

    if (
      node.children.length === 0 ||
      (node.children.length === 1 &&
        node.children[0].type === "text" &&
        node.children[0].value.trim().length === 0)
    ) {
      return node.clone({
        children: [],
        hasDanglingSpaces: node.children.length !== 0
      });
    }

    const isWhitespaceSensitive = isWhitespaceSensitiveNode(node);
    const isIndentationSensitive = isIndentationSensitiveNode(node);

    return node.clone({
      isWhitespaceSensitive,
      isIndentationSensitive,
      children: node.children
        // extract whitespace nodes
        .reduce((newChildren, child) => {
          if (child.type !== "text" || isWhitespaceSensitive) {
            return newChildren.concat(child);
          }

          const localChildren = [];

          const [, leadingSpaces, text, trailingSpaces] = child.value.match(
            /^(\s*)([\s\S]*?)(\s*)$/
          );

          if (leadingSpaces) {
            localChildren.push({ type: TYPE_WHITESPACE });
          }

          const ParseSourceSpan = child.sourceSpan.constructor;

          if (text) {
            localChildren.push({
              type: "text",
              value: text,
              sourceSpan: new ParseSourceSpan(
                child.sourceSpan.start.moveBy(leadingSpaces.length),
                child.sourceSpan.end.moveBy(-trailingSpaces.length)
              )
            });
          }

          if (trailingSpaces) {
            localChildren.push({ type: TYPE_WHITESPACE });
          }

          return newChildren.concat(localChildren);
        }, [])
        // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
        .reduce((newChildren, child, i, children) => {
          if (child.type === TYPE_WHITESPACE) {
            return newChildren;
          }

          const hasLeadingSpaces =
            i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
          const hasTrailingSpaces =
            i !== children.length - 1 &&
            children[i + 1].type === TYPE_WHITESPACE;

          return newChildren.concat(
            Object.assign({}, child, {
              hasLeadingSpaces,
              hasTrailingSpaces
            })
          );
        }, [])
    });
  });
}
360138
function removeNestedBlocks (ast) {
  var tagged;
  while((tagged = findNestedBlocks(ast)).length) {
    fast.forEach(tagged, function (item) {
      var node = item[0],
          parent = item[1],
          index = parent.body.indexOf(node);
      fast.apply(Array.prototype.splice, parent.body, fast.concat([index, 1], node.body));
    });
  }
  return ast;
}
713459
private Tuple3<ReadOnlyStyledDocument<PS, SEG, S>, RichTextChange<PS, SEG, S>, MaterializedListModification<Paragraph<PS, SEG, S>>> replace(
            BiIndex start, BiIndex end, UnaryOperator<ReadOnlyStyledDocument<PS, SEG, S>> f) {
        int pos = tree.getSummaryBetween(0, start.major).map(s -> s.length() + 1).orElse(0) + start.minor;

        List<Paragraph<PS, SEG, S>> removedPars =
                getParagraphs().subList(start.major, end.major + 1);

        return end.map(this::split).map((l0, r) -> {
            return start.map(l0::split).map((l, removed) -> {
                ReadOnlyStyledDocument<PS, SEG, S> replacement = f.apply(removed);
                ReadOnlyStyledDocument<PS, SEG, S> doc = l.concatR(replacement).concat(r);
                RichTextChange<PS, SEG, S> change = new RichTextChange<>(pos, removed, replacement);
                List<Paragraph<PS, SEG, S>> addedPars = doc.getParagraphs().subList(start.major, start.major + replacement.getParagraphCount());
                MaterializedListModification<Paragraph<PS, SEG, S>> parChange =
                        MaterializedListModification.create(start.major, removedPars, addedPars);
                return t(doc, change, parChange);
            });
        });
    }