TODO: replace with stream-based version
437162
private static String asString(Writable writable) {
        if (writable instanceof GPathResult) {
            return asString((GPathResult) writable); //GROOVY-4285
        }
        Writer sw = new StringWriter();
        try {
            writable.writeTo(sw);
        } catch (IOException e) {
            // ignore
        }
        return sw.toString();
    }
920682
def mutate_stream (instream, outstream):
    """"""

    chunk = None
    key = None
    data = None
    misclines = []

    for fullline in instream:
        line = fullline.split ('#', 1)[0]

        m = sectionre.match (line)
        if m is not None:
            # New chunk
            if chunk is not None:
                if key is not None:
                    chunk.data.set_one (key, data.strip ().decode ('utf8'))
                    key = data = None
                yield chunk
                chunk.emit (outstream)

            chunk = FileChunk ()
            for miscline in misclines:
                chunk._addLine (miscline, None)
            misclines = []
            chunk.data.section = m.group (1)
            chunk._addLine (fullline, None)
            continue

        if len (line.strip ()) == 0:
            if key is not None:
                chunk.data.set_one (key, data.strip ().decode ('utf8'))
                key = data = None
            if chunk is not None:
                chunk._addLine (fullline, None)
            else:
                misclines.append (fullline)
            continue

        m = escre.match (fullline)
        if m is not None:
            if chunk is None:
                raise InifileError ('key seen without section!')
            if key is not None:
                chunk.data.set_one (key, data.strip ().decode ('utf8'))
            key = m.group (1)
            data = m.group (2).replace (r'\"', '"').replace (r'\n', '\n').replace (r'\\', '\\')
            chunk.data.set_one (key, data.decode ('utf8'))
            chunk._addLine (fullline, key)
            key = data = None
            continue

        m = keyre.match (line)
        if m is not None:
            if chunk is None:
                raise InifileError ('key seen without section!')
            if key is not None:
                chunk.data.set_one (key, data.strip ().decode ('utf8'))
            key = m.group (1)
            data = m.group (2)
            if not data[-1].isspace ():
                data += ' '
            chunk._addLine (fullline, key)
            continue

        if line[0].isspace () and key is not None:
            data += line.strip () + ' '
            chunk._addLine (fullline, key)
            continue

        raise InifileError ('unparsable line: ' + line[:-1])

    if chunk is not None:
        if key is not None:
            chunk.data.set_one (key, data.strip ().decode ('utf8'))
        yield chunk
        chunk.emit (outstream)
119755
@Override
    public void replaceProperties(final IdentifierConverter<Resource, FedoraResource> idTranslator,
        final Model inputModel, final RdfStream originalTriples) throws MalformedRdfException {

        final Resource selfResource = idTranslator.reverse().convert(this);
        ensureInteractionModelDefaults(selfResource.toString(), inputModel);

        // remove any statements that update "relaxed" server-managed triples so they can be updated separately
        final List<Statement> filteredStatements = new ArrayList<>();
        final StmtIterator it = inputModel.listStatements();
        final Optional<String> resourceInteractionModel = getResourceInteraction();
        final boolean hasInteractionModel = resourceInteractionModel.isPresent();
        while (it.hasNext()) {
            final Statement next = it.next();
            if (RdfLexicon.isRelaxed.test(next.getPredicate())) {
                filteredStatements.add(next);
                it.remove();
            } else {
                if (hasInteractionModel) {
                    checkInteractionModel(next.asTriple(), resourceInteractionModel);
                }
            }
        }
        // remove any "relaxed" server-managed triples from the existing triples
        final RdfStream filteredTriples = new DefaultRdfStream(originalTriples.topic(),
                originalTriples.filter(triple -> !isRelaxed.test(createProperty(triple.getPredicate().getURI()))));



        try (final RdfStream replacementStream =
                new DefaultRdfStream(selfResource.asNode())) {

            final GraphDifferencer differencer =
                new GraphDifferencer(inputModel, filteredTriples);

            final StringBuilder exceptions = new StringBuilder();
            try (final DefaultRdfStream diffStream =
                    new DefaultRdfStream(replacementStream.topic(), differencer.difference())) {
                new RdfRemover(idTranslator, getSession(), diffStream).consume();
            } catch (final MalformedRdfException e) {
                exceptions.append(e.getMessage());
                exceptions.append("\n");
            } catch (final ConstraintViolationException e) {
                throw e;
            }

            try (
                final DefaultRdfStream notCommonStream =
                        new DefaultRdfStream(replacementStream.topic(), differencer.notCommon());
                final DefaultRdfStream testStream =
                        new DefaultRdfStream(replacementStream.topic(), differencer.notCommon())) {

                // do some very basic validation to catch invalid RDF
                // this uses the same checks that updateProperties() uses
                final Collection<ConstraintViolationException> errors = testStream
                        .flatMap(FedoraResourceImpl::validateTriple)
                        .filter(x -> x != null)
                        .collect(Collectors.toList());

                throwConstraintErrorsIfPresent(errors);

                new RdfAdder(idTranslator, getSession(), notCommonStream, inputModel.getNsPrefixMap()).consume();
            } catch (final MalformedRdfException e) {
                exceptions.append(e.getMessage());
            } catch (final ConstraintViolationException e) {
                throw e;
            }

            // If this resource's structural parent is an IndirectContainer, check whether the
            // ldp:insertedContentRelation property is present in the stream of changed triples.
            // If so, set the propertyChanged value to true.
            final AtomicBoolean propertyChanged = new AtomicBoolean();
            ldpInsertedContentProperty(getNode()).ifPresent(resource -> {
                propertyChanged.set(differencer.notCommon().map(Triple::getPredicate).anyMatch(resource::equals));
            });

            removeEmptyFragments();

            if (exceptions.length() > 0) {
                throw new MalformedRdfException(exceptions.toString());
            }

            try {
                touch(propertyChanged.get(), RelaxedPropertiesHelper.getCreatedDate(filteredStatements),
                        RelaxedPropertiesHelper.getCreatedBy(filteredStatements),
                        RelaxedPropertiesHelper.getModifiedDate(filteredStatements),
                        RelaxedPropertiesHelper.getModifiedBy(filteredStatements));
            } catch (final RepositoryException e) {
                throw new RuntimeException(e);
            }
        }
    }
1186784
@Override
    public String replace(File file, String flickrId, boolean async) throws FlickrException {
        Payload payload = new Payload(file, flickrId);
        return sendReplaceRequest(async, payload);
    }
583055
function transformChunk(chunk, encoding, done) {
    if (chunk.isNull()) return done();
    if (chunk.isStream()) return this.emit('error', new PluginError(logFlag, 'Streaming not supported'));
    if (
      !(chunk.isMarkdown = options.regexpMarkdown.test(chunk.relative)) &&
      !(chunk.isTemplate = options.regexpTemplate.test(chunk.relative)) &&
      !(chunk.isHtml = options.regexpHtml.test(chunk.relative))
    ) {
      return options.passThrough ? done(null, chunk) : done();
    }
    transformChunkData(chunk);
    if (chunk.data.draft && process.env.NODE_ENV !== 'development') return done();
    if (buffer.hasOwnProperty(chunk.relative)) {
      logDuplicate(chunk);
      return done();
    }
    transformChunkContents.call(this, chunk);
    buffer[chunk.relative] = chunk;
    done(null, chunk);
  }
1374757
private String stringReplace(final String source, final String find, final String replace) {
    if (source == null || find == null || replace == null)
      return source;
    final int index = source.indexOf(find);
    if (index == -1)
      return source; // no occurence, don't do anything;
    if (index == 0)
      return replace + source.substring(find.length());
    return source.substring(0, index) + replace + source.substring(index + find.length());
  }
368181
function(replace, count, callback) {
    return pathmap.replace(
      pathmap.chomp(this, pathmap.extname(this)), replace, callback);
  }
218043
@Override
	public int replace(int handle, Object obj) throws DataStoreException
    {
        if (SAFE_MODE) checkHandle(handle);
    	data[handle] = obj;
    	return handle;
    }
224336
function(stream) {
		var exportKey = function(obj, env) {
			var keyString = keyStringGenerator(obj, env);

			if(stream.constElements) {
				if(obj.___jp_originalJsonLine)
					return keyString + separator + obj.___jp_originalJsonLine;
			} else {
				if(obj.___jp_originalJsonLine)
					delete obj.___jp_originalJsonLine;
			}

			return keyString + separator + JSON.stringify(obj);
		};

		return stream.pipe(jp.map(exportKey));
	}
1209553
String replace(String source) {
        if (source == null)
            return null;
        Matcher m = PATTERN.matcher(source);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String var = m.group(1);
            String value = values.getProperty(var);
            String replacement = (value != null) ? replace(value) : "";
            m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
        }
        m.appendTail(sb);
        return sb.toString();
    }
1034893
async function replace(string, regex, callback) {
	regex.lastIndex = 0;

	/* get all data */
	const promises = [];
	string.replace(regex, (match, ...args) => {
		const promise = callback(match, ...args);
		promises.push(promise);
	});
	const data = await Promise.all(promises);

	/* replace all data */
	return data.length ? string.replace(regex, () => data.shift()) : string;
}
112206
@Override
    public String replace(InputStream in, String flickrId, boolean async) throws FlickrException {
        Payload payload = new Payload(in, flickrId);
        return sendReplaceRequest(async, payload);
    }
343911
function extractNestedStreams(obj) {
  return flatten(
    Object.keys(obj).map(key => {
      // DEPRECATED I can't think of a usecase
      // if (typeof obj[key] === 'object') {
      // 	return extractNestedStreams(obj[key]);
      // }
      if (obj[key] === null || obj[key] === undefined) {
        return [];
      }
      if (isStream(obj[key])) {
        return [
          {
            parent: obj,
            key,
            stream: obj[key]
          }
        ];
      }
      if (typeof obj[key] === "object") {
        return extractNestedStreams(obj[key]);
      }
      return [];
    })
  );
}
139815
function replace(haystack, needle) {
			const replacement = options.resolve ? notate(data, needle.trim()) : data[needle.trim()];

			return VALID_RESULT_TYPES.includes(typeof replacement) ? replacement : options.clean ? '' : haystack;
		}
716624
public boolean replace( Long key, TypeV oldValue, TypeV newValue ) {
    return replace(key.longValue(), oldValue, newValue);
  }
413836
function(stream, state) {
      if (stream.match(settings.rightDelimiter, true)) {
        if (settings.smartyVersion === 3) {
          state.depth--;
          if (state.depth <= 0) {
            state.tokenize = parsers.tokenizer;
          }
        } else {
          state.tokenize = parsers.tokenizer;
        }
        return helpers.cont("tag", null);
      }

      if (stream.match(settings.leftDelimiter, true)) {
        state.depth++;
        return helpers.cont("tag", "startTag");
      }

      var ch = stream.next();
      if (ch == "$") {
        stream.eatWhile(regs.validIdentifier);
        return helpers.cont("variable-2", "variable");
      } else if (ch == "|") {
        return helpers.cont("operator", "pipe");
      } else if (ch == ".") {
        return helpers.cont("operator", "property");
      } else if (regs.stringChar.test(ch)) {
        state.tokenize = parsers.inAttribute(ch);
        return helpers.cont("string", "string");
      } else if (regs.operatorChars.test(ch)) {
        stream.eatWhile(regs.operatorChars);
        return helpers.cont("operator", "operator");
      } else if (ch == "[" || ch == "]") {
        return helpers.cont("bracket", "bracket");
      } else if (ch == "(" || ch == ")") {
        return helpers.cont("bracket", "operator");
      } else if (/\d/.test(ch)) {
        stream.eatWhile(/\d/);
        return helpers.cont("number", "number");
      } else {

        if (state.last == "variable") {
          if (ch == "@") {
            stream.eatWhile(regs.validIdentifier);
            return helpers.cont("property", "property");
          } else if (ch == "|") {
            stream.eatWhile(regs.validIdentifier);
            return helpers.cont("qualifier", "modifier");
          }
        } else if (state.last == "pipe") {
          stream.eatWhile(regs.validIdentifier);
          return helpers.cont("qualifier", "modifier");
        } else if (state.last == "whitespace") {
          stream.eatWhile(regs.validIdentifier);
          return helpers.cont("attribute", "modifier");
        } if (state.last == "property") {
          stream.eatWhile(regs.validIdentifier);
          return helpers.cont("property", null);
        } else if (/\s/.test(ch)) {
          last = "whitespace";
          return null;
        }

        var str = "";
        if (ch != "/") {
          str += ch;
        }
        var c = null;
        while (c = stream.eat(regs.validIdentifier)) {
          str += c;
        }
        for (var i=0, j=keyFunctions.length; i<j; i++) {
          if (keyFunctions[i] == str) {
            return helpers.cont("keyword", "keyword");
          }
        }
        if (/\s/.test(ch)) {
          return null;
        }
        return helpers.cont("tag", "tag");
      }
    }
10210
@Deprecated @ReplacedBy(value="java.lang.String.replace()", reason="since 1.5")
    public static String replace (String source, String before, String after)
    {
        int pos = source.indexOf(before);
        if (pos == -1) {
            return source;
        }

        StringBuilder sb = new StringBuilder(source.length() + 32);

        int blength = before.length();
        int start = 0;
        while (pos != -1) {
            sb.append(source.substring(start, pos));
            sb.append(after);
            start = pos + blength;
            pos = source.indexOf(before, start);
        }
        sb.append(source.substring(start));

        return sb.toString();
    }