Create full path for excel file to save parsed translations strings.
        Returns:
            unicode: full path for excel file to save parsed translations strings.
969113
def output(self):
        

        path, src = os.path.split(self.src)
        src, ext = os.path.splitext(src)

        return os.path.join(path, "{src}.xls".format(**{"src": src, }))
1296992
def clean_translation(self):
        
        translation = self.cleaned_data['translation']

        if self.instance and self.instance.content_object:
            # do not allow string longer than translatable field
            obj = self.instance.content_object
            field = obj._meta.get_field(self.instance.field)
            max_length = field.max_length

            if max_length and len(translation) > max_length:
                raise forms.ValidationError(
                    _('The entered translation is too long. You entered '
                      '%(entered)s chars, max length is %(maxlength)s') % {
                        'entered': len(translation),
                        'maxlength': max_length,
                    }
                )
        else:
            raise forms.ValidationError(
                _('Can not store translation. First create all translation'
                  ' for this object')
            )
        return translation
1357285
def guess_path_encoding(file_path, default=DEFAULT_ENCODING):
    """"""
    with io.open(file_path, 'rb') as fh:
        return guess_file_encoding(fh, default=default)
734606
def save(self, filename, encoding ='ISO-8859-1', standalone='no'):
        
        f = codecs.open(filename, 'w', encoding)
        s = self.wrap_xml(self.getXML(), encoding, standalone)
        #s = s.replace("&", "&amp;")
        f.write(s)
        f.close()
1296111
def _get_path(fname: str) -> str:
    
    path = get_corpus_path(fname)
    if not path:
        download(fname)
        path = get_corpus_path(fname)
    return path
1060879
def _get_translations_multi_paths():
    
    ctx = _request_ctx_stack.top
    if ctx is None:
        return None

    translations = getattr(ctx, "babel_translations", None)
    if translations is None:
        babel_ext = ctx.app.extensions["babel"]
        translations = None
        trs = None

        # reverse order: thus the application catalog is loaded last, so that
        # translations from libraries can be overriden
        for (dirname, domain) in reversed(babel_ext._translations_paths):
            trs = Translations.load(
                dirname, locales=[flask_babel.get_locale()], domain=domain
            )

            # babel.support.Translations is a subclass of
            # babel.support.NullTranslations, so we test if object has a 'merge'
            # method

            if not trs or not hasattr(trs, "merge"):
                # got None or NullTranslations instance
                continue
            elif translations is not None and hasattr(translations, "merge"):
                translations.merge(trs)
            else:
                translations = trs

        # ensure translations is at least a NullTranslations object
        if translations is None:
            translations = trs

        ctx.babel_translations = translations

    return translations
588819
def save_csvf(data: list, fieldnames: Sequence[str], fpath: str, encoding: str, with_header: bool = False,
              crlf: bool = False, tsv: bool = False) -> str:
    
    with codecs.open(fpath, mode='w', encoding=encoding) as f:
        f.write(dump_csv(data, fieldnames, with_header=with_header, crlf=crlf, tsv=tsv))
        return fpath
624844
def _build_locale_table(filename_or_file):
    
    # Require the XML parser module only if we want the default mapping
    from xml.dom.minidom import parse

    dom = parse(filename_or_file)

    reps = dom.getElementsByTagName('representation')
    locs = map(lambda r: r.childNodes[0].data, reps)

    locale_map = {}
    for loc in locs:
        lang, _, reg = loc.partition('_')
        lang_map = locale_map.setdefault(lang, {'regs': [], 'default': reg})
        lang_map['regs'].append(reg)

    # Default region overrides (arbitrary)
    locale_map['en']['default'] = 'US'
    # Special case: Use es_ES for Spain and es_LA for everything else
    locale_map['es']['default'] = 'LA'
    locale_map['zh']['default'] = 'CN'
    locale_map['fr']['default'] = 'FR'
    locale_map['pt']['default'] = 'PT'

    return locale_map
769901
def read_string_from_file(path, encoding="utf8"):
  
  with codecs.open(path, "rb", encoding=encoding) as f:
    value = f.read()
  return value
272395
def csv_tolist(path_to_file, **kwargs):
    

    result = []

    encoding = kwargs.get('encoding', 'utf-8')
    delimiter = kwargs.get('delimiter', ',')
    dialect = kwargs.get('dialect', csv.excel)

    _, _ext = path_to_file.split('.', 1)

    try:

        file = codecs.open(path_to_file, 'r', encoding)
        items_file = io.TextIOWrapper(file, encoding=encoding)
        result = list(
            csv.reader(items_file, delimiter=delimiter, dialect=dialect))

        items_file.close()
        file.close()

    except Exception as ex:
        result = []
        logger.error('Fail parsing csv to list of rows - {}'.format(ex))

    return result
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
238949
def saveFileEnc(self, filename, encoding):
        
        ret = libxml2mod.xmlSaveFileEnc(filename, self._o, encoding)
        return ret
976977
def save_all(self, path, table_format='txt', sep='\t',
                 table_ext=None, float_format='%.12g'):
        

        if type(path) is str:
            path = path.rstrip('\\')
            path = Path(path)

        path.mkdir(parents=True, exist_ok=True)

        self.save(path=path,
                  table_format=table_format,
                  sep=sep,
                  table_ext=table_ext,
                  float_format=float_format)

        for ext, ext_name in zip(self.get_extensions(data=True),
                                 self.get_extensions()):
            ext_path = path / ext_name

            ext.save(path=ext_path,
                     table_format=table_format,
                     sep=sep,
                     table_ext=table_ext,
                     float_format=float_format)
        return self
1178341
def save_raw_pickle(hwr_objects):
    
    converted_hwr = []

    translate = {}
    translate_id = {}
    model_path = pkg_resources.resource_filename('hwrt', 'misc/')
    translation_csv = os.path.join(model_path, 'latex2writemathindex.csv')
    arguments = {'newline': '', 'encoding': 'utf8'}
    with open(translation_csv, 'rt', **arguments) as csvfile:
        contents = csvfile.read()
    lines = contents.split("\n")
    for csvrow in lines:
        csvrow = csvrow.split(',')
        if len(csvrow) == 1:
            writemathid = csvrow[0]
            latex = ""
        else:
            writemathid, latex = int(csvrow[0]), csvrow[1:]
            latex = ','.join(latex)
        translate[latex] = writemathid
        translate_id[writemathid] = latex

    for hwr in hwr_objects:
        hwr.formula_in_latex = translate_id[hwr.formula_id]

    formula_id2latex = {}
    for el in hwr_objects:
        if el.formula_id not in formula_id2latex:
            formula_id2latex[el.formula_id] = el.formula_in_latex

    for hwr in hwr_objects:
        hwr.formula_in_latex = translate_id[hwr.formula_id]
        hwr.raw_data_id = 42
        converted_hwr.append({'is_in_testset': 0,
                              'formula_id': hwr.formula_id,
                              'handwriting': hwr,
                              'id': 42,
                              'formula_in_latex': hwr.formula_in_latex})
    with open('crohme.pickle', 'wb') as f:
        pickle.dump({'formula_id2latex': formula_id2latex,
                     'handwriting_datasets': converted_hwr},
                    f,
                    protocol=pickle.HIGHEST_PROTOCOL)
1028515
def get_path(language):
  '''  '''
  filename = language.lower() + '.json'
  lang_file_path = os.path.join(_DEFAULT_DIR, filename)
  if not os.path.exists(lang_file_path):
    raise IOError('Could not find {} language file'.format(language))
  return lang_file_path
362930
function (/*String*/path, /*String?*/encoding) {
            if (encoding === 'utf-8') {
                encoding = 'utf8';
            }
            if (!encoding) {
                encoding = 'utf8';
            }

            var text = fs.readFileSync(path, encoding);

            //Hmm, would not expect to get A BOM, but it seems to happen,
            //remove it just in case.
            if (text.indexOf('\uFEFF') === 0) {
                text = text.substring(1, text.length);
            }

            return text;
        }
851282
def export(self, file_path=None, export_format=None):
        
        with io.open(file_path, mode='w', encoding="utf-8") as export_file:
            if export_format == 'yaml':
                import yaml
                yaml.safe_dump(self.to_dict(), export_file, default_flow_style=False)
            elif export_format == 'json':
                export_file.write(text_type(json.dumps(self.to_dict(), ensure_ascii=False)))
            return True