Traverse a dictionary recursively and save path

        Taken from:
  http://code.activestate.com/recipes/577982-recursively-walk-python-objects/
554107
def objwalk(self, obj, path=(), memo=None):
        

        # dual python 2/3 compatability, inspired by the "six" library
        string_types = (str, unicode) if str is bytes else (str, bytes)
        iteritems = lambda mapping: getattr(mapping, 'iteritems', mapping.items)()

        if memo is None:
            memo = set()
        iterator = None
        if isinstance(obj, Mapping):
            iterator = iteritems
        elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types):
            iterator = enumerate
        if iterator:
            if id(obj) not in memo:
                memo.add(id(obj))
                for path_component, value in iterator(obj):
                    for result in self.objwalk(value, path + (path_component,), memo):
                        yield result
                memo.remove(id(obj))
        else:
            yield path, obj
472875
def get_path(self, key):
        ""
        if key in self.keys():
            return (key,), self[key]
        else:
            key_path, res = (None, None)
            for sub_key, v in self.items():
                if isinstance(v, self.__class__):
                    key_path, res = v.get_path(key)
                elif hasattr(v, 'get'):
                    res = v.get(key)
                    key_path = (key,) if res is not None else None
                if res is not None and key_path is not None:
                    key_path = (sub_key,) + key_path
                    break
            return key_path, res
760325
def walk_tree(start, attr):
    
    path = [start]
    for child in path:
        yield child
        idx = path.index(child)
        for grandchild in reversed(getattr(child, attr)):
            path.insert(idx + 1, grandchild)
176467
def _walk_to_root(path):
    
    if not os.path.exists(path):
        raise IOError('Starting path not found')

    if os.path.isfile(path):
        path = os.path.dirname(path)

    last_dir = None
    current_dir = os.path.abspath(path)
    while last_dir != current_dir:
        yield current_dir
        parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
        last_dir, current_dir = current_dir, parent_dir
1301439
function traverse(object, visitor) {
        var child;

        if (!object) {
            return;
        }

        if (visitor.call(null, object) === false) {
            return false;
        }
        for (var i = 0, keys = Object.keys(object); i < keys.length; i++) {
            child = object[keys[i]];
            if (typeof child === 'object' && child !== null) {
                if (traverse(child, visitor) === false) {
                    return false;
                }
            }
        }
    }
1192839
function traverse (root, dirs, collect, next) {
  const rootPath = path.join (root, ...dirs);
  fs.lstat (rootPath, (err0) => {
    if (err0) {
      next (err0);
    } else {
      fs.readdir (rootPath, (_, files) => {
        let pending = files.length;
        for (let file of files) {
          const filePath = path.join (root, ...dirs, file);
          fs.lstat (filePath, (err1, stats) => {
            if (err1) {
              next (err1);
            } else {
              if (stats.isDirectory ()) {
                traverse (root, [...dirs, file], collect, err2 => {
                  if (err2) {
                    next (err2);
                  } else {
                    if (--pending === 0) {
                      next ();
                    }
                  }
                });
              } else {
                if (stats.isFile ()) {
                  collect (dirs, file, files);
                  if (--pending === 0) {
                    next ();
                  }
                }
              }
            }
          });
        }
      });
    }
  });
}
1241945
def import_recursive(path):
    
    results = {}
    obj = importlib.import_module(path)
    results[path] = obj
    path = getattr(obj, '__path__', os.path.dirname(obj.__file__))
    for loader, name, is_pkg in pkgutil.walk_packages(path):
        full_name = obj.__name__ + '.' + name
        results[full_name] = importlib.import_module(full_name)
        if is_pkg:
            results.update(import_recursive(full_name))
    return results
1341984
def traverse(self, traverseroot, function, cookie=0):
        
        if self.tree.ItemHasChildren(traverseroot):
            firstchild, cookie = self.tree.GetFirstChild(traverseroot)
            function(firstchild)
            self.traverse(firstchild, function, cookie)

        child = self.tree.GetNextSibling(traverseroot)
        if child:
            function(child)
            self.traverse(child, function, cookie)
1103103
function nestedPath (obj, path, val) {
  if (typeof obj !== 'object') {
    return obj
  }
  var keys = path.split('.')
  if (keys.length > 1) {
    path = keys.shift()
    return nestedPath(obj[path], keys.join('.'), val)
  }
  if (val !== undefined) {
    obj[path] = val
  }
  return obj[path]
}
405847
def recursive_asdict(d):
    """"""
    out = {}
    for k, v in asdict(d).iteritems():
        if hasattr(v, '__keylist__'):
            out[k] = recursive_asdict(v)
        elif isinstance(v, list):
            out[k] = []
            for item in v:
                if hasattr(item, '__keylist__'):
                    out[k].append(recursive_asdict(item))
                else:
                    out[k].append(item)
        else:
            out[k] = v
    return out
558313
def traverse_tree(cls, static_dir):
        """"""
        for root, dirs, files in os.walk(static_dir):
            for filename in files:
                if cls._pattern.match(filename):
                    APPS_INCLUDE_DIRS.append(static_dir)
                    return
77056
def _walk(self, path_to_root, record_dict):

        '''
            
        '''

    # split path to root into segments
        item_pattern = re.compile('\d+\\]')
        dot_pattern = re.compile('\\.|\\[')
        path_segments = dot_pattern.split(path_to_root)

    # construct empty fields
        record_endpoints = []

    # determine starting position
        if not path_segments[0]:
            path_segments.pop(0)
        
    # define internal recursive function
        def _walk_int(path_segments, record_dict):
            record_endpoint = record_dict
            for i in range(0, len(path_segments)):
                if item_pattern.match(path_segments[i]):
                    for j in range(0, len(record_endpoint)):
                        if len(path_segments) == 2:
                            record_endpoints.append(record_endpoint[j])
                        else:
                            stop_chain = False
                            for x in range(0, i):
                                if item_pattern.match(path_segments[x]):
                                    stop_chain = True
                            if not stop_chain:
                                shortened_segments = []
                                for z in range(i + 1, len(path_segments)):
                                    shortened_segments.append(path_segments[z])
                                _walk_int(shortened_segments, record_endpoint[j])
                else:
                    stop_chain = False
                    for y in range(0, i):
                        if item_pattern.match(path_segments[y]):
                            stop_chain = True
                    if not stop_chain:
                        if len(path_segments) == i + 1:
                            record_endpoints.append(record_endpoint[path_segments[i]])
                        else:
                            record_endpoint = record_endpoint[path_segments[i]]

    # conduct recursive walk
        _walk_int(path_segments, record_dict)

        return record_endpoints
633207
def _make_path(self, items):
        '''
        '''
        for key, val in items.items():
            if not isinstance(val, basestring):
                raise TypeError, ('Value "%s" for key "%s" must be an instance'
                                  ' of basestring' % (val, key))
            items[key] = quote_plus(val)

        try:
            path = self._url_format.format(**items)
        except AttributeError:
            # Old version of python
            path = self._url_format
            for key, val in items.items():
                path = path.replace('{%s}' % key, val)
        return path
1260521
def _traverse_results(value, fields, row, path):
    
    for f, v in value.iteritems():  # for each item in obj
        field_name = '{path}.{name}'.format(path=path, name=f) if path else f

        if not isinstance(v, (dict, list, tuple)):  # if not data structure
            if field_name in fields:
                row[fields.index(field_name)] = ensure_utf(v)

        elif isinstance(v, dict) and f != 'attributes':  # it is a dict
            _traverse_results(v, fields, row, field_name)
288304
def traverse(sexp, visitor, context=Visitor::Context.new)
      element_name, attrs, children = decompose_sexp(sexp)
      
      non_ns_attrs, ns_bindings = Namespace::non_ns_attrs_ns_bindings(context.ns_stack, element_name, attrs)

      context.ns_stack.push(ns_bindings)

      eelement_name = Namespace::explode_qname(context.ns_stack, element_name)
      eattrs = Namespace::explode_attr_qnames(context.ns_stack, non_ns_attrs)

      begin
        visitor.element(context, eelement_name, eattrs, ns_bindings) do
          children.each_with_index do |child, i|
            if child.is_a?(Array)
              traverse(child, visitor, context)
            else
              visitor.text(context, child)
            end
          end
        end
      ensure
        context.ns_stack.pop
      end

      visitor
    end
1241830
def __recur_to_dict(forlist, data_dict, res):
        
        # First we go through all attrs from the ForList and add respective
        #  keys on the dict.
        for a in forlist.attrs:
            a_list = a.split('.')
            if len(a_list) == 1:
                res = data_dict[a_list[0]]
                return res
            if a_list[0] in data_dict:
                tmp = res
                for i in a_list[1:-1]:
                    if not i in tmp:
                        tmp[i] = {}
                    tmp = tmp[i]
                if len(a_list) == 1:
                    tmp[a_list[0]] = data_dict[a_list[0]]
                else:
                    tmp[a_list[-1]] = reduce(
                        getattr,
                        a_list[1:],
                        data_dict[a_list[0]]
                    )
        # Then create a list for all children,
        # modify the datadict to fit the new child
        # and call myself
        for c in forlist.childs:
            it = c.name.split('.')
            res[it[-1]] = []
            for i, val in enumerate(
                    reduce(getattr, it[1:], data_dict[it[0]])
            ):
                new_data_dict = {c.var_from: val}
                if len(res[it[-1]]) <= i:
                    res[it[-1]].append({})
                res[it[-1]] = ForList.__recur_to_dict(
                    c, new_data_dict, res[it[-1]][i]
                )

        return res
1340226
function(obj, objDict) {
	    var parent = objDict[ obj.parentPath ];
	    if (parent) {
		if (parent.Substates == undefined)
		    parent.Substates = [];
		parent.Substates.push( obj );
	    }
	}