Apply a function recursively to each element of a nested data struct.
347847
def map_nested(function, data_struct, dict_only=False, map_tuple=False):
  """"""

  # Could add support for more exotic data_struct, like OrderedDict
  if isinstance(data_struct, dict):
    return {
        k: map_nested(function, v, dict_only, map_tuple)
        for k, v in data_struct.items()
    }
  elif not dict_only:
    types = [list]
    if map_tuple:
      types.append(tuple)
    if isinstance(data_struct, tuple(types)):
      mapped = [map_nested(function, v, dict_only, map_tuple)
                for v in data_struct]
      if isinstance(data_struct, list):
        return mapped
      else:
        return tuple(mapped)
  # Singleton
  return function(data_struct)
1006104
def flatten(struct):
    
    if struct is None:
        return []
    flat = []
    if isinstance(struct, dict):
        for key, result in struct.items():
            flat += flatten(result)
        return flat

    if isinstance(struct, basestring):
        return [struct]

    try:
        # if iterable
        for result in struct:
            flat += flatten(result)
        return flat
    except TypeError:
        pass

    return [struct]
491687
function recursive (node, depth, index) {
    let hashLeft
    let hashRight
    let summingBuffer

    // case with single node in tree
    if (depth === 0 && node.val !== undefined) {
      return getHash(node.val, depth, index * 2)
    }

    if (node.left === undefined) {
      throw new Error('Left node is missed.')
    }
    if (typeof node.left === 'string') {
      if (!validateHexadecimal(node.left)) {
        throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.')
      }
      hashLeft = node.left
    } else {
      if (!isObject(node.left)) {
        throw new TypeError('Invalid type of left node.')
      }
      if (node.left.val !== undefined) {
        hashLeft = getHash(node.left.val, depth, index * 2)
      } else {
        hashLeft = recursive(node.left, depth + 1, index * 2)
      }
    }

    if (depth === 0) {
      rootBranch = 'right'
    }

    if (node.right !== undefined) {
      if (typeof node.right === 'string') {
        if (!validateHexadecimal(node.right)) {
          throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.')
        }
        hashRight = node.right
      } else {
        if (!isObject(node.right)) {
          throw new TypeError('Invalid type of right node.')
        }

        if (node.right.val !== undefined) {
          hashRight = getHash(node.right.val, depth, index * 2 + 1)
        } else {
          hashRight = recursive(node.right, depth + 1, index * 2 + 1)
        }
      }

      summingBuffer = new Uint8Array(64)
      summingBuffer.set(hexadecimalToUint8Array(hashLeft))
      summingBuffer.set(hexadecimalToUint8Array(hashRight), 32)
      return hash(summingBuffer)
    }

    if (depth === 0 || rootBranch === 'left') {
      throw new Error('Right leaf is missed in left branch of tree.')
    }
    summingBuffer = hexadecimalToUint8Array(hashLeft)
    return hash(summingBuffer)
  }
527530
function( elems, callback, arg ) {
		var length, value,
			i = 0,
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArrayLike( elems ) ) {
			length = elems.length;
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}
		}

		// Flatten any nested arrays
		return concat.apply( [], ret );
	}
918850
function(recursive, callback) {
		var i, l, node,
			dict = {},
			self = this;

		$.each(NODE_ATTRS, function(i, a){
			if(self[a] || self[a] === false){
				dict[a] = self[a];
			}
		});
		if(!$.isEmptyObject(this.data)){
			dict.data = $.extend({}, this.data);
			if($.isEmptyObject(dict.data)){
				delete dict.data;
			}
		}
		if( callback ){
			callback(dict);
		}
		if( recursive ) {
			if(this.hasChildren()){
				dict.children = [];
				for(i=0, l=this.children.length; i<l; i++ ){
					node = this.children[i];
					if( !node.isStatusNode() ){
						dict.children.push(node.toDict(true, callback));
					}
				}
			}else{
//                dict.children = null;
			}
		}
		return dict;
	}
1358962
private static void recursiveSetSrid(Geometry geometry, int srid) {
		if (geometry != null) {
			geometry.setSrid(srid);
		}
		if (geometry.getGeometries() != null) {
			for (Geometry childGeometry : geometry.getGeometries()) {
				recursiveSetSrid(childGeometry, srid);
			}
		}
	}
483750
function nestedApply(obj, path, fun) {
	if (path.length === 0) {
		const _ret = fun(obj);
		return {
			ret: _ret,
			newObj: obj
		};
	}
	// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
	let newObj = obj;
	const last = path.pop();
	for (const elem of path) {
		if (!newObj[elem])
			newObj[elem] = {};
		newObj = newObj[elem];
	}
	const ret = fun(newObj[last]);
	return {
		ret,
		newObj
	};
}
1188164
function() {
			var parent = this.parent;
			var ix = parent.children.indexOf(this);
			var items = utils.flatten(arguments);
			spliceFn.apply(parent.children, [ix, 1].concat(items));
			
			// update parent
			items.forEach(function(item) {
				item.parent = parent;
			});
		}
504735
function( elems, callback, arg ) {
		var value,
			i = 0,
			length = elems.length,
			isArray = isArraylike( elems ),
			ret = [];

		// Go through the array, translating each of the items to their
		if ( isArray ) {
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}
		}

		// Flatten any nested arrays
		return core_concat.apply( [], ret );
	}
1248813
def flatten(d, sep='.'):
    """"""

    def _flatten(e, parent_key='', sep='.'):
        import collections

        prefix = parent_key + sep if parent_key else ''

        if isinstance(e, collections.MutableMapping):
            return tuple((prefix + k2, v2) for k, v in e.items() for k2, v2 in _flatten(v, k, sep))
        elif isinstance(e, collections.MutableSequence):
            return tuple((prefix + k2, v2) for i, v in enumerate(e) for k2, v2 in _flatten(v, str(i), sep))
        else:
            return (parent_key, (e,)),

    return tuple((k, v[0]) for k, v in _flatten(d, '', sep))
944423
function _mapDataValue(data, nestedSchema) {
    if (typeof nestedSchema === 'function') {
        return nestedSchema.apply(data);
    } else if (typeof nestedSchema === 'object') {
        return _map(data, nestedSchema);
    } else {
        return _getDataValue(data, nestedSchema);
    }
}
392475
def mutapply(self, function, fieldname):
        
        self[fieldname] = self.apply(function, fieldname)
86677
def _nested_add(nested_a, nested_b):
  """"""
  return nest.map(lambda a, b: a + b, nested_a, nested_b)
745074
def data_structure_builder(func):
    
    @wraps(func)
    def ds_builder_wrapper(function, *args, **kwargs):
        try:
            function = DSBuilder(function)
        except NoBuilder:
            pass
        return func(function, *args, **kwargs)

    return ds_builder_wrapper
1282637
def flatten(d, parent_key='', sep='__'):
    
    # http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys
    if type(d) == list:
        flat = []
        for entry in d:
            flat.append(flatten(entry, parent_key=parent_key, sep=sep))
        return flat
    else:
        items = []
        for k, v in d.items():
            new_key = parent_key + sep + k if parent_key else k

            if isinstance(v, collectionsAbc.MutableMapping):
                items.extend(flatten(v, new_key, sep=sep).items())
            else:
                items.append((new_key, v))


        return dict(items)
1130794
def _update_nested(key, val, data, allow_overwriting=False):
    
    if isinstance(val, dict):
        for sub_key, sub_val in val.items():
            data = _update_nested(key + [sub_key], sub_val, data, allow_overwriting=allow_overwriting)
    else:
        already_there = tz.get_in(key, data) is not None
        if already_there and val:
            if not allow_overwriting:
                raise ValueError("Duplicated key %s: %s and %s" % (key, val, tz.get_in(key, data)))
            else:
                already_there = False
        if val or not already_there:
            data = tz.update_in(data, key, lambda x: val)
    return data
651586
function _apply (mat, dim, callback) {
  let i, ret, tran

  if (dim <= 0) {
    if (!Array.isArray(mat[0])) {
      return callback(mat)
    } else {
      tran = _switch(mat)
      ret = []
      for (i = 0; i < tran.length; i++) {
        ret[i] = _apply(tran[i], dim - 1, callback)
      }
      return ret
    }
  } else {
    ret = []
    for (i = 0; i < mat.length; i++) {
      ret[i] = _apply(mat[i], dim - 1, callback)
    }
    return ret
  }
}