id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15,600
|
directory_data.py
|
translate_pootle/pootle/apps/pootle_data/directory_data.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.db.models import Max
from pootle_translationproject.models import TranslationProject
from .utils import RelatedStoresDataTool
class DirectoryDataTool(RelatedStoresDataTool):
"""Retrieves aggregate stats for a Directory"""
group_by = ("store__parent__tp_path", )
cache_key_name = "directory"
@property
def context_name(self):
return self.context.pootle_path
@property
def max_unit_revision(self):
try:
return self.context.translationproject.data_tool.max_unit_revision
except TranslationProject.DoesNotExist:
return self.all_stat_data.aggregate(rev=Max("max_unit_revision"))["rev"]
def filter_data(self, qs):
return (
qs.filter(
store__translation_project=self.context.translation_project,
store__parent__tp_path__startswith=self.context.tp_path)
.exclude(store__parent=self.context))
def get_children_stats(self, qs):
children = {}
for child in qs.iterator():
self.add_child_stats(children, child)
child_stores = self.data_model.filter(store__parent=self.context).values(
*("store__name", ) + self.max_fields + self.sum_fields)
for child in child_stores:
self.add_child_stats(
children,
child,
root=child["store__name"],
use_aggregates=False)
self.add_submission_info(self.stat_data, children)
self.add_last_created_info(child_stores, children)
return children
def get_root_child_path(self, child):
return child["store__parent__tp_path"][
len(self.context.tp_path):].split("/")[0]
| 2,009
|
Python
|
.py
| 47
| 34.489362
| 84
| 0.656074
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,601
|
0006_add_cascade_deletes.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0006_add_cascade_deletes.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-11-08 20:14
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pootle_data', '0005_add_store_and_tp_data'),
]
operations = [
migrations.AlterField(
model_name='storechecksdata',
name='store',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='check_data', to='pootle_store.Store'),
),
migrations.AlterField(
model_name='storedata',
name='store',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='data', to='pootle_store.Store'),
),
migrations.AlterField(
model_name='tpchecksdata',
name='tp',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='check_data', to='pootle_translationproject.TranslationProject'),
),
migrations.AlterField(
model_name='tpdata',
name='tp',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='data', to='pootle_translationproject.TranslationProject'),
),
]
| 1,336
|
Python
|
.py
| 31
| 34.451613
| 159
| 0.649231
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,602
|
0009_remove_extra_indeces.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0009_remove_extra_indeces.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-06-02 15:57
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pootle_store', '0030_remove_extra_indeces'),
('pootle_translationproject', '0007_set_tp_base_manager_name'),
('pootle_data', '0008_keep_data_on_delete'),
]
operations = [
migrations.AlterField(
model_name='storechecksdata',
name='name',
field=models.CharField(max_length=64),
),
migrations.AlterField(
model_name='tpchecksdata',
name='name',
field=models.CharField(max_length=64),
),
migrations.AlterUniqueTogether(
name='storechecksdata',
unique_together=set([]),
),
migrations.AlterUniqueTogether(
name='tpchecksdata',
unique_together=set([]),
),
migrations.AlterIndexTogether(
name='storechecksdata',
index_together=set([('name', 'category')]),
),
migrations.AlterIndexTogether(
name='tpchecksdata',
index_together=set([('name', 'category')]),
),
migrations.AlterUniqueTogether(
name='storechecksdata',
unique_together=set([('store', 'category', 'name')]),
),
migrations.AlterUniqueTogether(
name='tpchecksdata',
unique_together=set([('tp', 'category', 'name')]),
),
migrations.AlterField(
model_name='storechecksdata',
name='store',
field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, related_name='check_data', to='pootle_store.Store'),
),
migrations.AlterField(
model_name='tpchecksdata',
name='tp',
field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, related_name='check_data', to='pootle_translationproject.TranslationProject'),
),
]
| 2,145
|
Python
|
.py
| 57
| 28
| 175
| 0.595489
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,603
|
0003_index_unique_together.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0003_index_unique_together.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-19 09:17
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pootle_data', '0002_storechecksdata_tpchecksdata'),
]
operations = [
migrations.AlterUniqueTogether(
name='storechecksdata',
unique_together=set([('store', 'category', 'name')]),
),
migrations.AlterUniqueTogether(
name='tpchecksdata',
unique_together=set([('tp', 'category', 'name')]),
),
migrations.AlterIndexTogether(
name='storechecksdata',
index_together=set([('name', 'category'), ('store', 'category', 'name')]),
),
migrations.AlterIndexTogether(
name='tpchecksdata',
index_together=set([('name', 'category'), ('tp', 'category', 'name')]),
),
]
| 943
|
Python
|
.py
| 26
| 28
| 86
| 0.586623
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,604
|
0005_add_store_and_tp_data.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0005_add_store_and_tp_data.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pootle_data', '0004_remove_last_updated'),
]
operations = [
]
| 270
|
Python
|
.py
| 10
| 23
| 52
| 0.685039
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,605
|
0007_add_store_and_tp_data_again.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0007_add_store_and_tp_data_again.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pootle_data', '0006_add_cascade_deletes'),
]
operations = [
]
| 270
|
Python
|
.py
| 10
| 23
| 52
| 0.685039
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,606
|
0004_remove_last_updated.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0004_remove_last_updated.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-19 09:23
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pootle_data', '0003_index_unique_together'),
]
operations = [
migrations.RemoveField(
model_name='storedata',
name='last_updated_unit',
),
migrations.RemoveField(
model_name='tpdata',
name='last_updated_unit',
),
]
| 527
|
Python
|
.py
| 18
| 22.222222
| 54
| 0.603175
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,607
|
0001_initial.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pootle_statistics', '0004_fill_translated_wordcount'),
('pootle_translationproject', '0003_realpath_can_be_none'),
('pootle_store', '0013_set_store_filetype_again'),
]
operations = [
migrations.CreateModel(
name='StoreData',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('max_unit_mtime', models.DateTimeField(db_index=True, null=True, blank=True)),
('max_unit_revision', models.IntegerField(default=0, null=True, db_index=True, blank=True)),
('critical_checks', models.IntegerField(default=0, db_index=True)),
('pending_suggestions', models.IntegerField(default=0, db_index=True)),
('total_words', models.IntegerField(default=0, db_index=True)),
('translated_words', models.IntegerField(default=0, db_index=True)),
('fuzzy_words', models.IntegerField(default=0, db_index=True)),
('last_created_unit', models.OneToOneField(related_name='last_created_for_storedata', null=True, blank=True, to='pootle_store.Unit', on_delete=models.CASCADE)),
('last_submission', models.OneToOneField(related_name='storedata_stats_data', null=True, blank=True, to='pootle_statistics.Submission', on_delete=models.CASCADE)),
('last_updated_unit', models.OneToOneField(related_name='last_updated_for_storedata', null=True, blank=True, to='pootle_store.Unit', on_delete=models.CASCADE)),
('store', models.OneToOneField(related_name='data', to='pootle_store.Store', on_delete=models.CASCADE)),
],
options={
'db_table': 'pootle_store_data',
},
),
migrations.CreateModel(
name='TPData',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('max_unit_mtime', models.DateTimeField(db_index=True, null=True, blank=True)),
('max_unit_revision', models.IntegerField(default=0, null=True, db_index=True, blank=True)),
('critical_checks', models.IntegerField(default=0, db_index=True)),
('pending_suggestions', models.IntegerField(default=0, db_index=True)),
('total_words', models.IntegerField(default=0, db_index=True)),
('translated_words', models.IntegerField(default=0, db_index=True)),
('fuzzy_words', models.IntegerField(default=0, db_index=True)),
('last_created_unit', models.OneToOneField(related_name='last_created_for_tpdata', null=True, blank=True, to='pootle_store.Unit', on_delete=models.CASCADE)),
('last_submission', models.OneToOneField(related_name='tpdata_stats_data', null=True, blank=True, to='pootle_statistics.Submission', on_delete=models.CASCADE)),
('last_updated_unit', models.OneToOneField(related_name='last_updated_for_tpdata', null=True, blank=True, to='pootle_store.Unit', on_delete=models.CASCADE)),
('tp', models.OneToOneField(related_name='data', to='pootle_translationproject.TranslationProject', on_delete=models.CASCADE)),
],
options={
'db_table': 'pootle_tp_data',
},
),
]
| 3,575
|
Python
|
.py
| 51
| 57.078431
| 179
| 0.628019
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,608
|
0002_storechecksdata_tpchecksdata.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0002_storechecksdata_tpchecksdata.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pootle_translationproject', '0003_realpath_can_be_none'),
('pootle_store', '0016_blank_last_sync_revision'),
('pootle_data', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='StoreChecksData',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=64, db_index=True)),
('category', models.IntegerField(default=0, db_index=True)),
('count', models.IntegerField(default=0, db_index=True)),
('store', models.ForeignKey(related_name='check_data', to='pootle_store.Store', on_delete=models.CASCADE)),
],
options={
'db_table': 'pootle_store_check_data',
},
),
migrations.CreateModel(
name='TPChecksData',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=64, db_index=True)),
('category', models.IntegerField(default=0, db_index=True)),
('count', models.IntegerField(default=0, db_index=True)),
('tp', models.ForeignKey(related_name='check_data', to='pootle_translationproject.TranslationProject', on_delete=models.CASCADE)),
],
options={
'db_table': 'pootle_tp_check_data',
},
),
]
| 1,728
|
Python
|
.py
| 37
| 35.189189
| 146
| 0.575919
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,609
|
0010_not_null_max_revision_in_store_and_tp_data.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0010_not_null_max_revision_in_store_and_tp_data.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-12 12:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pootle_data', '0009_remove_extra_indeces'),
]
operations = [
migrations.AlterField(
model_name='storedata',
name='max_unit_revision',
field=models.IntegerField(blank=True, db_index=True, default=0),
),
migrations.AlterField(
model_name='tpdata',
name='max_unit_revision',
field=models.IntegerField(blank=True, db_index=True, default=0),
),
]
| 687
|
Python
|
.py
| 20
| 26.7
| 76
| 0.619335
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,610
|
0008_keep_data_on_delete.py
|
translate_pootle/pootle/apps/pootle_data/migrations/0008_keep_data_on_delete.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-17 19:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pootle_data', '0007_add_store_and_tp_data_again'),
]
operations = [
migrations.AlterField(
model_name='storedata',
name='last_created_unit',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='last_created_for_storedata', to='pootle_store.Unit'),
),
migrations.AlterField(
model_name='storedata',
name='last_submission',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='storedata_stats_data', to='pootle_statistics.Submission'),
),
migrations.AlterField(
model_name='tpdata',
name='last_created_unit',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='last_created_for_tpdata', to='pootle_store.Unit'),
),
migrations.AlterField(
model_name='tpdata',
name='last_submission',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='tpdata_stats_data', to='pootle_statistics.Submission'),
),
]
| 1,506
|
Python
|
.py
| 31
| 39.935484
| 180
| 0.660544
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,611
|
getters.py
|
translate_pootle/pootle/apps/pootle_checks/getters.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.delegate import check_updater, crud
from pootle.core.plugin import getter
from pootle_store.models import QualityCheck, Store
from pootle_translationproject.models import TranslationProject
from .utils import QualityCheckCRUD, StoreQCUpdater, TPQCUpdater
qc_crud = QualityCheckCRUD()
@getter(crud, sender=QualityCheck)
def data_crud_getter(**kwargs):
return qc_crud
@getter(check_updater, sender=TranslationProject)
def get_tp_check_updater(**kwargs_):
return TPQCUpdater
@getter(check_updater, sender=Store)
def get_store_check_updater(**kwargs_):
return StoreQCUpdater
| 885
|
Python
|
.py
| 22
| 38.227273
| 77
| 0.801876
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,612
|
constants.py
|
translate_pootle/pootle/apps/pootle_checks/constants.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
from translate.filters.decorators import Category
from pootle.i18n.gettext import ugettext_lazy as _
CATEGORY_IDS = OrderedDict(
[['critical', Category.CRITICAL],
['functional', Category.FUNCTIONAL],
['cosmetic', Category.COSMETIC],
['extraction', Category.EXTRACTION],
['other', Category.NO_CATEGORY]])
CATEGORY_CODES = {v: k for k, v in CATEGORY_IDS.iteritems()}
CATEGORY_NAMES = {
Category.CRITICAL: _("Critical"),
Category.COSMETIC: _("Cosmetic"),
Category.FUNCTIONAL: _("Functional"),
Category.EXTRACTION: _("Extraction"),
Category.NO_CATEGORY: _("Other")}
CHECK_NAMES = {
'accelerators': _(u"Accelerators"), # fixme duplicated
'acronyms': _(u"Acronyms"),
'blank': _(u"Blank"),
'brackets': _(u"Brackets"),
'compendiumconflicts': _(u"Compendium conflict"),
'credits': _(u"Translator credits"),
'dialogsizes': _(u"Dialog sizes"),
'doublequoting': _(u"Double quotes"), # fixme duplicated
'doublespacing': _(u"Double spaces"),
'doublewords': _(u"Repeated word"),
'emails': _(u"E-mail"),
'endpunc': _(u"Ending punctuation"),
'endwhitespace': _(u"Ending whitespace"),
'escapes': _(u"Escapes"),
'filepaths': _(u"File paths"),
'functions': _(u"Functions"),
'gconf': _(u"GConf values"),
'isfuzzy': _(u"Fuzzy"),
'kdecomments': _(u"Old KDE comment"),
'long': _(u"Long"),
'musttranslatewords': _(u"Must translate words"),
'newlines': _(u"Newlines"),
'nplurals': _(u"Number of plurals"),
'notranslatewords': _(u"Don't translate words"),
'numbers': _(u"Numbers"),
'options': _(u"Options"),
'printf': _(u"printf()"),
'puncspacing': _(u"Punctuation spacing"),
'purepunc': _(u"Pure punctuation"),
'pythonbraceformat': _(u"Python brace placeholders"),
'sentencecount': _(u"Number of sentences"),
'short': _(u"Short"),
'simplecaps': _(u"Simple capitalization"),
'simpleplurals': _(u"Simple plural(s)"),
'singlequoting': _(u"Single quotes"),
'startcaps': _(u"Starting capitalization"),
'startpunc': _(u"Starting punctuation"),
'startwhitespace': _(u"Starting whitespace"),
# Translators: This refers to tabulation characters
'tabs': _(u"Tabs"),
'unchanged': _(u"Unchanged"),
'untranslated': _(u"Untranslated"),
'urls': _(u"URLs"),
'validchars': _(u"Valid characters"),
'variables': _(u"Placeholders"),
'validxml': _(u"Valid XML"),
'xmltags': _(u"XML tags"),
# FIXME: make checks customisable
'ftl_format': _(u'ftl format'),
# Romanian-specific checks
'cedillas': _(u'Romanian: Avoid cedilla diacritics'),
'niciun_nicio': _(u'Romanian: Use "niciun"/"nicio"')}
EXCLUDED_FILTERS = [
'hassuggestion',
'spellcheck',
'isfuzzy',
'isreview',
'untranslated']
| 3,130
|
Python
|
.py
| 82
| 33.731707
| 77
| 0.648124
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,613
|
apps.py
|
translate_pootle/pootle/apps/pootle_checks/apps.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import importlib
from django.apps import AppConfig
class PootleChecksConfig(AppConfig):
name = "pootle_checks"
verbose_name = "Pootle Checks"
def ready(self):
importlib.import_module("pootle_checks.getters")
importlib.import_module("pootle_checks.receivers")
| 568
|
Python
|
.py
| 15
| 34.6
| 77
| 0.751371
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,614
|
receivers.py
|
translate_pootle/pootle/apps/pootle_checks/receivers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.dispatch import receiver
from pootle.core.delegate import check_updater, crud, lifecycle
from pootle.core.signals import (
create, delete, toggle, update_checks, update_data)
from pootle_store.models import QualityCheck, Store, Unit
from pootle_translationproject.models import TranslationProject
@receiver(delete, sender=QualityCheck)
def handle_qc_delete(**kwargs):
crud.get(QualityCheck).delete(**kwargs)
@receiver(create, sender=QualityCheck)
def handle_qc_create(**kwargs):
crud.get(QualityCheck).create(**kwargs)
@receiver(update_checks, sender=Unit)
def handle_unit_checks(**kwargs):
unit = kwargs["instance"]
keep_false_positives = kwargs.get("keep_false_positives", False)
unit.update_qualitychecks(keep_false_positives=keep_false_positives)
@receiver(toggle, sender=QualityCheck)
def handle_toggle_quality_check(**kwargs):
check = kwargs["instance"]
false_positive = kwargs["false_positive"]
unit = check.unit
reviewer = unit.change.reviewed_by
unit_lifecycle = lifecycle.get(Unit)(unit)
subs = []
check.false_positive = false_positive
check.save()
if check.false_positive:
subs.append(
unit_lifecycle.sub_mute_qc(quality_check=check,
submitter=reviewer))
else:
subs.append(
unit_lifecycle.sub_unmute_qc(quality_check=check,
submitter=reviewer))
unit_lifecycle.save_subs(subs=subs)
store = unit.store
update_data.send(store.__class__, instance=store)
@receiver(update_checks, sender=Store)
def store_checks_handler(**kwargs):
store = kwargs["instance"]
check_updater.get(Store)(
store,
units=kwargs.get("units"),
check_names=kwargs.get("check_names")).update(
clear_unknown=kwargs.get("clear_unknown", False),
update_data_after=kwargs.get("update_data_after", False))
@receiver(update_checks, sender=TranslationProject)
def tp_checks_handler(**kwargs):
tp = kwargs["instance"]
check_updater.get(TranslationProject)(
translation_project=tp,
stores=kwargs.get("stores"),
check_names=kwargs.get("check_names")).update(
clear_unknown=kwargs.get("clear_unknown", False),
update_data_after=kwargs.get("update_data_after", False))
| 2,643
|
Python
|
.py
| 63
| 35.84127
| 77
| 0.701091
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,615
|
utils.py
|
translate_pootle/pootle/apps/pootle_checks/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
from translate.filters import checks
from translate.filters.decorators import Category
from translate.lang import data
from django.utils.functional import cached_property
from django.utils.lru_cache import lru_cache
from pootle.core.bulk import BulkCRUD
from pootle.core.contextmanagers import bulk_operations
from pootle.core.signals import create, delete, update_data
from pootle_store.constants import UNTRANSLATED
from pootle_store.models import QualityCheck, Unit
from pootle_store.unit import UnitProxy
from pootle_translationproject.models import TranslationProject
from .constants import (
CATEGORY_CODES, CATEGORY_IDS, CATEGORY_NAMES, CHECK_NAMES,
EXCLUDED_FILTERS)
logger = logging.getLogger(__name__)
class QualityCheckCRUD(BulkCRUD):
model = QualityCheck
class CheckableUnit(UnitProxy):
"""CheckableUnit wraps a `Unit` values dictionary to provide a `Unit` like
instance that can be used by UnitQualityCheck
At a minimum the dict should contain source_f, target_f, store__id, and
store__translation_project__id
"""
@property
def store(self):
return self.store__id
@property
def tp(self):
return self.store__translation_project__id
@property
def language_code(self):
return self.store__translation_project__language__code
class UnitQualityCheck(object):
def __init__(self, unit, checker, original_checks, check_names):
"""Refreshes QualityChecks for a Unit
As this class can work with either `Unit` or `CheckableUnit` it only
uses a minimum of `Unit` attributes from `self.unit`.
:param unit: an instance of Unit or CheckableUnit
:param checker: a Checker for this Unit.
:param original_checks: current QualityChecks for this Unit
:param check_names: limit checks to given list of quality check names.
"""
self.checker = checker
self.unit = unit
self.original_checks = original_checks
self.check_names = check_names
@cached_property
def check_failures(self):
"""Current QualityCheck failure for the Unit
"""
if self.check_names is None:
return self.checker.run_filters(
self.unit, categorised=True)
return run_given_filters(
self.checker, self.unit, self.check_names)
@cached_property
def checks_qs(self):
"""QualityCheck queryset for the Unit
"""
return QualityCheck.objects.filter(unit=self.unit.id)
def delete_checks(self, checks):
"""Delete checks that are no longer used.
"""
return delete.send(
self.checks_qs.model,
objects=self.checks_qs.filter(name__in=checks))
def update(self):
"""Update QualityChecks for a Unit, deleting and unmuting as appropriate.
"""
# update the checks for this unit
updated = self.update_checks()
# delete any remaining checks that were only in the original list
deleted = (
self.original_checks and self.delete_checks(self.original_checks))
return (updated or deleted)
def update_checks(self):
"""Compare self.original_checks to the Units calculated QualityCheck failures.
Removes members of self.original_checks as they have been compared.
"""
updated = False
new_checks = []
for name in self.check_failures.iterkeys():
if name in self.original_checks:
# if the check is valid remove from the list and continue
del self.original_checks[name]
continue
# the check didnt exist previously - so create it
new_checks.append(
self.checks_qs.model(
unit_id=self.unit.id,
name=name,
message=self.check_failures[name]['message'],
category=self.check_failures[name]['category']))
updated = True
if new_checks:
create.send(self.checks_qs.model, objects=new_checks)
return updated
class QualityCheckUpdater(object):
def __init__(self, check_names=None, translation_project=None,
stores=None, units=None):
"""Refreshes QualityChecks for Units
:param check_names: limit checks to given list of quality check names.
:param translation_project: an instance of `TranslationProject` to
restrict the update to.
"""
self.check_names = check_names
self.translation_project = translation_project
self.stores = stores
self._units = units
self._updated_stores = {}
@cached_property
def checks(self):
"""Existing checks in the database for all units
"""
checks = self.checks_qs
check_keys = (
'id', 'name', 'unit_id',
'category', 'false_positive')
if self.check_names is not None:
checks = checks.filter(name__in=self.check_names)
all_units_checks = {}
for check in checks.values(*check_keys):
all_units_checks.setdefault(
check['unit_id'], {})[check['name']] = check
return all_units_checks
@property
def checks_qs(self):
"""QualityCheck queryset for all units, restricted to TP if set
"""
checks_qs = QualityCheck.objects.all()
if self.translation_project is not None:
tp_pk = self.translation_project.pk
checks_qs = checks_qs.filter(
unit__store__translation_project__pk=tp_pk)
if self.stores is not None:
checks_qs = checks_qs.filter(unit__store_id__in=self.stores)
if self._units is not None:
checks_qs = checks_qs.filter(
unit_id__in=self._units.values_list("id", flat=True))
return checks_qs
@cached_property
def units(self):
"""Result set of Units, restricted to TP if set
"""
if self._units is not None:
return self._units
units = Unit.objects.all()
if self.translation_project is not None:
units = units.filter(
store__translation_project=self.translation_project)
if self.stores is not None:
units = units.filter(store_id__in=self.stores)
return units
def clear_unknown_checks(self):
QualityCheck.delete_unknown_checks()
@lru_cache(maxsize=None)
def get_checker(self, tp_pk):
"""Return the site QualityChecker or the QualityCheck associated with
the a Unit's TP otherwise.
"""
try:
return TranslationProject.objects.get(id=tp_pk).checker
except TranslationProject.DoesNotExist:
# There seems to be a risk of dangling Stores with no TP
logger.error("Missing TP (pk '%s'). No checker retrieved.", tp_pk)
return None
@property
def tp_qs(self):
return TranslationProject.objects.all()
@property
def updated_stores(self):
return self._updated_stores
def log_debug(self):
pass
def update(self, clear_unknown=False, update_data_after=False):
"""Update/purge all QualityChecks for Units, and expire Store caches.
"""
self.log_debug()
if clear_unknown:
self.clear_unknown_checks()
with bulk_operations(QualityCheck):
self.update_untranslated()
self.update_translated()
updated = self.updated_stores
if update_data_after:
self.update_data(updated)
if "checks" in self.__dict__:
del self.__dict__["checks"]
self._updated_stores = {}
return updated
def update_data(self, updated):
if not updated:
return
if self.translation_project:
tps = {
self.translation_project.id: self.translation_project}
else:
tps = self.tp_qs.filter(
id__in=updated.keys()).in_bulk()
for tp, stores in updated.items():
tp = tps[tp]
update_data.send(
tp.__class__,
instance=tp,
object_list=tp.stores.filter(id__in=stores))
def update_translated_unit(self, unit, checker=None):
"""Update checks for a translated Unit
"""
unit = CheckableUnit(unit)
checker = UnitQualityCheck(
unit,
checker,
self.checks.get(unit.id, {}),
self.check_names)
if checker.update():
self.update_store(unit.tp, unit.store)
return True
return False
def update_translated(self):
"""Update checks for translated Units
"""
unit_fields = [
"id", "source_f", "target_f", "locations", "store__id",
"store__translation_project__language__code",
]
tp_key = "store__translation_project__id"
if self.translation_project is None:
unit_fields.append(tp_key)
checker = None
if self.translation_project is not None:
checker = self.translation_project.checker
translated = (
self.units.filter(state__gt=UNTRANSLATED)
.order_by("store", "index"))
updated_count = 0
for unit in translated.values(*unit_fields).iterator():
if self.translation_project is not None:
# if TP is set then manually add TP.id to the Unit value dict
unit[tp_key] = self.translation_project.id
else:
checker = self.get_checker(unit[tp_key])
if checker and self.update_translated_unit(unit, checker=checker):
updated_count += 1
# clear the cache of the remaining Store
return updated_count
def update_store(self, tp, store):
self._updated_stores[tp] = (
self._updated_stores.get(tp, set()))
self._updated_stores[tp].add(store)
def update_untranslated(self):
"""Delete QualityChecks for untranslated Units
"""
untranslated = self.checks_qs.exclude(unit__state__gt=UNTRANSLATED)
untranslated_stores = untranslated.values_list(
"unit__store__translation_project", "unit__store").distinct()
for tp, store in untranslated_stores.iterator():
self.update_store(tp, store)
return untranslated.delete()
class TPQCUpdater(QualityCheckUpdater):
def log_debug(self):
logger.debug(
"[checks] Update %s(%s) for %s stores and %s units",
self.__class__.__name__,
(self.translation_project.pootle_path
if self.translation_project
else ""),
"all" if self.stores is None else len(self.stores),
"all" if self._units is None else len(self._units))
class StoreQCUpdater(QualityCheckUpdater):
stores = None
def __init__(self, store, check_names=None, units=None):
"""Refreshes QualityChecks for Units
:param check_names: limit checks to given list of quality check names.
:param translation_project: an instance of `TranslationProject` to
restrict the update to.
"""
self.check_names = check_names
self.store = store
self._updated_stores = {}
self._units = units
def log_debug(self):
logger.debug(
"[checks] Update %s(%s) for %s units",
self.__class__.__name__,
self.store.pootle_path,
"all" if self._units is None else len(self._units))
@property
def checks_qs(self):
"""QualityCheck queryset for all units, restricted to TP if set
"""
checks_qs = QualityCheck.objects.all()
checks_qs = checks_qs.filter(unit__store_id=self.store.id)
if self._units is not None:
checks_qs = checks_qs.filter(unit_id__in=self._units)
return checks_qs
@property
def translation_project(self):
return self.store.translation_project
@cached_property
def units(self):
"""Result set of Units, restricted to TP if set
"""
if self._units:
return self.store.unit_set.filter(
id__in=self._units)
return self.store.unit_set
def update_data(self, updated_stores):
if not updated_stores:
return
update_data.send(
self.store.__class__,
instance=self.store)
def update_translated(self):
"""Update checks for translated Units
"""
unit_fields = ["id", "source_f", "target_f", "locations"]
checker = self.store.translation_project.checker
lang_code = self.store.translation_project.language.code
translated = (
self.units.filter(state__gt=UNTRANSLATED)
.order_by("store", "index"))
updated_count = 0
for unit in translated.values(*unit_fields).iterator():
unit["store__translation_project__id"] = self.translation_project.id
unit["store__id"] = self.store.id
unit["store__translation_project__language__code"] = lang_code
if self.update_translated_unit(unit, checker=checker):
updated_count += 1
return updated_count
def get_category_id(code):
return CATEGORY_IDS.get(code)
def get_category_code(cid):
return CATEGORY_CODES.get(cid)
def get_category_name(code):
return unicode(CATEGORY_NAMES.get(code))
def run_given_filters(checker, unit, check_names=None):
"""Run all the tests in this suite.
:rtype: Dictionary
:return: Content of the dictionary is as follows::
{'testname': {
'message': message_or_exception,
'category': failure_category
}}
Do some optimisation by caching some data of the unit for the
benefit of :meth:`~TranslationChecker.run_test`.
"""
if check_names is None:
check_names = []
checker.str1 = data.normalized_unicode(unit.source) or u""
checker.str2 = data.normalized_unicode(unit.target) or u""
checker.language_code = unit.language_code # XXX: comes from `CheckableUnit`
checker.hasplural = unit.hasplural()
checker.locations = unit.getlocations()
checker.results_cache = {}
failures = {}
for functionname in check_names:
if isinstance(checker, checks.TeeChecker):
for _checker in checker.checkers:
filterfunction = getattr(_checker, functionname, None)
if filterfunction:
checker = _checker
checker.str1 = data.normalized_unicode(unit.source) or u""
checker.str2 = data.normalized_unicode(unit.target) or u""
checker.language_code = unit.language_code
checker.hasplural = unit.hasplural()
checker.locations = unit.getlocations()
break
else:
filterfunction = getattr(checker, functionname, None)
# This filterfunction may only be defined on another checker if
# using TeeChecker
if filterfunction is None:
continue
filtermessage = filterfunction.__doc__
try:
filterresult = checker.run_test(filterfunction, unit)
except checks.FilterFailure as e:
filterresult = False
filtermessage = unicode(e)
except Exception as e:
if checker.errorhandler is None:
raise ValueError("error in filter %s: %r, %r, %s" %
(functionname, unit.source, unit.target, e))
else:
filterresult = checker.errorhandler(functionname, unit.source,
unit.target, e)
if not filterresult:
# We test some preconditions that aren't actually a cause for
# failure
if functionname in checker.defaultfilters:
failures[functionname] = {
'message': filtermessage,
'category': checker.categories[functionname],
}
checker.results_cache = {}
return failures
def get_qualitychecks():
available_checks = {}
checkers = [checker() for checker in checks.projectcheckers.values()]
for checker in checkers:
for filt in checker.defaultfilters:
if filt not in EXCLUDED_FILTERS:
# don't use an empty string because of
# http://bugs.python.org/issue18190
try:
getattr(checker, filt)(u'_', u'_')
except Exception as e:
# FIXME there must be a better way to get a list of
# available checks. Some error because we're not actually
# using them on real units.
logging.error("Problem with check filter '%s': %s",
filt, e)
continue
available_checks.update(checker.categories)
return available_checks
def get_qualitycheck_schema(path_obj=None):
d = {}
checks = get_qualitychecks()
for check, cat in checks.items():
if cat not in d:
d[cat] = {
'code': cat,
'name': get_category_code(cat),
'title': get_category_name(cat),
'checks': []
}
d[cat]['checks'].append({
'code': check,
'title': u"%s" % CHECK_NAMES.get(check, check),
'url': path_obj.get_translate_url(check=check) if path_obj else ''
})
result = sorted([item for item in d.values()],
key=lambda x: x['code'],
reverse=True)
return result
def get_qualitycheck_list(path_obj):
"""
Returns list of checks sorted in alphabetical order
but having critical checks first.
"""
result = []
checks = get_qualitychecks()
for check, cat in checks.items():
result.append({
'code': check,
'is_critical': cat == Category.CRITICAL,
'title': u"%s" % CHECK_NAMES.get(check, check),
'url': path_obj.get_translate_url(check=check)
})
def alphabetical_critical_first(item):
critical_first = 0 if item['is_critical'] else 1
return critical_first, item['title'].lower()
result = sorted(result, key=alphabetical_critical_first)
return result
| 18,998
|
Python
|
.py
| 463
| 30.963283
| 86
| 0.609083
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,616
|
__init__.py
|
translate_pootle/pootle/apps/pootle_checks/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
default_app_config = 'pootle_checks.apps.PootleChecksConfig'
| 337
|
Python
|
.py
| 8
| 41
| 77
| 0.768293
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,617
|
state.py
|
translate_pootle/pootle/core/state.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
logger = logging.getLogger(__name__)
class ItemState(object):
def __init__(self, state, state_type, **kwargs):
self.state = state
self.state_type = state_type
self.kwargs = kwargs
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and other.state_type == self.state_type
and other.state == self.state
and (sorted(self.kwargs.items())
== sorted(other.kwargs.items())))
def __getattr__(self, k):
if self.__dict__.get("kwargs") and k in self.__dict__["kwargs"]:
return self.kwargs[k]
return self.__getattribute__(k)
def __str__(self):
return (
"<%s(%s): %s %s>"
% (self.__class__.__name__,
self.state.context,
self.state_type,
self.kwargs))
class State(object):
item_state_class = ItemState
prefix = "state"
def __init__(self, context, load=True, **kwargs):
self.context = context
self.__state__ = {}
self.kwargs = kwargs
if load:
self.reload()
def __contains__(self, k):
return k in self.__state__ and self.__state__[k]
def __eq__(self, other):
return (
self.__class__ == other.__class__
and self.context == other.context
and sorted(self.kwargs.items()) == sorted(other.kwargs.items())
and self.prefix == other.prefix)
def __getitem__(self, k):
return self.__state__[k]
def __setitem__(self, k, v):
self.__state__[k] = v
def __iter__(self):
for k in self.__state__:
if self.__state__[k]:
yield k
def __str__(self):
if not self.has_changed:
return (
"<%s(%s): Nothing to report>"
% (self.__class__.__name__,
self.context))
return (
"<%s(%s): %s>"
% (self.__class__.__name__,
self.context,
', '.join(["%s: %s" % (k, len(self.__state__[k]))
for k in self.states
if self.__state__[k]])))
@property
def changed(self):
return {k: len(v) for k, v in self.__state__.items() if v}
@property
def has_changed(self):
return any(self.__state__.values())
@property
def states(self):
return [x[6:] for x in dir(self) if x.startswith("state_")]
def add(self, k, v):
if k in self.__state__:
self.__state__[k].append(v)
def clear_cache(self):
self.__state__ = {k: [] for k in self.states}
def reload(self):
self.clear_cache()
# logger.debug("Checking state")
# reload_start = time.time()
for k in self.states:
# start = time.time()
state_attr = getattr(
self, "%s_%s" % (self.prefix, k), None)
count = 0
if callable(state_attr):
for v in state_attr(**self.kwargs):
count += 1
self.add(
k, self.item_state_class(self, k, **v))
else:
for v in state_attr:
count += 1
self.add(
k, self.item_state_class(self, k, **v))
# logger.debug(
# "Checked '%s' (%s) in %s seconds",
# k, count, time.time() - start)
# logger.debug(
# "Reloaded state in %s seconds",
# time.time() - reload_start)
return self
| 3,943
|
Python
|
.py
| 110
| 25.318182
| 77
| 0.493435
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,618
|
signals.py
|
translate_pootle/pootle/core/signals.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.dispatch import Signal
changed = Signal(
providing_args=["instance", "key", "value", "old_value"],
use_caching=True)
config_updated = Signal(
providing_args=["instance", "updates"],
use_caching=True)
create = Signal(
providing_args=["instance", "objects"],
use_caching=True)
delete = Signal(
providing_args=["instance", "objects"],
use_caching=True)
update = Signal(
providing_args=["instance", "objects"],
use_caching=True)
update_checks = Signal(
providing_args=["instance", "keep_false_positives"],
use_caching=True)
update_data = Signal(providing_args=["instance"], use_caching=True)
update_revisions = Signal(providing_args=["instance"], use_caching=True)
filetypes_changed = Signal(
providing_args=["instance", "filetype"],
use_caching=True)
update_scores = Signal(
providing_args=["instance", "users"],
use_caching=True)
toggle = Signal(
providing_args=["instance", "false_positive"],
use_caching=True)
| 1,294
|
Python
|
.py
| 38
| 31.078947
| 77
| 0.714286
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,619
|
proxy.py
|
translate_pootle/pootle/core/proxy.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
class BaseProxy(object):
"""Base Proxy class to wrap an object"""
__slots__ = ["_obj", "__weakref__"]
def __init__(self, obj):
object.__setattr__(self, "_obj", obj)
def __getattribute__(self, name):
return getattr(object.__getattribute__(self, "_obj"), name)
def __delattr__(self, name):
delattr(object.__getattribute__(self, "_obj"), name)
def __setattr__(self, name, value):
setattr(object.__getattribute__(self, "_obj"), name, value)
def __nonzero__(self):
return bool(object.__getattribute__(self, "_obj"))
def __str__(self):
return str(object.__getattribute__(self, "_obj"))
_special_names = [
'__abs__', '__add__', '__and__', '__call__', '__cmp__', '__coerce__',
'__contains__', '__delitem__', '__delslice__', '__div__', '__divmod__',
'__eq__', '__float__', '__floordiv__', '__ge__', '__getitem__',
'__getslice__', '__gt__', '__hash__', '__hex__', '__iadd__', '__iand__',
'__idiv__', '__idivmod__', '__ifloordiv__', '__ilshift__', '__imod__',
'__imul__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__',
'__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__',
'__long__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__',
'__neg__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__',
'__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rfloorfiv__', '__rlshift__', '__rmod__',
'__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
'__rtruediv__', '__rxor__', '__setitem__', '__setslice__', '__sub__',
'__truediv__', '__xor__', 'next',
]
@classmethod
def _create_class_proxy(cls, theclass):
"""creates a proxy for the given class"""
def make_method(name):
def method(self, *args, **kw):
_method = getattr(
object.__getattribute__(self, "_obj"), name)
return _method(*args, **kw)
return method
namespace = {}
for name in cls._special_names:
if hasattr(theclass, name):
namespace[name] = make_method(name)
return type("%s(%s)" % (cls.__name__, theclass.__name__), (cls,), namespace)
def __new__(cls, obj, *args, **kwargs):
"""
creates an proxy instance referencing `obj`. (obj, *args, **kwargs) are
passed to this class' __init__, so deriving classes can define an
__init__ method of their own.
note: _class_proxy_cache is unique per deriving class (each deriving
class must hold its own cache)
"""
try:
cache = cls.__dict__["_class_proxy_cache"]
except KeyError:
cls._class_proxy_cache = cache = {}
try:
theclass = cache[obj.__class__]
except KeyError:
cache[obj.__class__] = theclass = cls._create_class_proxy(obj.__class__)
ins = object.__new__(theclass)
theclass.__init__(ins, obj, *args, **kwargs)
return ins
class AttributeProxy(BaseProxy):
"""Wraps an object, but allows getting setting of attributes on wrapper"""
def __getattribute__(self, name):
obj = object.__getattribute__(self, "_obj")
if hasattr(obj, name):
return getattr(obj, name)
return object.__getattribute__(self, name)
def __setattr__(self, name, value):
obj = object.__getattribute__(self, "_obj")
if hasattr(obj, name):
setattr(obj, name, value)
object.__setattr__(self, name, value)
def __delattr__(self, name):
obj = object.__getattribute__(self, "_obj")
if hasattr(obj, name):
delattr(obj, name)
object.__delattr__(self, name)
| 4,154
|
Python
|
.py
| 88
| 38.715909
| 84
| 0.51742
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,620
|
serializers.py
|
translate_pootle/pootle/core/serializers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
class Serializer(object):
def __init__(self, context, data):
self.context = context
self.original_data = data
@property
def data(self):
return self.original_data
class Deserializer(object):
def __init__(self, context, data):
self.context = context
self.original_data = data
@property
def data(self):
return self.original_data
| 681
|
Python
|
.py
| 21
| 27.619048
| 77
| 0.687117
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,621
|
paginator.py
|
translate_pootle/pootle/core/paginator.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.core.paginator import Paginator
def paginate(request, queryset, items=30, page=None):
paginator = Paginator(queryset, items)
if page is None:
try:
page = int(request.GET.get('page', 1))
except ValueError:
# It wasn't an int, so use 1.
page = 1
# If page value is too large.
page = min(page, paginator.num_pages)
return paginator.page(page)
| 704
|
Python
|
.py
| 19
| 32
| 77
| 0.680882
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,622
|
sync.py
|
translate_pootle/pootle/core/sync.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from dirsync.syncer import Syncer as BaseSyncer
class Syncer(BaseSyncer):
"""Overridden due to noisy logging in dirsync.Syncer"""
pkg_name = "dirsync"
def log(self, msg, debug=False):
if debug:
self.logger.debug(
"[%s] %s",
self.pkg_name, msg)
else:
self.logger.info(
"[%s] %s",
self.pkg_name, msg)
def report(self):
"""Print report of work at the end"""
# We need only the first 4 significant digits
tt = (str(self._endtime - self._starttime))[:4]
self.log(
'%d directories parsed, %d files copied' %
(self._numdirs, self._numfiles),
debug=not self._numfiles)
if self._numdelfiles:
self.log('%d files were purged.' % self._numdelfiles)
if self._numdeldirs:
self.log('%d directories were purged.' % self._numdeldirs)
if self._numnewdirs:
self.log('%d directories were created.' % self._numnewdirs)
if self._numupdates:
self.log('%d files were updated by timestamp.' % self._numupdates)
# Failure stats
if self._numcopyfld:
self.log('there were errors in copying %d files.'
% self._numcopyfld)
if self._numdirsfld:
self.log('there were errors in creating %d directories.'
% self._numdirsfld)
if self._numupdsfld:
self.log('there were errors in updating %d files.'
% self._numupdsfld)
if self._numdeldfld:
self.log('there were errors in purging %d directories.'
% self._numdeldfld)
if self._numdelffld:
self.log('there were errors in purging %d files.'
% self._numdelffld)
self.log(
'%s finished in %s seconds.'
% (self.pkg_name, tt),
debug=True)
def sync(sourcedir, targetdir, action, **options):
copier = Syncer(sourcedir, targetdir, action, **options)
copier.do_work()
# print report at the end
copier.report()
return set(copier._changed).union(copier._added).union(copier._deleted)
| 2,519
|
Python
|
.py
| 62
| 30.596774
| 78
| 0.584357
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,623
|
user.py
|
translate_pootle/pootle/core/user.py
|
from django.contrib.auth import get_user_model
def get_system_user():
return get_user_model().objects.get_system_user()
def get_system_user_id():
return get_system_user().id
| 188
|
Python
|
.py
| 5
| 33.8
| 53
| 0.745763
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,624
|
bulk.py
|
translate_pootle/pootle/core/bulk.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
from bulk_update.helper import bulk_update
logger = logging.getLogger(__name__)
class BulkCRUD(object):
model = None
def __repr__(self):
return (
"<%s:%s>"
% (self.__class__.__name__,
str(self.model._meta)))
@property
def qs(self):
return self.model.objects
def pre_delete(self, instance=None, objects=None):
pass
def post_delete(self, instance=None, objects=None, pre=None, result=None):
pass
def pre_create(self, instance=None, objects=None):
pass
def post_create(self, instance=None, objects=None, pre=None, result=None):
pass
def pre_update(self, instance=None, objects=None, values=None):
pass
def post_update(self, instance=None, objects=None, pre=None, result=None,
values=None):
pass
def bulk_update(self, objects, fields=None):
bulk_update(
objects,
update_fields=fields)
def create(self, **kwargs):
if "instance" in kwargs:
pre = self.pre_create(instance=kwargs["instance"])
result = kwargs["instance"].save()
self.post_create(instance=kwargs["instance"], pre=pre, result=result)
if "objects" in kwargs:
pre = self.pre_delete(objects=kwargs["objects"])
result = self.model.objects.bulk_create(
kwargs["objects"])
logger.debug(
"[crud] Created (%s): %s",
len(result),
self.model.__name__)
self.post_create(objects=kwargs["objects"], pre=pre, result=result)
def delete(self, **kwargs):
if "instance" in kwargs:
pre = self.pre_delete(instance=kwargs["instance"])
result = kwargs["instance"].delete()
self.post_delete(instance=kwargs["instance"], pre=pre, result=result)
if "objects" in kwargs:
pre = self.pre_delete(objects=kwargs["objects"])
result = kwargs["objects"].select_for_update().delete()
logger.debug(
"[crud] Deleted (%s): %s",
str(result),
self.model.__name__)
self.post_delete(objects=kwargs["objects"], pre=pre, result=result)
def update_object(self, obj, update):
for k, v in update.items():
if not getattr(obj, k) == v:
setattr(obj, k, v)
yield k
def update_objects(self, to_update, updates, objects):
if not updates:
objects += list(to_update)
to_update = []
for obj in to_update:
if updates.get(obj.pk):
for field in self.update_object(obj, updates[obj.pk]):
yield field
objects.append(obj)
def objects_to_fetch(self, objects, updates):
ids_to_fetch = (
set((updates or {}).keys())
- set(obj.id for obj in objects))
if ids_to_fetch:
return self.select_for_update(
self.qs.filter(id__in=ids_to_fetch))
def select_for_update(self, qs):
return qs
def update_object_list(self, **kwargs):
fields = (
set(kwargs["update_fields"])
if kwargs.get("update_fields")
else set())
objects = []
if "objects" in kwargs and kwargs["objects"] is not None:
fields |= set(
self.update_objects(
kwargs["objects"],
kwargs.get("updates"),
objects))
return objects, (fields or None)
def update_common_objects(self, ids, values):
objects = self.select_for_update(self.model.objects).filter(id__in=ids)
pre = self.pre_update(objects=objects, values=values)
result = objects.select_for_update().update(**values)
self.post_update(
objects=objects, pre=pre, result=result, values=values)
return result
def all_updates_common(self, updates):
values = {}
first = True
for item, _update in updates.items():
if not first and len(values) != len(_update):
return False
for k, v in _update.items():
if first:
values[k] = v
continue
if k not in values or values[k] != v:
return False
first = False
return values
def update_object_dict(self, objects, updates, fields):
extra_fields = None
to_fetch = self.objects_to_fetch(objects, updates)
if to_fetch is None and not objects:
return set()
if not objects:
common_updates = self.all_updates_common(updates)
if common_updates:
return self.update_common_objects(
updates.keys(),
common_updates)
if to_fetch is not None:
extra_fields = set(
self.update_objects(
to_fetch.iterator(),
updates,
objects))
if objects:
pre = self.pre_update(objects=objects)
if fields is not None:
fields = list(
fields | extra_fields
if extra_fields is not None
else fields)
result = self.bulk_update(
objects,
fields=fields)
self.post_update(objects=objects, pre=pre, result=result)
return result
def update_object_instance(self, instance):
pre = self.pre_update(instance=instance)
result = instance.save()
self.post_update(instance=instance, pre=pre, result=result)
return result
def update(self, **kwargs):
if kwargs.get("instance") is not None:
return self.update_object_instance(kwargs["instance"])
objects, fields = self.update_object_list(**kwargs)
updated = self.update_object_dict(objects, kwargs.get("updates"), fields)
total = (updated or 0) + len(objects)
logger.debug(
"[crud] Updated (%s): %s %s",
total,
self.model.__name__,
"%s" % (", ".join(fields or [])))
return total
| 6,621
|
Python
|
.py
| 167
| 28.281437
| 81
| 0.555867
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,625
|
browser.py
|
translate_pootle/pootle/core/browser.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.i18n.gettext import ugettext_lazy as _
HEADING_CHOICES = [
{
'id': 'name',
'class': 'stats',
'display_name': _("Name"),
},
{
'id': 'priority',
'class': 'stats-number sorttable_numeric',
'display_name': _("Priority"),
},
{
'id': 'project',
'class': 'stats',
'display_name': _("Project"),
},
{
'id': 'language',
'class': 'stats',
'display_name': _("Language"),
},
{
'id': 'progress',
'class': 'stats',
# Translators: noun. The graphical representation of translation status
'display_name': _("Progress"),
},
{
'id': 'activity',
'class': 'stats sorttable_numeric when-loaded',
'display_name': _("Last Activity"),
},
{
'id': 'critical',
'class': 'stats-number sorttable_numeric when-loaded',
'display_name': _("Critical"),
},
{
'id': 'suggestions',
'class': 'stats-number sorttable_numeric when-loaded',
# Translators: The number of suggestions pending review
'display_name': _("Suggestions"),
},
{
'id': 'need-translation',
'class': 'stats-number sorttable_numeric when-loaded',
'display_name': _("Incomplete"),
},
{
'id': 'total',
'class': 'stats-number sorttable_numeric when-loaded',
# Translators: Heading representing the total number of words of a file
# or directory
'display_name': _("Total"),
},
{
'id': 'last-updated',
'class': 'stats sorttable_numeric when-loaded',
'display_name': _("Last updated"),
},
]
def get_table_headings(choices):
"""Filters the list of available table headings to the given `choices`."""
return filter(lambda x: x['id'] in choices, HEADING_CHOICES)
def make_generic_item(path_obj, **kwargs):
"""Template variables for each row in the table."""
return {
'sort': kwargs.get("sort"),
'href': path_obj.get_absolute_url(),
'href_translate': path_obj.get_translate_url(),
'title': path_obj.name,
'code': path_obj.code,
'is_disabled': getattr(path_obj, 'disabled', False),
}
def make_directory_item(directory, **filters):
item = make_generic_item(directory, **filters)
item.update({
'icon': 'folder',
})
return item
def make_store_item(store):
item = make_generic_item(store)
item.update({
'icon': 'file',
})
return item
def get_parent(path_obj):
"""Retrieves a representation of the parent object.
:param path_obj: either a `Directory` or Store` instance.
"""
parent_dir = path_obj.parent
if parent_dir.is_project():
return None
if parent_dir.is_language():
label = _('Back to language')
else:
label = _('Back to parent folder')
return {
'title': label,
'href': parent_dir.get_absolute_url()
}
def make_project_item(translation_project):
item = make_generic_item(translation_project)
item.update({
'icon': 'project',
'title': translation_project.project.name,
})
return item
def make_language_item(translation_project):
item = make_generic_item(translation_project)
item.update({
'icon': 'language',
'title': translation_project.language.name,
})
return item
def make_xlanguage_item(resource_obj):
translation_project = resource_obj.tp
item = make_generic_item(resource_obj)
item.update({
'icon': 'language',
'code': translation_project.language.code,
'title': translation_project.language.name,
})
return item
def make_project_list_item(project):
item = make_generic_item(project)
item.update({
'icon': 'project',
'title': project.fullname,
})
return item
| 4,213
|
Python
|
.py
| 139
| 23.978417
| 79
| 0.601136
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,626
|
language.py
|
translate_pootle/pootle/core/language.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.utils.translation import to_locale
# these languages need to have their cldr name adjusted for use in ui
# http://cldr.unicode.org/development/development-process/design-proposals/\
# grammar-and-capitalization-for-date-time-elements
UPPERCASE_UI = [
"sv", "ca", "es", "ru", "uk", "it", "nl", "pt", "pt_PT", "cs", "hr"]
class LanguageCode(object):
def __init__(self, code):
self.code = code
@property
def normalized(self):
return self.code.replace("_", "-").replace("@", "-").lower()
@property
def base_code(self):
separator = self.normalized.rfind('-')
return (
self.code[:separator]
if separator >= 0
else self.code)
def matches(self, other, ignore_dialect=True):
return (
(to_locale(self.code)
== to_locale(other.code))
or (ignore_dialect
and (self.base_code
== (other.base_code))))
| 1,262
|
Python
|
.py
| 33
| 31.575758
| 77
| 0.62377
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,627
|
response.py
|
translate_pootle/pootle/core/response.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
logger = logging.getLogger(__name__)
class ItemResponse(object):
def __init__(self, response, action_type, complete=True, msg=None, **kwargs):
self.response = response
self.action_type = action_type
self.complete = complete
self.msg = msg or ""
self.kwargs = kwargs
def __str__(self):
extra = ""
if self.failed:
extra = " FAILED"
if self.msg:
extra = "%s %s" % (extra, self.msg)
if self.kwargs:
extra = "%s %s" % (extra, str(self.kwargs))
return (
"<%s(%s): %s%s>"
% (self.__class__.__name__,
self.response,
self.action_type,
extra))
@property
def failed(self):
return not self.complete
class Response(object):
__responses__ = None
response_class = ItemResponse
def __init__(self, context):
self.context = context
self.__responses__ = {}
self.clear_cache()
def __getitem__(self, k):
return self.__responses__[k]
def __iter__(self):
for k in self.__responses__:
if self.__responses__[k]:
yield k
def __len__(self):
return len([x for x in self.__iter__()])
def __str__(self):
failed = ""
if self.has_failed:
failed = "FAIL "
if self.made_changes:
return (
"<%s(%s): %s%s>"
% (self.__class__.__name__,
self.context,
failed,
self.success))
return (
"<%s(%s): %sNo changes made>"
% (self.__class__.__name__,
self.context,
failed))
@property
def has_failed(self):
return len(list(self.failed())) > 0
@property
def made_changes(self):
return len(list(self.completed())) > 0
@property
def response_types(self):
return self.__responses__.keys()
@property
def success(self):
return ', '.join(
["%s: %s" % (k, len(list(self.completed(k))))
for k in self.response_types
if len(list(self.completed(k)))])
def add(self, response_type, complete=True, msg=None, **kwargs):
response = self.response_class(
self, response_type, complete=complete, msg=msg, **kwargs)
if response_type not in self.__responses__:
self.__responses__[response_type] = []
self.__responses__[response_type].append(response)
return response
def clear_cache(self):
for k in self.response_types:
self.__responses__[k] = []
def completed(self, *response_types):
response_types = response_types or self.response_types
for response_type in response_types:
for response in self.__responses__[response_type]:
if not response.failed:
yield response
def failed(self, *response_types):
response_types = response_types or self.response_types
for response_type in response_types:
for response in self.__responses__[response_type]:
if response.failed:
yield response
| 3,559
|
Python
|
.py
| 101
| 25.742574
| 81
| 0.549505
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,628
|
dateparse.py
|
translate_pootle/pootle/core/dateparse.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.utils import dateparse as django_dateparse
def parse_datetime(value):
"""Parse a ISO 8601 formatted value into a date or datetime object.
Django's own date parsing facilities differentiate date and datetime
parsing. We need to parse dates and datetimes either way, so this is a
convenience wrapper.
:return: either a `datetime` or a `date` object. If the provided input
string doesn't represent a valid date or datetime, `None` will be
returned instead.
"""
try:
datetime_obj = django_dateparse.parse_datetime(value)
except ValueError:
datetime_obj = None
# Not a valid datetime, check with date
if datetime_obj is None:
try:
datetime_obj = django_dateparse.parse_date(value)
except ValueError:
datetime_obj = None
return datetime_obj
| 1,145
|
Python
|
.py
| 28
| 35.5
| 77
| 0.711712
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,629
|
display.py
|
translate_pootle/pootle/core/display.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.utils.functional import cached_property
class ItemDisplay(object):
def __init__(self, section, item):
self.section = section
self.item = item
def __str__(self):
return "%s\n" % str(self.item)
class SectionDisplay(object):
item_class = ItemDisplay
def __init__(self, context, name):
self.context = context
self.name = name
def __str__(self):
description = ""
if self.description:
description = "%s\n" % self.description
result = (
"%s\n%s\n%s\n"
% (self.title,
"-" * len(self.title),
description))
for item in self:
result += str(item)
return "%s\n" % result
@property
def data(self):
return self.context.context[self.name]
def __iter__(self):
failed = False
if isinstance(self.data, (str, unicode)):
failed = True
try:
iterable = iter(self.data)
except TypeError:
failed = True
if failed:
raise TypeError(
"Invalid type (%s) for section '%s': "
"context sections should be non-string iterables"
% (type(self.data), self.name))
for item in iterable:
yield self.item_class(self, item)
@cached_property
def items(self):
return list(self)
@property
def description(self):
return self.info.get('description', "")
@property
def info(self):
if self.context.context_info:
info = self.context.context_info.get(self.name, {})
else:
info = {}
if "title" not in info:
info["title"] = self.name
return info
@property
def title(self):
return (
"%s (%s)"
% (self.info['title'], len(self.items)))
class Display(object):
context_info = None
section_class = SectionDisplay
no_results_msg = ""
def __init__(self, context):
self.context = context
def __str__(self):
result = ""
for section in self.sections:
result += str(self.section(section))
if not result:
result = self.no_results_msg
return "%s\n" % result
@property
def sections(self):
return [
section
for section
in self.context
if self.context[section]]
def section(self, section):
return self.section_class(self, section)
| 2,834
|
Python
|
.py
| 91
| 22.615385
| 77
| 0.565809
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,630
|
cache.py
|
translate_pootle/pootle/core/cache.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings
from django.core.cache import cache as default_cache, caches
from django.core.cache.backends.base import InvalidCacheBackendError
from django.core.exceptions import ImproperlyConfigured
PERSISTENT_STORES = ('redis',)
def make_method_key(model, method, key):
"""Creates a cache key for model's `method` method.
:param model: A model instance
:param method: Method name to cache
:param key: a unique key to identify the object to be cached
"""
prefix = 'method-cache'
if isinstance(model, basestring):
name = model
else:
name = (model.__name__
if hasattr(model, '__name__')
else model.__class__.__name__)
key = make_key(**key) if isinstance(key, dict) else key
return u':'.join([prefix, name, method, key])
def make_key(*args, **kwargs):
"""Creates a cache key with key-value pairs from a dict."""
return ':'.join([
'%s=%s' % (k, v) for k, v in sorted(kwargs.iteritems())
])
def get_cache(cache=None):
"""Return ``cache`` or the 'default' cache if ``cache`` is not specified or
``cache`` is not configured.
:param cache: The name of the requested cache.
"""
try:
# Check for proper Redis persistent backends
# FIXME: this logic needs to be a system sanity check
if (cache in PERSISTENT_STORES and
(cache not in settings.CACHES or 'RedisCache' not in
settings.CACHES[cache]['BACKEND'] or
settings.CACHES[cache].get('TIMEOUT', '') is not None)):
raise ImproperlyConfigured(
'Pootle requires a Redis-backed caching backend for %r '
'with `TIMEOUT: None`. Please review your settings.' % cache
)
return caches[cache]
except InvalidCacheBackendError:
return default_cache
| 2,166
|
Python
|
.py
| 51
| 35.72549
| 79
| 0.65619
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,631
|
batch.py
|
translate_pootle/pootle/core/batch.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
import time
from bulk_update.helper import bulk_update
logger = logging.getLogger(__name__)
class Batch(object):
def __init__(self, target, batch_size=10000):
self.target = target
self.batch_size = batch_size
def batched_create(self, qs, create_method, reduces=True):
complete = 0
offset = 0
if isinstance(qs, (list, tuple)):
total = len(qs)
else:
total = qs.count()
start = time.time()
step = (
self.batch_size
if not reduces
else 0)
while True:
complete += self.batch_size
result = self.target.bulk_create(
self.target.model(
**create_method(
*(args
if isinstance(args, (list, tuple))
else [args])))
for args
in self.iterate_qs(qs, offset))
if not result:
break
logger.debug(
"added %s/%s in %s seconds",
min(complete, total),
total,
(time.time() - start))
yield result
if complete > total:
break
offset = offset + step
def create(self, qs, create_method, reduces=True):
created = 0
for result in self.batched_create(qs, create_method, reduces):
created += len(result)
return created
def iterate_qs(self, qs, offset):
if isinstance(qs, (list, tuple)):
return qs[offset:offset + self.batch_size]
return qs[offset:offset + self.batch_size].iterator()
def bulk_update(self, objects, update_fields=None):
return bulk_update(objects, update_fields=update_fields)
def objects_to_update(self, qs, offset, update_method=None):
if not update_method:
return list(self.iterate_qs(qs, offset))
return [
update_method(item)
for item
in self.iterate_qs(qs, offset)]
def batched_update(self, qs, update_method=None, reduces=True,
update_fields=None):
complete = 0
offset = 0
if isinstance(qs, (list, tuple)):
total = len(qs)
else:
total = qs.count()
start = time.time()
step = (
self.batch_size
if not reduces
else 0)
while True:
complete += self.batch_size
objects_to_update = self.objects_to_update(qs, offset, update_method)
if not objects_to_update:
break
result = self.bulk_update(
objects=objects_to_update,
update_fields=update_fields)
logger.debug(
"updated %s/%s in %s seconds",
min(complete, total),
total,
(time.time() - start))
yield result
if complete > total:
break
offset = offset + step
def update(self, qs, update_method=None, reduces=True, update_fields=None):
return sum(
self.batched_update(
qs,
update_method,
reduces,
update_fields))
| 3,618
|
Python
|
.py
| 103
| 23.592233
| 81
| 0.531848
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,632
|
log.py
|
translate_pootle/pootle/core/log.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
# Log actions
STORE_ADDED = 'SA'
STORE_OBSOLETE = 'SO'
STORE_RESURRECTED = 'SR'
STORE_DELETED = 'SD'
CMD_EXECUTED = 'X'
SCORE_CHANGED = 'SC'
def cmd_log(*args, **kwargs):
import os
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pootle.settings')
fn = settings.LOGGING.get('handlers').get('log_action').get('filename')
dft = settings.LOGGING.get('formatters').get('action').get('datefmt')
with open(fn, 'a') as logfile:
cmd = ' '.join(args)
message = "%(user)s\t%(action)s\t%(cmd)s" % {
'user': 'system',
'action': CMD_EXECUTED,
'cmd': cmd
}
from datetime import datetime
now = datetime.now()
d = {
'message': message,
'asctime': now.strftime(dft)
}
logfile.write("[%(asctime)s]\t%(message)s\n" % d)
def store_log(*args, **kwargs):
logger = logging.getLogger('action')
d = {}
for p in ['user', 'path', 'action', 'store']:
d[p] = kwargs.pop(p, '')
message = "%(user)s\t%(action)s\t%(path)s\t%(store)s" % d
logger.debug(message)
| 1,441
|
Python
|
.py
| 42
| 28.785714
| 77
| 0.616606
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,633
|
initdb.py
|
translate_pootle/pootle/core/initdb.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from django.utils.translation import ugettext_noop as _
from pootle.core.contextmanagers import keep_data
from pootle.core.models import Revision
from pootle.core.signals import update_revisions
from pootle_app.models import Directory
from pootle_app.models.permissions import PermissionSet, get_pootle_permission
from pootle_format.models import Format
from pootle_fs.utils import FSPlugin
from pootle_language.models import Language
from pootle_project.models import Project
from staticpages.models import StaticPage as Announcement
logger = logging.getLogger(__name__)
class InitDB(object):
def init_db(self, create_projects=True):
with transaction.atomic():
with keep_data(signals=(update_revisions, )):
self._init_db(create_projects)
def _init_db(self, create_projects=True):
"""Populate the database with default initial data.
This creates the default database to get a working Pootle installation.
"""
self.create_formats()
self.create_revision()
self.create_essential_users()
self.create_root_directories()
self.create_template_languages()
self.create_default_languages()
if create_projects:
self.create_terminology_project()
self.create_pootle_permissions()
self.create_pootle_permission_sets()
if create_projects:
self.create_default_projects()
def create_formats(self):
from pootle.core.delegate import formats
formats.get().initialize()
def _create_object(self, model_klass, **criteria):
instance, created = model_klass.objects.get_or_create(**criteria)
if created:
logger.debug(
"Created %s: '%s'",
instance.__class__.__name__, instance)
else:
logger.debug(
"%s already exists - skipping: '%s'",
instance.__class__.__name__, instance)
return instance, created
def _create_pootle_user(self, **criteria):
user, created = self._create_object(get_user_model(), **criteria)
if created:
user.set_unusable_password()
user.save()
return user
def _create_pootle_permission_set(self, permissions, **criteria):
permission_set, created = self._create_object(PermissionSet,
**criteria)
if created:
permission_set.positive_permissions.set(permissions)
permission_set.save()
return permission_set
def create_revision(self):
Revision.initialize()
def create_essential_users(self):
"""Create the 'default' and 'nobody' User instances.
These users are required for Pootle's permission system.
"""
# The nobody user is used to represent an anonymous user in cases
# where we need to associate model information with such a user. An
# example is in the permission system: we need a way to store rights
# for anonymous users; thus we use the nobody user.
criteria = {
'username': u"nobody",
'full_name': u"any anonymous user",
'is_active': True,
}
self._create_pootle_user(**criteria)
# The 'default' user represents any valid, non-anonymous user and is
# used to associate information any such user. An example is in the
# permission system: we need a way to store default rights for users.
# We use the 'default' user for this.
#
# In a future version of Pootle we should think about using Django's
# groups to do better permissions handling.
criteria = {
'username': u"default",
'full_name': u"any authenticated user",
'is_active': True,
}
self._create_pootle_user(**criteria)
def create_pootle_permissions(self):
"""Create Pootle's directory level permissions."""
args = {
'app_label': "pootle_app",
'model': "directory",
}
pootle_content_type = self._create_object(ContentType, **args)[0]
pootle_content_type.save()
# Create the permissions.
permissions = [
{
'name': _("Can access a project"),
'codename': "view",
},
{
'name': _("Cannot access a project"),
'codename': "hide",
},
{
'name': _("Can make a suggestion for a translation"),
'codename': "suggest",
},
{
'name': _("Can submit a translation"),
'codename': "translate",
},
{
'name': _("Can review suggestions"),
'codename': "review",
},
{
'name': _("Can perform administrative tasks"),
'codename': "administrate",
},
]
criteria = {
'content_type': pootle_content_type,
}
for permission in permissions:
criteria.update(permission)
self._create_object(Permission, **criteria)
def create_pootle_permission_sets(self):
"""Create the default permission set for the 'nobody' and 'default' users.
'nobody' is the anonymous (non-logged in) user, and 'default' is the
logged in user.
"""
User = get_user_model()
nobody = User.objects.get(username='nobody')
default = User.objects.get(username='default')
view = get_pootle_permission('view')
suggest = get_pootle_permission('suggest')
translate = get_pootle_permission('translate')
# Default permissions for tree root.
criteria = {
'user': nobody,
'directory': Directory.objects.root,
}
self._create_pootle_permission_set([view, suggest], **criteria)
criteria['user'] = default
self._create_pootle_permission_set(
[view, suggest, translate], **criteria)
# Default permissions for templates language.
# Override with no permissions for templates language.
criteria = {
'user': nobody,
'directory': Directory.objects.get(pootle_path="/templates/"),
}
self._create_pootle_permission_set([], **criteria)
criteria['user'] = default
self._create_pootle_permission_set([], **criteria)
def require_english(self):
"""Create the English Language item."""
criteria = {
'code': "en",
'fullname': u"English",
'nplurals': 2,
'pluralequation': "(n != 1)",
}
en = self._create_object(Language, **criteria)[0]
return en
def create_root_directories(self):
"""Create the root Directory items."""
root = self._create_object(Directory, **dict(name=""))[0]
self._create_object(Directory, **dict(name="projects", parent=root))
def create_template_languages(self):
"""Create the 'templates' and English languages.
The 'templates' language is used to give users access to the
untranslated template files.
"""
self._create_object(
Language, **dict(code="templates", fullname="Templates"))
self.require_english()
def create_terminology_project(self):
"""Create the terminology project.
The terminology project is used to display terminology suggestions
while translating.
"""
criteria = {
'code': "terminology",
'fullname': u"Terminology",
'source_language': self.require_english(),
'checkstyle': "terminology",
}
po = Format.objects.get(name="po")
terminology = self._create_object(Project, **criteria)[0]
terminology.filetypes.add(po)
terminology.config["pootle_fs.fs_type"] = "localfs"
terminology.config["pootle_fs.fs_url"] = (
"{POOTLE_TRANSLATION_DIRECTORY}%s"
% terminology.code)
terminology.config["pootle_fs.translation_mappings"] = dict(
default="/<language_code>/<dir_path>/<filename>.<ext>")
plugin = FSPlugin(terminology)
plugin.fetch()
plugin.add()
plugin.sync()
def create_default_projects(self):
"""Create the default projects that we host.
You might want to add your projects here, although you can also add
things through the web interface later.
"""
en = self.require_english()
po = Format.objects.get(name="po")
criteria = {
'code': u"tutorial",
'source_language': en,
'fullname': u"Tutorial",
'checkstyle': "standard"}
tutorial = self._create_object(Project, **criteria)[0]
tutorial.filetypes.add(po)
tutorial.config["pootle_fs.fs_type"] = "localfs"
tutorial.config["pootle_fs.fs_url"] = (
"{POOTLE_TRANSLATION_DIRECTORY}%s"
% tutorial.code)
tutorial.config["pootle_fs.translation_mappings"] = dict(
default="/<language_code>/<dir_path>/<filename>.<ext>")
plugin = FSPlugin(tutorial)
plugin.fetch()
plugin.add()
plugin.sync()
criteria = {
'active': True,
'title': "Project instructions",
'body': (
'Tutorial project where users can play with Pootle and learn '
'more about translation and localisation.\n'
'\n'
'For more help on localisation, visit the [localization '
'guide](http://docs.translatehouse.org/projects/'
'localization-guide/en/latest/guide/start.html).'),
'virtual_path': "announcements/projects/"+tutorial.code,
}
self._create_object(Announcement, **criteria)
def create_default_languages(self):
"""Create the default languages."""
from translate.lang import data, factory
# import languages from toolkit
for code in data.languages.keys():
ttk_lang = factory.getlanguage(code)
criteria = {
'code': code,
'fullname': ttk_lang.fullname,
'nplurals': ttk_lang.nplurals,
'pluralequation': ttk_lang.pluralequation}
if hasattr(ttk_lang, "specialchars"):
criteria['specialchars'] = ttk_lang.specialchars
self._create_object(Language, **criteria)
| 11,174
|
Python
|
.py
| 268
| 31.552239
| 82
| 0.600534
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,634
|
paths.py
|
translate_pootle/pootle/core/paths.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pathlib
import posixpath
from hashlib import md5
from django.utils.encoding import force_bytes
from pootle.core.decorators import persistent_property
from pootle.core.delegate import revision
class Paths(object):
def __init__(self, context, q, show_all=False):
self.context = context
self.q = q
self.show_all = show_all
@property
def rev_cache_key(self):
return revision.get(
self.context.directory.__class__)(
self.context.directory).get(key="stats")
@property
def cache_key(self):
return (
"%s.%s.%s"
% (md5(force_bytes(self.q)).hexdigest(),
self.rev_cache_key,
self.show_all))
@property
def store_qs(self):
raise NotImplementedError
@property
def stores(self):
stores = self.store_qs.exclude(obsolete=True)
if not self.show_all:
stores = stores.exclude(
translation_project__project__disabled=True)
return stores.exclude(is_template=True).filter(
tp_path__contains=self.q).order_by()
@persistent_property
def paths(self):
stores = set(
st[1:]
for st
in self.stores.values_list("tp_path", flat=True))
dirs = set()
for store in stores:
if posixpath.dirname(store) in dirs:
continue
dirs = (
dirs
| (set(
"%s/" % str(p)
for p
in pathlib.PosixPath(store).parents
if str(p) != ".")))
return sorted(
dirs | stores,
key=lambda path: (posixpath.dirname(path), posixpath.basename(path)))
| 2,057
|
Python
|
.py
| 61
| 24.639344
| 81
| 0.584887
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,635
|
exceptions.py
|
translate_pootle/pootle/core/exceptions.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
class Http400(Exception):
pass
class MissingPluginError(KeyError):
pass
class NotConfiguredError(KeyError):
pass
class MissingHandlerError(KeyError):
pass
| 454
|
Python
|
.py
| 15
| 27.666667
| 77
| 0.772622
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,636
|
contextmanagers.py
|
translate_pootle/pootle/core/contextmanagers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import threading
import types
from contextlib import contextmanager, nested
from django.dispatch import Signal, receiver
from pootle.core.signals import (
create, delete, update, update_checks, update_data, update_revisions,
update_scores)
class BulkUpdated(object):
create = None
delete_qs = None
delete = None
delete_ids = None
update_qs = None
update = None
updates = None
update_fields = None
update_objects = None
@contextmanager
def suppress_signal(signal, suppress=None):
lock = threading.Lock()
suppressed_thread = threading.current_thread().ident
_orig_send = signal.send
_orig_connect = signal.connect
temp_signal = Signal()
def _should_suppress(*args, **kwargs):
sender = args[0] if args else kwargs.get("sender")
return (
threading.current_thread().ident == suppressed_thread
and (not suppress
or not sender
or sender in suppress))
def suppressed_send(self, *args, **kwargs):
return (
_orig_send(*args, **kwargs)
if not _should_suppress(*args, **kwargs)
else temp_signal.send(*args, **kwargs))
def suppressed_connect(self, func, *args, **kwargs):
return (
_orig_connect(func, *args, **kwargs)
if not _should_suppress(*args, **kwargs)
else temp_signal.connect(func, *args, **kwargs))
with lock:
signal.send = types.MethodType(suppressed_send, signal)
signal.connect = types.MethodType(suppressed_connect, signal)
try:
yield
finally:
with lock:
signal.send = _orig_send
signal.connect = _orig_connect
@contextmanager
def keep_data(keep=True, signals=None, suppress=None):
signals = (
signals
or (update_checks,
update_data,
update_revisions,
update_scores))
if keep:
with nested(*[suppress_signal(s, suppress) for s in signals]):
yield
else:
yield
def _create_handler(updated, **kwargs):
to_create = kwargs.get("objects") or []
to_create += (
[kwargs.get("instance")]
if kwargs.get("instance")
else [])
if to_create:
updated.create = (updated.create or []) + to_create
def _delete_handler(updated, **kwargs):
if "objects" in kwargs:
if updated.delete_qs is None:
updated.delete_qs = kwargs["objects"]
else:
updated.delete_qs = (
updated.delete_qs
| kwargs["objects"])
if "instance" in kwargs:
if updated.delete_ids is None:
updated.delete_ids = set()
updated.delete_ids.add(kwargs["instance"].pk)
def _update_handler(updated, **kwargs):
if kwargs.get("update_fields"):
if updated.update_fields is None:
updated.update_fields = set()
# update these fields (~only)
updated.update_fields = (
updated.update_fields
| set(kwargs["update_fields"]))
if "updates" in kwargs:
# dict of pk: dict(up=date)
updated.updates = (
kwargs["updates"]
if updated.updates is None
else (updated.updates.update(kwargs["updates"])
or updated.updates))
if "objects" in kwargs:
updated.update_objects = (
kwargs["objects"]
if updated.update_objects is None
else (updated.update_objects
+ kwargs["objects"]))
if "instance" in kwargs:
updated.update_objects = (
[kwargs["instance"]]
if updated.update_objects is None
else (updated.update_objects
+ [kwargs["instance"]]))
def _callback_handler(model, updated):
# delete
to_delete = None
if updated.delete_ids is not None:
to_delete = model.objects.filter(
pk__in=updated.delete_ids)
if updated.delete_qs is not None:
to_delete = (
updated.delete_qs
if to_delete is None
else to_delete | updated.delete_qs)
if to_delete is not None:
delete.send(
model,
objects=to_delete)
# create
if updated.create is not None:
create.send(
model,
objects=updated.create)
# update
should_update = (
updated.update_objects is not None
or updated.updates is not None)
if should_update:
update.send(
model,
objects=updated.update_objects,
updates=updated.updates,
update_fields=updated.update_fields)
@contextmanager
def bulk_context(model=None, **kwargs):
updated = BulkUpdated()
signals = [create, delete, update]
create_handler = kwargs.pop("create", _create_handler)
delete_handler = kwargs.pop("delete", _delete_handler)
update_handler = kwargs.pop("update", _update_handler)
callback_handler = kwargs.pop("callback", _callback_handler)
with keep_data(signals=signals, suppress=(model, )):
@receiver(create, sender=model)
def handle_create(**kwargs):
create_handler(updated, **kwargs)
@receiver(delete, sender=model)
def handle_delete(**kwargs):
delete_handler(updated, **kwargs)
@receiver(update, sender=model)
def handle_update(**kwargs):
update_handler(updated, **kwargs)
yield
callback_handler(model, updated)
@contextmanager
def bulk_operations(model=None, models=None, **kwargs):
if models is None and model is not None:
models = [model]
with nested(*(bulk_context(m, **kwargs) for m in models)):
yield
| 6,041
|
Python
|
.py
| 173
| 26.751445
| 77
| 0.614976
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,637
|
primitives.py
|
translate_pootle/pootle/core/primitives.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
class PrefixedDict(object):
def __init__(self, context, prefix):
self.__context = context
self.__prefix = prefix
def __getitem__(self, k):
return self.__context["%s%s" % (self.__prefix, k)]
def __setitem__(self, k, v):
self.__context["%s%s" % (self.__prefix, k)] = v
def get(self, k, default=None):
try:
return self.__context["%s%s" % (self.__prefix, k)]
except KeyError:
return default
| 756
|
Python
|
.py
| 20
| 32.1
| 77
| 0.617808
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,638
|
helpers.py
|
translate_pootle/pootle/core/helpers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.utils import dateformat
SIDEBAR_COOKIE_NAME = 'pootle-browser-sidebar'
def get_sidebar_announcements_context(request, objects):
"""Return the announcements context for the browser pages sidebar.
:param request: a :cls:`django.http.HttpRequest` object.
:param objects: a tuple of Project, Language and TranslationProject to
retrieve the announcements for. Any of those can be
missing, but it is recommended for them to be in that exact
order.
"""
must_show_announcement = False
announcements = []
if SIDEBAR_COOKIE_NAME in request.COOKIES:
try:
is_sidebar_open = bool(int(request.COOKIES[SIDEBAR_COOKIE_NAME]))
except ValueError:
is_sidebar_open = True
request.session['is_sidebar_open'] = is_sidebar_open
else:
is_sidebar_open = request.session.get('is_sidebar_open', True)
for item in objects:
announcement = item.get_announcement(request.user)
if announcement is None:
continue
announcements.append(announcement)
if request.user.is_anonymous:
# Do not store announcement mtimes for anonymous user.
continue
ann_mtime = dateformat.format(announcement.modified_on, 'U')
stored_mtime = request.session.get(announcement.virtual_path, None)
if ann_mtime != stored_mtime:
# Some announcement has been changed or was never displayed before,
# so display sidebar and save the changed mtimes in the session to
# not display it next time unless it is necessary.
must_show_announcement = True
request.session[announcement.virtual_path] = ann_mtime
ctx = {
'announcements': announcements,
'is_sidebar_open': must_show_announcement or is_sidebar_open,
'has_sidebar': len(announcements) > 0,
}
return ctx
| 2,236
|
Python
|
.py
| 49
| 37.367347
| 79
| 0.673422
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,639
|
url_helpers.py
|
translate_pootle/pootle/core/url_helpers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import re
import urllib
import urlparse
from django.urls import reverse
def split_pootle_path(pootle_path):
"""Split an internal `pootle_path` into proper parts.
:return: A tuple containing each part of a pootle_path`::
(language code, project code, directory path, filename)
"""
slash_count = pootle_path.count(u'/')
parts = pootle_path.split(u'/', 3)[1:]
language_code = None
project_code = None
ctx = ''
if slash_count != 0 and pootle_path != '/projects/':
# /<lang_code>/
if slash_count == 2:
language_code = parts[0]
# /projects/<project_code>/
elif pootle_path.startswith('/projects/'):
project_code = parts[1]
ctx = parts[2]
# /<lang_code>/<project_code>/*
elif slash_count != 1:
language_code = parts[0]
project_code = parts[1]
ctx = parts[2]
dir_path, filename = os.path.split(ctx)
if dir_path:
dir_path = u'/'.join([dir_path, '']) # Add trailing slash
return (language_code, project_code, dir_path, filename)
def to_tp_relative_path(pootle_path):
"""Returns a path relative to translation projects.
If `pootle_path` is `/af/project/dir1/dir2/file.po`, this will
return `dir1/dir2/file.po`.
"""
return u'/'.join(pootle_path.split(u'/')[3:])
def get_path_parts(path):
"""Returns a list of `path`'s parent paths plus `path`."""
if not path:
return []
parent = os.path.split(path)[0]
parent_parts = parent.split(u'/')
if len(parent_parts) == 1 and parent_parts[0] == u'':
parts = []
else:
parts = [u'/'.join(parent_parts[:parent_parts.index(part) + 1] + [''])
for part in parent_parts]
# If present, don't forget to include the filename
if path not in parts:
parts.append(path)
# Everything has a root
parts.insert(0, u'')
return parts
def get_editor_filter(state=None, check=None, user=None, month=None,
sort=None, search=None, sfields=None,
check_category=None):
"""Return a filter string to be appended to a translation URL."""
filter_string = ''
if state is not None:
filter_string = '#filter=%s' % state
if user is not None:
filter_string += '&user=%s' % user
if month is not None:
filter_string += '&month=%s' % month
elif check is not None:
filter_string = '#filter=checks&checks=%s' % check
elif check_category is not None:
filter_string = '#filter=checks&category=%s' % check_category
elif search is not None:
filter_string = '#search=%s' % urllib.quote_plus(search)
if sfields is not None:
if not isinstance(sfields, list):
sfields = [sfields]
filter_string += '&sfields=%s' % ','.join(sfields)
if sort is not None:
if filter_string:
filter_string += '&sort=%s' % sort
else:
filter_string = '#sort=%s' % sort
return filter_string
def get_previous_url(request):
"""Returns the current domain's referer URL.
It also discards any URLs that might come from translation editor
pages, assuming that any URL path containing `/translate/` refers to
an editor instance.
If none of the conditions are met, the URL of the app's home is
returned.
:param request: Django's request object.
"""
referer_url = request.META.get('HTTP_REFERER', '')
if referer_url:
parsed_referer = urlparse.urlparse(referer_url)
referer_host = parsed_referer.netloc
referer_path = parsed_referer.path
referer_query = parsed_referer.query
server_host = request.get_host()
if referer_host == server_host and '/translate/' not in referer_path:
# Remove query string if present
if referer_query:
referer_url = referer_url[:referer_url.index('?')]
# But ensure `?details` is not missed out
if 'details' in referer_query:
referer_url = '%s?details' % referer_url
return referer_url
return reverse('pootle-home')
def urljoin(base, *url_parts):
"""Joins URL parts with a `base` and removes any duplicated slashes in
`url_parts`.
"""
new_url = urlparse.urljoin(base, '/'.join(url_parts))
new_url = list(urlparse.urlparse(new_url))
new_url[2] = re.sub('/{2,}', '/', new_url[2])
return urlparse.urlunparse(new_url)
| 4,854
|
Python
|
.py
| 122
| 32.377049
| 78
| 0.619595
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,640
|
decorators.py
|
translate_pootle/pootle/core/decorators.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
import time
from functools import wraps
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from pootle.i18n.gettext import ugettext as _
from pootle_app.models.permissions import (check_permission,
get_matching_permissions)
from pootle_project.models import Project, ProjectSet
from .cache import get_cache
from .exceptions import Http400
from .url_helpers import split_pootle_path
logger = logging.getLogger(__name__)
CLS2ATTR = {
'TranslationProject': 'translation_project',
'Project': 'project',
'Language': 'language',
}
def get_path_obj(func):
from pootle_language.models import Language
from pootle_translationproject.models import TranslationProject
@wraps(func)
def wrapped(request, *args, **kwargs):
if request.is_ajax():
pootle_path = request.GET.get('path', None)
if pootle_path is None:
raise Http400(_('Arguments missing.'))
language_code, project_code, dir_path, filename = \
split_pootle_path(pootle_path)
kwargs['dir_path'] = dir_path
kwargs['filename'] = filename
# Remove potentially present but unwanted args
try:
del kwargs['language_code']
del kwargs['project_code']
except KeyError:
pass
else:
language_code = kwargs.pop('language_code', None)
project_code = kwargs.pop('project_code', None)
if language_code and project_code:
try:
path_obj = TranslationProject.objects.get_for_user(
user=request.user,
language_code=language_code,
project_code=project_code,
)
except TranslationProject.DoesNotExist:
path_obj = None
if path_obj is None:
if not request.is_ajax():
# Explicit selection via the UI: redirect either to
# ``/language_code/`` or ``/projects/project_code/``
user_choice = request.COOKIES.get('user-choice', None)
if user_choice and user_choice in ('language', 'project',):
url = {
'language': reverse('pootle-language-browse',
args=[language_code]),
'project': reverse('pootle-project-browse',
args=[project_code, '', '']),
}
response = redirect(url[user_choice])
response.delete_cookie('user-choice')
return response
raise Http404
elif language_code:
user_projects = Project.accessible_by_user(request.user)
language = get_object_or_404(Language, code=language_code)
children = language.children \
.filter(project__code__in=user_projects)
language.set_children(children)
path_obj = language
elif project_code:
try:
path_obj = Project.objects.get_for_user(project_code,
request.user)
except Project.DoesNotExist:
raise Http404
else: # No arguments: all user-accessible projects
user_projects = Project.objects.for_user(request.user)
path_obj = ProjectSet(user_projects)
request.ctx_obj = path_obj
request.ctx_path = path_obj.pootle_path
request.resource_obj = path_obj
request.pootle_path = path_obj.pootle_path
return func(request, path_obj, *args, **kwargs)
return wrapped
def permission_required(permission_code):
"""Checks for `permission_code` in the current context.
To retrieve the proper context, the `get_path_obj` decorator must be
used along with this decorator.
"""
def wrapped(func):
@wraps(func)
def _wrapped(request, *args, **kwargs):
path_obj = args[0]
directory = getattr(path_obj, 'directory', path_obj)
# HACKISH: some old code relies on
# `request.translation_project`, `request.language` etc.
# being set, so we need to set that too.
attr_name = CLS2ATTR.get(path_obj.__class__.__name__,
'path_obj')
setattr(request, attr_name, path_obj)
request.permissions = get_matching_permissions(request.user,
directory)
if not permission_code:
return func(request, *args, **kwargs)
if not check_permission(permission_code, request):
raise PermissionDenied(
_("Insufficient rights to access this page."),
)
return func(request, *args, **kwargs)
return _wrapped
return wrapped
def admin_required(func):
@wraps(func)
def wrapped(request, *args, **kwargs):
if not request.user.is_superuser:
raise PermissionDenied(
_("You do not have rights to administer Pootle.")
)
return func(request, *args, **kwargs)
return wrapped
class persistent_property(object):
"""
Similar to cached_property, except it caches in the memory cache rather
than on the instance if possible.
By default it will look on the class for an attribute `cache_key` to get
the class cache_key. The attribute can be changed by setting the `key_attr`
parameter in the decorator.
The class cache_key is combined with the name of the decorated property
to get the final cache_key for the property.
If no cache_key attribute is present or returns None, it will use instance
caching by default. This behaviour can be switched off by setting
`always_cache` to False in the decorator.
"""
def __init__(self, func, name=None, key_attr=None, always_cache=True,
ns_attr=None, version_attr=None):
self.func = func
self.__doc__ = getattr(func, '__doc__')
self.name = name or func.__name__
self.ns_attr = ns_attr or "ns"
self.key_attr = key_attr or "cache_key"
self.version_attr = version_attr or "sw_version"
self.always_cache = always_cache
def _get_cache_key(self, instance):
ns = getattr(instance, self.ns_attr, "pootle.core")
sw_version = getattr(instance, self.version_attr, "")
cache_key = getattr(instance, self.key_attr, None)
if cache_key:
return (
"%s.%s.%s.%s"
% (ns, sw_version, cache_key, self.name))
def __get__(self, instance, cls=None):
if instance is None:
return self
cache_key = self._get_cache_key(instance)
if cache_key:
cache = get_cache('lru')
cached = cache.get(cache_key)
if cached is not None:
# cache hit
return cached
# cache miss
start = time.time()
res = self.func(instance)
timetaken = time.time() - start
cache.set(cache_key, res)
logger.debug(
"[cache] generated %s in %s seconds",
cache_key, timetaken)
return res
elif self.always_cache:
res = instance.__dict__[self.name] = self.func(instance)
return res
return self.func(instance)
| 8,109
|
Python
|
.py
| 185
| 31.821622
| 79
| 0.581103
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,641
|
forms.py
|
translate_pootle/pootle/core/forms.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import base64
import json
import logging
import re
import time
from hashlib import sha1
from random import randint
from django import forms
from django.conf import settings
from django.core.paginator import Paginator
from django.core.validators import MinLengthValidator
from django.utils.safestring import mark_safe
from pootle.core.delegate import paths
from pootle.i18n.gettext import ugettext as _, ugettext_lazy
from .utils.json import jsonify
class PathsSearchForm(forms.Form):
step = 20
q = forms.CharField(max_length=255)
page = forms.IntegerField(required=False)
def __init__(self, *args, **kwargs):
self.context = kwargs.pop("context")
min_length = kwargs.pop("min_length", 3)
super(PathsSearchForm, self).__init__(*args, **kwargs)
validators = [
v for v in self.fields['q'].validators
if not isinstance(v, MinLengthValidator)]
validators.append(MinLengthValidator(min_length))
self.fields["q"].validators = validators
@property
def paths_util(self):
return paths.get(self.context.__class__)
def search(self, *la, **kwa):
q = self.cleaned_data["q"]
page = self.cleaned_data["page"] or 1
offset = (page - 1) * self.step
results = self.paths_util(
self.context,
q,
show_all=kwa.get("show_all", False)).paths
return dict(
more_results=len(results) > (offset + self.step),
results=results[offset:offset + self.step])
# MathCaptchaForm Copyright (c) 2007, Dima Dogadaylo (www.mysoftparade.com)
# Copied from http://djangosnippets.org/snippets/506/
# GPL compatible According to djangosnippets terms and conditions
class MathCaptchaForm(forms.Form):
"""Lightweight mathematical captcha where human is asked to solve
a simple mathematical calculation like 3+5=?. It don't use database
and don't require external libraries.
From concatenation of time, question, answer, settings.SITE_URL and
settings.SECRET_KEY is built hash that is validated on each form
submission. It makes impossible to "record" valid captcha form
submission and "replay" it later - form will not be validated
because captcha will be expired.
For more info see:
http://www.mysoftparade.com/blog/improved-mathematical-captcha/
"""
A_RE = re.compile("^(\d+)$")
captcha_answer = forms.CharField(
max_length=2, required=True,
widget=forms.TextInput(attrs={'size': '2'}), label='')
captcha_token = forms.CharField(max_length=200, required=True,
widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
"""Initalise captcha_question and captcha_token for the form."""
super(MathCaptchaForm, self).__init__(*args, **kwargs)
# reset captcha for unbound forms
if not self.data:
self.reset_captcha()
def reset_captcha(self):
"""Generate new question and valid token for it, reset previous answer
if any.
"""
q, a = self._generate_captcha()
expires = time.time() + \
getattr(settings, 'CAPTCHA_EXPIRES_SECONDS', 60*60)
token = self._make_token(q, a, expires)
self.initial['captcha_token'] = token
self._plain_question = q
# reset captcha fields for bound form
if self.data:
def _reset():
self.data['captcha_token'] = token
self.data['captcha_answer'] = ''
if hasattr(self.data, '_mutable') and not self.data._mutable:
self.data._mutable = True
_reset()
self.data._mutable = False
else:
_reset()
self.fields['captcha_answer'].label = mark_safe(self.knotty_question)
def _generate_captcha(self):
"""Generate question and return it along with correct answer."""
a, b = randint(1, 9), randint(1, 9)
return ("%s+%s" % (a, b), a+b)
def _make_token(self, q, a, expires):
data = base64.urlsafe_b64encode(jsonify({'q': q, 'expires': expires}))
return self._sign(q, a, expires) + data
def _sign(self, q, a, expires):
plain = [getattr(settings, 'SITE_URL', ''), settings.SECRET_KEY,
q, a, expires]
plain = "".join([str(p) for p in plain])
return sha1(plain).hexdigest()
@property
def plain_question(self):
return self._plain_question
@property
def knotty_question(self):
"""Wrap plain_question in some invisibe for humans markup with random
nonexisted classes, that makes life of spambots a bit harder because
form of question is vary from request to request.
"""
digits = self._plain_question.split('+')
return "+".join(['<span class="captcha-random-%s">%s</span>' %
(randint(1, 9), d) for d in digits])
def clean_captcha_token(self):
t = self._parse_token(self.cleaned_data['captcha_token'])
if time.time() > t['expires']:
raise forms.ValidationError(_("Time to answer has expired"))
self._plain_question = t['q']
return t
def _parse_token(self, t):
try:
sign, data = t[:40], t[40:]
data = json.loads(base64.urlsafe_b64decode(str(data)))
return {'q': data['q'],
'expires': float(data['expires']),
'sign': sign}
except Exception as e:
logging.info("Captcha error: %r", e)
# l10n for bots? Rather not
raise forms.ValidationError("Invalid captcha!")
def clean_captcha_answer(self):
a = self.A_RE.match(self.cleaned_data.get('captcha_answer'))
if not a:
raise forms.ValidationError(_("Enter a number"))
return int(a.group(0))
def clean(self):
"""Check captcha answer."""
cd = self.cleaned_data
# don't check captcha if no answer
if 'captcha_answer' not in cd:
return cd
t = cd.get('captcha_token')
if t:
form_sign = self._sign(t['q'], cd['captcha_answer'],
t['expires'])
if form_sign != t['sign']:
self._errors['captcha_answer'] = [_("Incorrect")]
else:
self.reset_captcha()
return super(MathCaptchaForm, self).clean()
class PaginatingForm(forms.Form):
page_field = "page_no"
per_page_field = "results_per_page"
page_no = forms.IntegerField(
required=False,
initial=1,
min_value=1,
max_value=100)
results_per_page = forms.IntegerField(
required=False,
initial=10,
min_value=10,
max_value=100,
widget=forms.NumberInput(attrs=dict(step=10)))
class FormWithActionsMixin(forms.Form):
action_choices = ()
action_field = "actions"
comment_field = "comment"
select_all_field = "select_all"
actions = forms.ChoiceField(
required=False,
label=ugettext_lazy("With selected"),
widget=forms.Select(attrs={'class': 'js-select2'}),
choices=(
("", "----"),
("reject", _("Reject")),
("accept", _("Accept"))))
comment = forms.CharField(
label=ugettext_lazy("Add comment"),
required=False,
widget=forms.Textarea(attrs=dict(rows=2)))
select_all = forms.BooleanField(
required=False,
label=ugettext_lazy(
"Select all items matching filter criteria, including those not "
"shown"),
widget=forms.CheckboxInput(
attrs={"class": "js-formtable-select-all"}))
def __init__(self, *args, **kwargs):
super(FormWithActionsMixin, self).__init__(*args, **kwargs)
if self.comment_field != "comment":
del self.fields["comment"]
self.fields[self.action_field].choices = self.action_choices
def should_save(self):
return (
self.is_valid()
and self.cleaned_data.get(self.action_field)
and self.cleaned_data.get(self.search_field))
class FormtableForm(PaginatingForm, FormWithActionsMixin):
search_field = None
msg_err_no_action = _("You must specify an action to take")
msg_err_no_search_field = _("A valid search field must be specified")
def __init__(self, *args, **kwargs):
super(FormtableForm, self).__init__(*args, **kwargs)
if not self.search_field or self.search_field not in self.fields:
raise ValueError(self.msg_err_no_search_field)
self._search_filters = {}
self._results_per_page = self.fields[self.per_page_field].initial
self._page_no = self.fields[self.page_field].initial
@property
def filter_fields(self):
return [k for k in self.fields if k.startswith("filter_")]
def count_choices(self, choices):
return choices.count()
def clean(self):
if self.per_page_field in self.errors:
del self.errors[self.per_page_field]
self.cleaned_data[self.per_page_field] = (
self.fields[self.per_page_field].initial)
if self.page_field in self.errors:
del self.errors[self.page_field]
self.cleaned_data[self.page_field] = (
self.fields[self.page_field].initial)
# set the page_no if not set
self.cleaned_data[self.page_field] = (
self.cleaned_data.get(self.page_field)
or self.fields[self.page_field].initial)
# set the results_per_page if not set
self.cleaned_data[self.per_page_field] = (
self.cleaned_data.get(self.per_page_field)
or self.fields[self.per_page_field].initial)
# if you select members of the search_field or check
# select_all, you must specify an action
missing_action = (
(self.cleaned_data[self.search_field]
or self.cleaned_data[self.select_all_field])
and not self.cleaned_data[self.action_field])
if missing_action:
self.add_error(
self.action_field,
forms.ValidationError(self.msg_err_no_action))
self._search_filters = {
k: v
for k, v in self.cleaned_data.items()
if k in self.filter_fields}
# limit the search_field queryset to criteria
self.fields[self.search_field].queryset = self.search()
# validate and update the pagination if required
should_validate_pagination = (
(self.cleaned_data[self.page_field]
!= self.fields[self.page_field].initial
or (self.cleaned_data[self.per_page_field]
!= self.fields[self.per_page_field].initial)))
if should_validate_pagination:
self.cleaned_data[self.per_page_field] = (
self.cleaned_data[self.per_page_field]
- self.cleaned_data[self.per_page_field] % 10)
self._page_no = self.valid_page_no(
self.fields[self.search_field].queryset,
self.cleaned_data[self.page_field],
self.cleaned_data[self.per_page_field])
self.cleaned_data[self.page_field] = self._page_no
should_update_data = (
self.page_field in self.data
and self.data[self.page_field] != self._page_no)
if should_update_data:
# update the initial if necessary
self.data = self.data.copy()
self.data[self.page_field] = self._page_no
self._page_no = self.cleaned_data[self.page_field]
self._results_per_page = self.cleaned_data[self.per_page_field]
def valid_page_no(self, choices, page_no, results_per_page):
max_page = (
self.count_choices(choices)
/ float(results_per_page))
# add an extra page if number of choices is not divisible
max_page = (
int(max_page) + 1
if not max_page.is_integer()
else int(max_page))
# ensure page_no is within range 1 - max
return max(1, min(page_no, max_page))
def search(self):
"""Filter the total queryset for the search_field using
any filter_field criteria
"""
self.is_valid()
return self.fields[self.search_field].queryset
def batch(self):
self.is_valid()
paginator = Paginator(
self.fields[self.search_field].queryset,
self._results_per_page)
return paginator.page(self._page_no)
| 12,988
|
Python
|
.py
| 303
| 33.462046
| 78
| 0.610795
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,642
|
delegate.py
|
translate_pootle/pootle/core/delegate.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.plugin.delegate import Getter, Provider
config = Getter(providing_args=["instance"])
search_backend = Getter(providing_args=["instance"])
lang_mapper = Getter(providing_args=["instance"])
state = Getter()
response = Getter()
check_updater = Getter()
comparable_event = Getter()
contributors = Getter()
crud = Getter()
display = Getter()
event_score = Provider()
event_formatters = Provider()
formats = Getter()
format_registration = Provider()
format_classes = Provider()
format_diffs = Provider()
format_updaters = Provider()
format_syncers = Provider()
frozen = Getter()
filetype_tool = Getter()
grouped_events = Getter()
lifecycle = Getter()
log = Getter()
stemmer = Getter()
site_languages = Getter()
terminology = Getter()
terminology_matcher = Getter()
tp_tool = Getter()
data_tool = Getter()
data_updater = Getter()
language_code = Getter()
language_team = Getter()
membership = Getter()
paths = Getter()
profile = Getter()
review = Getter()
revision = Getter()
revision_updater = Getter()
scores = Getter()
score_updater = Getter()
site = Getter()
states = Getter()
stopwords = Getter()
text_comparison = Getter()
panels = Provider()
serializers = Provider(providing_args=["instance"])
deserializers = Provider(providing_args=["instance"])
subcommands = Provider()
uniqueid = Getter()
unitid = Provider()
url_patterns = Provider()
wordcount = Getter()
# view.context_data
context_data = Provider(providing_args=["view", "context"])
upstream = Provider()
versioned = Getter()
| 1,782
|
Python
|
.py
| 64
| 26.734375
| 77
| 0.755698
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,643
|
http.py
|
translate_pootle/pootle/core/http.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.http import HttpResponse
from .utils.json import jsonify
class JsonResponse(HttpResponse):
"""An HTTP response class that consumes data to be serialized to JSON.
:param data: Data to be dumped into json.
"""
def __init__(self, data, **kwargs):
kwargs.setdefault('content_type', 'application/json')
data = jsonify(data)
super(JsonResponse, self).__init__(content=data, **kwargs)
class JsonResponseBadRequest(JsonResponse):
status_code = 400
class JsonResponseForbidden(JsonResponse):
status_code = 403
class JsonResponseNotFound(JsonResponse):
status_code = 404
class JsonResponseServerError(JsonResponse):
status_code = 500
| 981
|
Python
|
.py
| 25
| 35.44
| 77
| 0.744161
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,644
|
mail.py
|
translate_pootle/pootle/core/mail.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.core.mail import EmailMultiAlternatives, get_connection
def send_mail(subject, message, from_email, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
connection=None, html_message=None, headers=None,
cc=None, bcc=None):
"""Override django send_mail function to allow use of custom email headers.
"""
connection = connection or get_connection(username=auth_user,
password=auth_password,
fail_silently=fail_silently)
mail = EmailMultiAlternatives(subject, message,
from_email, recipient_list,
connection=connection, headers=headers,
cc=cc, bcc=bcc)
if html_message:
mail.attach_alternative(html_message, 'text/html')
return mail.send()
| 1,219
|
Python
|
.py
| 24
| 38.333333
| 79
| 0.617845
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,645
|
filters.py
|
translate_pootle/pootle/core/markup/filters.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from ..utils.html import rewrite_links
__all__ = (
'get_markup_filter_name', 'get_markup_filter_display_name',
'get_markup_filter', 'apply_markup_filter',
)
def rewrite_internal_link(link):
"""Converts `link` into an internal link.
Any active static pages defined for a site can be linked by pointing
to its virtual path by starting the anchors with the `#/` sequence
(e.g. `#/the/virtual/path`).
Links pointing to non-existent pages will return `#`.
Links not starting with `#/` will be omitted.
"""
if not link.startswith('#/'):
return link
from staticpages.models import AbstractPage
virtual_path = link[2:]
url = u'#'
for page_model in AbstractPage.__subclasses__():
try:
page = page_model.objects.live().get(virtual_path=virtual_path,)
url = page.get_absolute_url()
except ObjectDoesNotExist:
pass
return url
def get_markup_filter_name():
"""Returns the current markup filter's name."""
name = get_markup_filter()[0]
return 'html' if name is None else name
def get_markup_filter_display_name():
"""Returns a nice version for the current markup filter's name."""
name = get_markup_filter_name()
return {
'textile': u'Textile',
'markdown': u'Markdown',
'restructuredtext': u'reStructuredText',
'html': u'HTML',
}.get(name)
def get_markup_filter():
"""Returns the configured filter as a tuple with name and args.
If there is any problem it returns (None, '').
"""
try:
markup_filter, markup_kwargs = settings.POOTLE_MARKUP_FILTER
if markup_filter is None:
return (None, "unset")
elif markup_filter == 'textile':
import textile # noqa
elif markup_filter == 'markdown':
import markdown # noqa
elif markup_filter == 'restructuredtext':
import docutils # noqa
elif markup_filter == 'html':
pass
else:
return (None, '')
except Exception:
return (None, '')
return (markup_filter, markup_kwargs)
def apply_markup_filter(text):
"""Applies a text-to-HTML conversion function to a piece of text and
returns the generated HTML.
The function to use is derived from the value of the setting
``POOTLE_MARKUP_FILTER``, which should be a 2-tuple:
* The first element should be the name of a markup filter --
e.g., "markdown" -- to apply. If no markup filter is desired,
set this to None.
* The second element should be a dictionary of keyword
arguments which will be passed to the markup function. If no
extra arguments are desired, set this to an empty
dictionary; some arguments may still be inferred as needed,
however.
So, for example, to use Markdown with bleach cleaning turned on (cleaning
removes non-whitelisted HTML), put this in your settings file::
POOTLE_MARKUP_FILTER = ('markdown', {})
Currently supports Textile, Markdown and reStructuredText, using
names identical to the template filters found in
``django.contrib.markup``.
Borrowed from http://djangosnippets.org/snippets/104/
"""
markup_filter_name, markup_kwargs = get_markup_filter()
if not text.strip():
return text
html = text
if markup_filter_name is not None:
if markup_filter_name == 'textile':
import textile
if 'encoding' not in markup_kwargs:
markup_kwargs.update(encoding=settings.DEFAULT_CHARSET)
if 'output' not in markup_kwargs:
markup_kwargs.update(output=settings.DEFAULT_CHARSET)
html = textile.textile(text, **markup_kwargs)
elif markup_filter_name == 'markdown':
import bleach
import markdown
# See ALLOWED_TAGS, ALLOWED_ATTRIBUTES and ALLOWED_STYLES
# https://github.com/mozilla/bleach/blob/master/bleach/sanitizer.py
tags = bleach.ALLOWED_TAGS + [
u'h1', u'h2', u'h3', u'h4', u'h5',
u'p', u'pre',
u'img',
u'hr',
u'span',
]
attrs = bleach.ALLOWED_ATTRIBUTES.copy()
attrs.update({
'img': ['alt', 'src'],
})
styles = bleach.ALLOWED_STYLES
tags_provided = ('clean' in markup_kwargs
and 'extra_tags' in markup_kwargs['clean'])
if tags_provided:
tags += markup_kwargs['clean']['extra_tags']
attrs_provided = ('clean' in markup_kwargs
and 'extra_attrs' in markup_kwargs['clean'])
if attrs_provided:
attrs.update(markup_kwargs['clean']['extra_attrs'])
styles_provided = ('clean' in markup_kwargs
and 'extra_styles' in markup_kwargs['clean'])
if styles_provided:
styles += markup_kwargs['clean']['extra_styles']
html = bleach.clean(markdown.markdown(text, **markup_kwargs),
tags=tags, attributes=attrs, styles=styles)
elif markup_filter_name == 'restructuredtext':
from docutils import core
if 'settings_overrides' not in markup_kwargs:
markup_kwargs.update(
settings_overrides=getattr(
settings,
"RESTRUCTUREDTEXT_FILTER_SETTINGS",
{},
)
)
if 'writer_name' not in markup_kwargs:
markup_kwargs.update(writer_name='html4css1')
parts = core.publish_parts(source=text, **markup_kwargs)
html = parts['html_body']
return rewrite_links(html, rewrite_internal_link)
| 6,324
|
Python
|
.py
| 147
| 32.959184
| 79
| 0.60652
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,646
|
__init__.py
|
translate_pootle/pootle/core/markup/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from .fields import Markup, MarkupField
from .filters import (
get_markup_filter_name, get_markup_filter_display_name,
get_markup_filter, apply_markup_filter)
from .widgets import MarkupTextarea
__all__ = (
'Markup', 'MarkupField', 'get_markup_filter_name',
'get_markup_filter_display_name', 'get_markup_filter',
'apply_markup_filter', 'MarkupTextarea')
| 652
|
Python
|
.py
| 16
| 38.3125
| 77
| 0.744076
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,647
|
widgets.py
|
translate_pootle/pootle/core/markup/widgets.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django import forms
__all__ = ('MarkupTextarea',)
class MarkupTextarea(forms.widgets.Textarea):
def render(self, name, value, attrs=None):
if value is not None and not isinstance(value, unicode):
value = value.raw
return super(MarkupTextarea, self).render(name, value, attrs)
| 595
|
Python
|
.py
| 14
| 38.714286
| 77
| 0.724739
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,648
|
fields.py
|
translate_pootle/pootle/core/markup/fields.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
from lxml.etree import ParserError
from lxml.html.clean import clean_html
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.safestring import mark_safe
from .filters import apply_markup_filter
from .widgets import MarkupTextarea
__all__ = ('Markup', 'MarkupField',)
logger = logging.getLogger('pootle.markup')
_rendered_cache_key = lambda obj, pk, field: '_%s_%s_%s_rendered' % \
(obj, pk, field)
class Markup(object):
def __init__(self, instance, field_name, rendered_cache_key):
self.instance = instance
self.field_name = field_name
self.cache_key = rendered_cache_key
@property
def raw(self):
return self.instance.__dict__[self.field_name]
@raw.setter
def raw(self, value):
setattr(self.instance, self.field_name, value)
@property
def rendered(self):
rendered = cache.get(self.cache_key)
if not rendered:
logger.debug(u'Caching rendered output of %r', self.cache_key)
rendered = apply_markup_filter(self.raw)
cache.set(self.cache_key, rendered,
settings.POOTLE_CACHE_TIMEOUT)
return rendered
def __unicode__(self):
try:
return mark_safe(clean_html(self.rendered))
except ParserError:
return u''
def __nonzero__(self):
return self.raw.strip() != '' and self.raw is not None
class MarkupDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, owner):
if obj is None:
raise AttributeError('Can only be accessed via an instance.')
markup = obj.__dict__[self.field.name]
if markup is None:
return None
cache_key = _rendered_cache_key(obj.__class__.__name__,
obj.pk,
self.field.name)
return Markup(obj, self.field.name, cache_key)
def __set__(self, obj, value):
if isinstance(value, Markup):
obj.__dict__[self.field.name] = value.raw
else:
obj.__dict__[self.field.name] = value
class MarkupField(models.TextField):
description = 'Text field supporting different markup formats.'
def contribute_to_class(self, cls, name):
super(MarkupField, self).contribute_to_class(cls, name)
setattr(cls, self.name, MarkupDescriptor(self))
def pre_save(self, model_instance, add):
value = super(MarkupField, self).pre_save(model_instance, add)
if not add:
# Invalidate cache to force rendering upon next retrieval
cache_key = _rendered_cache_key(model_instance.__class__.__name__,
model_instance.pk,
self.name)
logger.debug('Invalidating cache for %r', cache_key)
cache.delete(cache_key)
return value.raw
def get_prep_value(self, value):
if isinstance(value, Markup):
return value.raw
return value
def to_python(self, value):
return self.get_prep_value(value)
def value_to_string(self, obj):
value = self.value_from_object(obj)
return self.get_prep_value(value)
def formfield(self, **kwargs):
defaults = {'widget': MarkupTextarea}
defaults.update(kwargs)
return super(MarkupField, self).formfield(**defaults)
def deconstruct(self):
name, path, args, kwargs = super(MarkupField, self).deconstruct()
kwargs.pop('help_text', None)
return name, path, args, kwargs
| 4,034
|
Python
|
.py
| 97
| 32.309278
| 78
| 0.620991
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,649
|
utils.py
|
translate_pootle/pootle/core/schema/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.db import connection
def get_current_db_type():
with connection.cursor() as cursor:
if hasattr(cursor.db, "mysql_version"):
return 'mysql'
return cursor.db.settings_dict['ENGINE'].split('.')[-1]
| 517
|
Python
|
.py
| 13
| 36.076923
| 77
| 0.708583
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,650
|
base.py
|
translate_pootle/pootle/core/schema/base.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.apps import apps
from django.conf import settings
from .mysql import MySQLSchemaDumper
from .utils import get_current_db_type
class UnsupportedDBError(Exception):
pass
class SchemaTool(object):
def __init__(self, *app_labels):
self.schema_dumper = None
if not app_labels:
app_labels = [app_label.split('.')[-1]
for app_label in settings.INSTALLED_APPS]
self.app_configs = dict(
[(app_label, apps.get_app_config(app_label))
for app_label in app_labels])
db_type = get_current_db_type()
if db_type == 'mysql':
self.schema_dumper = MySQLSchemaDumper()
else:
raise UnsupportedDBError(u"'%s' database is not supported"
% db_type)
def get_tables(self):
tables = []
for app_label in self.app_configs:
tables += self.get_app_tables(app_label)
return tables
def get_app_tables(self, app_label):
app_config = self.app_configs[app_label]
return [model._meta.db_table
for model in app_config.get_models(include_auto_created=True)]
def get_app_by_table(self, table_name):
for app_label in self.app_configs:
if table_name in self.get_app_tables(app_label):
return app_label
def get_defaults(self):
if self.schema_dumper is not None:
return self.schema_dumper.get_defaults()
def get_table_fields(self, table_name):
if self.schema_dumper is not None:
return self.schema_dumper.get_table_fields(table_name)
def get_table_indices(self, table_name):
if self.schema_dumper is not None:
return self.schema_dumper.get_table_indices(table_name)
def get_table_constraints(self, table_name):
if self.schema_dumper is not None:
return self.schema_dumper.get_table_constraints(table_name)
| 2,256
|
Python
|
.py
| 53
| 33.886792
| 78
| 0.642596
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,651
|
mysql.py
|
translate_pootle/pootle/core/schema/mysql.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.db import connection
def type_cast(value):
if isinstance(value, long):
return int(value)
return value
def fetchall_asdicts(cursor, fields, sort_by_field):
"""Return all rows from a cursor as a dict filtered by fields."""
columns = [u"%s" % col[0].lower() for col in cursor.description]
return sorted(
[{k: type_cast(v) for k, v in zip(columns, row) if k in fields}
for row in cursor.fetchall()],
key=lambda x: x.get(sort_by_field))
def list2dict(items, key_field):
result = {}
for d in items:
key = d[key_field]
if key not in result:
del d[key_field]
result[key] = d
elif 'column_names' in result[key]:
result[key]['column_names'].append(d['column_name'])
else:
result[key]['column_names'] = [result[key]['column_name'],
d['column_name']]
del result[key]['column_name']
return result
class MySQLSchemaDumper(object):
def get_defaults(self):
sql = ("SELECT default_character_set_name, default_collation_name "
"FROM information_schema.SCHEMATA WHERE schema_name = '%s'")
with connection.cursor() as cursor:
cursor.execute(sql % cursor.db.settings_dict['NAME'])
character_set, collation = cursor.fetchone()
return dict(character_set=character_set, collation=collation)
def get_table_fields(self, table_name):
fields = ('field', 'type', 'collation', 'key', 'extra')
with connection.cursor() as cursor:
cursor.execute("SHOW FULL COLUMNS FROM %s" % table_name)
result = list2dict(
fetchall_asdicts(cursor, fields, 'field'),
'field')
return result
def get_table_indices(self, table_name):
fields = ('non_unique', 'key_name', 'column_name')
with connection.cursor() as cursor:
cursor.execute("SHOW INDEX FROM %s" % table_name)
result = list2dict(
fetchall_asdicts(cursor, fields, 'column_name'),
'key_name')
return result
def get_table_constraints(self, table_name):
fields = ('table_name', 'column_name', 'constraint_name',
'referenced_table_name', 'referenced_column_name')
sql = (
"SELECT %s from INFORMATION_SCHEMA.KEY_COLUMN_USAGE "
"WHERE TABLE_NAME = '%s' AND CONSTRAINT_SCHEMA = '%s'" % (
', '.join(fields),
table_name,
connection.settings_dict['NAME'])
)
with connection.cursor() as cursor:
cursor.execute(sql)
result = list2dict(
fetchall_asdicts(cursor, fields, 'column_name'),
'constraint_name')
return result
| 3,146
|
Python
|
.py
| 73
| 33.273973
| 77
| 0.595285
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,652
|
dump.py
|
translate_pootle/pootle/core/schema/dump.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import json
from collections import OrderedDict
from pootle.core.utils.json import PootleJSONEncoder
class JSONOutput(object):
indent = 4
def out(self, obj):
return json.dumps(obj, indent=self.indent, cls=PootleJSONEncoder)
class BaseSchemaDump(object):
out_class = JSONOutput
def __init__(self):
self._data = OrderedDict()
def load(self, data):
self._data.update(data)
def __str__(self):
return self.out_class().out(self._data)
class SchemaTableDump(BaseSchemaDump):
def __init__(self, name):
self.name = name
self.fields = None
self.indices = None
self.constraints = None
super(SchemaTableDump, self).__init__()
def load(self, data):
attr_names = ['fields', 'indices', 'constraints']
for attr_name in attr_names:
if attr_name in data:
setattr(self, attr_name, data[attr_name])
super(SchemaTableDump, self).load(data)
class SchemaAppDump(BaseSchemaDump):
def __init__(self, name):
self.name = name
self.tables = OrderedDict()
super(SchemaAppDump, self).__init__()
self._data['tables'] = OrderedDict()
def load(self, data):
if 'tables' in data:
for table_name in data['tables']:
table_dump = SchemaTableDump(table_name)
table_dump.load(data['tables'][table_name])
self.add_table(table_dump)
def add_table(self, table_dump):
self.tables[table_dump.name] = table_dump
self._data['tables'][table_dump.name] = table_dump._data
def get_table(self, table_name):
return self.tables.get(table_name, None)
class SchemaDump(BaseSchemaDump):
def __init__(self):
self.defaults = None
self.apps = OrderedDict()
super(SchemaDump, self).__init__()
self._data['apps'] = OrderedDict()
def load(self, data):
if 'defaults' in data:
self.defaults = data['defaults']
self._data['defaults'] = self.defaults
if 'apps' in data:
for app_label in data['apps']:
app_dump = SchemaAppDump(app_label)
app_dump.load(data['apps'][app_label])
self.add_app(app_dump)
if 'tables' in data:
self.tables = data['tables']
self._data['tables'] = self.tables
def add_app(self, app_dump):
self.apps[app_dump.name] = app_dump
self._data['apps'][app_dump.name] = app_dump._data
def app_exists(self, app_label):
return app_label in self.apps
def get_app(self, app_label):
return self.apps.get(app_label, None)
def set_table_list(self, data):
self.load(data={'tables': data})
| 3,055
|
Python
|
.py
| 79
| 30.708861
| 77
| 0.619661
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,653
|
__init__.py
|
translate_pootle/pootle/core/models/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from .revision import Revision
from .virtualresource import VirtualResource
__all__ = ('Revision', 'VirtualResource')
| 396
|
Python
|
.py
| 10
| 38.3
| 77
| 0.767624
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,654
|
revision.py
|
translate_pootle/pootle/core/models/revision.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from ..cache import get_cache
cache = get_cache('redis')
class NoRevision(Exception):
pass
class Revision(object):
"""Wrapper around the revision counter stored in Redis."""
CACHE_KEY = 'pootle:revision'
INITIAL = 0
@classmethod
def initialize(cls, force=False):
"""Initializes the revision with `cls.INITIAL`.
:param force: whether to overwrite the number if there's a
revision already set or not.
:return: `True` if the initial value was set, `False` otherwise.
"""
if force:
return cls.set(cls.INITIAL)
return cls.add(cls.INITIAL)
@classmethod
def get(cls):
"""Gets the current revision number.
:return: The current revision number, or `None` if
there's no revision set.
"""
return cache.get(cls.CACHE_KEY)
@classmethod
def set(cls, value):
"""Sets the revision number to `value`, regardless of whether
there's a value previously set or not.
:return: `True` if the value was set, `False` otherwise.
"""
return cache.set(cls.CACHE_KEY, value)
@classmethod
def add(cls, value):
"""Sets the revision number to `value`, only if there's no
revision already set.
:return: `True` if the value was set, `False` otherwise.
"""
return cache.add(cls.CACHE_KEY, value)
@classmethod
def incr(cls):
"""Increments the revision number.
:return: the new revision number after incrementing it, or the
initial number if there's no revision stored yet.
"""
try:
return cache.incr(cls.CACHE_KEY)
except ValueError:
raise NoRevision()
| 2,038
|
Python
|
.py
| 56
| 29.196429
| 77
| 0.641365
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,655
|
virtualresource.py
|
translate_pootle/pootle/core/models/virtualresource.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from ..mixins import TreeItem
class VirtualResource(TreeItem):
"""An object representing a virtual resource.
A virtual resource doesn't live in the DB and has a unique
`pootle_path` of its own. It's a simple collection of actual
resources.
For instance, this can be used in projects to have cross-language
references.
Don't use this object as-is, rather subclass it and adapt the
implementation details for each context.
"""
def __init__(self, resources, pootle_path, *args, **kwargs):
self.resources = resources #: Collection of underlying resources
self.pootle_path = pootle_path
self.context = kwargs.pop("context", None)
super(VirtualResource, self).__init__(*args, **kwargs)
def __unicode__(self):
return self.pootle_path
# # # TreeItem
def get_children(self):
return self.resources
def get_cachekey(self):
return self.pootle_path
# # # /TreeItem
| 1,257
|
Python
|
.py
| 31
| 35.387097
| 77
| 0.699093
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,656
|
core.py
|
translate_pootle/pootle/core/templatetags/core.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django import template
from django.utils.html import escapejs
from django.utils.safestring import mark_safe
from ..utils.json import jsonify
register = template.Library()
@register.filter
def to_js(value):
"""Returns a string which leaves the value readily available for JS
consumption.
"""
return mark_safe('JSON.parse("%s")' % escapejs(jsonify(value)))
@register.filter
def map_to_lengths(value):
"""Maps a list value by replacing each element with its length.
"""
return [len(e) for e in value]
@register.inclusion_tag('includes/formtable.html')
def formtable(formtable):
return dict(formtable=formtable)
| 952
|
Python
|
.py
| 27
| 32.703704
| 77
| 0.755191
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,657
|
__init__.py
|
translate_pootle/pootle/core/mixins/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from .treeitem import TreeItem, CachedTreeItem, CachedMethods
__all__ = ('TreeItem', 'CachedTreeItem', 'CachedMethods')
| 398
|
Python
|
.py
| 9
| 42.888889
| 77
| 0.759067
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,658
|
treeitem.py
|
translate_pootle/pootle/core/mixins/treeitem.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
__all__ = ('TreeItem', 'CachedTreeItem', 'CachedMethods')
logger = logging.getLogger('stats')
class NoCachedStats(Exception):
pass
class CachedMethods(object):
"""Cached method names."""
CHECKS = 'get_checks'
WORDCOUNT_STATS = 'get_wordcount_stats'
LAST_ACTION = 'get_last_action'
SUGGESTIONS = 'get_suggestion_count'
MTIME = 'get_mtime'
LAST_UPDATED = 'get_last_updated'
# Check refresh_stats command when add a new CachedMethod
@classmethod
def get_all(cls):
return [getattr(cls, x) for x in
filter(lambda x: x[:2] != '__' and x != 'get_all', dir(cls))]
class TreeItem(object):
def __init__(self, *args, **kwargs):
self._children = None
self.initialized = False
super(TreeItem, self).__init__()
def get_children(self):
"""This method will be overridden in descendants"""
return []
def set_children(self, children):
self._children = children
self.initialized = True
def get_parents(self):
"""This method will be overridden in descendants"""
return []
def get_cachekey(self):
"""This method will be overridden in descendants"""
raise NotImplementedError('`get_cachekey()` not implemented')
def initialize_children(self):
if not self.initialized:
self._children = self.get_children()
self.initialized = True
@property
def children(self):
if not self.initialized:
self.initialize_children()
return self._children
def get_critical_url(self, **kwargs):
return self.get_translate_url(check_category='critical', **kwargs)
class CachedTreeItem(TreeItem):
# this is here for models/migrations that have it as a base class
pass
| 2,100
|
Python
|
.py
| 56
| 31.303571
| 77
| 0.663038
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,659
|
browse.py
|
translate_pootle/pootle/core/views/browse.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
from django.utils.functional import cached_property
from pootle.core.decorators import persistent_property
from pootle.core.delegate import panels, scores
from pootle.core.helpers import (
SIDEBAR_COOKIE_NAME, get_sidebar_announcements_context)
from pootle.core.utils.stats import (
TOP_CONTRIBUTORS_CHUNK_SIZE, get_translation_states)
from pootle.i18n import formatter
from .base import PootleDetailView
from .display import ChecksDisplay, StatsDisplay
logger = logging.getLogger(__name__)
class PootleBrowseView(PootleDetailView):
template_name = 'browser/index.html'
table_fields = None
is_store = False
object_children = ()
page_name = "browse"
view_name = ""
panel_names = ('children', )
@property
def checks(self):
return ChecksDisplay(self.object).checks_by_category
@property
def path(self):
return self.request.path
@property
def states(self):
states = get_translation_states(self.object)
stats = self.stats
for state in states:
if state["state"] == "untranslated":
if stats["total"]:
stats[state["state"]] = state["count"] = (
stats["total"] - stats["fuzzy"] - stats["translated"])
else:
stats[state["state"]] = state["count"] = stats[state["state"]]
if state.get("count"):
state["count_display"] = formatter.number(state["count"])
state["percent"] = round(
float(state["count"]) / stats["total"], 3)
state["percent_display"] = formatter.percent(
state["percent"], "#,##0.0%")
return states
@cached_property
def cache_key(self):
return (
"%s.%s.%s.%s.%s"
% (self.page_name,
self.view_name,
self.object.data_tool.cache_key,
self.show_all,
self.request_lang))
@property
def show_all(self):
return (
self.request.user.is_superuser
or "administrate" in self.request.permissions)
@persistent_property
def stats(self):
stats = self.object.data_tool.get_stats(user=self.request.user)
return StatsDisplay(self.object, stats=stats).stats
@property
def can_translate(self):
return bool(
not self.is_templates_context
and (self.request.user.is_superuser
or self.language
or self.project))
@property
def can_translate_stats(self):
return bool(
not self.is_templates_context
and (self.request.user.is_superuser
or self.language))
@property
def has_vfolders(self):
return False
@property
def sidebar_announcements(self):
return get_sidebar_announcements_context(
self.request,
(self.object, ))
@persistent_property
def has_disabled(self):
return any(
item.get('is_disabled')
for item
in self.object_children or [])
def add_child_stats(self, items):
stats = self.stats
for item in items:
if item["code"] in stats["children"]:
item["stats"] = stats["children"][item["code"]]
elif item["title"] in stats["children"]:
item["stats"] = stats["children"][item["title"]]
return items
def get(self, *args, **kwargs):
response = super(PootleBrowseView, self).get(*args, **kwargs)
response.delete_cookie(SIDEBAR_COOKIE_NAME)
return response
@cached_property
def scores(self):
return scores.get(
self.score_context.__class__)(
self.score_context)
@property
def score_context(self):
return self.object
@persistent_property
def top_scorer_data(self):
chunk_size = TOP_CONTRIBUTORS_CHUNK_SIZE
def scores_to_json(score):
score["user"] = score["user"].to_dict()
return score
top_scorers = self.scores.display(
limit=chunk_size,
formatter=scores_to_json)
return dict(
items=list(top_scorers),
has_more_items=len(self.scores.top_scorers) > chunk_size)
@property
def panels(self):
_panels = panels.gather(self.__class__)
for panel in self.panel_names:
if panel in _panels:
yield _panels[panel](self).content
else:
logger.warning("Unrecognized panel '%s'", panel)
@property
def is_templates_context(self):
return self.object.pootle_path.startswith("/templates/")
def get_context_data(self, *args, **kwargs):
filters = {}
if self.has_vfolders:
filters['sort'] = 'priority'
show_translation_links = (
(self.request.user.is_superuser
or self.language)
and not self.object.pootle_path.startswith("/templates"))
if show_translation_links:
url_action_continue = self.object.get_translate_url(
state='incomplete',
**filters)
url_action_fixcritical = self.object.get_critical_url(
**filters)
url_action_review = self.object.get_translate_url(
state='suggestions',
**filters)
url_action_view_all = self.object.get_translate_url(state='all')
else:
url_action_continue = None
url_action_fixcritical = None
url_action_review = None
url_action_view_all = None
ctx = self.sidebar_announcements
ctx.update(super(PootleBrowseView, self).get_context_data(*args, **kwargs))
stats = self.stats.copy()
del stats["children"]
ctx.update(
{'page': self.page_name,
'checks': self.checks,
'translation_states': self.states,
'stats': stats,
'can_translate': self.can_translate,
'can_translate_stats': self.can_translate_stats,
'cache_key': self.cache_key,
'url_action_continue': url_action_continue,
'url_action_fixcritical': url_action_fixcritical,
'url_action_review': url_action_review,
'url_action_view_all': url_action_view_all,
'top_scorers': self.top_scorer_data,
'has_disabled': self.has_disabled,
'templates_context': self.is_templates_context,
'panels': self.panels,
'is_store': self.is_store,
'browser_extends': self.template_extends})
return ctx
| 7,056
|
Python
|
.py
| 185
| 28.172973
| 83
| 0.59269
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,660
|
mixins.py
|
translate_pootle/pootle/core/views/mixins.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.utils.decorators import method_decorator
from pootle.core.delegate import context_data
from pootle.i18n.gettext import ugettext as _
from ..http import JsonResponse, JsonResponseBadRequest
class SuperuserRequiredMixin(object):
"""Require users to have the `is_superuser` bit set."""
def dispatch(self, request, *args, **kwargs):
if not request.user.is_superuser:
msg = _('You do not have rights to administer Pootle.')
raise PermissionDenied(msg)
return super(SuperuserRequiredMixin, self).dispatch(request, *args,
**kwargs)
class UserObjectMixin(object):
"""Generic field definitions to be reused across user views."""
context_object_name = 'object'
slug_field = 'username'
slug_url_kwarg = 'username'
@property
def model(self):
return get_user_model()
class TestUserFieldMixin(object):
"""Require a field from the URL pattern to match a field of the
current user.
The URL pattern field used for comparing against the current user
can be customized by setting the `username_field` attribute.
Note that there's free way for admins.
"""
test_user_field = 'username'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
user = self.request.user
url_field_value = kwargs[self.test_user_field]
field_value = getattr(user, self.test_user_field, '')
can_access = user.is_superuser or \
unicode(field_value) == url_field_value
if not can_access:
raise PermissionDenied(_('You cannot access this page.'))
return super(TestUserFieldMixin, self).dispatch(*args, **kwargs)
class NoDefaultUserMixin(object):
"""Removes the `default` special user from views."""
def dispatch(self, request, *args, **kwargs):
username = kwargs.get('username', None)
if username is not None and username == 'default':
raise Http404
return super(NoDefaultUserMixin, self) \
.dispatch(request, *args, **kwargs)
class AjaxResponseMixin(object):
"""Mixin to add AJAX support to a form.
This needs to be used with a `FormView`.
"""
def form_invalid(self, form):
super(AjaxResponseMixin, self).form_invalid(form)
return JsonResponseBadRequest({'errors': form.errors})
def form_valid(self, form):
super(AjaxResponseMixin, self).form_valid(form)
return JsonResponse({})
class GatherContextMixin(object):
def gather_context_data(self, context):
context.update(
context_data.gather(
sender=self.__class__,
context=context, view=self))
return context
def render_to_response(self, context, **response_kwargs):
return super(GatherContextMixin, self).render_to_response(
self.gather_context_data(context),
**response_kwargs)
class PootleJSONMixin(GatherContextMixin):
response_class = JsonResponse
def get_response_data(self, context):
"""Override this method if you need to render a template with the context object
but wish to include the rendered output within a JSON response
"""
return context
def render_to_response(self, context, **response_kwargs):
"""Overriden to call `get_response_data` with output from
`get_context_data`
"""
response_kwargs.setdefault('content_type', self.content_type)
return self.response_class(
self.get_response_data(self.gather_context_data(context)),
**response_kwargs)
| 4,155
|
Python
|
.py
| 93
| 37.215054
| 88
| 0.683478
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,661
|
translate.py
|
translate_pootle/pootle/core/views/translate.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
from django.conf import settings
from pootle.core.url_helpers import get_previous_url
from pootle_app.models.permissions import check_permission
from pootle_checks.constants import CATEGORY_IDS, CHECK_NAMES
from pootle_checks.utils import get_qualitycheck_schema, get_qualitychecks
from pootle_misc.forms import make_search_form
from .base import PootleDetailView
class PootleTranslateView(PootleDetailView):
template_name = "editor/main.html"
page_name = "translate"
view_name = ""
@property
def check_data(self):
return self.object.data_tool.get_checks()
@property
def checks(self):
check_data = self.check_data
checks = get_qualitychecks()
schema = {sc["code"]: sc for sc in get_qualitycheck_schema()}
_checks = {}
for check, checkid in checks.items():
if check not in check_data:
continue
_checkid = schema[checkid]["name"]
_checks[_checkid] = _checks.get(
_checkid, dict(checks=[], title=schema[checkid]["title"]))
_checks[_checkid]["checks"].append(
dict(
code=check,
title=CHECK_NAMES[check],
count=check_data[check]))
return OrderedDict(
(k, _checks[k])
for k in CATEGORY_IDS.keys()
if _checks.get(k))
@property
def ctx_path(self):
return self.pootle_path
@property
def vfolder_pk(self):
return ""
@property
def display_vfolder_priority(self):
return False
@property
def chunk_size(self):
return self.request.user.get_unit_rows()
def get_context_data(self, *args, **kwargs):
ctx = super(PootleTranslateView, self).get_context_data(*args, **kwargs)
ctx.update(
{'page': self.page_name,
'chunk_size': self.chunk_size,
'current_vfolder_pk': self.vfolder_pk,
'ctx_path': self.ctx_path,
'display_priority': self.display_vfolder_priority,
'checks': self.checks,
'cantranslate': check_permission("translate", self.request),
'cansuggest': check_permission("suggest", self.request),
'canreview': check_permission("review", self.request),
'search_form': make_search_form(request=self.request),
'previous_url': get_previous_url(self.request),
'POOTLE_MT_BACKENDS': settings.POOTLE_MT_BACKENDS,
'AMAGAMA_URL': settings.AMAGAMA_URL,
'AMAGAMA_SOURCE_LANGUAGES': settings.AMAGAMA_SOURCE_LANGUAGES,
'editor_extends': self.template_extends})
return ctx
| 3,030
|
Python
|
.py
| 74
| 32.175676
| 80
| 0.633367
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,662
|
formtable.py
|
translate_pootle/pootle/core/views/formtable.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.template.loader import render_to_string
class Formtable(object):
row_field = ""
filters_template = ""
actions_field = "actions"
form_method = "POST"
form_action = ""
form_css_class = "formtable"
def __init__(self, form, **kwargs):
self.form = form
self.kwargs = kwargs
@property
def form_attrs(self):
return {
"method": self.form_method,
"class": self.form_css_class,
"action": self.form_action}
@property
def table_attrs(self):
return dict({"class": "pootle-table centered"})
@property
def actions(self):
return self.form[self.actions_field]
@property
def columns(self):
return self.kwargs.get("columns", ())
@property
def comment(self):
return (
self.form[self.form.comment_field]
if self.form.comment_field
else "")
@property
def sort_columns(self):
return self.kwargs.get("sort_columns", ())
@property
def colspan(self):
return len(self.columns)
@property
def page(self):
return self.kwargs.get("page", ())
@property
def page_no(self):
return self.form[self.form.page_field]
@property
def results_per_page(self):
return self.form[self.form.per_page_field]
@property
def rows(self):
return (
self.form[self.row_field]
if (self.row_field in self.form.fields
and self.form.fields[self.row_field].choices)
else [])
@property
def filters(self):
return (
render_to_string(
self.filters_template,
context=dict(formtable=self))
if self.filters_template
else "")
@property
def form_method(self):
return self.kwargs.get("method", "POST")
@property
def select_all(self):
return self.form[self.form.select_all_field]
@property
def table_css_class(self):
return 'pootle-table centered'
| 2,359
|
Python
|
.py
| 78
| 22.897436
| 77
| 0.610522
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,663
|
api.py
|
translate_pootle/pootle/core/views/api.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import json
import operator
from django.db.models import ObjectDoesNotExist, ProtectedError, Q
from django.forms.models import modelform_factory
from django.http import Http404
from django.views.generic import View
from pootle.core.http import JsonResponse
from pootle_config.utils import ObjectConfig
class APIView(View):
"""View to implement internal RESTful APIs.
Based on djangbone https://github.com/af/djangbone
"""
# Model on which this view operates. Setting this is required
model = None
# Base queryset for accessing data. If `None`, model's default manager will
# be used
base_queryset = None
# Set this to restrict the view to a subset of the available methods
restrict_to_methods = None
# Field names to be included
fields = ()
# Individual forms to use for each method. By default it'll auto-populate
# model forms built using `self.model` and `self.fields`
add_form_class = None
edit_form_class = None
# Tuple of sensitive field names that will be excluded from any serialized
# responses
sensitive_field_names = ('password', 'pw')
# Set to an integer to enable GET pagination
page_size = None
# HTTP GET parameter to use for accessing pages
page_param_name = 'p'
# HTTP GET parameter to use for search queries
search_param_name = 'q'
# Field names in which searching will be allowed
search_fields = None
m2m = ()
config = ()
@property
def allowed_methods(self):
methods = [m for m in self.http_method_names if hasattr(self, m)]
if self.restrict_to_methods is not None:
restricted_to = map(lambda x: x.lower(), self.restrict_to_methods)
methods = filter(lambda x: x in restricted_to, methods)
return methods
def __init__(self, *args, **kwargs):
if self.model is None:
raise ValueError('No model class specified.')
self.pk_field_name = self.model._meta.pk.name
if self.base_queryset is None:
self.base_queryset = self.model._default_manager
self._init_fields()
self._init_forms()
return super(APIView, self).__init__(*args, **kwargs)
def _init_fields(self):
if len(self.fields) < 1:
form = self.add_form_class or self.edit_form_class
if form is not None:
config_fields = dict(self.config).keys()
self.fields = [
x for x
in form._meta.fields
if x not in self.m2m
and x not in config_fields]
else: # Assume all fields by default
self.fields = (f.name for f in self.model._meta.fields)
self.serialize_fields = (f for f in self.fields if
f not in self.sensitive_field_names)
def _init_forms(self):
if 'post' in self.allowed_methods and self.add_form_class is None:
self.add_form_class = modelform_factory(self.model,
fields=self.fields)
if 'put' in self.allowed_methods and self.edit_form_class is None:
self.edit_form_class = modelform_factory(self.model,
fields=self.fields)
def dispatch(self, request, *args, **kwargs):
if request.method.lower() in self.allowed_methods:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
"""GET handler."""
if kwargs.get(self.pk_field_name, None) is not None:
return self.get_single_item(request, *args, **kwargs)
return self.get_collection(request, *args, **kwargs)
def get_single_item(self, request, *args, **kwargs):
"""Returns a single model instance."""
try:
qs = self.base_queryset.filter(pk=kwargs[self.pk_field_name])
assert len(qs) == 1
except AssertionError:
raise Http404
return JsonResponse(self.qs_to_values(qs))
def get_collection(self, request, *args, **kwargs):
"""Retrieve a full collection."""
return JsonResponse(self.qs_to_values(self.base_queryset))
def post(self, request, *args, **kwargs):
"""Creates a new model instance.
The form to be used can be customized by setting
`self.add_form_class`. By default a model form will be used with
the fields from `self.fields`.
"""
try:
request_dict = json.loads(request.body)
except ValueError:
return self.status_msg('Invalid JSON data', status=400)
form = self.add_form_class(request_dict)
if form.is_valid():
new_object = form.save()
# Serialize the new object to json using our built-in methods. The
# extra DB read here is not ideal, but it keeps the code DRY:
wrapper_qs = self.base_queryset.filter(pk=new_object.pk)
return JsonResponse(
self.qs_to_values(wrapper_qs, single_object=True)
)
return self.form_invalid(form)
def put(self, request, *args, **kwargs):
"""Update the current model."""
if self.pk_field_name not in kwargs:
return self.status_msg('PUT is not supported for collections',
status=405)
try:
request_dict = json.loads(request.body)
instance = self.base_queryset.get(pk=kwargs[self.pk_field_name])
except ValueError:
return self.status_msg('Invalid JSON data', status=400)
except ObjectDoesNotExist:
raise Http404
form = self.edit_form_class(request_dict, instance=instance)
if form.is_valid():
item = form.save()
wrapper_qs = self.base_queryset.filter(id=item.id)
return JsonResponse(
self.qs_to_values(wrapper_qs, single_object=True)
)
return self.form_invalid(form)
def delete(self, request, *args, **kwargs):
"""Delete the model and return its JSON representation."""
if self.pk_field_name not in kwargs:
return self.status_msg('DELETE is not supported for collections',
status=405)
qs = self.base_queryset.filter(id=kwargs[self.pk_field_name])
if qs:
output = self.qs_to_values(qs)
obj = qs[0]
try:
obj.delete()
return JsonResponse(output)
except ProtectedError as e:
return self.status_msg(e[0], status=405)
raise Http404
def serialize_m2m(self, info, item):
for k in self.m2m:
info[k] = [
str(x) for x
in getattr(item, k).values_list("pk", flat=True)]
def serialize_config(self, info, item):
config = ObjectConfig(item)
for k, v in self.config:
info[k] = config.get(v)
def handle_single(self, queryset):
result = queryset.values(*self.serialize_fields)[0]
if self.m2m:
self.serialize_m2m(result, queryset[0])
if self.config:
self.serialize_config(result, queryset[0])
return result
def _filter_keyword(self, queryset):
search_keyword = self.request.GET.get(self.search_param_name, None)
if search_keyword is not None:
filter_by = self.get_search_filter(search_keyword)
return queryset.filter(filter_by)
return queryset
def _paginate(self, queryset):
# Process pagination options if they are enabled
if isinstance(self.page_size, int):
try:
page_param = self.request.GET.get(self.page_param_name, 1)
page_number = int(page_param)
offset = (page_number - 1) * self.page_size
except ValueError:
offset = 0
queryset = queryset.all()[offset:offset + self.page_size]
return queryset
def handle_multiple(self, queryset):
queryset = self._filter_keyword(queryset)
queryset = self._paginate(queryset)
fields = set(self.serialize_fields) | set(["pk"])
result = {
x["pk"]: x
for x
in queryset.values(*fields)}
if self.m2m:
queryset = queryset.prefetch_related(*self.m2m)
for item in queryset.iterator():
info = result[item.pk]
if "pk" not in fields:
del info["pk"]
if self.m2m:
self.serialize_m2m(info, item)
if self.config:
self.serialize_config(info, item)
return {
'models': result.values(),
'count': queryset.count()}
def qs_to_values(self, queryset, single_object=False):
"""Convert a queryset to values for further serialization.
:param single_object: if `True` (or the URL specified an id), it
will return a single element.
If `False`, an array of objects in `models` and the total object
count in `count` is returned.
"""
if single_object or self.kwargs.get(self.pk_field_name):
return self.handle_single(queryset)
else:
return self.handle_multiple(queryset)
def get_search_filter(self, keyword):
search_fields = getattr(self, 'search_fields', None)
if search_fields is None:
search_fields = self.fields # Assume all fields
field_queries = list(
zip(map(lambda x: '%s__icontains' % x, search_fields),
(keyword,)*len(search_fields))
)
lookups = [Q(x) for x in field_queries]
return reduce(operator.or_, lookups)
def status_msg(self, msg, status=400):
return JsonResponse({'msg': msg}, status=status)
def form_invalid(self, form):
return JsonResponse({'errors': form.errors}, status=400)
| 10,533
|
Python
|
.py
| 239
| 33.543933
| 79
| 0.604242
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,664
|
display.py
|
translate_pootle/pootle/core/views/display.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.utils.functional import cached_property
from django.utils.html import escape, format_html
from django.utils.safestring import mark_safe
from pootle.i18n import formatter
from pootle.i18n.dates import timesince
from pootle.i18n.gettext import ugettext as _
from pootle_checks.utils import get_qualitycheck_list
STAT_KEYS = [
"total", "critical", "incomplete",
"suggestions", "fuzzy", "untranslated"]
class ActionDisplay(object):
def __init__(self, action, locale=None):
self.action = action
self.locale = locale
@property
def since(self):
return timesince(
self.action["mtime"],
locale=self.locale)
@property
def check_name(self):
return self.action.get("check_name")
@property
def checks_url(self):
return self.action.get("checks_url")
@property
def check_display_name(self):
return escape(self.action["check_display_name"])
@property
def display_name(self):
return escape(self.action["displayname"])
@property
def profile_url(self):
return self.action["profile_url"]
@property
def unit_url(self):
return self.action.get("unit_url")
@property
def unit_source(self):
return self.action.get("unit_source")
@property
def params(self):
params = dict(
user=self.formatted_user,
source=self.formatted_source)
if self.check_name:
params["check"] = format_html(
u"<a href='{}'>{}</a>",
self.checks_url,
self.check_display_name)
return params
@property
def formatted_user(self):
return format_html(
u"<a href='{}' class='user-name'>{}</a>",
self.profile_url,
self.display_name)
@property
def formatted_source(self):
return format_html(
u"<a href='{}'>{}</a>",
self.unit_url,
self.unit_source)
@property
def action_type(self):
return self.action["type"]
@property
def translation_action_type(self):
return self.action.get("translation_action_type")
@property
def message(self):
msg = ""
params = self.params
if (self.action_type == 2):
msg = _('%(user)s removed translation for %(source)s', params)
if (self.action_type == 3):
msg = _('%(user)s accepted suggestion for %(source)s', params)
if (self.action_type == 4):
msg = _('%(user)s uploaded file', params)
if (self.action_type == 6):
msg = _('%(user)s muted %(check)s for %(source)s', params)
if (self.action_type == 7):
msg = _('%(user)s unmuted %(check)s for %(source)s', params)
if (self.action_type == 8):
msg = _('%(user)s added suggestion for %(source)s', params)
if (self.action_type == 9):
msg = _('%(user)s rejected suggestion for %(source)s', params)
if (self.action_type in [1, 5]):
if self.translation_action_type == 0:
msg = _('%(user)s translated %(source)s', params)
if self.translation_action_type == 1:
msg = _('%(user)s edited %(source)s', params)
if self.translation_action_type == 2:
# Translators: pre-translate is translating with first 100% TM match
msg = _('%(user)s pre-translated %(source)s', params)
if self.translation_action_type == 3:
msg = _('%(user)s removed translation for %(source)s', params)
if self.translation_action_type == 4:
msg = _('%(user)s reviewed %(source)s', params)
if self.translation_action_type == 5:
msg = _('%(user)s marked as needs work %(source)s', params)
return mark_safe(msg)
class ChecksDisplay(object):
def __init__(self, context):
self.context = context
@property
def check_schema(self):
return get_qualitycheck_list(self.context)
@cached_property
def check_data(self):
return self.context.data_tool.get_checks()
@property
def checks_by_category(self):
_checks = []
for check in self.check_schema:
if check["code"] not in self.check_data:
continue
check["count"] = self.check_data[check["code"]]
check["count_display"] = formatter.number(check["count"])
_checks.append(check)
return _checks
class StatsDisplay(object):
def __init__(self, context, stats=None):
self.context = context
self._stats = stats
def localize_stats(self, stats):
for k in STAT_KEYS:
if k in stats and isinstance(stats[k], (int, long, float)):
stats[k + '_display'] = formatter.number(stats[k])
@cached_property
def stat_data(self):
if self._stats is not None:
return self._stats
return self.context.data_tool.get_stats()
@cached_property
def stats(self):
stats = self.stat_data
self.add_children_info(stats)
self.localize_stats(stats)
if stats.get("last_submission"):
stats["last_submission"]["msg"] = (
self.get_action_message(stats["last_submission"]))
return stats
def add_children_info(self, stats):
for k, child in stats["children"].items():
is_template = (
self.context.pootle_path.startswith("/templates/")
or k.startswith("templates-")
or k == "templates")
if is_template:
child["incomplete"] = "---"
child["untranslated"] = "---"
child["critical"] = "---"
child["suggestions"] = "---"
if "last_submission" in child:
del child["last_submission"]
else:
child["incomplete"] = child["total"] - child["translated"]
child["untranslated"] = child["total"] - child["translated"]
self.localize_stats(child)
def get_action_message(self, action):
return ActionDisplay(action).message
| 6,542
|
Python
|
.py
| 169
| 29.455621
| 84
| 0.58378
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,665
|
__init__.py
|
translate_pootle/pootle/core/views/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.views.defaults import (permission_denied as django_403,
page_not_found as django_404,
server_error as django_500)
from .api import APIView
from .base import PootleAdminView, PootleJSON
from .browse import PootleBrowseView
from .translate import PootleTranslateView
__all__ = (
'APIView', 'PootleJSON', 'PootleAdminView', 'PootleBrowseView',
'PootleTranslateView')
def permission_denied(request, exception):
return django_403(request, exception, template_name='errors/403.html')
def page_not_found(request, exception):
return django_404(request, exception, template_name='errors/404.html')
def server_error(request):
return django_500(request, template_name='errors/500.html')
| 1,063
|
Python
|
.py
| 23
| 40.869565
| 77
| 0.726214
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,666
|
admin.py
|
translate_pootle/pootle/core/views/admin.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.urls import reverse
from django.views.generic import FormView, TemplateView
from pootle.core.views.mixins import SuperuserRequiredMixin
class PootleFormView(FormView):
@property
def success_kwargs(self):
return {}
@property
def success_url(self):
return reverse(
self.success_url_pattern,
kwargs=self.success_kwargs)
def form_valid(self, form):
if form.should_save():
form.save()
self.add_success_message(form)
return super(PootleFormView, self).form_valid(form)
return self.render_to_response(self.get_context_data(form=form))
def add_success_message(self, form):
pass
class PootleAdminView(SuperuserRequiredMixin, TemplateView):
pass
class PootleAdminFormView(SuperuserRequiredMixin, PootleFormView):
pass
| 1,139
|
Python
|
.py
| 31
| 31.096774
| 77
| 0.720803
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,667
|
base.py
|
translate_pootle/pootle/core/views/base.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.utils.translation import get_language
from django.views.decorators.cache import never_cache
from django.views.generic import DetailView
from pootle.core.delegate import site_languages
from pootle.core.url_helpers import get_path_parts
from pootle.i18n.gettext import ugettext as _
from pootle_app.models.permissions import check_permission
from pootle_misc.util import ajax_required
from .decorators import requires_permission, set_permissions
from .mixins import GatherContextMixin, PootleJSONMixin
class PootleDetailView(GatherContextMixin, DetailView):
translate_url_path = ""
browse_url_path = ""
resource_path = ""
view_name = ""
sw_version = 0
ns = "pootle.core"
@property
def browse_url(self):
return reverse(
self.browse_url_path,
kwargs=self.url_kwargs)
@property
def cache_key(self):
return (
"%s.%s.%s.%s"
% (self.page_name,
self.view_name,
self.object.data_tool.cache_key,
self.request_lang))
@property
def request_lang(self):
return get_language()
@cached_property
def has_admin_access(self):
return check_permission('administrate', self.request)
@property
def language(self):
if self.tp:
return self.tp.language
@property
def permission_context(self):
return self.get_object()
@property
def pootle_path(self):
return self.object.pootle_path
@property
def project(self):
if self.tp:
return self.tp.project
@property
def tp(self):
return None
@property
def translate_url(self):
return reverse(
self.translate_url_path,
kwargs=self.url_kwargs)
@set_permissions
@requires_permission("view")
def dispatch(self, request, *args, **kwargs):
# get funky with the request 8/
return super(PootleDetailView, self).dispatch(request, *args, **kwargs)
@property
def languages(self):
languages = site_languages.get()
languages = (
languages.all_languages
if self.has_admin_access
else languages.languages)
lang_map = {
v: k
for k, v
in languages.items()}
return OrderedDict(
(lang_map[v], v)
for v
in sorted(languages.values()))
def get_context_data(self, *args, **kwargs):
return {
'object': self.object,
'pootle_path': self.pootle_path,
'project': self.project,
'language': self.language,
"all_languages": self.languages,
'translation_project': self.tp,
'has_admin_access': self.has_admin_access,
'resource_path': self.resource_path,
'resource_path_parts': get_path_parts(self.resource_path),
'translate_url': self.translate_url,
'browse_url': self.browse_url,
'paths_placeholder': _("Entire Project"),
'unit_api_root': "/xhr/units/"}
class PootleJSON(PootleJSONMixin, PootleDetailView):
@never_cache
@method_decorator(ajax_required)
@set_permissions
@requires_permission("view")
def dispatch(self, request, *args, **kwargs):
return super(PootleJSON, self).dispatch(request, *args, **kwargs)
class PootleAdminView(DetailView):
@set_permissions
@requires_permission("administrate")
def dispatch(self, request, *args, **kwargs):
return super(PootleAdminView, self).dispatch(request, *args, **kwargs)
@property
def permission_context(self):
return self.get_object().directory
def post(self, *args, **kwargs):
return self.get(*args, **kwargs)
| 4,271
|
Python
|
.py
| 121
| 27.917355
| 79
| 0.652923
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,668
|
paths.py
|
translate_pootle/pootle/core/views/paths.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.generic import FormView
from pootle.core.exceptions import Http400
from pootle.core.forms import PathsSearchForm
from pootle_misc.util import ajax_required
from .decorators import requires_permission, set_permissions
from .mixins import PootleJSONMixin
class PootlePathsJSON(PootleJSONMixin, FormView):
form_class = PathsSearchForm
@never_cache
@method_decorator(ajax_required)
@set_permissions
@requires_permission("view")
def dispatch(self, request, *args, **kwargs):
return super(PootlePathsJSON, self).dispatch(request, *args, **kwargs)
@property
def permission_context(self):
return self.context.directory
def get_context_data(self, **kwargs):
context = super(PootlePathsJSON, self).get_context_data(**kwargs)
form = context["form"]
return (
dict(items=form.search(show_all=self.request.user.is_superuser))
if form.is_valid()
else dict(items=[]))
def get_form_kwargs(self):
kwargs = super(PootlePathsJSON, self).get_form_kwargs()
kwargs["data"] = self.request.POST
kwargs["context"] = self.context
return kwargs
def form_valid(self, form):
return self.render_to_response(
self.get_context_data(form=form))
def form_invalid(self, form):
raise Http400(form.errors)
| 1,763
|
Python
|
.py
| 43
| 35.465116
| 78
| 0.718549
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,669
|
panels.py
|
translate_pootle/pootle/core/views/panels.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.template import loader
from django.utils.functional import cached_property
from pootle.core.decorators import persistent_property
class Panel(object):
template_name = None
panel_name = None
def __init__(self, view):
self.view = view
def get_context_data(self):
return {}
def render(self):
if not self.template_name:
return ""
return loader.render_to_string(
self.template_name, context=self.get_context_data())
@cached_property
def cache_key(self):
return (
"panel.%s.%s"
% (self.panel_name, self.view.cache_key))
@persistent_property
def content(self):
return self.render()
class TablePanel(Panel):
template_name = "browser/includes/table_panel.html"
table = None
def get_context_data(self):
return dict(table=self.table)
| 1,174
|
Python
|
.py
| 35
| 27.857143
| 77
| 0.678793
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,670
|
widgets.py
|
translate_pootle/pootle/core/views/widgets.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.forms import CheckboxInput, Select, SelectMultiple
from django.utils.encoding import force_text
from django.utils.html import escape
from django.utils.safestring import SafeText, mark_safe
class TableSelectMultiple(SelectMultiple):
"""
Provides selection of items via checkboxes, with a table row
being rendered for each item, the first cell in which contains the
checkbox.
When providing choices for this field, give the item as the second
item in all choice tuples. For example, where you might have
previously used::
field.choices = [(item.id, item.name) for item in item_list]
...you should use::
field.choices = [(item.id, item) for item in item_list]
"""
def __init__(self, item_attrs, *args, **kwargs):
"""
item_attrs
Defines the attributes of each item which will be displayed
as a column in each table row, in the order given.
Any callables in item_attrs will be called with the item to be
displayed as the sole parameter.
Any callable attribute names specified will be called and have
their return value used for display.
All attribute values will be escaped.
"""
super(TableSelectMultiple, self).__init__(*args, **kwargs)
self.item_attrs = item_attrs
def render(self, name, value, attrs=None, choices=()):
if value is None:
value = []
has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs or {})
output = []
# Normalize to strings.
str_values = set([force_text(v) for v in value])
for i, (option_value, item) in enumerate(self.choices):
# If an ID attribute was given, add a numeric index as a suffix,
# so that the checkboxes don't all have the same ID attribute.
if has_id:
final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
cb = CheckboxInput(
final_attrs,
check_test=lambda value: value in str_values)
option_value = force_text(option_value)
rendered_cb = cb.render(name, option_value)
output.append(u'<tr>')
output.append(u'<td class="row-select">%s</td>' % rendered_cb)
for attr in self.item_attrs:
css_name = attr
if callable(attr):
content = attr(item)
css_name = attr.__name__.strip("_")
elif hasattr(item, attr):
if callable(getattr(item, attr)):
content = getattr(item, attr)()
else:
content = getattr(item, attr)
else:
content = item[attr]
if not isinstance(content, SafeText):
content = escape(content)
css = (
' class="field-%s"'
% css_name.lower().replace("_", "-").replace(" ", "-"))
output.append(u'<td%s>%s</td>' % (css, content))
output.append(u'</tr>')
return mark_safe(u'\n'.join(output))
class RemoteSelectWidget(Select):
def render_options(self, selected_choices):
return ""
| 3,599
|
Python
|
.py
| 79
| 34.746835
| 78
| 0.589158
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,671
|
decorators.py
|
translate_pootle/pootle/core/views/decorators.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import functools
from django.core.exceptions import PermissionDenied
from pootle.i18n.gettext import ugettext as _
from pootle_app.models.permissions import get_matching_permissions
def check_directory_permission(permission_codename, request, directory):
"""Checks if the current user has `permission_codename`
permissions for a given directory.
"""
if request.user.is_superuser:
return True
if permission_codename == 'view':
context = None
context = getattr(directory, "tp", None)
if context is None:
context = getattr(directory, "project", None)
if context is None:
return True
return context.is_accessible_by(request.user)
return (
"administrate" in request.permissions
or permission_codename in request.permissions)
def set_permissions(f):
@functools.wraps(f)
def method_wrapper(self, request, *args, **kwargs):
if not hasattr(request, "permissions"):
request.permissions = get_matching_permissions(
request.user,
self.permission_context) or []
return f(self, request, *args, **kwargs)
return method_wrapper
def requires_permission(permission):
def class_wrapper(f):
@functools.wraps(f)
def method_wrapper(self, request, *args, **kwargs):
directory_permission = check_directory_permission(
permission, request, self.permission_context)
check_class_permission = (
directory_permission
and hasattr(self, "required_permission")
and permission != self.required_permission)
if check_class_permission:
directory_permission = check_directory_permission(
self.required_permission, request, self.permission_context)
if not directory_permission:
raise PermissionDenied(
_("Insufficient rights to access this page."), )
return f(self, request, *args, **kwargs)
return method_wrapper
return class_wrapper
| 2,401
|
Python
|
.py
| 56
| 34.214286
| 79
| 0.66366
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,672
|
db.py
|
translate_pootle/pootle/core/utils/db.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from contextlib import contextmanager
from django.db import connection
@contextmanager
def useable_connection():
connection.close_if_unusable_or_obsolete()
yield
connection.close_if_unusable_or_obsolete()
def set_mysql_collation_for_column(apps, cursor, model, column, collation, schema):
"""Set the collation for a mysql column if it is not set already
"""
# Check its mysql - should probs check its not too old.
if not hasattr(cursor.db, "mysql_version"):
return
# Get the db_name
db_name = cursor.db.get_connection_params()['db']
# Get table_name
table_name = apps.get_model(model)._meta.db_table
# Get the current collation
cursor.execute(
"SELECT COLLATION_NAME"
" FROM `information_schema`.`columns`"
" WHERE TABLE_SCHEMA = '%s'"
" AND TABLE_NAME = '%s'"
" AND COLUMN_NAME = '%s';"
% (db_name, table_name, column))
current_collation = cursor.fetchone()[0]
if current_collation != collation:
# set collation
cursor.execute(
"ALTER TABLE `%s`.`%s`"
" MODIFY `%s`"
" %s"
" CHARACTER SET utf8"
" COLLATE %s"
" NOT NULL;"
% (db_name, table_name,
column, schema, collation))
| 1,598
|
Python
|
.py
| 44
| 29.818182
| 83
| 0.634478
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,673
|
templates.py
|
translate_pootle/pootle/core/utils/templates.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.template import Context, Template, TemplateDoesNotExist
from django.template.engine import Engine
def render_as_template(string, context=None):
context = context or {}
context = Context(context)
return Template(string).render(context=context)
def get_template_source(name, dirs=None):
"""Retrieves the template's source contents.
:param name: Template's filename, as passed to the template loader.
:param dirs: list of directories to optionally override the defaults.
:return: tuple including file contents and file path.
"""
loaders = []
for loader in Engine.get_default().template_loaders:
# The cached loader includes the actual loaders underneath
if hasattr(loader, 'loaders'):
loaders.extend(loader.loaders)
else:
loaders.append(loader)
for loader in loaders:
try:
return loader.load_template_source(name, template_dirs=dirs)
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(name)
| 1,329
|
Python
|
.py
| 32
| 36.03125
| 77
| 0.720714
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,674
|
ptempfile.py
|
translate_pootle/pootle/core/utils/ptempfile.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import tempfile
from django.conf import settings
def mkstemp(*args, **kwargs):
"""Wrap tempfile.mkstemp, setting the permissions of the created temporary
file as specified in settings (see bug 1983).
"""
fd, name = tempfile.mkstemp(*args, **kwargs)
if hasattr(os, 'fchmod'):
os.fchmod(fd, settings.POOTLE_SYNC_FILE_MODE)
else:
os.chmod(name, settings.POOTLE_SYNC_FILE_MODE)
return fd, name
| 723
|
Python
|
.py
| 20
| 32.75
| 78
| 0.722461
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,675
|
timezone.py
|
translate_pootle/pootle/core/utils/timezone.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import datetime
from django.conf import settings
from django.utils import timezone
# Timezone aware minimum for datetime (if appropriate) (bug 2567)
datetime_min = datetime.datetime.min
if settings.USE_TZ:
datetime_min = timezone.make_aware(datetime_min, timezone.utc)
def localdate(dt=None):
dt = dt or timezone.now()
return timezone.localtime(dt).date()
def make_aware(value, tz=None):
"""Makes a `datetime` timezone-aware.
:param value: `datetime` object to make timezone-aware.
:param tz: `tzinfo` object with the timezone information the given value
needs to be converted to. By default, site's own default timezone will
be used.
"""
if getattr(settings, 'USE_TZ', False) and timezone.is_naive(value):
use_tz = tz if tz is not None else timezone.get_default_timezone()
value = timezone.make_aware(value, timezone=use_tz)
return value
def make_naive(value, tz=None):
"""Makes a `datetime` naive, i.e. not aware of timezones.
:param value: `datetime` object to make timezone-aware.
:param tz: `tzinfo` object with the timezone information the given value
needs to be converted to. By default, site's own default timezone will
be used.
"""
if getattr(settings, 'USE_TZ', False) and timezone.is_aware(value):
use_tz = tz if tz is not None else timezone.get_default_timezone()
value = timezone.make_naive(value, timezone=use_tz)
return value
def aware_datetime(*args, **kwargs):
"""Creates a `datetime` object and makes it timezone-aware.
:param args: arguments passed to `datetime` constructor.
:param tz: timezone in which the `datetime` should be constructed. Note that
this bypasses passing `tzinfo` to the `datetime` constructor, as it is
known not to play well with DST (unless only UTC is used).
"""
tz = kwargs.pop('tz', None)
return make_aware(datetime.datetime(*args, **kwargs), tz=tz)
| 2,252
|
Python
|
.py
| 48
| 42.145833
| 80
| 0.713763
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,676
|
html.py
|
translate_pootle/pootle/core/utils/html.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from lxml.html import rewrite_links as lxml_rewrite_links
def rewrite_links(input_html, callback, **kwargs):
"""Thin wrapper around lxml's `rewrite_links()` that prevents extra HTML
markup from being produced when there's no root tag present in the
input HTML.
This is needed as a workaround for #3889, and it simply wraps the input
text within `<div>...</div>` tags.
"""
return lxml_rewrite_links(u'<div>%s</div>' % input_html,
callback, **kwargs)
| 786
|
Python
|
.py
| 17
| 41.588235
| 77
| 0.699346
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,677
|
deprecation.py
|
translate_pootle/pootle/core/utils/deprecation.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings
from django.core import checks
DEPRECATIONS = [
# (old, new, deprecated_version, removed_version)
# ('OLD', 'NEW', '2.7', '2.9'),
# ('REMOVED', None, '2.7', '2.9'),
('TITLE', 'POOTLE_TITLE', '2.7', '2.8'),
('CAN_CONTACT', 'POOTLE_CONTACT_ENABLED', '2.7', '2.8'),
('CAN_REGISTER', 'POOTLE_SIGNUP_ENABLED', '2.7', '2.8'),
('CONTACT_EMAIL', 'POOTLE_CONTACT_EMAIL', '2.7', '2.8'),
('POOTLE_REPORT_STRING_ERRORS_EMAIL', 'POOTLE_CONTACT_REPORT_EMAIL',
'2.7', '2.8'),
('PODIRECTORY', 'POOTLE_TRANSLATION_DIRECTORY', '2.7', '2.8'),
('MARKUP_FILTER', 'POOTLE_MARKUP_FILTER', '2.7', '2.8'),
('USE_CAPTCHA', 'POOTLE_CAPTCHA_ENABLED', '2.7', '2.8'),
('POOTLE_TOP_STATS_CACHE_TIMEOUT', None, '2.7', None),
('MT_BACKENDS', 'POOTLE_MT_BACKENDS', '2.7', '2.8'),
('ENABLE_ALT_SRC', None, '2.5', None),
('VCS_DIRECTORY', None, '2.7', None),
('CONTRIBUTORS_EXCLUDED_NAMES', None, '2.7', None),
('CONTRIBUTORS_EXCLUDED_PROJECT_NAMES', None, '2.7', None),
('MIN_AUTOTERMS', None, '2.7', None),
('MAX_AUTOTERMS', None, '2.7', None),
('DESCRIPTION', None, '2.7', None),
('FUZZY_MATCH_MAX_LENGTH', None, '2.7', None),
('FUZZY_MATCH_MIN_SIMILARITY', None, '2.7', None),
('OBJECT_CACHE_TIMEOUT', 'POOTLE_CACHE_TIMEOUT', '2.7', '2.8'),
('LEGALPAGE_NOCHECK_PREFIXES', 'POOTLE_LEGALPAGE_NOCHECK_PREFIXES',
'2.7', '2.8'),
('CUSTOM_TEMPLATE_CONTEXT', 'POOTLE_CUSTOM_TEMPLATE_CONTEXT',
'2.7', '2.8'),
('EXPORTED_DIRECTORY_MODE', None, '2.7', None),
('EXPORTED_FILE_MODE', 'POOTLE_SYNC_FILE_MODE', '2.7', '2.8'),
('POOTLE_SCORE_COEFFICIENTS', 'POOTLE_SCORES', '2.8', '2.8'),
]
def check_deprecated_settings(app_configs=None, **kwargs):
errors = []
for old, new, dep_ver, remove_ver in DEPRECATIONS:
# Old setting just disappeared, we just want you to cleanup
if hasattr(settings, old) and new is None:
errors.append(checks.Info(
("Setting %s was removed in Pootle %s." %
(old, dep_ver)),
hint=("Remove %s from your settings." % old),
id="pootle.I002",
))
continue
# Both old and new defined, we'd like you to remove the old setting
if hasattr(settings, old) and hasattr(settings, new):
errors.append(checks.Info(
("Setting %s was replaced by %s in Pootle %s. Both are set." %
(old, new, dep_ver)),
hint=("Remove %s from your settings." % old),
id="pootle.I002",
))
continue
# Old setting is present and new setting is not defined:
# - Warn and copy
# - Fail hard if its too old
if hasattr(settings, old) and not hasattr(settings, new):
from pootle import VERSION
if VERSION >= tuple(int(x) for x in remove_ver.split(".")):
errors.append(checks.Critical(
("Setting %s is deprecated and was removed in Pootle %s." %
(old, remove_ver)),
hint=("Use %s instead." % new),
id="pootle.W002",
))
else:
errors.append(checks.Warning(
("Setting %s is deprecated and will be removed in "
"Pootle %s." % (old, remove_ver)),
hint=("Use %s instead." % new),
id="pootle.W002",
))
setattr(settings, new, getattr(settings, old))
continue
return errors
| 3,913
|
Python
|
.py
| 85
| 36.741176
| 79
| 0.561812
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,678
|
redis_rq.py
|
translate_pootle/pootle/core/utils/redis_rq.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from redis.connection import ConnectionError
from django_rq.queues import get_queue
from django_rq.workers import Worker
def redis_is_running():
"""Checks is redis is running
:returns: `True` if redis is running, `False` otherwise.
"""
try:
queue = get_queue()
Worker.all(queue.connection)
except ConnectionError:
return False
return True
def rq_workers_are_running():
"""Checks if there are any rq workers running
:returns: `True` if there are rq workers running, `False` otherwise.
"""
if redis_is_running():
queue = get_queue()
if len(queue.connection.smembers(Worker.redis_workers_keys)):
return True
return False
| 997
|
Python
|
.py
| 29
| 29.793103
| 77
| 0.703125
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,679
|
stats.py
|
translate_pootle/pootle/core/utils/stats.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.i18n.gettext import ugettext_lazy as _
# Maximal number of top contributors which is loaded for each request
TOP_CONTRIBUTORS_CHUNK_SIZE = 10
def get_translation_states(path_obj):
states = []
def make_dict(state, title, filter_url=True):
filter_name = filter_url and state or None
return {
'state': state,
'title': title,
'url': path_obj.get_translate_url(state=filter_name)
}
states.append(make_dict('total', _("Total"), False))
states.append(make_dict('translated', _("Translated")))
states.append(make_dict('fuzzy', _("Fuzzy")))
states.append(make_dict('untranslated', _("Untranslated")))
return states
| 989
|
Python
|
.py
| 24
| 36.208333
| 77
| 0.685475
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,680
|
version.py
|
translate_pootle/pootle/core/utils/version.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
# Some functions are taken from or modelled on the version management in
# Django. Those are:
# Copyright (c) Django Software Foundation and individual contributors. All
# rights reserved.
from __future__ import print_function
import datetime
import os
import subprocess
try:
from django.utils.lru_cache import lru_cache
except ImportError:
# Required for Python 2.7 support and when backported Django version is
# unavailable
def lru_cache():
def fake(func):
return func
return fake
from pootle.constants import VERSION
CANDIDATE_MARKERS = ('alpha', 'beta', 'rc', 'final')
def get_version(version=None):
"""Returns a PEP 440-compliant version number from VERSION.
The following examples show a progression from development through
pre-release to release and the resultant versions generated:
>>> get_version((2, 7, 1, 'alpha', 0))
'2.7.1.dev20150530132219'
>>> get_version((2, 7, 1, 'alpha', 1))
'2.7.1a1'
>>> get_version((2, 7, 1, 'beta', 1))
'2.7.1b1'
>>> get_version((2, 7, 1, 'rc', 2))
'2.7.1rc2'
>>> get_version((2, 7, 1, 'final', 0))
'2.7.1'
"""
version = get_complete_version(version)
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|rc}N - for alpha, beta and rc releases
main = get_main_version(version)
candidate_pos = _get_candidate_pos(version)
candidate = version[candidate_pos]
candidate_extra = version[candidate_pos+1]
sub = ''
if _is_development_candidate(version):
git_changeset = get_git_changeset()
if git_changeset:
sub = '.dev%s' % git_changeset
else:
sub = '.dev0'
elif candidate != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'}
sub = mapping[candidate] + str(candidate_extra)
return str(main + sub)
def _is_development_candidate(version):
"""Is this a pre-alpha release
>>> _is_development_candidate((2, 1, 0, 'alpha', 0))
True
>>> _is_development_candidate((2, 1, 0, 'beta', 1))
False
"""
candidate_pos = _get_candidate_pos(version)
candidate = version[candidate_pos]
candidate_extra = version[candidate_pos+1]
return candidate == 'alpha' and candidate_extra == 0
def _get_candidate_pos(version):
"""Returns the position of the candidate marker.
>>> _get_candidate_pos((1, 2, 0, 'alpha', 0))
3
"""
return [i for i, part in enumerate(version)
if part in CANDIDATE_MARKERS][0]
def _get_candidate(version):
"""Returns the candidate. One of alpha, beta, rc or final.
>>> _get_candidate((0, 1, 2, 'rc', 1))
'rc'
"""
return version[_get_candidate_pos(version)]
def _get_version_string(parts):
"""Returns an X.Y.Z version from the list of version parts.
>>> _get_version_string((1, 1, 0))
'1.1.0'
>>> _get_version_string((1, 1, 0, 1))
'1.1.0.1'
"""
return '.'.join(str(x) for x in parts)
def get_main_version(version=None):
"""Returns main version (X.Y[.Z]) from VERSION.
>>> get_main_version((1, 2, 3, 'alpha', 1))
'1.2.3'
"""
version = get_complete_version(version)
candidate_pos = _get_candidate_pos(version)
return _get_version_string(version[:candidate_pos])
def get_major_minor_version(version=None):
"""Returns X.Y from VERSION.
>>> get_major_minor_version((1, 2, 3, 'final', 0))
'1.2'
"""
version = get_complete_version(version)
return _get_version_string(version[:2])
def get_complete_version(version=None):
"""Returns a tuple of the Pootle version. Or the supplied ``version``
>>> get_complete_version((1, 2, 3, 'alpha', 0))
(1, 2, 3, 'alpha', 0)
"""
if version is not None:
return version
return VERSION
def get_docs_version(version=None, positions=2):
"""Return the version used in documentation.
>>> get_docs_version((1, 2, 1, 'alpha', 0))
'dev'
>>> get_docs_version((1, 2, 1, 'rc', 2))
'1.2'
"""
version = get_complete_version(version)
candidate_pos = _get_candidate_pos(version)
if positions > candidate_pos:
positions = candidate_pos
if _is_development_candidate(version):
return 'dev'
return _get_version_string(version[:positions])
def get_rtd_version(version=None):
"""Return the docs version string reported in the RTD site."""
version_str = get_docs_version(version=version, positions=2)
return (
'latest'
if version_str == 'dev'
else 'stable-%s.x' % (version_str, )
)
def _shell_command(command):
"""Return the first result of a shell ``command``"""
repo_dir = os.path.dirname(os.path.abspath(__file__))
try:
command_subprocess = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=repo_dir,
universal_newlines=True
)
except OSError:
return None
return command_subprocess.communicate()[0]
@lru_cache()
def get_git_changeset():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
>>> get_git_changeset()
'20150530132219'
"""
timestamp = _shell_command(
['/usr/bin/git', 'log', '--pretty=format:%ct', '--quiet', '-1', 'HEAD']
)
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S')
@lru_cache()
def get_git_branch():
"""Returns the current git branch.
>>> get_git_branch()
'feature/proper_version'
"""
branch = _shell_command(['/usr/bin/git', 'symbolic-ref', '-q',
'HEAD'])
if not branch:
return None
return "/".join(branch.strip().split("/")[2:])
@lru_cache()
def get_git_hash():
"""Returns the current git commit hash or None.
>>> get_git_hash()
'ad768e8'
"""
git_hash = _shell_command(
['/usr/bin/git', 'rev-parse', '--verify', '--short', 'HEAD']
)
if git_hash:
return git_hash.strip()
return None
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
if argv[1] == "main":
print(get_main_version())
elif argv[1] == "major_minor":
print(get_major_minor_version())
elif argv[1] == "docs":
print(get_docs_version())
else:
print(get_version())
def is_prerelease(version=None):
"""Is this a final release or not"""
return _get_candidate(get_complete_version(version)) != 'final'
| 7,189
|
Python
|
.py
| 206
| 29.242718
| 79
| 0.6304
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,681
|
json.py
|
translate_pootle/pootle/core/utils/json.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from __future__ import absolute_import
import json
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.utils.encoding import force_text
from django.utils.functional import Promise
from ..markup import Markup
class PootleJSONEncoder(DjangoJSONEncoder):
"""Custom JSON encoder for Pootle.
This is mostly implemented to avoid calling `force_text` all the time on
certain types of objects.
https://docs.djangoproject.com/en/1.10/topics/serialization/#djangojsonencoder
"""
def default(self, obj):
if isinstance(obj, (Promise, Markup)):
return force_text(obj)
return super(PootleJSONEncoder, self).default(obj)
def jsonify(obj):
"""Serialize Python `obj` object into a JSON string."""
if settings.DEBUG:
indent = 4
else:
indent = None
return json.dumps(obj, indent=indent, cls=PootleJSONEncoder)
| 1,214
|
Python
|
.py
| 31
| 35.064516
| 82
| 0.745517
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,682
|
dateformat.py
|
translate_pootle/pootle/core/utils/dateformat.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.utils import timezone
from django.utils.dateformat import DateFormat as DjangoDateFormat
class DateFormat(DjangoDateFormat):
def c(self):
return self.data.isoformat(' ')
def format(value, format_string='c'):
df = DateFormat(timezone.localtime(value))
return df.format(format_string)
| 597
|
Python
|
.py
| 15
| 37
| 77
| 0.763478
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,683
|
multistring.py
|
translate_pootle/pootle/core/utils/multistring.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from translate.misc.multistring import multistring
SEPARATOR = "__%$%__%$%__%$%__"
PLURAL_PLACEHOLDER = "__%POOTLE%_$NUMEROUS$__"
def list_empty(strings):
"""Check if list is exclusively made of empty strings.
useful for detecting empty multistrings and storing them as a
simple empty string in db.
"""
for string in strings:
if len(string) > 0:
return False
return True
def parse_multistring(db_string):
"""Parses a `db_string` coming from the DB into a multistring object."""
if not isinstance(db_string, basestring):
raise ValueError('Parsing into a multistring requires a string input.')
strings = db_string.split(SEPARATOR)
if strings[-1] == PLURAL_PLACEHOLDER:
strings = strings[:-1]
plural = True
else:
plural = len(strings) > 1
ms = multistring(strings, encoding="UTF-8")
ms.plural = plural
return ms
def unparse_multistring(values):
"""Converts a `values` multistring object or a list of strings back to the
in-DB multistring representation.
"""
if not (isinstance(values, multistring) or isinstance(values, list)):
return values
try:
values_list = list(values.strings)
has_plural_placeholder = getattr(values, 'plural', False)
except AttributeError:
values_list = values
has_plural_placeholder = False
if list_empty(values_list):
return ''
if len(values_list) == 1 and has_plural_placeholder:
values_list.append(PLURAL_PLACEHOLDER)
return SEPARATOR.join(values_list)
| 1,867
|
Python
|
.py
| 49
| 32.714286
| 79
| 0.687743
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,684
|
aggregate.py
|
translate_pootle/pootle/core/utils/aggregate.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
"""Wrappers around Django 1.1+ aggregate query functions."""
from django.db.models import Max
def max_column(queryset, column, default):
result = queryset.aggregate(result=Max(column))['result']
if result is None:
return default
return result
| 542
|
Python
|
.py
| 14
| 36
| 77
| 0.744275
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,685
|
subcommands.py
|
translate_pootle/pootle/core/management/subcommands.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
from django.utils.functional import cached_property
from dj import subcommand
from pootle.core.delegate import subcommands
class CommandWithSubcommands(subcommand.CommandWithSubcommands):
@cached_property
def subcommands(self):
return OrderedDict(subcommands.gather(self.__class__))
| 617
|
Python
|
.py
| 15
| 38.6
| 77
| 0.796639
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,686
|
results.py
|
translate_pootle/pootle/core/plugin/results.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
class Gathered(object):
def __init__(self, provider):
self.provider = provider
self.__results__ = []
def add_result(self, func, gathered):
self.__results__.append((func, gathered))
class GatheredDict(Gathered):
@property
def results(self):
gathered = OrderedDict()
for func_, result in self.__results__:
if result:
try:
gathered.update(result)
except TypeError:
# Result is ignored if you cant update a dict with it
pass
return gathered
def get(self, k, default=None):
try:
return self[k]
except KeyError:
return default
def keys(self):
return self.results.keys()
def values(self):
return [self[k] for k in self.results]
def items(self):
return [(k, self[k]) for k in self.results]
def __contains__(self, k):
return k in self.results
def __getitem__(self, k):
return self.results[k]
def __iter__(self):
for k in self.results.keys():
yield k
class GatheredList(Gathered):
@property
def results(self):
gathered = []
for func_, result in self.__results__:
if isinstance(result, (list, tuple)):
gathered.extend(result)
return gathered
def __iter__(self):
for item in self.results:
yield item
| 1,798
|
Python
|
.py
| 55
| 24.436364
| 77
| 0.593387
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,687
|
__init__.py
|
translate_pootle/pootle/core/plugin/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from delegate import getter, provider
__all__ = ("getter", "provider")
| 349
|
Python
|
.py
| 9
| 37.444444
| 77
| 0.744807
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,688
|
exceptions.py
|
translate_pootle/pootle/core/plugin/exceptions.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
class StopProviding(Exception):
def __init__(self, *args, **kwargs):
self.result = kwargs.pop("result", None)
| 400
|
Python
|
.py
| 10
| 37.5
| 77
| 0.72093
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,689
|
delegate.py
|
translate_pootle/pootle/core/plugin/delegate.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.dispatch import Signal
from django.dispatch.dispatcher import NO_RECEIVERS, NONE_ID, _make_id, weakref
from .exceptions import StopProviding
from .results import GatheredDict
class Provider(Signal):
result_class = GatheredDict
def __init__(self, *args, **kwargs):
self.result_class = kwargs.pop("result_class", self.result_class)
self._sender_map = {}
super(Provider, self).__init__(*args, **kwargs)
def gather(self, sender=None, **named):
gathered = self.result_class(self)
named["gathered"] = gathered
no_receivers = (
not self.receivers
or (sender and self.use_caching
and not self._dead_receivers
and self.sender_receivers_cache.get(sender) is NO_RECEIVERS))
if no_receivers:
return gathered
for provider in self._live_receivers(sender):
try:
gathered.add_result(
provider,
provider(signal=self, sender=sender, **named))
except StopProviding as e:
# allow a provider to prevent further gathering
gathered.add_result(
provider,
e.result)
break
return gathered
def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
super(Provider, self).connect(receiver, sender, weak, dispatch_uid)
self._sender_map[_make_id(sender)] = sender
def _live_receivers(self, sender):
"""
Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.
"""
with self.lock:
self._clear_dead_receivers()
senderkey = _make_id(sender)
receivers = []
for (receiverkey, r_senderkey), receiver in self.receivers:
r_sender = self._sender_map[r_senderkey]
if r_senderkey == NONE_ID or r_senderkey == senderkey:
receivers.append(receiver)
elif sender and issubclass(sender, r_sender):
receivers.append(receiver)
if self.use_caching and sender:
if not receivers:
self.sender_receivers_cache[sender] = NO_RECEIVERS
else:
# Note, we must cache the weakref versions.
self.sender_receivers_cache[sender] = receivers
non_weak_receivers = []
for receiver in receivers:
if isinstance(receiver, weakref.ReferenceType):
# Dereference the weak reference.
receiver = receiver()
if receiver is not None:
non_weak_receivers.append(receiver)
else:
non_weak_receivers.append(receiver)
return non_weak_receivers
def provider(signal, **kwargs):
def _decorator(func):
if isinstance(signal, (list, tuple)):
for s in signal:
s.connect(func, **kwargs)
else:
signal.connect(func, **kwargs)
return func
return _decorator
class Getter(Signal):
def __init__(self, *args, **kwargs):
super(Getter, self).__init__(*args, **kwargs)
self.use_caching = True
def get(self, sender=None, **named):
receivers_cache = self.sender_receivers_cache.get(sender)
no_receivers = (
not self.receivers
or receivers_cache is NO_RECEIVERS)
if no_receivers:
return None
elif receivers_cache:
for receiver in receivers_cache:
if isinstance(receiver, weakref.ReferenceType):
# Dereference the weak reference.
receiver = receiver()
if receiver is not None:
response = receiver(signal=self, sender=sender, **named)
if response is not None:
return response
for receiver in self._live_receivers(sender):
response = receiver(signal=self, sender=sender, **named)
if response is not None:
return response
def getter(signal, **kwargs):
def _connect(s, func, **kwargs):
senders = kwargs.pop('sender', None)
if isinstance(senders, (list, tuple)):
for sender in senders:
s.connect(func, sender=sender, **kwargs)
else:
s.connect(func, sender=senders, **kwargs)
def _decorator(func):
if isinstance(signal, (list, tuple)):
for s in signal:
_connect(s, func, **kwargs)
else:
_connect(signal, func, **kwargs)
return func
return _decorator
| 5,114
|
Python
|
.py
| 123
| 30.154472
| 79
| 0.584758
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,690
|
broker.py
|
translate_pootle/pootle/core/search/broker.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import importlib
import logging
from . import SearchBackend
class SearchBroker(SearchBackend):
def __init__(self, config_name=None):
super(SearchBroker, self).__init__(config_name)
self._servers = {}
if self._settings is None:
return
for server in self._settings:
if config_name is None or server in config_name:
try:
_module = '.'.join(
self._settings[server]['ENGINE'].split('.')[:-1])
_search_class = \
self._settings[server]['ENGINE'].split('.')[-1]
except KeyError:
logging.warning("Search engine '%s' is missing the "
"required 'ENGINE' setting", server)
break
try:
module = importlib.import_module(_module)
try:
self._servers[server] = getattr(module,
_search_class)(server)
except AttributeError:
logging.warning("Search backend '%s'. No search class "
"'%s' defined.", server, _search_class)
except ImportError:
logging.warning("Search backend '%s'. Cannot import '%s'",
server, _module)
def search(self, unit):
if not self._servers:
return []
results = []
counter = {}
for server in self._servers:
for result in self._servers[server].search(unit):
translation_pair = result['source'] + result['target']
if translation_pair not in counter:
counter[translation_pair] = result['count']
results.append(result)
else:
counter[translation_pair] += result['count']
for item in results:
item['count'] = counter[item['source']+item['target']]
# Results are in the order of the TM servers, so they must be sorted by
# score so the better matches are presented to the user.
results = sorted(results, reverse=True,
key=lambda item: item['score'])
return results
def update(self, language, obj):
for server in self._servers:
if self._servers[server].is_auto_updatable:
self._servers[server].update(language, obj)
| 2,829
|
Python
|
.py
| 62
| 31
| 79
| 0.527042
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,691
|
__init__.py
|
translate_pootle/pootle/core/search/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from .base import SearchBackend
from .broker import SearchBroker
from .backends import ElasticSearchBackend
__all__ = ('SearchBackend', 'SearchBroker', 'ElasticSearchBackend')
| 454
|
Python
|
.py
| 11
| 40
| 77
| 0.779545
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,692
|
base.py
|
translate_pootle/pootle/core/search/base.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings
SERVER_SETTINGS_NAME = 'POOTLE_TM_SERVER'
class SearchBackend(object):
def __init__(self, config_name=None):
self._setup_settings(config_name)
self.weight = 1.0
def _setup_settings(self, config_name):
self._settings = getattr(settings, SERVER_SETTINGS_NAME, None)
if config_name is not None:
self._settings = self._settings[config_name]
@property
def is_auto_updatable(self):
"""Tells if TM is automatically updated from DB translations.
Basically this tells if TM is the 'local' TM.
"""
for key, value in getattr(settings, SERVER_SETTINGS_NAME, {}).items():
if (value['INDEX_NAME'] == self._settings['INDEX_NAME'] and
key == 'local'):
return True
return False
def search(self, unit):
"""Search for TM results.
:param unit: :cls:`~pootle_store.models.Unit`
:return: list of results or [] for no results or offline
"""
raise NotImplementedError
def update(self, language, obj):
"""Add a unit to the backend"""
pass
| 1,444
|
Python
|
.py
| 36
| 32.944444
| 78
| 0.644907
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,693
|
__init__.py
|
translate_pootle/pootle/core/search/backends/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from .elasticsearch import ElasticSearchBackend
__all__ = ('ElasticSearchBackend', )
| 363
|
Python
|
.py
| 9
| 39
| 77
| 0.763533
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,694
|
elasticsearch.py
|
translate_pootle/pootle/core/search/backends/elasticsearch.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from __future__ import absolute_import
import logging
import Levenshtein
try:
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import ElasticsearchException
except ImportError:
Elasticsearch = None
from ..base import SearchBackend
__all__ = ('ElasticSearchBackend',)
logger = logging.getLogger(__name__)
DEFAULT_MIN_SIMILARITY = 0.7
def filter_hits_by_distance(hits, source_text,
min_similarity=DEFAULT_MIN_SIMILARITY):
"""Returns ES `hits` filtered according to their Levenshtein distance
to the `source_text`.
Any hits with a similarity value (0..1) lower than `min_similarity` will be
discarded. It's assumed that `hits` is already sorted from higher to lower
score.
"""
if min_similarity <= 0 or min_similarity >= 1:
min_similarity = DEFAULT_MIN_SIMILARITY
filtered_hits = []
for hit in hits:
hit_source_text = hit['_source']['source']
distance = Levenshtein.distance(source_text, hit_source_text)
similarity = (
1 - distance / float(max(len(source_text), len(hit_source_text)))
)
logger.debug(
'Similarity: %.2f (distance: %d)\nOriginal:\t%s\nComparing with:\t%s',
similarity, distance, source_text, hit_source_text
)
if similarity < min_similarity:
break
filtered_hits.append(hit)
return filtered_hits
class ElasticSearchBackend(SearchBackend):
def __init__(self, config_name):
super(ElasticSearchBackend, self).__init__(config_name)
self._es = self._get_es_server()
self._create_index_if_missing()
self.weight = min(max(self._settings.get('WEIGHT', self.weight),
0.0), 1.0)
def _get_es_server(self):
return Elasticsearch([
{'host': self._settings['HOST'],
'port': self._settings['PORT']},
])
def _create_index_if_missing(self):
try:
if not self._es.indices.exists(self._settings['INDEX_NAME']):
self._es.indices.create(self._settings['INDEX_NAME'])
except ElasticsearchException as e:
self._log_error(e)
def _is_valuable_hit(self, unit, hit):
return str(unit.id) != hit['_id']
def _es_call(self, cmd, *args, **kwargs):
try:
return getattr(self._es, cmd)(*args, **kwargs)
except ElasticsearchException as e:
self._log_error(e)
return None
def _log_error(self, e):
logger.error("Elasticsearch error for server(%s:%s): %s",
self._settings.get("HOST"), self._settings.get("PORT"), e)
def search(self, unit):
counter = {}
res = []
language = unit.store.translation_project.language.code
es_res = self._es_call(
"search",
index=self._settings['INDEX_NAME'],
doc_type=language,
body={
"query": {
"match": {
"source": {
"query": unit.source,
"fuzziness": 'AUTO',
}
}
}
}
)
if es_res is None:
# ElasticsearchException - eg ConnectionError.
return []
elif es_res == "":
# There seems to be an issue with urllib where an empty string is
# returned
logger.error("Elasticsearch search (%s:%s) returned an empty "
"string: %s", self._settings["HOST"],
self._settings["PORT"], unit)
return []
hits = filter_hits_by_distance(
es_res['hits']['hits'],
unit.source,
min_similarity=self._settings.get('MIN_SIMILARITY',
DEFAULT_MIN_SIMILARITY)
)
for hit in hits:
if self._is_valuable_hit(unit, hit):
body = hit['_source']
translation_pair = body['source'] + body['target']
if translation_pair not in counter:
counter[translation_pair] = 1
res.append({
'unit_id': hit['_id'],
'source': body['source'],
'target': body['target'],
'project': body['project'],
'path': body['path'],
'username': body['username'],
'fullname': body['fullname'],
'email_md5': body['email_md5'],
'iso_submitted_on': body.get('iso_submitted_on', None),
'display_submitted_on': body.get('display_submitted_on',
None),
'score': hit['_score'] * self.weight,
})
else:
counter[translation_pair] += 1
for item in res:
item['count'] = counter[item['source']+item['target']]
return res
def update(self, language, obj):
self._es_call(
"index",
index=self._settings['INDEX_NAME'],
doc_type=language,
body=obj,
id=obj['id']
)
| 5,682
|
Python
|
.py
| 141
| 27.858156
| 82
| 0.529134
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,695
|
dates.py
|
translate_pootle/pootle/i18n/dates.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from datetime import datetime
from django.conf import settings
from .formatter import get_locale_formats
def timesince(timestamp, locale=None):
timedelta = datetime.now() - datetime.fromtimestamp(timestamp)
formatted = get_locale_formats(locale).timedelta(timedelta, format='long')
if formatted:
return formatted
return get_locale_formats(
settings.LANGUAGE_CODE).timedelta(timedelta, format='long')
| 712
|
Python
|
.py
| 17
| 38.705882
| 78
| 0.763768
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,696
|
formatter.py
|
translate_pootle/pootle/i18n/formatter.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from __future__ import absolute_import
from babel import (UnknownLocaleError, core as babel_core,
support as babel_support)
from django.conf import settings
from django.utils.translation import get_language, to_locale
def get_locale_formats(locale=None):
languages = [locale] if locale else []
languages += [get_language(), settings.LANGUAGE_CODE, 'en-us']
for language in languages:
try:
locale = babel_core.Locale.parse(to_locale(language))
break
except UnknownLocaleError:
continue
return babel_support.Format(locale)
def _clean_zero(number):
if number is None or number == '':
return 0
return number
def number(number):
number = _clean_zero(number)
return get_locale_formats().number(number)
def percent(number, format=None):
number = _clean_zero(number)
return get_locale_formats().percent(number, format)
| 1,216
|
Python
|
.py
| 32
| 32.9375
| 77
| 0.70844
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,697
|
gettext.py
|
translate_pootle/pootle/i18n/gettext.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from translate.lang import data as langdata
from django.conf import settings
from django.utils import translation
from django.utils.functional import lazy
from django.utils.translation import _trans
def _format_translation(message, variables=None):
"""Overrides the gettext function, handling variable errors more
gracefully.
This is needed to avoid tracebacks on translation errors with live
translation.
"""
if variables is not None:
try:
return message % variables
except Exception:
pass
return message
def ugettext(message, variables=None):
return _format_translation(_trans.ugettext(message), variables)
def gettext(message, variables=None):
return _format_translation(_trans.gettext(message), variables)
def ungettext(singular, plural, number, variables=None):
return _format_translation(_trans.ungettext(singular, plural, number),
variables)
def ngettext(singular, plural, number, variables=None):
return _format_translation(_trans.ngettext(singular, plural, number), variables)
gettext_lazy = lazy(gettext, str)
ugettext_lazy = lazy(ugettext, unicode)
ngettext_lazy = lazy(ngettext, str)
ungettext_lazy = lazy(ungettext, unicode)
def tr_lang(language_name):
"""Translates language names."""
return langdata.tr_lang(
translation.to_locale(
translation.get_language()
or settings.LANGUAGE_CODE))(language_name)
def language_dir(language_code):
"""Returns whether the language is right to left"""
RTL_LANGS = [
# Helpful list of RTL codes:
# https://en.wikipedia.org/wiki/Right-to-left#RTL_Wikipedia_languages
'ar', 'arc', 'bcc', 'bqi', 'ckb', 'dv', 'fa', 'glk', 'he', 'ks', 'lrc',
'mzn', 'pnb', 'ps', 'sd', 'ug', 'ur', 'yi', 'nqo',
# and
# https://github.com/i18next/i18next/blob/ee3afd8e5d958e8d703a208194e59fa5228165fd/src/i18next.js#L257-L262
'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm',
'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp',
'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh',
'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'iw', 'pbt', 'pbu', 'pst', 'prp',
'prd', 'ydd', 'yds', 'yih', 'ji', 'hbo', 'men', 'xmn', 'jpr', 'peo',
'pes', 'prs', 'sam',
]
shortcode = language_code[:3]
if not shortcode.isalpha():
shortcode = language_code[:2]
if shortcode in RTL_LANGS:
return "rtl"
return "ltr"
| 2,857
|
Python
|
.py
| 65
| 38.061538
| 115
| 0.652943
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,698
|
override.py
|
translate_pootle/pootle/i18n/override.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
"""Overrides and support functions for arbitrary locale support."""
import os
from translate.lang import data
from django.utils import translation
from django.utils.translation import LANGUAGE_SESSION_KEY, trans_real
from pootle.i18n import gettext
def find_languages(locale_path):
"""Generate supported languages list from the :param:`locale_path`
directory.
"""
dirs = os.listdir(locale_path)
langs = []
for lang in dirs:
if (data.langcode_re.match(lang) and
os.path.isdir(os.path.join(locale_path, lang))):
langs.append((trans_real.to_language(lang),
data.languages.get(lang, (lang,))[0]))
return langs
def supported_langs():
"""Returns a list of supported locales."""
from django.conf import settings
return settings.LANGUAGES
def get_language_supported(lang_code, supported):
normalized = data.normalize_code(data.simplify_to_common(lang_code))
if normalized in supported:
return normalized
# FIXME: horribly slow way of dealing with languages with @ in them
for lang in supported.keys():
if normalized == data.normalize_code(lang):
return lang
return None
def get_lang_from_session(request, supported):
if not hasattr(request, 'session'):
return None
lang_code = request.session.get(LANGUAGE_SESSION_KEY, None)
if not lang_code:
return None
return get_language_supported(lang_code, supported)
def get_lang_from_cookie(request, supported):
"""See if the user's browser sent a cookie with a preferred language."""
from django.conf import settings
lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
if not lang_code:
return None
return get_language_supported(lang_code, supported)
def get_lang_from_http_header(request, supported):
"""If the user's browser sends a list of preferred languages in the
HTTP_ACCEPT_LANGUAGE header, parse it into a list. Then walk through
the list, and for each entry, we check whether we have a matching
pootle translation project. If so, we return it.
If nothing is found, return None.
"""
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
for accept_lang, __ in trans_real.parse_accept_lang_header(accept):
if accept_lang == '*':
return None
supported_lang = get_language_supported(accept_lang, supported)
if supported_lang:
return supported_lang
return None
def get_language_from_request(request, check_path=False):
"""Try to get the user's preferred language by first checking the
cookie and then by checking the HTTP language headers.
If all fails, try fall back to default language.
"""
supported = dict(supported_langs())
for lang_getter in (get_lang_from_session,
get_lang_from_cookie,
get_lang_from_http_header):
lang = lang_getter(request, supported)
if lang is not None:
return lang
from django.conf import settings
if settings.LANGUAGE_CODE in supported:
return settings.LANGUAGE_CODE
return 'en-us'
def get_language_bidi():
"""Override for Django's get_language_bidi that's aware of more RTL
languages.
"""
return gettext.language_dir(translation.get_language()) == 'rtl'
def hijack_translation():
"""Sabotage Django's fascist linguistical regime."""
# Override functions that check if language is known to Django
translation.check_for_language = lambda lang_code: True
trans_real.check_for_language = lambda lang_code: True
translation.get_language_from_request = get_language_from_request
# Override django's inadequate bidi detection
translation.get_language_bidi = get_language_bidi
| 4,107
|
Python
|
.py
| 96
| 36.760417
| 77
| 0.704996
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,699
|
contact.py
|
translate_pootle/tests/views/contact.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from __future__ import absolute_import
import pytest
from django.urls import reverse
from pootle_store.models import Unit
@pytest.mark.django_db
def test_contact_report_form_view(client, request_users, rf):
unit = Unit.objects.last()
url = '%s?report=%s' % (reverse('pootle-contact-report-error'), unit.pk)
user = request_users["user"]
if user.username != "nobody":
client.login(username=user.username, password=user.password)
response = client.get(url)
assert response.status_code == 200
assert 'contact_form_title' in response.context
assert response.context['contact_form_url'] == url
assert response.context['form'].unit == unit
assert response.context['view'].unit == unit
@pytest.mark.django_db
def test_contact_report_form_view_no_unit(client, member, rf):
url = reverse('pootle-contact-report-error')
client.login(username=member.username, password=member.password)
response = client.get(url)
assert response.status_code == 200
assert response.context['view'].unit is None
assert 'context' not in response.context['view'].get_initial()
@pytest.mark.django_db
def test_contact_report_form_view_blank_unit(client, member, rf):
url = '%s?report=' % reverse('pootle-contact-report-error')
client.login(username=member.username, password=member.password)
response = client.get(url)
assert response.status_code == 200
assert response.context['view'].unit is None
@pytest.mark.django_db
def test_contact_report_form_view_no_numeric_unit(client, member, rf):
url = '%s?report=STRING' % reverse('pootle-contact-report-error')
client.login(username=member.username, password=member.password)
response = client.get(url)
assert response.status_code == 200
assert response.context['view'].unit is None
@pytest.mark.django_db
def test_contact_report_form_view_unexisting_unit(client, member, rf):
unit_pk = 99999999
Unit.objects.filter(id=unit_pk).delete() # Ensure unit doesn't exist.
url = '%s?report=%s' % (reverse('pootle-contact-report-error'), unit_pk)
client.login(username=member.username, password=member.password)
response = client.get(url)
assert response.status_code == 200
assert response.context['view'].unit is None
| 2,560
|
Python
|
.tac
| 55
| 42.654545
| 77
| 0.73572
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|