<commit_before>from hb_res.storage import ExplanationStorage

__author__ = 'skird'

import codecs
from hb_res.explanations.Explanation import Explanation


class FileExplanationStorage(ExplanationStorage):
    """
    Class representing explanation resource connected with some text file
    """

    def __init__(self, path_to_file):
        self.file_name = path_to_file
        self.descriptor = codecs.open(self.file_name, mode='a', encoding='utf-8')

    def entries(self):
        self.descriptor.flush()
        for line in open(self.file_name):
            yield Explanation.decode(line.strip())

    def add_entry(self, entry: Explanation) -> None:
        print(entry, file=self.descriptor)

    def clear(self) -> None:
        self.descriptor = codecs.open(self.file_name, mode='w', encoding='utf-8')

    def close(self) -> None:
        self.descriptor.flush()

    def __getitem__(self, key):
        for explanation in self.entries():
            if explanation.key == key:
                return explanation
<commit_msg>Fix permission-denied error in read-only context<commit_after>from hb_res.storage import ExplanationStorage
from hb_res.explanations.Explanation import Explanation

__author__ = 'skird'


class FileExplanationStorage(ExplanationStorage):
    """
    Class representing explanation resource connected with some text file
    """

    def __init__(self, path_to_file):
        self.file_name = path_to_file
        self.write_desc = None

    def entries(self):
        if self.write_desc is not None:
            self.write_desc.flush()
        with open(self.file_name, encoding='utf-8') as read_desc:
            for line in read_desc:
                yield Explanation.decode(line.strip())

    def add_entry(self, entry: Explanation) -> None:
        if self.write_desc is None:
            self.write_desc = open(self.file_name, mode='a', encoding='utf-8')
        print(entry, file=self.write_desc)

    def clear(self) -> None:
        if self.write_desc is not None:
            self.write_desc.close()
        self.write_desc = open(self.file_name, mode='w', encoding='utf-8')

    def close(self) -> None:
        if self.write_desc is not None:
            self.write_desc.close()

    def __getitem__(self, key):
        for explanation in self.entries():
            if explanation.key == key:
                return explanation

{'fraction_non_alphanumeric': 0.10008410428931876, 'fraction_numerical': 0.0021026072329688814, 'mean_word_length': 2.7702060221870046, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1676338', 'n_tokens_mistral': 707, 'n_tokens_neox': 675, 'n_words': 172}