recursively label combinators with the json path
546063
function label (composition) {
  const label = path => (composition, name, array) => {
    const p = path + (name !== undefined ? (array === undefined ? `.${name}` : `[${name}]`) : '')
    composition = visit(composition, label(p)) // copy
    composition.path = p
    return composition
  }
  return label('')(composition)
}
173830
def json_path_components(path):
    
    if isinstance(path, str):
        path = path.split('.')

    return list(path)
314233
def dict_flat_generator(value, attname=None, splitter=JSPLITTER,
                        dumps=None, prefix=None, error=ValueError,
                        recursive=True):
    ''''''
    if not isinstance(value, dict) or not recursive:
        if not prefix:
            raise error('Cannot assign a non dictionary to a JSON field')
        else:
            name = '%s%s%s' % (attname, splitter,
                               prefix) if attname else prefix
            yield name, dumps(value) if dumps else value
    else:
        # loop over dictionary
        for field in value:
            val = value[field]
            key = prefix
            if field:
                key = '%s%s%s' % (prefix, splitter,
                                  field) if prefix else field
            for k, v2 in dict_flat_generator(val, attname, splitter, dumps,
                                             key, error, field):
                yield k, v2
86257
function childNodesFromPaths (files, parent, renderLabelFn, originalFiles, baseDir) {
  // Group by first path element
  var groups = _.groupBy(files, file => file.match(/^[^/]*\/?/))
  return Object.keys(groups).map(function (groupKey) {
    const group = groups[groupKey]
    // Is this group explicitly part of the result, or
    // just implicit through its children
    const explicit = group.indexOf(groupKey) >= 0
    let index = -1
    if (explicit) {
      index = originalFiles.indexOf(parent.replace(baseDir, '') + groupKey)
    }

    return {
      label: renderLabelFn(parent, groupKey, explicit, explicit ? index : -1),
      nodes: childNodesFromPaths(
        // Remove parent directory from file paths
        group
          .map(node => node.substr(groupKey.length))
          // Skip the empty path
          .filter(node => node),
        // New parent..., normalize to one trailing slash
        parent + groupKey,
        renderLabelFn,
        originalFiles,
        baseDir
      )
    }
  })
}
121629
def inherited_labels(cls):
        
        return [scls.__label__ for scls in cls.mro()
                if hasattr(scls, '__label__') and not hasattr(
                scls, '__abstract_node__')]
348744
def json_string(self):
        
        def visit_children(node):
            """ Recursively visit the fragments_tree """
            output_fragments = []
            for child in node.children_not_empty:
                fragment = child.value
                text = fragment.text_fragment
                output_fragments.append({
                    "id": text.identifier,
                    "language": text.language,
                    "lines": text.lines,
                    "begin": gf.time_to_ssmmm(fragment.begin),
                    "end": gf.time_to_ssmmm(fragment.end),
                    "children": visit_children(child)
                })
            return output_fragments
        output_fragments = visit_children(self.fragments_tree)
        return gf.safe_unicode(
            json.dumps({"fragments": output_fragments}, indent=1, sort_keys=True)
        )
1158713
def mmap_key(metric_name, name, labelnames, labelvalues):
    """"""
    # ensure labels are in consistent order for identity
    labels = dict(zip(labelnames, labelvalues))
    return json.dumps([metric_name, name, labels], sort_keys=True)
1161906
def get_label_names(ctx):
    """"""
    labels = [
        label
        for label in ctx.__dict__
        if not label.startswith("_")
        and label
        not in [
            "children",
            "exception",
            "invokingState",
            "parentCtx",
            "parser",
            "start",
            "stop",
        ]
    ]
    return labels
588102
def mergeWithLabels(json, firstField, firstFieldLabel, secondField, secondFieldLabel):
    
    merged = []

    for i in range(0, len(json[firstField])):
        merged.append({ firstFieldLabel : json[firstField][i],
                        secondFieldLabel : json[secondField][i] })
    return merged
120595
def _SGraphFromJsonTree(json_str):
    
    g = json.loads(json_str)
    vertices = [_Vertex(x['id'],
                dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id']))
                                                      for x in g['vertices']]
    edges = [_Edge(x['src'], x['dst'],
             dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'src' and k != 'dst']))
                                                      for x in g['edges']]
    sg = _SGraph().add_vertices(vertices)
    if len(edges) > 0:
        sg = sg.add_edges(edges)
    return sg
6410
def _fix_json_agents(ag_obj):
    """"""
    if isinstance(ag_obj, str):
        logger.info("Fixing string agent: %s." % ag_obj)
        ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}}
    elif isinstance(ag_obj, list):
        # Recursive for complexes and similar.
        ret = [_fix_json_agents(ag) for ag in ag_obj]
    elif isinstance(ag_obj, dict) and 'TEXT' in ag_obj.keys():
        ret = deepcopy(ag_obj)
        text = ret.pop('TEXT')
        ret['db_refs']['TEXT'] = text
    else:
        ret = ag_obj
    return ret
1237363
def trl(label, desc = "", tokens = {}, options = {})
      tr(label, desc, tokens, options.merge(:skip_decorations => true))
    end
128163
def dominator_tree(graph):
    
    todo = Queue()
    done = set()
    dominator = Tree(None)
    nodes = list(graph.nodes)

    while True:
        # FIGURE OUT NET ITEM TO WORK ON
        if todo:
            node = todo.pop()
        elif nodes:
            node = nodes.pop()
            if len(nodes) % 1000 == 0:
                Log.note("{{num}} nodes remaining", num=len(nodes))
        else:
            break
        if node in done:
            continue

        parents = graph.get_parents(node) - {node}
        if not parents:
            # node WITHOUT parents IS A ROOT
            done.add(node)
            dominator.add_edge(Edge(ROOTS, node))
            continue

        not_done = parents - done
        if not_done:
            # THERE ARE MORE parents TO DO FIRST
            more_todo = not_done - todo
            if not more_todo:
                # ALL PARENTS ARE PART OF A CYCLE, MAKE node A ROOT
                done.add(node)
                dominator.add_edge(Edge(LOOPS, node))
            else:
                # DO THE PARENTS BEFORE node
                todo.push(node)
                for p in more_todo:
                    todo.push(p)
            continue

        # WE CAN GET THE DOMINATORS FOR ALL parents
        if len(parents) == 1:
            # SHORTCUT
            dominator.add_edge(Edge(list(parents)[0], node))
            done.add(node)
            continue

        paths_from_roots = [
            list(reversed(dominator.get_path_to_root(p)))
            for p in parents
        ]

        if any(p[0] is ROOTS for p in paths_from_roots):
            # THIS OBJECT CAN BE REACHED FROM A ROOT, IGNORE PATHS FROM LOOPS
            paths_from_roots = [p for p in paths_from_roots if p[0] is ROOTS]
            if len(paths_from_roots) == 1:
                # SHORTCUT
                dom = paths_from_roots[0][-1]
                dominator.add_edge(Edge(dom, node))
                done.add(node)
                continue

        # FIND COMMON PATH FROM root
        num_paths = len(paths_from_roots)
        for i, x in enumerate(zip_longest(*paths_from_roots)):
            if x.count(x[0]) != num_paths:
                dom = paths_from_roots[0][i-1]
                if dom is LOOPS:
                    # CAN BE REACHED FROM MORE THAN ONE LOOP, PICK ONE TO BLAME
                    dom = paths_from_roots[0][-1]
                break
        else:
            # ALL PATHS IDENTICAL
            dom = paths_from_roots[0][-1]

        dominator.add_edge(Edge(dom, node))
        done.add(node)

    return dominator
591508
def label( self, node ):
        """"""
        result = []
        if node.get('type'):
            result.append( node['type'] )
        if node.get('name' ):
            result.append( node['name'] )
        elif node.get('value') is not None:
            result.append( unicode(node['value'])[:32])
        if 'module' in node and not node['module'] in result:
            result.append( ' in %s'%( node['module'] ))
        if node.get( 'size' ):
            result.append( '%s'%( mb( node['size'] )))
        if node.get( 'totsize' ):
            result.append( '(%s)'%( mb( node['totsize'] )))
        parent_count = len( node.get('parents',()))
        if parent_count > 1:
            result.append( '/%s refs'%( parent_count ))
        return " ".join(result)
159443
def _jsonld(graph, format, *args, **kwargs):
    """"""
    import json

    from pyld import jsonld
    from renku.models._jsonld import asjsonld

    output = getattr(jsonld, format)([
        asjsonld(action) for action in graph.activities.values()
    ])
    return json.dumps(output, indent=2)
590727
def tree_label(self):
        ''''''
        titles = []
        page = self
        while page:
            titles.append(page.title)
            page = page.parent
        return smart_text(' > '.join(reversed(titles)))
1030379
function transitiveClosure(nodeLabels, graph) {
  let madeProgress = false;
  do {
    madeProgress = false;
    for (const [ src, values ] of Array.from(nodeLabels.entries())) {
      const targets = graph[src];
      if (targets) {
        for (const target of targets) {
          for (const value of values) {
            madeProgress = multiMapSet(nodeLabels, target, value) || madeProgress;
          }
        }
      }
    }
  } while (madeProgress);
}