<commit_before>"""
Support for models' internal Translation class.
"""

## TO DO: this is messy and needs to be cleaned up

from django.db import models
from django.db.models.base import ModelBase
from django.dispatch.dispatcher import connect
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import signals
from languages import *
from manager import MultilingualModelManager
from exceptions import TranslationDoesNotExist

from django.contrib.admin.templatetags.admin_modify import StackedBoundRelatedObject

class TransBoundRelatedObject(StackedBoundRelatedObject):
    """
    This class changes the template for translation objects.
    """
    def template_name(self):
        return "admin/edit_inline_translations.html"

def translation_save_translated_fields(instance, **kwargs):
    """
    Save all the translations of instance in post_save signal handler.
    """
    instance.get_translation_set().all().delete()
    for translation in getattr(instance, '_translation_cache', {}).values():
        # set the translation ID just in case the translation was
        # created while instance was not stored in the DB yet
        translation.master_id = instance.id
        translation.save()

def fill_translation_cache(instance):
    """
    Fill the translation cache using information received in the
    instance objects as extra fields.

    You can not do this in post_init because the extra fields are
    assigned by QuerySet.iterator after model initialization.
    """

    if hasattr(instance, '_translation_cache'):
        # do not refill the cache
        return

    instance._translation_cache = {}
    for language_id in get_language_id_list():<commit_msg>Improved translation editor: it now correctly orders translations.  This fixes #4.<commit_after>"""
Support for models' internal Translation class.
"""

## TO DO: this is messy and needs to be cleaned up

from django.db import models
from django.db.models.base import ModelBase
from django.dispatch.dispatcher import connect
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import signals
from languages import *
from manager import MultilingualModelManager
from exceptions import TranslationDoesNotExist

from django.contrib.admin.templatetags.admin_modify import StackedBoundRelatedObject

class TransBoundRelatedObject(StackedBoundRelatedObject):
    """
    This class changes the template for translation objects.

    It also reorders the translation list to match the list of
    languages specified in settings file.
    """
    def __init__(self, related_object, field_mapping, original):
        super(TransBoundRelatedObject, self).__init__(related_object,
                                                      field_mapping,
                                                      original)

        # reorder field wrappers to match the ordering of languages
        # specified in settings

        # 1. find corresponding language for each mapping
        
        mappings_with_lang = {}
        mappings_without_lang = []
        for idx, mapping in self.field_mappings.items():
            if mapping['original']:
                mappings_with_lang[mapping['original'].language_id] = idx
            else:
                mappings_without_lang.append(idx)

        # 2. reorder the wrappers according to what you found in #1

        new_form_field_collection_wrappers = []
        ffcw = self.form_field_collection_wrappers
        for language_id in get_language_id_list():
            idx = mappings_with_lang.get(language_id, None)
            if idx is None:
                idx = mappings_without_lang.pop(0)
            new_form_field_collection_wrappers.append(ffcw[idx])
        self.form_field_collection_wrappers = new_form_field_collection_wrappers

    def template_name(self):
        return "admin/edit_inline_translations.html"

def translation_save_translated_fields(instance, **kwargs):
    """
    Save all the translations of instance in post_save signal handler.
    """
    instance.get_translation_set().all().delete()
    for translation in getattr(instance, '_translation_cache', {}).values():
        # set the translation ID just in case the translation was
        # created while instance was not stored in the DB yet
        translation.master_id = instance.id
        translation.save()

def fill_translation_cache(instance):
    """
    Fill the translation cache using information received in the
    instance objects as extra fields.

    You can not do this in post_init because the extra fields are
    assigned by QuerySet.iterator after model initialization.
    """

    if hasattr(instance, '_translation_cache'):
        # do not refill the cache
        return

    instance._translation_cache = {}
    for language_id in get_language_id_list():
{'fraction_non_alphanumeric': 0.06363636363636363, 'fraction_numerical': 0.0010330578512396695, 'mean_word_length': 3.224258289703316, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2616051', 'n_tokens_mistral': 1214, 'n_tokens_neox': 1180, 'n_words': 412}