Accepts a marathon container and pulls out the nested values into the top level
491587
def flatten_container(self, container):
        
        for names in ARG_MAP.values():

            if names[TransformationTypes.MARATHON.value]['name'] and \
                            '.' in names[TransformationTypes.MARATHON.value]['name']:
                marathon_dotted_name = names[TransformationTypes.MARATHON.value]['name']
                parts = marathon_dotted_name.split('.')

                if parts[-2] == 'parameters':
                    # Special lookup for docker parameters
                    common_type = names[TransformationTypes.MARATHON.value].get('type')
                    result = self._lookup_parameter(container, parts[-1], common_type)
                    if result:
                        container[marathon_dotted_name] = result
                else:
                    result = lookup_nested_dict(container, *parts)
                    if result:
                        container[marathon_dotted_name] = result
        return container
1054860
def _parse_container(tokens, index, for_or_if=None):
    """"""

    # Store the opening bracket.
    items = [Atom(Token(*tokens[index]))]
    index += 1

    num_tokens = len(tokens)
    while index < num_tokens:
        tok = Token(*tokens[index])

        if tok.token_string in ',)]}':
            # First check if we're at the end of a list comprehension or
            # if-expression. Don't add the ending token as part of the list
            # comprehension or if-expression, because they aren't part of those
            # constructs.
            if for_or_if == 'for':
                return (ListComprehension(items), index - 1)

            elif for_or_if == 'if':
                return (IfExpression(items), index - 1)

            # We've reached the end of a container.
            items.append(Atom(tok))

            # If not, then we are at the end of a container.
            if tok.token_string == ')':
                # The end of a tuple.
                return (Tuple(items), index)

            elif tok.token_string == ']':
                # The end of a list.
                return (List(items), index)

            elif tok.token_string == '}':
                # The end of a dictionary or set.
                return (DictOrSet(items), index)

        elif tok.token_string in '([{':
            # A sub-container is being defined.
            (container, index) = _parse_container(tokens, index)
            items.append(container)

        elif tok.token_string == 'for':
            (container, index) = _parse_container(tokens, index, 'for')
            items.append(container)

        elif tok.token_string == 'if':
            (container, index) = _parse_container(tokens, index, 'if')
            items.append(container)

        else:
            items.append(Atom(tok))

        index += 1

    return (None, None)
574795
def path_upper(
        cls, object_id, limit_depth=1000000, db_session=None, *args, **kwargs
    ):
        
        tablename = cls.model.__table__.name
        raw_q = """
            WITH RECURSIVE subtree AS (
                    SELECT res.*, 1 as depth FROM {tablename} res
                    WHERE res.resource_id = :resource_id
                  UNION ALL
                    SELECT res_u.*, depth+1 as depth
                    FROM {tablename} res_u, subtree st
                    WHERE res_u.resource_id = st.parent_id
            )
            SELECT * FROM subtree WHERE depth<=:depth;
        """.format(
            tablename=tablename
        )
        db_session = get_db_session(db_session)
        q = (
            db_session.query(cls.model)
            .from_statement(sa.text(raw_q))
            .params(resource_id=object_id, depth=limit_depth)
        )
        return q
709647
def call(monads, inner_values = [], &block)
      head, *tail = *monads

      if tail.length.zero?
        map(head, inner_values, &block)
      else
        flat_map(head, tail, inner_values, &block)
      end
    end
1110170
function (nodes, i, container, _parent, counter) {
	var node = nodes[i].clone();

	nodes[i].clear();

	return function (others) {
		var local_promises = [];
		if (node.children.length) {
			transclude(others, node.children);
		}

		node.children    = others;
		node.is_resolved = true;

		collect_components([node], container, local_promises, _parent, counter);

		return $q.all(local_promises).then(function () {
			nodes[i] = node;
		});
	};
}
589687
def _handle_runs(self, relpath, params):
    """"""
    runs_by_day = self._partition_runs_by_day()
    args = self._default_template_args('run_list.html')
    args['runs_by_day'] = runs_by_day
    content = self._renderer.render_name('base.html', args).encode("utf-8")
    self._send_content(content, 'text/html')
164661
function addMatchers(sections, tree, resultSections, results, index){
	var hasAll = getChild(tree, WILDCARD_ALL);
	if(hasAll) addValue(resultSections.concat(WILDCARD_ALL), hasAll, results);

	var isEnd = index === sections.length;
	if(isEnd) {
		addValue(resultSections, tree, results);
		return;
	}

	var hasOne = getChild(tree, WILDCARD_ONE);
	if (hasOne) addMatchers(
		sections,
		hasOne,
		resultSections.concat(WILDCARD_ONE),
		results,
		index + 1
	);

	var section = sections[index];
	var hasSection = getChild(tree, section);
	if (hasSection) addMatchers(
		sections,
		hasSection,
		resultSections.concat(section),
		results,
		index + 1
	);
}
879075
def collapse_nested(self, cats, max_nestedness=10):
        
        children = []
        removed = set()
        nestedness = max_nestedness

        old = list(self.widget.options.values())
        nested = [cat for cat in old if getattr(cat, 'cat') is not None]
        parents = {cat.cat for cat in nested}
        parents_to_remove = cats
        while len(parents_to_remove) > 0 and nestedness > 0:
            for cat in nested:
                if cat.cat in parents_to_remove:
                    children.append(cat)
            removed = removed.union(parents_to_remove)
            nested = [cat for cat in nested if cat not in children]
            parents_to_remove = {c for c in children if c in parents - removed}
            nestedness -= 1
        self.remove(children)
842539
def _get_schema_from_list(frum, table_name, parent, nested_path, columns):
    

    for d in frum:
        row_type = python_type_to_json_type[d.__class__]

        if row_type != "object":
            # EXPECTING PRIMITIVE VALUE
            full_name = parent
            column = columns[full_name]
            if not column:
                column = Column(
                    name=concat_field(table_name, full_name),
                    es_column=full_name,
                    es_index=".",
                    es_type=d.__class__.__name__,
                    jx_type=None,  # WILL BE SET BELOW
                    last_updated=Date.now(),
                    nested_path=nested_path,
                )
                columns.add(column)
            column.es_type = _merge_python_type(column.es_type, d.__class__)
            column.jx_type = python_type_to_json_type[column.es_type]
        else:
            for name, value in d.items():
                full_name = concat_field(parent, name)
                column = columns[full_name]
                if not column:
                    column = Column(
                        name=concat_field(table_name, full_name),
                        es_column=full_name,
                        es_index=".",
                        es_type=value.__class__.__name__,
                        jx_type=None,  # WILL BE SET BELOW
                        last_updated=Date.now(),
                        nested_path=nested_path,
                    )
                    columns.add(column)
                if is_container(value):  # GET TYPE OF MULTIVALUE
                    v = list(value)
                    if len(v) == 0:
                        this_type = none_type.__name__
                    elif len(v) == 1:
                        this_type = v[0].__class__.__name__
                    else:
                        this_type = reduce(
                            _merge_python_type, (vi.__class__.__name__ for vi in value)
                        )
                else:
                    this_type = value.__class__.__name__
                column.es_type = _merge_python_type(column.es_type, this_type)
                column.jx_type = python_type_to_json_type[column.es_type]

                if this_type in {"object", "dict", "Mapping", "Data"}:
                    _get_schema_from_list(
                        [value], table_name, full_name, nested_path, columns
                    )
                elif this_type in {"list", "FlatList"}:
                    np = listwrap(nested_path)
                    newpath = unwraplist([join_field(split_field(np[0]) + [name])] + np)
                    _get_schema_from_list(
                        value, table_name, full_name, newpath, columns
                    )
279515
function topLevelItems(root) {
            var topLevel = [];
            function recur(item) {
                if (isTopLevel(item)) {
                    topLevel.push(item);
                    if (item.children) {
                        for (var _i = 0, _a = item.children; _i < _a.length; _i++) {
                            var child = _a[_i];
                            recur(child);
                        }
                    }
                }
            }
            recur(root);
            return topLevel;
            function isTopLevel(item) {
                switch (navigationBarNodeKind(item)) {
                    case 221 /* ClassDeclaration */:
                    case 192 /* ClassExpression */:
                    case 224 /* EnumDeclaration */:
                    case 222 /* InterfaceDeclaration */:
                    case 225 /* ModuleDeclaration */:
                    case 256 /* SourceFile */:
                    case 223 /* TypeAliasDeclaration */:
                    case 279 /* JSDocTypedefTag */:
                        return true;
                    case 148 /* Constructor */:
                    case 147 /* MethodDeclaration */:
                    case 149 /* GetAccessor */:
                    case 150 /* SetAccessor */:
                        return hasSomeImportantChild(item);
                    case 180 /* ArrowFunction */:
                    case 220 /* FunctionDeclaration */:
                    case 179 /* FunctionExpression */:
                        return isTopLevelFunctionDeclaration(item);
                    default:
                        return false;
                }
                function isTopLevelFunctionDeclaration(item) {
                    if (!item.node.body) {
                        return false;
                    }
                    switch (navigationBarNodeKind(item.parent)) {
                        case 226 /* ModuleBlock */:
                        case 256 /* SourceFile */:
                        case 147 /* MethodDeclaration */:
                        case 148 /* Constructor */:
                            return true;
                        default:
                            return hasSomeImportantChild(item);
                    }
                }
                function hasSomeImportantChild(item) {
                    return ts.forEach(item.children, function (child) {
                        var childKind = navigationBarNodeKind(child);
                        return childKind !== 218 /* VariableDeclaration */ && childKind !== 169 /* BindingElement */;
                    });
                }
            }
        }
447679
def _to_ijv(ss, row_levels=(0, ), column_levels=(1, ), sort_labels=False):
    
    # index and column levels must be a partition of the index
    _check_is_partition([row_levels, column_levels], range(ss.index.nlevels))

    # from the SparseSeries: get the labels and data for non-null entries
    values = ss._data.internal_values()._valid_sp_values

    nonnull_labels = ss.dropna()

    def get_indexers(levels):
        """ Return sparse coords and dense labels for subset levels """

        # TODO: how to do this better? cleanly slice nonnull_labels given the
        # coord
        values_ilabels = [tuple(x[i] for i in levels)
                          for x in nonnull_labels.index]
        if len(levels) == 1:
            values_ilabels = [x[0] for x in values_ilabels]

        # # performance issues with groupby ###################################
        # TODO: these two lines can rejplace the code below but
        # groupby is too slow (in some cases at least)
        # labels_to_i = ss.groupby(level=levels, sort=sort_labels).first()
        # labels_to_i[:] = np.arange(labels_to_i.shape[0])

        def _get_label_to_i_dict(labels, sort_labels=False):
            """ Return OrderedDict of unique labels to number.
            Optionally sort by label.
            """
            labels = Index(lmap(tuple, labels)).unique().tolist()  # squish
            if sort_labels:
                labels = sorted(list(labels))
            d = OrderedDict((k, i) for i, k in enumerate(labels))
            return (d)

        def _get_index_subset_to_coord_dict(index, subset, sort_labels=False):
            ilabels = list(zip(*[index._get_level_values(i) for i in subset]))
            labels_to_i = _get_label_to_i_dict(ilabels,
                                               sort_labels=sort_labels)
            labels_to_i = Series(labels_to_i)
            if len(subset) > 1:
                labels_to_i.index = MultiIndex.from_tuples(labels_to_i.index)
                labels_to_i.index.names = [index.names[i] for i in subset]
            else:
                labels_to_i.index = Index(x[0] for x in labels_to_i.index)
                labels_to_i.index.name = index.names[subset[0]]

            labels_to_i.name = 'value'
            return (labels_to_i)

        labels_to_i = _get_index_subset_to_coord_dict(ss.index, levels,
                                                      sort_labels=sort_labels)
        # #####################################################################
        # #####################################################################

        i_coord = labels_to_i[values_ilabels].tolist()
        i_labels = labels_to_i.index.tolist()

        return i_coord, i_labels

    i_coord, i_labels = get_indexers(row_levels)
    j_coord, j_labels = get_indexers(column_levels)

    return values, i_coord, j_coord, i_labels, j_labels
746798
def store_nested(key, value)
      var = unnest(key).reverse.inject(value) do |memo,k|
              if k.is_a?(Symbol)
                {k => memo}
              else
                ar = []
                ar[k] = memo
                ar
              end
            end
      deep_merge! var
    end
507877
def from_parent_deeper(
        cls, parent_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
    ):
        

        if parent_id:
            limiting_clause = "res.parent_id = :parent_id"
        else:
            limiting_clause = "res.parent_id is null"
        tablename = cls.model.__table__.name
        raw_q = """
            WITH RECURSIVE subtree AS (
                    SELECT res.*, 1 AS depth, LPAD(res.ordering::CHARACTER VARYING, 7, '0') AS sorting,
                    res.resource_id::CHARACTER VARYING AS path
                    FROM {tablename} AS res WHERE {limiting_clause}
                  UNION ALL
                    SELECT res_u.*, depth+1 AS depth,
                    (st.sorting::CHARACTER VARYING || '/' || LPAD(res_u.ordering::CHARACTER VARYING, 7, '0') ) AS sorting,
                    (st.path::CHARACTER VARYING || '/' || res_u.resource_id::CHARACTER VARYING ) AS path
                    FROM {tablename} res_u, subtree st
                    WHERE res_u.parent_id = st.resource_id
            )
            SELECT * FROM subtree WHERE depth<=:depth ORDER BY sorting;
        """.format(
            tablename=tablename, limiting_clause=limiting_clause
        )  # noqa
        db_session = get_db_session(db_session)
        text_obj = sa.text(raw_q)
        query = db_session.query(cls.model, "depth", "sorting", "path")
        query = query.from_statement(text_obj)
        query = query.params(parent_id=parent_id, depth=limit_depth)
        return query
1147622
private void buildRuntimeTree() {
    updateRuntime();
    RuntimeInfo rootInfo = findRuntime();
    String rootPath = rootInfo.getHtmlFramePath();

    root = new RuntimeNode();
    root.setFrameName(rootPath);
    root.setRuntimeID(rootInfo.getRuntimeID());

    List<RuntimeInfo> runtimesInfos = Lists.newArrayList(runtimesList.values());
    runtimesInfos.remove(rootInfo);

    for (RuntimeInfo runtimeInfo : runtimesInfos) {
      // Only add frames which are beneath the root frame
      if (runtimeInfo.getHtmlFramePath().startsWith(rootPath)) {
        addNode(runtimeInfo, root);
      }
    }
  }
548083
def tabulate_body(
    obj,
    level_keys,
    v_level_indexes,
    h_level_indexes,
    v_level_sort_keys=None,
    h_level_sort_keys=None,
):
    
    v_key_sorted = make_sorter(v_level_sort_keys, v_level_indexes)
    h_key_sorted = make_sorter(h_level_sort_keys, h_level_indexes)

    h_level_keys = [level_keys[level] for level in h_level_indexes]
    v_level_keys = [level_keys[level] for level in v_level_indexes]

    h_key_tuples = h_key_sorted(product(*h_level_keys))
    v_key_tuples = v_key_sorted(product(*v_level_keys))

    h_size = len(h_key_tuples)
    v_size = len(v_key_tuples)

    table = [[MISSING for _ in range(h_size)] for _ in range(v_size)]

    for h_index, h_keys in enumerate(h_key_tuples):
        for v_index, v_keys in enumerate(v_key_tuples):
            key_path = [None] * len(level_keys)
            merge_into_by_index(key_path, h_level_indexes, h_keys)
            merge_into_by_index(key_path, v_level_indexes, v_keys)
            for v_level, v_key in zip(v_level_indexes, v_keys):
                key_path[v_level] = v_key

            item = obj
            for key in key_path:
                try:
                    item = item[key]
                except (IndexError, KeyError):
                    break
            else:  # no-break
                table[v_index][h_index] = item

    return table, v_key_tuples, h_key_tuples
776695
function splitNesting(value) {
    value = value.trim();
    var result = [];
    var accum = '';
    var depth = 0;
    for (var offset = 0; offset < value.length; offset++) {
        var c = value[offset];
        if (c === ',' && depth === 0) {
            result.push(accum);
            accum = '';
        }
        else {
            accum += c;
            if (c === '(') {
                depth++;
            }
            else if (c === ')') {
                depth--;
                if (depth === -1) {
                    throw new Error('unbalanced parenthsis');
                }
            }
        }
    }
    if (accum) {
        result.push(accum);
    }
    return result;
}
979334
function(context, args, stack) {
		var xpr = args[0],
			index = args[1],
			templ = args[2],
			val = xpr.__interpolable__ ? xpr.output(context) : xpr,
			rest = new Template(templ._queue.slice(index)),
			instance,
			obj = {
				val: val,
				rest: rest,
				stack: []
			};
		stack.push(obj);
		if (val)
			firstPass(rest, context, obj.stack);
		else if (xpr.__interpolable__)
			instance = xpr.subscribeTo(context, function(value) {
				if (value) {
					obj.val = value;
					instance.destroy();
					firstPass(rest, context, obj.stack);
				}
			});
	}