Recursive method for folding references
766204
def fold_references_helper(entity, array_of_refs, organization)
      ref = array_of_refs.shift
      field = entity[ref]
      return if field.blank?

      # Follow embedment path, remplace if it's not an array or a hash
      case field
      when Array
        field.each do |f|
          fold_references_helper(f, array_of_refs.dup, organization)
        end
      when Hash
        fold_references_helper(entity[ref], array_of_refs, organization)
      else
        id = field
        entity[ref] = [id_hash(id, organization)]
      end
    end
987801
function recursiveMapping(source) {
			if (source.type === 'array') {
				if (source.items['$ref'] || source.items.type === 'object') {
					source.items = mapSimpleField(source.items);
				}
				else if (source.items.type === 'object') {
					recursiveMapping(source.items);
				}
				else mapSimpleField(source);
			}
			else if (source.type === 'object') {
				for (var property in source.properties) {
					if (source.properties[property]['$ref']) {
						source.properties[property] = mapSimpleField(source.properties[property]);
					}
					else if (source.properties[property].type === 'object' || source.properties[property].type === 'array') {
						recursiveMapping(source.properties[property]);
					}
				}
			}
			else if (source.schema) {
				if (source.schema.type === 'object') {
					for (var property in source.schema.properties) {
						if (source.schema.properties[property]['$ref']) {
							source.schema.properties[property] = mapSimpleField(source.schema.properties[property]);
						}
					}
				}
			}
			else {
				//map simple inputs if any
				source = mapSimpleField(source);
			}
		}
1240868
def parent(self) -> Optional['CtsReference']:
        
        if self.start.depth == 1 and (self.end is None or self.end.depth <= 1):
            return None
        else:
            if self.start.depth > 1 and (self.end is None or self.end.depth == 0):
                return CtsReference("{0}{1}".format(
                    ".".join(self.start.list[:-1]),
                    self.start.subreference or ""
                ))
            elif self.start.depth > 1 and self.end is not None and self.end.depth > 1:
                _start = self.start.list[0:-1]
                _end = self.end.list[0:-1]
                if _start == _end and \
                        self.start.subreference is None and \
                        self.end.subreference is None:
                    return CtsReference(
                        ".".join(_start)
                    )
                else:
                    return CtsReference("{0}{1}-{2}{3}".format(
                        ".".join(_start),
                        self.start.subreference or "",
                        ".".join(_end),
                        self.end.subreference or ""
                    ))
1060317
function foldR(fn, startValue, list) {
      
   return list 
            ? fn(foldR(fn, startValue, tail(list)), head(list))
            : startValue
            ;
}
1275124
def _compile_references(self, url, tree):
        '''
        
        '''
        references = []
        for ref in tree.findall('.//{%s}catalogRef' % INV_NS):
            # Check skips
            title = ref.get("{%s}title" % XLINK_NS)
            if any([x.match(title) for x in self.skip]):
                logger.info("Skipping catalogRef based on 'skips'.  Title: %s" % title)
                continue
            references.append(construct_url(url, ref.get("{%s}href" % XLINK_NS)))
        return references
74851
function lazyVisitChildren(len, children, i, f, k) {
    while (i < len) {
        var child = children[i++];
        if (child && !isEmptyNode(child)) return lazyVisit(child, f, [len, children, i, f, k]);
    }
    return appk(k);
}
493740
function foldLiterals(nodes) {
  return nodes.reduce(function(c, e) {
    if (e.type === 'Literal') {
      var last = c[c.length - 1];
      if (last && last.type === 'Literal') {
        c.pop();
        return c.concat(literal(last.value + e.value));
      }
    }
    return c.concat(e);
  }, [])
}
621908
function createCharacterIterator(startPos, backward, endPos, characterOptions) {
        log.info("createCharacterIterator called backwards " + backward + " and with endPos " + (endPos ? endPos.inspect() : ""));

        // Adjust the end position to ensure that it is actually reached
        if (endPos) {
            if (backward) {
                if (isCollapsedNode(endPos.node)) {
                    endPos = startPos.previousVisible();
                }
            } else {
                if (isCollapsedNode(endPos.node)) {
                    endPos = endPos.nextVisible();
                }
            }
        }
        log.info("endPos now " + (endPos ? endPos.inspect() : "") + ", startPos " + startPos.inspect());

        var pos = startPos, finished = false;

        function next() {
            log.debug("****** NEXT CALLED. FINISHED IS " + finished + ", pos is " + (pos ? pos.inspect() : "non-existent"));
            var charPos = null;
            if (backward) {
                charPos = pos;
                if (!finished) {
                    pos = pos.previousVisible();
                    finished = !pos || (endPos && pos.equals(endPos));
                }
            } else {
                if (!finished) {
                    charPos = pos = pos.nextVisible();
                    finished = !pos || (endPos && pos.equals(endPos));
                }
            }
            if (finished) {
                pos = null;
            }
            log.info("Finished: " + finished);
            return charPos;
        }

        var previousTextPos, returnPreviousTextPos = false;

        return {
            next: function() {
                if (returnPreviousTextPos) {
                    returnPreviousTextPos = false;
                    return previousTextPos;
                } else {
                    var pos, character;
                    while ( (pos = next()) ) {
                        character = pos.getCharacter(characterOptions);
                        if (character) {
                            previousTextPos = pos;
                            return pos;
                        }
                    }
                    return null;
                }
            },

            rewind: function() {
                if (previousTextPos) {
                    returnPreviousTextPos = true;
                } else {
                    throw module.createError("createCharacterIterator: cannot rewind. Only one position can be rewound.");
                }
            },

            dispose: function() {
                startPos = endPos = null;
            }
        };
    }
1230585
def _recursive_repr(item):
    
    if isinstance(item, basestring):
        result = str(item)
    elif isinstance(item, list):
        result = '[{}]'.format(', '.join([_recursive_repr(x) for x in item]))
    elif isinstance(item, dict):
        kv_pairs = ['{}: {}'.format(_recursive_repr(k), _recursive_repr(item[k])) for k in sorted(item)]
        result = '{' + ', '.join(kv_pairs) + '}'
    else:
        result = repr(item)
    return result
863952
def flatten_repetition(list, named)
      if list.any? { |e| e.instance_of?(Hash) }
        # If keyed subtrees are in the array, we'll want to discard all 
        # strings inbetween. To keep them, name them. 
        return list.select { |e| e.instance_of?(Hash) }
      end

      if list.any? { |e| e.instance_of?(Array) }
        # If any arrays are nested in this array, flatten all arrays to this
        # level. 
        return list.
          select { |e| e.instance_of?(Array) }.
          flatten(1)
      end

      # Consistent handling of empty lists, when we act on a named result        
      return [] if named && list.empty?

      # If there are only strings, concatenate them and return that. 
      foldl(list.compact) { |s,e| s+e }
    end
10776
function foldR1(fn, list) {
      
   return tail(list) 
            ? fn(foldR1(fn, tail(list)), head(list))
            : head(list)
            ;
}
142966
private Collection<TreeWitnessGenerator> getTreeWitnessGenerators(QueryFolding qf) {
		Collection<TreeWitnessGenerator> twg = null;
		log.debug("CHECKING WHETHER THE FOLDING {} CAN BE GENERATED: ", qf); 
		for (TreeWitnessGenerator g : allTWgenerators) {
			Intersection<ObjectPropertyExpression> subp = qf.getProperties();
			if (!subp.subsumes(g.getProperty())) {
				log.debug("      NEGATIVE PROPERTY CHECK {}", g.getProperty());
				continue;
			}
			else
				log.debug("      POSITIVE PROPERTY CHECK {}", g.getProperty());

			Intersection<ClassExpression> subc = qf.getInternalRootConcepts();
			if (!g.endPointEntailsAnyOf(subc)) {
				 log.debug("        ENDTYPE TOO SPECIFIC: {} FOR {}", subc, g);
				 continue;			
			}
			else
				 log.debug("        ENDTYPE IS FINE: TOP FOR {}", g);

			boolean failed = false;
			for (TreeWitness tw : qf.getInteriorTreeWitnesses()) 
				if (!g.endPointEntailsAnyOf(tw.getGeneratorSubConcepts())) { 
					log.debug("        ENDTYPE TOO SPECIFIC: {} FOR {}", tw, g);
					failed = true;
					break;
				} 
				else
					log.debug("        ENDTYPE IS FINE: {} FOR {}", tw, g);
				
			if (failed)
				continue;
			
			if (twg == null) 
				twg = new LinkedList<>();
			twg.add(g);
			log.debug("        OK");
		}
		return twg;
	}
528413
def _dereference(cls, documents, references):
        """"""

        # Dereference each reference
        for path, projection in references.items():

            # Check there is a $ref in the projection, else skip it
            if '$ref' not in projection:
                continue

            # Collect Ids of documents to dereference
            ids = set()
            for document in documents:
                value = cls._path_to_value(path, document)
                if not value:
                    continue

                if isinstance(value, list):
                    ids.update(value)

                elif isinstance(value, dict):
                    ids.update(value.values())

                else:
                    ids.add(value)

            # Find the referenced documents
            ref = projection.pop('$ref')
            frames = ref.many(
                {'_id': {'$in': list(ids)}},
                projection=projection
                )
            frames = {f._id: f for f in frames}

            # Add dereferenced frames to the document
            for document in documents:
                value = cls._path_to_value(path, document)
                if not value:
                    continue

                if isinstance(value, list):
                    # List of references
                    value = [frames[id] for id in value if id in frames]

                elif isinstance(value, dict):
                    # Dictionary of references
                    value = {key: frames.get(id) for key, id in value.items()}

                else:
                    value = frames.get(value, None)

                child_document = document
                keys = cls._path_to_keys(path)
                for key in keys[:-1]:
                    child_document = child_document[key]
                child_document[keys[-1]] = value
317068
private static List<Object> mergeReferenceValues(AttributeDefinition attrDef, Object... values) {
        List<Object> merged = new ArrayList<Object>();
        for (Object value : values) {
            if (value instanceof String) {
                merged.addAll(getAsList((String) value, attrDef));
            } else if (value instanceof List<?>) {
                for (Object ce : (List<?>) value) {
                    if (ce instanceof ConfigElement) {
                        // Get the ID for this ConfigElement. If it's specified, remove the ID from the merged list.
                        // This gets rid of ref attributes that point to a nested element
                        String id = (String) ((ConfigElement) ce).getAttribute("id");
                        if (id != null) {
                            merged.remove(id);
                        }
                        merged.add(ce);
                    } else if (ce instanceof ConfigElement.Reference) {
                        merged.add(ce);
                    } else if (ce instanceof String) {
                        if (!merged.contains(ce))
                            merged.add(ce);
                    }
                }

            }
        }

        return merged;
    }
312889
def _represent_fold(fold_location, fold_ir_blocks):
    """"""
    start_let_template = u'$%(mark_name)s = %(base_location)s'
    traverse_edge_template = u'.%(direction)s("%(edge_name)s")'
    base_template = start_let_template + traverse_edge_template
    edge_direction, edge_name = fold_location.get_first_folded_edge()
    mark_name, _ = fold_location.get_location_name()
    base_location_name, _ = fold_location.base_location.get_location_name()

    validate_safe_string(mark_name)
    validate_safe_string(base_location_name)
    validate_safe_string(edge_direction)
    validate_safe_string(edge_name)

    template_data = {
        'mark_name': mark_name,
        'base_location': base_location_name,
        'direction': edge_direction,
        'edge_name': edge_name,
    }
    final_string = base_template % template_data

    for block in fold_ir_blocks:
        if isinstance(block, Filter):
            final_string += u'[' + block.predicate.to_match() + u']'
        elif isinstance(block, Traverse):
            template_data = {
                'direction': block.direction,
                'edge_name': block.edge_name,
            }
            final_string += traverse_edge_template % template_data
        elif isinstance(block, MarkLocation):
            # MarkLocation blocks inside a fold do not result in any MATCH output.
            pass
        else:
            raise AssertionError(u'Found an unexpected IR block in the folded IR blocks: '
                                 u'{} {} {}'.format(type(block), block, fold_ir_blocks))

    # Workaround for OrientDB's inconsistent return type when filtering a list.
    # https://github.com/orientechnologies/orientdb/issues/7811
    final_string += '.asList()'

    return final_string
989057
def fold_enrichment(self):
        """"""
        return self.k / (self.K*(self.cutoff/float(self.N)))
194886
function fold(count, buf)
{
  if(!count || buf.length % 2) return buf;
  var ret = buf.slice(0,buf.length/2);
  for(i = 0; i < ret.length; i++) ret[i] = ret[i] ^ buf[i+ret.length];
  return fold(count-1,ret);
}