flatten a (semi) nest roles structure
773227
def _flatten(self, roles=None, groups=None):
        
        if roles is None:
            roles_in = copy.deepcopy(self.roles_raw)
        else:
            roles_in = roles
        for roleid in roles_in:
            role = roles_in[roleid]
            if groups is not None:
                role['backends_groups'] = self._merge_groups(
                    [role['backends_groups'], groups],
                    )
            if 'subroles' in role:
                self._flatten(
                    role['subroles'],
                    role['backends_groups'],
                    )
                del role['subroles']

            self.flatten[roleid] = role
711139
def flatten_group(group_to_flatten, root, recursive=True,
                  group_filter=lambda x: True, path_filter=lambda x: True,
                  path_conversions=CONVERSIONS,
                  group_search_xpath=SVG_GROUP_TAG):
    """"""

    if not any(group_to_flatten is descendant for descendant in root.iter()):
        warnings.warn('The requested group_to_flatten is not a '
                      'descendant of root')
        # We will shortcut here, because it is impossible for any paths
        # to be returned anyhow.
        return []

    # We create a set of the unique IDs of each element that we wish to
    # flatten, if those elements are groups. Any groups outside of this
    # set will be skipped while we flatten the paths.
    desired_groups = set()
    if recursive:
        for group in group_to_flatten.iter():
            desired_groups.add(id(group))
    else:
        desired_groups.add(id(group_to_flatten))

    def desired_group_filter(x):
        return (id(x) in desired_groups) and group_filter(x)

    return flatten_all_paths(root, desired_group_filter, path_filter,
                             path_conversions, group_search_xpath)
746069
function flatten (arr) {
  return arr.reduce(function (acc, curr) {
    return acc.concat(Array.isArray(curr) ? flatten(curr) : curr)
  }, [])
}
1351821
function flatten(source) {
  var output = {};

  function step(object, prev) {
    for (var key in object) {
      if (has.call(object, key)) {
        var value = object[key];
        var newKey = prev ? prev + ' ' + key : key;

        if (!is.array(value) && is.object(value)) {
          return step(value, newKey);
        }

        output[newKey] = value;
      }
    }
  }

  step(source);

  return output;
}
1213486
def flatten(lst):
    """"""
    def flatten_aux(item, accumulated):
        if type(item) != list:
            accumulated.append(item)
        else:
            for l in item:
                flatten_aux(l, accumulated)
    accumulated = []
    flatten_aux(lst,accumulated)
    return accumulated
1254184
def _flattenComponent(glyphSet, component):
    """"""

    glyph = glyphSet[component.baseGlyph]
    if not glyph.components:
        transformation = Transform(*component.transformation)
        return [(component.baseGlyph, transformation)]

    all_flattened_components = []
    for nested in glyph.components:
        flattened_components = _flattenComponent(glyphSet, nested)
        for i, (_, tr) in enumerate(flattened_components):
            tr = tr.transform(component.transformation)
            flattened_components[i] = (flattened_components[i][0], tr)
        all_flattened_components.extend(flattened_components)
    return all_flattened_components
1125210
function flattenIterNodes(nodes) {
  var result = [];
  for (var i = 0; i < nodes.length; ++i) {
    if (nodes[i]._node.ctorName === '_iter') {
      result.push.apply(result, flattenIterNodes(nodes[i].children));
    } else {
      result.push(nodes[i]);
    }
  }
  return result;
}
894336
function stringifyRole(role){
  if (typeof role == 'string')
    return role;

  if (!role)
    return '';

  return [
    role.role || '',
    role.roleId ? '(' + role.roleId + ')' : '',
    role.subrole ? '/' + role.subrole : ''
  ].join('');
}
1152888
def merge_nested_environment_dicts(env_dicts, env_name=None, env_root=None):
    """"""
    # If the provided dictionary is just a single "level" (no nested
    # environments), it applies to all environments
    if all(isinstance(val, (six.string_types, list))
           for (_key, val) in env_dicts.items()):
        return flatten_path_lists(env_dicts, env_root)

    if env_name is None:
        if env_dicts.get('*'):
            return flatten_path_lists(env_dicts.get('*'), env_root)
        raise AttributeError("Provided config key:val pairs %s aren't usable with no environment provided" % env_dicts)  # noqa pylint: disable=line-too-long

    if not env_dicts.get('*') and not env_dicts.get(env_name):
        raise AttributeError("Provided config key:val pairs %s aren't usable with environment %s" % (env_dicts, env_name))  # noqa pylint: disable=line-too-long

    combined_dicts = merge_dicts(env_dicts.get('*', {}),
                                 env_dicts.get(env_name, {}))
    return flatten_path_lists(combined_dicts, env_root)
581606
function unnest($columns) {
        const queue = [];
        let $node;

        // Push the root unordered list item into the queue.
        queue.push($columns.children());

        while (queue.length) {
            $node = queue.shift();

            $node.children(itemSelector).each(function (item, el) {
                const $this = $(this);
                const $child = $this.children(columnSelector),
                      $ancestor = $this.parent().parent();

                // Retain item hierarchy (because it is lost after flattening).
                if ($ancestor.length && $this.data(`${namespace}-ancestor`) == null) {
                    // Use addBack to reset all selection chains.
                    $(this).siblings().addBack().data(`${namespace}-ancestor`, $ancestor);
                }

                if ($child.length) {
                    queue.push($child);
                    $(this).data(`${namespace}-child`, $child).addClass(`${namespace}-parent`);
                }

                // Causes item siblings to have a flattened DOM lineage.
                $(this).parent(columnSelector).appendTo($columns).addClass(`${namespace}-column`);
            });
        }
    }
17874
function flattenNodeGenerator(node, parent, index, settings, stack) {
  const { itemsKey, idKey } = settings;

  return function flattenNode(list) {
    node = settings.initNode(node);
    node[idKey] = node[idKey] || settings.generateUniqueId();
    list.push(node);

    if (node[itemsKey]) {
      for (let i = 0, len = node[itemsKey].length; i < len; i++) {
        stack.push(
          flattenNodeGenerator(
            node[itemsKey][i],
            node,
            i,
            settings,
            stack
          )
        );
      }
    }

    if (parent && parent[itemsKey]) {
      // Records children' id
      parent[itemsKey][index] = node[idKey];
      node.parent = parent[idKey];
    }

    return list;
  };
}
464964
def flatten_dict(source, ancestors=None):
  """"""
  if not ancestors:
    ancestors = ()
  for key in source:
    if isinstance(source[key], dict):
      yield from flatten_dict(source[key], ancestors + (key, ))
    else:
      yield (ancestors + (key, ), source[key])
1192774
def _recursive_upsert(context, params, data):
    """"""
    children = params.get("children", {})
    nested_calls = []
    for child_params in children:
        key = child_params.get("key")
        child_data_list = ensure_list(data.pop(key))
        if isinstance(child_data_list, dict):
            child_data_list = [child_data_list]
        if not (isinstance(child_data_list, list) and
                all(isinstance(i, dict) for i in child_data_list)):
            context.log.warn(
                "Expecting a dict or a lost of dicts as children for key", key
            )
            continue
        if child_data_list:
            table_suffix = child_params.get("table_suffix", key)
            child_params["table"] = params.get("table") + "_" + table_suffix
            # copy some properties over from parent to child
            inherit = child_params.get("inherit", {})
            for child_data in child_data_list:
                for dest, src in inherit.items():
                    child_data[dest] = data.get(src)
                nested_calls.append((child_params, child_data))
    # Insert or update data
    _upsert(context, params, data)
    for child_params, child_data in nested_calls:
        _recursive_upsert(context, child_params, child_data)
1257565
def flatten_privileges (privileges, context = nil, flattened_privileges = Set.new)
      # TODO caching?
      raise AuthorizationUsageError, "No context given or inferable from object" unless context
      privileges.reject {|priv| flattened_privileges.include?(priv)}.each do |priv|
        flattened_privileges << priv
        flatten_privileges(rev_priv_hierarchy[[priv, nil]], context, flattened_privileges) if rev_priv_hierarchy[[priv, nil]]
        flatten_privileges(rev_priv_hierarchy[[priv, context]], context, flattened_privileges) if rev_priv_hierarchy[[priv, context]]
      end
      flattened_privileges.to_a
    end
1011902
def flatten(self):
        
        d = self.as_dict()
        del d['leader']
        return [s for s in [v.strip() for v in flatten(d)] if s]
609897
function flatten(srcArr, isDeep) {
      var tmpArr = [];
      forEach(srcArr, function (val) {
        if (isArr(val)) {
          tmpArr.push.apply(tmpArr, isDeep ? flatten(val, true) : val);
        } else {
          tmpArr.push(val);
        }
      });
      return tmpArr;
    }
1125851
function flatten(source, opts) {
  opts = opts || {};
  var delimiter = opts.delimiter = opts.delimiter || '.';
  var o = {};
  function iterate(source, parts) {
    var k, v;
    parts = parts || [];
    for(k in source) {
      v = source[k];
      if(v && typeof v === 'object' && Object.keys(v).length) {
        iterate(v, parts.concat(k));
      }else{
        o[parts.concat(k).join(delimiter)] = v;
      }
    }
  }
  iterate(source);
  return o;
}