from cone.ugm.utils import general_settings from plumber import Behavior from plumber import default from plumber import plumb from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory('cone.ugm') class AutoIncrementForm(Behavior): """Plumbing behavior for setting user id by auto increment logic. For user add form. """ @default @property def autoincrement_support(self): settings = general_settings(self.model) return settings.attrs.user_id_autoincrement == 'True' @default @property def next_principal_id(self): settings = general_settings(self.model) prefix = settings.attrs.user_id_autoincrement_prefix default = int(settings.attrs.user_id_autoincrement_start) search = u'%s*' % prefix backend = self.model.parent.backend backend.invalidate() result = backend.search(attrlist=['id'], criteria={'id': search}) if result and isinstance(result[0][1]['id'], list):
from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory('kotti_blog') def kotti_configure(settings): settings['pyramid.includes'] += ' kotti_blog.views' settings['kotti.available_types'] +=\ ' kotti_blog.resources.Blog kotti_blog.resources.BlogEntry' settings['kotti.populators'] += ' kotti_blog.populate.populate_settings'
import colander import deform.widget import deform_bootstrap.widget from deform.i18n import _ as deform_i18n from ..util import get_all_permissions from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory('substanced') class CSRFToken(colander.SchemaNode): schema_type = colander.String widget = deform.widget.HiddenWidget() def validator(self, node, value): request = self.bindings['request'] token = request.session.get_csrf_token() if value != token: raise colander.Invalid(node, _('Invalid cross-site scripting token'), value) def after_bind(self, node, kw): token = kw['request'].session.get_csrf_token() self.default = token
# -*- coding: utf-8 -*- import logging from pyramid.security import DENY_ALL from pyramid.i18n import TranslationStringFactory from c2cgeoportal.models import * # noqa # from c2cgeoportal.models import _schema _ = TranslationStringFactory('demo-server') log = logging.getLogger(__name__) LayerInternalWMS.__acl__ = [DENY_ALL] LayerExternalWMS.__acl__ = [DENY_ALL] LayerWMTS.__acl__ = [DENY_ALL] WMTSDimension.__acl__ = [DENY_ALL]
HTTPUnauthorized) import transaction from .. import get_default_context, get_locale_from_request from ...lib.utils import get_global_base_url from ...auth import (R_PARTICIPANT, R_SYSADMIN, R_ADMINISTRATOR, SYSTEM_ROLES, P_SYSADMIN, P_ADMIN_DISC, Everyone) from ...auth.util import (add_multiple_users_csv, user_has_permission, get_permissions) from ...models import (Discussion, DiscussionPermission, Role, Permission, UserRole, LocalUserRole, Preferences, User, Username, AgentProfile, IMAPMailbox, MailingList) from ...models.auth import create_default_permissions from ...nlp.translation_service import DummyGoogleTranslationService _ = TranslationStringFactory('assembl') class PseudoDiscussion(object): id = 0 topic = "Administration" slug = "admin" homepage_url = None logo = None def translation_service(self): return None def get_base_url(self, *args): return get_global_base_url(True)
import math import datetime as dt from dateutil.parser import parse as dparse from dateutil.relativedelta import relativedelta from pyramid.view import view_config from pyramid.httpexceptions import HTTPForbidden from sqlalchemy import func from netprofile.common.hooks import register_hook from netprofile.db.connection import DBSession from netprofile_stashes.models import Stash from netprofile_access.models import AccessEntity from .models import (AccessSession, AccessSessionHistory) _ = TranslationStringFactory('netprofile_sessions') _st = TranslationStringFactory('netprofile_stashes') @register_hook('core.dpanetabs.access.AccessEntity') def _dpane_access_sessions(tabs, model, req): if not req.has_permission('SESSIONS_LIST'): return loc = req.localizer tabs.extend(({ 'title': loc.translate(_('Active Sessions')), 'iconCls': 'ico-mod-accesssession', 'xtype': 'grid_sessions_AccessSession', 'stateId': None, 'stateful': False, 'hideColumns': ('entity', ),
from pyramid.i18n import TranslationStringFactory from pyramid.view import view_config, view_defaults from testscaffold.grids import UsersGrid, UserPermissionsGrid from testscaffold.models.user import User from testscaffold.util import safe_integer from testscaffold.validation.forms import (UserAdminCreateForm, UserAdminUpdateForm, DirectPermissionForm) from testscaffold.views.shared.users import UsersShared, USERS_PER_PAGE from testscaffold.views import BaseView log = logging.getLogger(__name__) _ = TranslationStringFactory('testscaffold') @view_defaults(route_name='admin_objects', permission='admin_users') class AdminUsersViews(BaseView): def __init__(self, request): super(AdminUsersViews, self).__init__(request) self.shared = UsersShared(request) @view_config(renderer='testscaffold:templates/admin/users/index.jinja2', match_param=('object=users', 'verb=GET')) def collection_list(self): page = safe_integer(self.request.GET.get('page', 1)) user_paginator = self.shared.collection_list(page=page) start_number = (USERS_PER_PAGE * (self.shared.page - 1) + 1) or 1 user_grid = UsersGrid(user_paginator,
# Public License along with NetProfile. If not, see # <http://www.gnu.org/licenses/>. from __future__ import (unicode_literals, print_function, absolute_import, division) from netprofile.common.modules import ModuleBase from sqlalchemy.orm.exc import NoResultFound from pyramid.i18n import TranslationStringFactory from ._version import get_versions __version__ = get_versions()['version'] del get_versions _ = TranslationStringFactory('netprofile_dialup') class Module(ModuleBase): def __init__(self, mmgr): self.mmgr = mmgr mmgr.cfg.add_translation_dirs('netprofile_dialup:locale/') mmgr.cfg.scan() @classmethod def get_models(cls): from netprofile_dialup import models return (models.IPPool, models.NAS, models.NASPool) @classmethod def get_sql_data(cls, modobj, vpair, sess):
from sqlalchemy.orm import relationship, backref from geoalchemy import GeometryColumn, Geometry, Polygon, GeometryDDL from formalchemy import Column from pyramid.security import Allow, ALL_PERMISSIONS, DENY_ALL from pyramid.i18n import TranslationStringFactory from c2cgeoportal import schema, parentschema, srid from c2cgeoportal.lib import caching from c2cgeoportal.lib.sqlalchemy_ import JSONEncodedDict __all__ = [ 'Base', 'DBSession', 'Functionality', 'User', 'Role', 'TreeItem', 'TreeGroup', 'LayerGroup', 'Theme', 'Layer', 'RestrictionArea' ] _ = TranslationStringFactory('c2cgeoportal') log = logging.getLogger(__name__) Base = sqlahelper.get_base() DBSession = sqlahelper.get_session() DBSessions = { 'dbsession': DBSession, } AUTHORIZED_ROLE = 'role_admin' if schema is not None: _schema = schema else: raise Exception(
# -*- coding: utf-8 -*- import logging from pyramid.i18n import TranslationStringFactory from c2cgeoportal_commons.models.main import * # noqa _ = TranslationStringFactory('waddle-server') LOG = logging.getLogger(__name__)
from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory('Courts-Of-Chaos') def my_view(request): return {'project': 'Courts-Of-Chaos'}
# # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. from pyramid.i18n import get_localizer, TranslationStringFactory from pyramid.threadlocal import get_current_request translation_domain = 'yithlibraryserver' TranslationString = TranslationStringFactory(translation_domain) def deform_translator(term): return get_localizer(get_current_request()).translate(term) def locale_negotiator(request): available_languages = request.registry.settings['available_languages'] return request.accept_language.best_match(available_languages)
from pyramid.i18n import TranslationStringFactory m2m_groups_tsf = TranslationStringFactory('m2m_groups') def includeme(config): config.scan() config.include('m2m_groups.models')
# -*- coding: utf-8 -*- """ Define a message factory and a locale negotiator.""" from pyramid.i18n import TranslationStringFactory MessageFactory = TranslationStringFactory('anuket') def locale_negotiator(request): """ Return a locale name by looking at the ``Accept-Language`` HTTP header. :param request: a ``pyramid.request`` object :return: the language code """ settings = request.registry.settings available_languages = settings['pyramid.available_languages'].split() return request.accept_language.best_match(available_languages)
import markdown import pkg_resources import requests import rpm from bodhi.server import ffmarkdown, log, buildsys, Session from bodhi.server.config import config from bodhi.server.exceptions import RepodataException if typing.TYPE_CHECKING: # pragma: no cover from bodhi.server import models # noqa: 401 import mako # noqa: 401 _ = TranslationStringFactory('bodhi') http_session = requests.Session() def header(x): """Display a given message as a heading.""" return "%s\n %s\n%s\n" % ('=' * 80, x, '=' * 80) def get_rpm_header(nvr, tries=0): """ Get the rpm header for a given build. Args: nvr (str): The name-version-release string of the build you want headers for.
from pyramid.i18n import get_localizer, TranslationStringFactory from pyramid.threadlocal import get_current_request def add_renderer_globals(event): request = event.get('request') if request is None: request = get_current_request() event['_'] = request.translate event['localizer'] = request.localizer tsf = TranslationStringFactory('stock') def add_localizer(event): request = event.request localizer = get_localizer(request) def auto_translate(string): return localizer.translate(tsf(string)) request.localizer = localizer request.translate = auto_translate
from sys import argv from logging import getLogger from pyramid.i18n import TranslationStringFactory APP_NAME = 'arche_celery' _ = TranslationStringFactory(APP_NAME) logger = getLogger(__name__) DEFAULT_CONFIGURATION = { '%s.worker_auth' % APP_NAME: 'arche_celery.authentication.worker_auth', } def includeme(config): settings = config.registry.settings for (k, v) in DEFAULT_CONFIGURATION.items(): if k not in settings: settings[k] = v config.include('pyramid_celery') #FIXME: option to add configurator object or specify ini file? #FIXME: This is not the best way to figure out the ini file. ini_file = None if '%s.ini' % APP_NAME in settings: ini_file = settings['%s.ini' % APP_NAME] else: for arg in argv: if arg.endswith('.ini'): ini_file = arg break if ini_file:
# # Copyright (c) 2015-2019 Thierry Florac <tflorac AT ulthar.net> # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # """PyAMS_catalog package PyAMS extensions for Hypatia catalog """ __docformat__ = 'restructuredtext' from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory('pyams_catalog') def includeme(config): """pyams_catalog features include""" from .include import include_package # pylint: disable=import-outside-toplevel include_package(config)
from geoalchemy2.shape import to_shape from deform.widget import HiddenWidget from c2cgeoform.ext import colander_ext, deform_ext from c2cgeoportal_commons.models import Base, schema, srid from c2cgeoportal_commons.models.sqlalchemy import JSONEncodedDict try: from pyramid.security import Allow, ALL_PERMISSIONS, DENY_ALL # Fallback if pyramid do not exists, used by QGIS server plugin except ImportError: # pragma: no cover Allow = ALL_PERMISSIONS = DENY_ALL = None try: from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory("c2cgeoportal") except ImportError: def _(s): return s LOG = logging.getLogger(__name__) AUTHORIZED_ROLE = "role_admin" if schema is not None: _schema = schema else: # pragma: no cover raise Exception("schema not specified, you need to add it to your config") if srid is not None:
# # Copyright (c) 2015-2019 Thierry Florac <tflorac AT ulthar.net> # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # """PyAMS_site package PyAMS site management features """ __docformat__ = 'restructuredtext' from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory('pyams_site') def includeme(config): """pyams_site features include""" from .include import include_package # pylint: disable=import-outside-toplevel include_package(config)
from cone.app.ugm import ugm_backend from plumber import Behavior from plumber import default from plumber import plumb from pyramid.i18n import TranslationStringFactory from pyramid.security import ALL_PERMISSIONS from pyramid.security import Allow from pyramid.security import Deny from pyramid.security import Everyone from pyramid.security import remember from pyramid.threadlocal import get_current_request from zope.interface import implementer import logging logger = logging.getLogger('cone.app') _ = TranslationStringFactory('cone.app') DEFAULT_ROLES = [ ('viewer', _('role_viewer', default='Viewer')), ('editor', _('role_editor', default='Editor')), ('admin', _('role_admin', default='Admin')), ('manager', _('role_manager', default='Manager')), ] authenticated_permissions = [ 'view', ] viewer_permissions = [ 'view', 'list', ]
from adhocracy_core.interfaces import IPool from adhocracy_core.interfaces import IResource from adhocracy_core.resources import add_resource_type_to_registry from adhocracy_core.resources.pool import pool_meta from adhocracy_core.resources.asset import add_assets_service from adhocracy_core.resources.badge import add_badges_service from adhocracy_core.sheets.asset import IHasAssetPool from adhocracy_core.sheets.badge import IHasBadgesPool from adhocracy_core.sheets.description import IDescription from adhocracy_core.sheets.embed import IEmbed from adhocracy_core.sheets.embed import IEmbedCodeConfig from adhocracy_core.sheets.embed import embed_code_config_adapter from adhocracy_core.sheets.notification import IFollowable from adhocracy_core.sheets.anonymize import IAllowAddAnonymized _ = TranslationStringFactory('adhocracy') class IProcess(IPool): """Participation Process Pool.""" process_meta = pool_meta._replace(content_name=_('Process'), iresource=IProcess, permission_create='create_process', is_sdi_addable=True, after_creation=( add_assets_service, add_badges_service, ), default_workflow='sample',
import unittest from pyramid import testing from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory('autograph') class ViewTests(unittest.TestCase): def setUp(self): testing.setUp() def tearDown(self): testing.tearDown() def test_my_view(self): from autograph.views import my_view request = testing.DummyRequest() response = my_view(request) self.assertEqual(response['project'], 'autograph')
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import hashlib import os from pyramid.i18n import TranslationStringFactory from pyramid import threadlocal _ = TranslationStringFactory("pyramid") from appenlight import security from appenlight.lib import helpers, generate_random_string from appenlight.models.services.config import ConfigService def gen_urls(request): urls = { "baseUrl": request.route_url("/"), "applicationsNoId": request.route_url("applications_no_id"), "applications": request.route_url("applications", resource_id="REPLACE_ID").replace( "REPLACE_ID", ":resourceId"),
return hasattr(self, k) def __getitem__(self, k): try: return getattr(self, k) except AttributeError: raise KeyError def __setitem__(self, k, v): setattr(self, k, v) def get(self, k, default=None): return getattr(self, k, default) fe_tsf = TranslationStringFactory('FormEncode') def get_default_translate_fn(request): pyramid_translate = get_localizer(request).translate def translate(s): if not isinstance(s, TranslationString): s = fe_tsf(s) return pyramid_translate(s) return translate class Form(object):
import wtforms as wtf from wtforms import validators from pyramid.i18n import TranslationStringFactory from intranet3.models import DBSession, Tracker, Project, Client from intranet3.models.project import STATUS from .utils import EntityChoices, UserChoices _ = TranslationStringFactory('intranet3') class ProjectForm(wtf.Form): """ Project form """ name = wtf.TextField(_(u"Project name"), validators=[validators.Required()]) coordinator_id = wtf.SelectField(_(u"Coordinator"), validators=[], choices=UserChoices(empty=True)) tracker_id = wtf.SelectField(_(u"Tracker"), validators=[validators.Required()], choices=EntityChoices( Tracker, lambda tracker: tracker.name)) status = wtf.SelectField(_(u"Status"), validators=[validators.Required()], choices=STATUS) turn_off_selectors = wtf.BooleanField(_(u"Turn off selectors"), validators=[], default=True) project_selector = wtf.TextField(_(u"Project selector"), validators=[]) component_selector = wtf.TextField(_(u"Component selector"), validators=[]) version_selector = wtf.TextField(_(u"Version selector"), validators=[])
# -*- coding: utf-8 -*- ''' Created on Nov 8, 2013 @author: mendt ''' from pyramid.i18n import get_localizer, TranslationStringFactory tsf = TranslationStringFactory('vkviewer') LOCALES = ('en', 'de') def add_renderer_globals(event): request = event.get('request') if request is None: request = get_current_request() event['_'] = request.translate event['localizer'] = request.localizer def add_localizer(event): request = event.request localizer = get_localizer(request) def auto_translate(string): return localizer.translate(tsf(string)) request.localizer = localizer request.translate = auto_translate
""" ploud.themegallery """ from pyramid.i18n import TranslationStringFactory MessageFactory = _ = TranslationStringFactory('ploud.themegallery') def includeme(config): config.scan('ploud.themegallery')
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import logging from pyramid.i18n import TranslationStringFactory log = logging.getLogger('pontus') _ = TranslationStringFactory('pontus') def includeme(config): # pragma: no cover config.include('.') config.scan('.') config.add_static_view('pontusstatic', 'pontus:static', cache_max_age=86400)
# -*- coding: utf-8 -*- """ Created on 2015-10-26 :author: Joseph Rawson ([email protected]) """ from kotti.resources import File from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory('kotti_dashboard') def kotti_configure(settings): """ Add a line like this to you .ini file:: kotti.configurators = kotti_dashboard.kotti_configure to enable the ``kotti_dashboard`` add-on. :param settings: Kotti configuration dictionary. :type settings: dict """ settings['pyramid.includes'] += ' kotti_dashboard pyramid_mako' def includeme(config): """ Don't add this to your ``pyramid_includes``, but add the ``kotti_configure`` above to your ``kotti.configurators`` instead.