def apply_coreferences(document, coreferences):
    # For each token index make a list of the occurrences there
    occurrences = defaultdict(list)
    for occurrence in document.entity_occurrences.all():
        for i in range(occurrence.offset, occurrence.offset_end):
            occurrences[i].append(occurrence)

    entities = []  # Existing entities referenced by correferences
    pickable_as_representant = []
    missing = []  # References that have no entity occurrence yet
    for i, j, head in sorted(coreferences):
        if occurrences[head]:
            for x in occurrences[head]:
                entities.append(x.entity)
                if not x.anaphora:
                    pickable_as_representant.append(x.entity)
        else:
            missing.append((i, j, head))

    if not pickable_as_representant:
        return
    issues = issues_merging_entities(document, entities)
    if issues:
        raise CoreferenceError(issues)

    from_ner = [r for r in pickable_as_representant if not r.gazette]
    if from_ner:
        canonical = from_ner[0]
    else:
        canonical = pickable_as_representant[0]

    # Each missing coreference needs to be created into an occurrence now
    for i, j, head in missing:
        if j - i >= 5:  # If the entity is a long phrase then just keep one token
            i = head
            j = head + 1
        EntityOccurrence.objects.get_or_create(
            document=document,
            entity=canonical,
            offset=i,
            offset_end=j,
            alias=" ".join(document.tokens[i:j]),
            defaults={'anaphora': True})

    # Finally, the merging 'per se', where all things are entity occurrences
    for entity in set(x for x in entities if x != canonical):
        for occurrence in EntityOccurrence.objects.filter(entity=entity,
                                                          document=document):
            occurrence.entity = canonical
            occurrence.save()
Makes all entity ocurrences listed in `coreferences` have the same
dataset/ETHPy150Open machinalis/iepy/iepy/preprocess/stanford_preprocess.py/apply_coreferences