Write all translations to cache
3908
public function write()
    {
        foreach (config('squanto.locales', []) as $locale) {
            $this->writeLocale($locale, Line::getValuesByLocale($locale));
        }

        return $this;
    }
489506
def _write_ndarrays_cache_to_disk(self):
        """"""
        for h5loc, arrs in self._ndarrays_cache.items():
            title = arrs[0].title
            chunkshape = (self.chunksize,) + arrs[0].shape[1:] if self.chunksize is not\
                                                           None else None

            arr = NDArray(np.concatenate(arrs), h5loc=h5loc, title=title)

            if h5loc not in self._ndarrays:
                loc, tabname = os.path.split(h5loc)
                ndarr = self.h5file.create_earray(
                    loc,
                    tabname,
                    tb.Atom.from_dtype(arr.dtype),
                    (0, ) + arr.shape[1:],
                    chunkshape=chunkshape,
                    title=title,
                    filters=self.filters,
                    createparents=True,
                )
                self._ndarrays[h5loc] = ndarr
            else:
                ndarr = self._ndarrays[h5loc]

            idx_table_h5loc = h5loc + '_indices'
            if idx_table_h5loc not in self.indices:
                self.indices[idx_table_h5loc] = HDF5IndexTable(idx_table_h5loc)
            idx_tab = self.indices[idx_table_h5loc]

            for arr_length in (len(a) for a in arrs):
                idx_tab.append(arr_length)

            ndarr.append(arr)

        self._ndarrays_cache = defaultdict(list)
575429
def tr8n_translations_cache_tag(opts = {})
      html = []

      opts[:translations_element_id] ||= :tr8n_translations
      client_sdk_var_name = opts[:client_var_name] || :tr8nProxy

      default_source_url = "#{controller.controller_name}/#{controller.action_name}.js"
      source = Tr8n::TranslationSource.find_or_create(opts[:source] || default_source_url)

      if Tr8n::Config.enable_browser_cache?  
        # translations are loaded through a script
        js_source = "/tr8n/api/language/translate.js?cache=true&callback=Tr8n.SDK.Proxy.registerTranslationKeys&source=#{CGI.escape(source.source)}&t=#{source.updated_at.to_i}"
        html << "<script type='text/javascript' src='#{js_source}'></script>"
      else  
        # translations are embedded right into the page
        html << "<script>"

        keys = Tr8n::TranslationKey.where(["(id in (select distinct(translation_key_id) from tr8n_translation_key_sources where translation_source_id = ?))", source.id])
        translations = []
        keys.each_with_index do |tkey, index|
          trn = tkey.translate(Tr8n::Config.current_language, {}, {:api => true})
          translations << trn 
        end

        html << "Tr8n.SDK.Proxy.registerTranslationKeys(#{translations.to_json});"
        html << "</script>"
      end
        
      html.join('').html_safe
    end
1220268
def _write_to_cache(self, expr, res):
        """"""
        res = dedent(res)
        super()._write_to_cache(expr, res)
326717
def save_translations(self, instances):
        
        if not isinstance(instances, (list, tuple)):
            instances = [instances]

        for instance in instances:

            translations = []

            for obj in instance._linguist.translation_instances:
                if obj.field_name:
                    obj.object_id = instance.pk
                    if (obj.is_new and obj.field_value) or (
                        obj.has_changed and not obj.is_new
                    ):
                        field = instance.get_field_object(obj.field_name, obj.language)
                        if hasattr(field, "pre_save") and callable(field.pre_save):
                            obj.field_value = field.pre_save(instance, True)

                    translations.append(obj)

            to_create = [
                (obj, self.model(**obj.attrs))
                for obj in translations
                if obj.is_new and obj.field_value
            ]
            to_update = [
                obj for obj in translations if obj.has_changed and not obj.is_new
            ]
            to_delete = [obj for obj in translations if obj.deleted]

            created = True

            if to_create:
                objects = [obj for cached, obj in to_create]
                try:
                    with transaction.atomic():
                        self.bulk_create(objects)
                except IntegrityError:
                    created = False

            if to_update:
                for obj in to_update:
                    self.filter(**obj.lookup).update(field_value=obj.field_value)
                    obj.has_changed = False

            if created:
                for cached, obj in to_create:
                    cached.is_new = False
                    cached.has_changed = False

            if to_delete:
                for obj in to_delete:
                    self.filter(**obj.lookup).delete()
                    obj.has_changed = False
704273
def _read_cache(self):
        """"""
        if os.path.exists(self.filepath):
            with open(self.filepath, 'rt', encoding='utf8') as fh:
                lines = [x.strip() for x in fh]
        else:
            logger.debug("Index not found, starting empty")
            lines = []
        return lines
710607
def memoize(f):
    """"""
    # Determine the location of the cache.
    cache_dirname = os.path.join(_get_xdg_cache_home(), 'proselint')
    legacy_cache_dirname = os.path.join(os.path.expanduser("~"), ".proselint")

    if not os.path.isdir(cache_dirname):
        # Migrate the cache from the legacy path to XDG complaint location.
        if os.path.isdir(legacy_cache_dirname):
            os.rename(legacy_cache_dirname, cache_dirname)
        # Create the cache if it does not already exist.
        else:
            os.makedirs(cache_dirname)

    cache_filename = f.__module__ + "." + f.__name__
    cachepath = os.path.join(cache_dirname, cache_filename)

    @functools.wraps(f)
    def wrapped(*args, **kwargs):

        # handle instance methods
        if hasattr(f, '__self__'):
            args = args[1:]

        signature = (f.__module__ + '.' + f.__name__).encode("utf-8")

        tempargdict = inspect.getcallargs(f, *args, **kwargs)

        for item in list(tempargdict.items()):
            signature += item[1].encode("utf-8")

        key = hashlib.sha256(signature).hexdigest()

        try:
            cache = _get_cache(cachepath)
            return cache[key]
        except KeyError:
            value = f(*args, **kwargs)
            cache[key] = value
            cache.sync()
            return value
        except TypeError:
            call_to = f.__module__ + '.' + f.__name__
            print('Warning: could not disk cache call to %s;'
                  'it probably has unhashable args. Error: %s' %
                  (call_to, traceback.format_exc()))
            return f(*args, **kwargs)

    return wrapped
173620
def _cache_translation(translation, timeout=cache.default_timeout):
    
    if not appsettings.PARLER_ENABLE_CACHING:
        return

    if translation.master_id is None:
        raise ValueError("Can't cache unsaved translation")

    # Cache a translation object.
    # For internal usage, object parameters are not suited for outside usage.
    fields = translation.get_translated_fields()
    values = {'id': translation.id}
    for name in fields:
        values[name] = getattr(translation, name)

    key = get_translation_cache_key(translation.__class__, translation.master_id, translation.language_code)
    cache.set(key, values, timeout=timeout)
1059592
def prefetch_translations(instances, **kwargs):
    
    from .mixins import ModelMixin

    if not isinstance(instances, collections.Iterable):
        instances = [instances]

    populate_missing = kwargs.get("populate_missing", True)
    grouped_translations = utils.get_grouped_translations(instances, **kwargs)

    # In the case of no translations objects
    if not grouped_translations and populate_missing:
        for instance in instances:
            instance.populate_missing_translations()

    for instance in instances:
        if (
            issubclass(instance.__class__, ModelMixin)
            and instance.pk in grouped_translations
        ):
            for translation in grouped_translations[instance.pk]:
                instance._linguist.set_cache(instance=instance, translation=translation)
            if populate_missing:
                instance.populate_missing_translations()
594001
def set_cache(
        self,
        instance=None,
        translation=None,
        language=None,
        field_name=None,
        field_value=None,
    ):
        
        if instance is not None and translation is not None:
            cached_obj = CachedTranslation.from_object(translation)
            instance._linguist_translations[translation.field_name][
                translation.language
            ] = cached_obj
            return cached_obj

        if instance is None:
            instance = self.instance

        cached_obj = self.get_cache(
            instance,
            translation=translation,
            field_value=field_value,
            language=language,
            field_name=field_name,
        )

        if field_value is None and cached_obj.field_value:
            cached_obj.deleted = True

        if field_value != cached_obj.field_value:
            cached_obj.has_changed = True
            cached_obj.field_value = field_value

        return cached_obj
1294935
public function registerCacheFlusher()
    {
        $command = new TranslationsCacheFlushCommand( $this->app['translation.cache.repository'], true );

        $this->app['command.translator:flush'] = $command;
        $this->commands( 'command.translator:flush' );
    }
295525
def lazy_translations(cls):
        """"""
        return {
            cloudfiles.errors.NoSuchContainer: errors.NoContainerException,
            cloudfiles.errors.NoSuchObject: errors.NoObjectException,
        }
1139577
def save_output_in_cache(name, filename, output):
    
    cache_filename = _get_cache_filename(name, filename)
    with _open_for_write(cache_filename) as f:
        f.write(output)
439373
def cache_script(script, text, opts={}):
    """"""
    global script_cache
    if script not in script_cache:
        update_script_cache(script, text, opts)
        pass
    return script
72186
def write_cache(cache, opts):
    '''
    
    '''
    cache_file = get_cache(opts)

    try:
        _cache = salt.utils.stringutils.to_bytes(
            salt.utils.yaml.safe_dump(cache)
        )
        with salt.utils.files.fopen(cache_file, 'wb+') as fp_:
            fp_.write(_cache)
        return True
    except (IOError, OSError):
        log.error('Failed to cache mounts',
                  exc_info_on_loglevel=logging.DEBUG)
        return False
1346468
def add_to_hash(all_translations, lang)
      levels = self.name.split('.')
      add_to_hash_rec(all_translations, levels, lang.to_s)
    end
167976
def _write_index_file(data_dir):
    
    cached_words = [
        w
        for w in _get_words(data_dir)
        if data_dir.joinpath("translations/{}.html".format(w)).is_file()
    ]

    content_str = _create_index_content(cached_words)
    html_string = HTML_TEMPLATE.replace("{% word %}", "Index")
    html_string = html_string.replace("{% content %}", content_str)

    filename = data_dir.joinpath("index.html")
    save_file(filename, html_string, mk_parents=True)