Map a Jena Node to a Stream of Strings. Any non-URI, non-Literals map to an empty Stream,
making this suitable to use with flatMap.
497884
private static Stream<String> nodeToStringStream(final org.apache.jena.graph.Node object) {
        if (object.isURI()) {
            return of(object.getURI());
        } else if (object.isLiteral()) {
            return of(object.getLiteralValue().toString());
        } else {
            return empty();
        }
    }
1338830
public PythonDataStream<SingleOutputStreamOperator<PyObject>> flat_map(
		FlatMapFunction<PyObject, Object> flat_mapper) throws IOException {
		return new PythonSingleOutputStreamOperator(stream.flatMap(new PythonFlatMapFunction(flat_mapper)));
	}
1296657
private static List<Map<String, String>> loadWords(InputStream stream) {
    List<Map<String, String>> list = new ArrayList<>();
    try (
      InputStreamReader isr = new InputStreamReader(stream, FILE_ENCODING);
      BufferedReader br = new BufferedReader(isr);
    ) {
      String line;

      Tokenizer wordTokenizer = new Breton().getWordTokenizer();
      while ((line = br.readLine()) != null) {
        line = line.trim();
        if (line.isEmpty() || line.charAt(0) == '#') { // ignore comments
          continue;
        }
        String[] parts = line.split("=");
        if (parts.length != 2) {
          throw new IOException("Format error in file "
                  + JLanguageTool.getDataBroker().getFromRulesDirAsUrl(FILE_NAME)
                  + ", line: " + line);
        }
        String[] wrongForms = parts[0].split("\\|"); // multiple incorrect forms
        for (String wrongForm : wrongForms) {
          int wordCount = 0;
          List<String> tokens = wordTokenizer.tokenize(wrongForm);
          for (String token : tokens) {
            if (!StringTools.isWhitespace(token)) {
              wordCount++;
            }
          }
          // grow if necessary
          for (int i = list.size(); i < wordCount; i++) {
            list.add(new HashMap<>());
          }
          list.get(wordCount - 1).put(wrongForm, parts[1]);
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    // seal the result (prevent modification from outside this class)
    List<Map<String,String>> result = new ArrayList<>();
    for (Map<String, String> map : list) {
      result.add(Collections.unmodifiableMap(map));
    }
    return Collections.unmodifiableList(result);
  }
761141
def _rdf2dot_simple(g, stream):
    """"""
    from itertools import chain

    import re

    path_re = re.compile(
        r'file:///(?P<type>[a-zA-Z]+)/'
        r'(?P<commit>\w+)'
        r'(?P<path>.+)?'
    )

    inputs = g.query(
        """
        SELECT ?input ?role ?activity ?comment
        WHERE {
            ?activity (prov:qualifiedUsage/prov:entity) ?input .
            ?activity prov:qualifiedUsage ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:entity ?input .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun .
            ?activity rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )
    outputs = g.query(
        """
        SELECT ?activity ?role ?output ?comment
        WHERE {
            ?output (prov:qualifiedGeneration/prov:activity) ?activity .
            ?output prov:qualifiedGeneration ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:activity ?activity .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun ;
                      rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )

    activity_nodes = {}
    artifact_nodes = {}
    for source, role, target, comment, in chain(inputs, outputs):
        # extract the pieces of the process URI
        src_path = path_re.match(source).groupdict()
        tgt_path = path_re.match(target).groupdict()

        # write the edge
        stream.write(
            '\t"{src_commit}:{src_path}" -> '
            '"{tgt_commit}:{tgt_path}" '
            '[label={role}] \n'.format(
                src_commit=src_path['commit'][:5],
                src_path=src_path.get('path') or '',
                tgt_commit=tgt_path['commit'][:5],
                tgt_path=tgt_path.get('path') or '',
                role=role
            )
        )
        if src_path.get('type') == 'commit':
            activity_nodes.setdefault(source, {'comment': comment})
            artifact_nodes.setdefault(target, {})
        if tgt_path.get('type') == 'commit':
            activity_nodes.setdefault(target, {'comment': comment})
            artifact_nodes.setdefault(source, {})

    # customize the nodes
    for node, content in activity_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[shape=box label="#{commit}:{path}:{comment}"] \n'.format(
                comment=content['comment'],
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    for node, content in artifact_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[label="#{commit}:{path}"] \n'.format(
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    stream.write('}\n')
504164
public final static <T, R> Stream<R> flatMapStream(final Stream<T> stream, final Function<? super T, ? extends BaseStream<? extends R, ?>> fn) {
        return stream.flatMap(fn.andThen(bs -> {

            if (bs instanceof Stream)
                return (Stream<R>) bs;
            else
                return Streams.stream(bs.iterator());

        }));
    }
1339467
@SuppressWarnings("unchecked")
  Map<String, Object> flatten(Map<String, Object> source) {
    Map<String, Object> result = new LinkedHashMap<>();

    for (String key : source.keySet()) {
      Object value = source.get(key);

      if (value instanceof Map) {
        Map<String, Object> subMap = flatten((Map<String, Object>) value);

        for (String subkey : subMap.keySet()) {
          result.put(key + "." + subkey, subMap.get(subkey));
        }
      } else if (value instanceof Collection) {
        StringBuilder joiner = new StringBuilder();
        String separator = "";

        for (Object element : ((Collection) value)) {
          Map<String, Object> subMap = flatten(Collections.singletonMap(key, element));
          joiner
              .append(separator)
              .append(subMap.entrySet().iterator().next().getValue().toString());

          separator = ",";
        }

        result.put(key, joiner.toString());
      } else {
        result.put(key, value);
      }
    }

    return result;
  }
1174919
public final static <T, R> Stream<R> flatMapCompletableFuture(final Stream<T> stream,
            final Function<? super T, CompletableFuture<? extends R>> fn) {
        return stream.flatMap(in -> Streams.completableFutureToStream(fn.apply(in)));

    }
440877
@Override
  protected PyExpr visitListLiteralNode(ListLiteralNode node) {
    return PyExprUtils.convertIterableToPyListExpr(
        node.getChildren().stream().map(n -> visit(n)).collect(Collectors.toList()));
  }
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 [];
    })
  );
}
1122387
@SafeVarargs
    @SuppressWarnings("unchecked")
    public static <T> Stream<T> stream(Iterable<T>... iterables) {
        List<Iterator<T>> iterators = Arrays.stream(iterables)
            .map(Iterable::iterator)
            .collect(Collectors.toList());

        return stream(iterators.toArray(new Iterator[iterables.length]));
    }
821052
def make_streams(name, value, boundary, encoding):
    """"""

    filename = None
    mime = None

    # user passed in a special dict.
    if isinstance(value, collections.Mapping) and "name" in value and "value" in value:
        filename = value["name"]
        try:
            mime = value["mime"]
        except KeyError:
            pass
        value = value["value"]

    if not filename:
        filename = getattr(value, "name", None)
        if filename:
            filename = os.path.split(filename)[1]

    mime = mime or "application/octet-stream"

    name, filename, mime = [escape_header(v) for v in (name, filename, mime)]

    stream = BytesIO()
    stream.write("--{}\r\n".format(boundary).encode(encoding))
    if not filename:
        stream.write(
            'Content-Disposition: form-data; name="{}"\r\n'.format(name).encode(
                encoding
            )
        )
    else:
        stream.write(
            'Content-Disposition: form-data; name="{}"; filename="{}"\r\n'.format(
                name, filename
            ).encode(encoding)
        )
        if mime:
            stream.write("Content-Type: {}\r\n".format(mime).encode(encoding))
    stream.write(b"\r\n")

    if hasattr(value, "read"):
        stream.seek(0)
        return stream, value, BytesIO("\r\n".encode(encoding))

    # not a file-like object, encode headers and value in one go
    value = value if isinstance(value, (str, bytes)) else json.dumps(value)
    if isinstance(value, bytes):
        stream.write(value)
    else:
        stream.write(value.encode(encoding))
    stream.write(b"\r\n")
    stream.seek(0)
    return (stream,)
382455
private static @Nonnull Map<String, String> attributesToMap(NamedNodeMap nnm) {
        return IntStream.range(0, nnm.getLength())
                    .mapToObj(nnm::item)
                    .collect(toMap(Node::getNodeName, Node::getNodeValue));
    }
338272
public static RdfStream fromModel(final Node node, final Model model) {
        return new DefaultRdfStream(node,
                stream(spliteratorUnknownSize(model.listStatements(), IMMUTABLE), false).map(Statement::asTriple));
    }
1340539
public Map<Any2<Integer, String>, String> getStringMap() {
        return data.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().mapCombine(Object::toString, Object::toString, Object::toString)));
    }
7910
private static Stream<Node> streamAttributes(Node node) {
        final NamedNodeMap attributes = node.getAttributes();
        if (attributes == null) return Stream.empty();
        return IntStream.range(0, attributes.getLength()).mapToObj(attributes::item);
    }
356932
public static <T> Stream<T> toStream(Optional<T> opt) {
    return Arrays.asList(opt.orElse(null)).stream().filter(y -> null != y);
  }
989337
public static <T> Stream<T> ofNullable(Iterable<T> iterable) {
        return null == iterable ? Stream.empty() : stream(iterable);
    }