django.utils.translation.gettext.format

Here are the examples of the python api django.utils.translation.gettext.format taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

78 Examples 7

3 Source : authentication.py
with Apache License 2.0
from Clivern

    def __call__(self, request):
        """Execute Middleware

        Args:
            request: request instance
        """
        self.logger.info(_("Authenticate {method} Request to {path}").format(
            method=request.method,
            path=request.path
        ))

        response = self.get_response(request)

        return response

3 Source : authorization.py
with Apache License 2.0
from Clivern

    def __call__(self, request):
        """Execute Middleware

        Args:
            request: request instance
        """
        self.logger.info(_("Authorize {method} Request to {path}").format(
            method=request.method,
            path=request.path
        ))

        response = self.get_response(request)

        return response

3 Source : edit_handlers.py
with BSD 3-Clause "New" or "Revised" License
from coderedcorp

    def bind_to(self, model=None, instance=None, request=None, form=None):
        new = super().bind_to(model=model)
        if self.heading is None:
            new.heading = _('{} submissions').format(model.get_verbose_name())
        return new

    def render(self):

3 Source : recurrence.py
with BSD 3-Clause "New" or "Revised" License
from linuxsoftware

    def __getDailyWhen(self):
        if self.interval > 1:
            retval = _("Every {n} days").format(n=self.interval)
        else:
            retval = _("Daily")
        return retval

    def __getWeeklyWhen(self, offset):

3 Source : recurrence.py
with BSD 3-Clause "New" or "Revised" License
from linuxsoftware

    def __getWeeklyWhen(self, offset):
        retval = hrJoin([d._getPluralWhen(offset) for d in self.byweekday])
        if self.interval == 2:
            retval = _("Fortnightly on {days}").format(days=retval)
        elif self.interval > 2:
            retval = _("Every {n} weeks on {days}").format(n=self.interval,
                                                           days=retval)
        return retval

    def __getMonthlyWhen(self, offset):

3 Source : recurrence.py
with BSD 3-Clause "New" or "Revised" License
from linuxsoftware

    def __getYearlyWhen(self, offset):
        months = hrJoin([MONTH_NAMES[m] for m in self.bymonth])
        of = " "+_("of {months}").format(months=months)
        retval = self.__getMonthlyYearlyWhen(offset, of)
        if self.interval >= 2:
            retval = _("{when}, every {n} years")   \
                         .format(when=retval, n=self.interval)
        return retval

    def __getMonthlyYearlyWhen(self, offset, of):

3 Source : recurrence.py
with BSD 3-Clause "New" or "Revised" License
from linuxsoftware

    def __getWhenWithOffsetMonthdays(self, offset, of):
        theOrdinal = hrJoin([toTheOrdinal(d, False) for d in self.bymonthday])
        if offset != 0:
             retval = _("{DaysOffset} {theOrdinal} day")  \
                      .format(DaysOffset=toDaysOffsetStr(offset),
                              theOrdinal=theOrdinal)
        else:
             TheOrdinal = theOrdinal[0].upper() + theOrdinal[1:]
             retval = _("{TheOrdinal} day").format(TheOrdinal=TheOrdinal)
        retval += of
        return retval

# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------

3 Source : idp.py
with GNU Lesser General Public License v3.0
from longguikeji

    def metadata(cls, tenant_uuid, app_id) -> str:
        """ Get the IDP metadata as a string. """
        conf = IdPConfig()
        try:
            conf.load(cls.construct_metadata(
                tenant_uuid, app_id, with_local_sp=False))
            metadata = entity_descriptor(conf)
        except Exception as err:
            raise ImproperlyConfigured( # pylint: disable=raise-missing-from
                _(
                    'Could not instantiate IDP metadata based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}'
                ).format(
                    str(err)
                )
            )
        return str(metadata)

3 Source : SsoEntryView.py
with GNU Lesser General Public License v3.0
from longguikeji

def sso_entry(request, tenant_uuid, app_id, passed_data, binding):
    """
    创建登陆进程
    """
    try:
        saml_request = passed_data['SAMLRequest']
    except (KeyError, MultiValueDictKeyError) as err:
        raise ValidationError(_('not a valid SAMLRequest: {}').format(repr(err))) # pylint: disable=raise-missing-from

    request.session['Binding'] = binding
    request.session['SAMLRequest'] = saml_request
    request.session['RelayState'] = passed_data.get('RelayState', '')
    return HttpResponseRedirect(reverse('api:saml2idp:saml_login_process', args=(tenant_uuid, app_id)))


@method_decorator(never_cache, "dispatch")

3 Source : sp.py
with GNU Lesser General Public License v3.0
from longguikeji

    def metadata(cls, tenant_uuid) -> str:
        """ Get the SP metadata as a string. """
        create_self_signed_cert(tenant_uuid)

        conf = SPConfig()
        try:
            conf.load(cls.construct_metadata(
                tenant_uuid, with_local_sp=False))
            metadata = entity_descriptor(conf)
        except Exception as err:
            raise ImproperlyConfigured(  # pylint: disable=raise-missing-from
                _(
                    'Could not instantiate SP metadata based on the SAML_SP_CONFIG settings and configured ServiceProviders: {}'
                ).format(
                    str(err)
                )
            )
        return str(metadata)

3 Source : process.py
with GNU General Public License v3.0
from Mercado-Social-de-Madrid

    def sponsor_updated(self, user):
        if self.sponsor:
            message = _('Madrina actualizada: {}').format(self.sponsor)
            self.workflow.add_comment(user, message)

            if self.workflow.is_first_step():
                self.workflow.complete_current_step(user)
        # TODO: In the future, notify users?


    def update(self, event):

3 Source : duration_utils.py
with GNU General Public License v3.0
from observatorycontrolsystem

def get_time_allocation(instrument_type, proposal_id, min_window_time, max_window_time):
    timeall = None
    try:
        timeall = Proposal.objects.get(pk=proposal_id).timeallocation_set.get(
            semester__start__lte=min_window_time,
            semester__end__gte=max_window_time,
            instrument_types__contains=[instrument_type])
    except Exception:
        logger.warn(_("proposal {0} has overlapping time allocations for {1}").format(proposal_id, instrument_type))
    return timeall


def get_time_allocation_key(instrument_type, min_window_time, max_window_time):

3 Source : serializers.py
with GNU General Public License v3.0
from observatorycontrolsystem

    def validate(self, data):
        if data['start'] >= data['end']:
            msg = _("Cadence end '{}' cannot be earlier than cadence start '{}'.").format(data['start'], data['end'])
            raise serializers.ValidationError(msg)
        return data


class ConstraintsSerializer(serializers.ModelSerializer):

3 Source : serializers.py
with GNU General Public License v3.0
from observatorycontrolsystem

    def validate_instrument_type(self, value):
        is_staff = False
        request_context = self.context.get('request')
        if request_context:
            is_staff = request_context.user.is_staff
        if value and value not in configdb.get_instrument_type_codes({}, only_schedulable=(not is_staff)):
            raise serializers.ValidationError(
                _('Invalid instrument type {}. Valid instruments may include: {}').format(
                    value, ', '.join(configdb.get_instrument_type_codes({}, only_schedulable=(not is_staff)))
                )
            )
        return value

    def validate(self, data):

3 Source : target_helpers.py
with GNU General Public License v3.0
from observatorycontrolsystem

    def validate(self):
        ECCENTRICITY_LIMIT = 0.9
        if self.is_valid() and 'COMET' not in self._data['scheme'] and self._data['eccentricity'] > ECCENTRICITY_LIMIT:
            msg = _("ORBITAL_ELEMENTS pointing of scheme {} requires eccentricity to be lower than {}. ").format(
                self._data['scheme'], ECCENTRICITY_LIMIT
            )
            msg += _("Submit with scheme MPC_COMET to use your eccentricity of {}.").format(
                self._data['eccentricity']
            )
            self.error_dict['scheme'] = msg


class SatelliteTargetHelper(BaseTargetHelper):

3 Source : manage_group.py
with GNU Affero General Public License v3.0
from openedx

    def _handle_remove(self, group_name):
        """
        Remove the group named by the string group_name, if it exists.
        """

        try:
            Group.objects.get(name=group_name).delete()
            self.stderr.write(_('Removed group: "{}"').format(group_name))
        except Group.DoesNotExist:
            self.stderr.write(_('Did not find a group with name "{}" - skipping.').format(group_name))

    @transaction.atomic

3 Source : manage_user.py
with GNU Affero General Public License v3.0
from openedx

    def _maybe_update(self, user, attribute, new_value):
        """
        DRY helper.  If the specified attribute of the user differs from the
        specified value, it will be updated.
        """
        old_value = getattr(user, attribute)
        if new_value != old_value:
            self.stderr.write(
                _('Setting {attribute} for user "{username}" to "{new_value}"').format(
                    attribute=attribute, username=user.username, new_value=new_value
                )
            )
            setattr(user, attribute, new_value)

    def _check_email_match(self, user, email):

3 Source : manage_user.py
with GNU Affero General Public License v3.0
from openedx

    def _check_email_match(self, user, email):
        """
        DRY helper.

        Requiring the user to specify both username and email will help catch
        certain issues, for example if the expected username has already been
        taken by someone else.
        """
        if user.email.lower() != email.lower():
            # The passed email address doesn't match this username's email address.
            # Assume a problem and fail.
            raise CommandError(
                _(
                    'Skipping user "{}" because the specified and existing email '
                    'addresses do not match.'
                ).format(user.username)
            )

    def _handle_remove(self, username, email):

3 Source : manage_user.py
with GNU Affero General Public License v3.0
from openedx

    def _handle_remove(self, username, email):
        """
        If a user with the given username and email exists, delete them.
        """
        try:
            user = get_user_model().objects.get(username=username)
        except get_user_model().DoesNotExist:
            self.stderr.write(_('Did not find a user with username "{}" - skipping.').format(username))
            return
        self._check_email_match(user, email)
        self.stderr.write(_('Removing user: "{}"').format(user))
        user.delete()

    @transaction.atomic

3 Source : admin_actions.py
with BSD 2-Clause "Simplified" License
from peppelinux

def send_reset_token_email(modeladmin, request, queryset):
    num_sync = 0
    for i in queryset:
        num_sync += 1
        msg = _('{}, email sent').format(i.__str__())
        ch_msg = _('Password reset token sent {}').format(i.__str__())
        messages.add_message(request, messages.INFO, msg)
        logger.info(msg)
        LogEntry.objects.log_action(
            user_id         = request.user.pk,
            content_type_id = ContentType.objects.get_for_model(i).pk,
            object_id       = i.pk,
            object_repr     = i.__str__(),
            action_flag     = ADDITION,
            change_message  = ch_msg)
    if num_sync:
        messages.add_message(request, messages.INFO, _('{} Token sent via E-Mail').format(num_sync))
send_reset_token_email.short_description = _("Send reset Password Token via E-Mail")

3 Source : admin_actions.py
with BSD 2-Clause "Simplified" License
from peppelinux

def lock_account(modeladmin, request, queryset):
    num_sync = 0
    for i in queryset:
        num_sync += 1
        i.lock()
        msg = _('{}, disabled').format(i.__str__())
        logger.info(msg)
        messages.add_message(request, messages.WARNING, )
        LogEntry.objects.log_action(
            user_id         = request.user.pk,
            content_type_id = ContentType.objects.get_for_model(i).pk,
            object_id       = i.pk,
            object_repr     = i.__str__(),
            action_flag     = CHANGE,
            change_message  = _('Locked User (pwdAccountLockedTime)')
            )
    if num_sync:
        messages.add_message(request, messages.INFO, _('{} Accounts disabled').format(num_sync))
lock_account.short_description = _("Lock Account with pwdAccountLockedTime: {}").format(settings.PPOLICY_PERMANENT_LOCKED_TIME)

3 Source : admin_actions.py
with BSD 2-Clause "Simplified" License
from peppelinux

def disable_account(modeladmin, request, queryset):
    num_sync = 0
    for i in queryset:
        num_sync += 1
        i.disable()
        msg = _('{}, disabled').format(i.__str__())
        logger.info(msg)
        messages.add_message(request, messages.WARNING, msg)
        LogEntry.objects.log_action(
            user_id         = request.user.pk,
            content_type_id = ContentType.objects.get_for_model(i).pk,
            object_id       = i.pk,
            object_repr     = i.__str__(),
            action_flag     = CHANGE,
            change_message  = _('Disabled User (pwdAccountLockedTime)')
            )
    if num_sync:
        messages.add_message(request, messages.INFO, _('{} Accounts disabled').format(num_sync))
disable_account.short_description = _("Disable Account (expire password)")

3 Source : admin_actions.py
with BSD 2-Clause "Simplified" License
from peppelinux

def enable_account(modeladmin, request, queryset):
    num_sync = 0
    for i in queryset:
        num_sync += 1
        i.enable()
        msg = _('{}, enabled').format(i.__str__())
        logger.info(msg)
        messages.add_message(request, messages.INFO, msg)
        LogEntry.objects.log_action(
            user_id         = request.user.pk,
            content_type_id = ContentType.objects.get_for_model(i).pk,
            object_id       = i.pk,
            object_repr     = i.__str__(),
            action_flag     = CHANGE,
            change_message  = _('Enabled User (pwdAccountLockedTime)')
            )
    if num_sync:
        messages.add_message(request, messages.INFO, _('{} Accounts enabled').format(num_sync))
enable_account.short_description = _("Enable Account - Clean pwdAccountLockedTime")

3 Source : dynamic_fields.py
with Apache License 2.0
from UniversitaDellaCalabria

    def raise_error(self, name, cleaned_data, **kwargs):
        errors = []
        if cleaned_data and self.max_permitted>0 and len(cleaned_data)>self.max_permitted:
            errors.append(_("Numero massimo di scelte consentito: {}").format(self.max_permitted))
        return errors


class CustomFileField(FileField, BaseCustomField):

3 Source : decorators.py
with Apache License 2.0
from UniversitaDellaCalabria

def store_params_in_session_func(func_to_decorate):
    """ store_params_in_session as a funcion decorator
    """
    def new_func(*original_args, **original_kwargs):
        request = original_args[0]
        try:
            store_params_in_session(request)
            return func_to_decorate(*original_args, **original_kwargs)
        except Exception as e:  # pragma: no cover
            msg = _('not a valid SAMLRequest: {}').format(e)
            return render(request, 'error.html',
                          {'exception_type': msg,
                           'exception_msg': _('Please renew your SAML Request'),
                           'extra_message': _not_valid_saml_msg},
                          status=403)
    return new_func


def require_saml_request(func_to_decorate):

3 Source : validators.py
with Apache License 2.0
from UniversitaDellaCalabria

def validate_file_extension(f):
    if hasattr(f.file, 'content_type'):
        content_type = f.file.content_type
        if not content_type.lower() in settings.PERMITTED_UPLOAD_FILETYPE:
            raise ValidationError(_('Estensione del file non accettata: "{}". '
                                    'Inserisci solo {}').format(content_type,
                                                                settings.PERMITTED_UPLOAD_FILETYPE,))

def validate_file_size(f):

3 Source : validators.py
with Apache License 2.0
from UniversitaDellaCalabria

def validate_file_size(f):
    if f.size > int(settings.MAX_UPLOAD_SIZE):
        raise ValidationError(_('Dimensione del file troppo grande: {} bytes. '
                                'Max {} bytes').format(f.size,
                                                 settings.MAX_UPLOAD_SIZE,))

def validate_file_length(f):

3 Source : validators.py
with Apache License 2.0
from UniversitaDellaCalabria

def validate_file_length(f):
    file_name = os.path.basename(f.name)
    if len(file_name) > settings.ATTACH_NAME_MAX_LEN:
        raise ValidationError(_('Lunghezza del nome del file troppo grande: {} caratteri. '
                                'Max {} caratteri').format(len(file_name),
                                                           settings.ATTACH_NAME_MAX_LEN,))

3 Source : views.py
with MIT License
from vicktornl

    def form_valid(self, form):
        remote_image = urlretrieve(self.image.url)
        with open(remote_image[0], "rb") as image_file:
            width, height = get_image_dimensions(image_file)
            wagtail_image = WagtailImage.objects.create(
                title=form.cleaned_data["title"],
                file=File(image_file),
                collection=form.cleaned_data["collection"],
                width=width,
                height=height,
            )
        messages.success(
            self.request, _("Stock image '{0}' saved.").format(self.image.id)
        )
        return HttpResponseRedirect(
            reverse("wagtailimages:edit", args=[wagtail_image.id])
        )

    def post(self, request, id, *args, **kwargs):

0 Source : error.py
with Apache License 2.0
from Clivern

def handler404(request, exception=None, template_name="templates/index.html"):
    """404 Error Page"""

    logger = Logger().get_logger(__name__)

    if exception is not None:
        # Log exceptions only on debug mode
        logger.debug("Route Not Found: {exception}".format(
            exception=exception
        ))

    context = {
        "title": _("404 | {}").format(get_config("app_name", "Cattle")),
        "description": get_config("app_description", ""),
        "base_url": get_config("app_url", ""),
    }

    return render(request, template_name, context, status=404)


def handler500(request, exception=None, template_name="templates/index.html"):

0 Source : error.py
with Apache License 2.0
from Clivern

def handler500(request, exception=None, template_name="templates/index.html"):
    """500 Error Page"""

    logger = Logger().get_logger(__name__)

    if exception is not None:
        logger.error("Internal Server Error: {exception}".format(
            exception=exception
        ))

    context = {
        "title": _("500 | {}").format(get_config("app_name", "Cattle")),
        "description": get_config("app_description", ""),
        "base_url": get_config("app_url", ""),
    }

    return render(request, template_name, context, status=500)


def csrf_failure(request, reason=""):

0 Source : logging.py
with Apache License 2.0
from Clivern

    def __call__(self, request):
        """Execute Middleware

        Args:
            request: request instance
        """
        start_time = time.time()

        self.logger.info(_("Incoming {method} Request to {path} with {body} and headers {headers}").format(
            method=request.method,
            path=request.path,
            body=request.body,
            headers=request.headers
        ))

        response = self.get_response(request)

        resp_time = (time.time() - start_time) * 1000

        if request.resolver_match and request.resolver_match.url_name:
            route = "/".join([x.title() for x in request.resolver_match.url_name.split(".")])
            record_metric("HTTPRequestCount/Route/{}".format(route), 1)

        # Send Metrics to NR
        record_metric("HTTPRequestCount", 1)
        record_metric("LatencyMillisec", resp_time)

        if isinstance(response, JsonResponse):
            self.logger.info(_("Outgoing {status} Response to {path} with {body} and latency {latency_millisec} millisec").format(
                status=response.status_code,
                path=request.path,
                body=response.content,
                latency_millisec=resp_time
            ))
        else:
            self.logger.info(_("Outgoing {status} Response to {path}:   <  html>.. and latency {latency_millisec} millisec").format(
                status=response.status_code,
                path=request.path,
                latency_millisec=resp_time
            ))

        return response

0 Source : class_checkin_dude.py
with GNU General Public License v2.0
from costasiella

    def class_checkin_subscription_subtract_credit(self, schedule_item_attendance):
        """
        Subtract one credit from a subscription when checking in to a class
        :param account_subscription:
        :param schedule_item:
        :param date:
        :return:
        """
        from ..dudes import AppSettingsDude, ClassScheduleDude
        from ..models import AccountSubscriptionCredit

        app_settings_dude = AppSettingsDude()
        class_schedule_dude = ClassScheduleDude()

        schedule_item_otc = class_schedule_dude.schedule_class_with_otc_data(
            schedule_item_attendance.schedule_item,
            schedule_item_attendance.date
        )

        # Get otc date time, type and location, if any.
        description = _("{date} {time} - {classtype} in {location}").format(
            date=schedule_item_attendance.date.strftime(
                app_settings_dude.date_format
            ),
            time=schedule_item_attendance.schedule_item.time_start.strftime(
                app_settings_dude.time_format
            ),
            classtype=schedule_item_otc.organization_classtype.name,
            location=schedule_item_otc.organization_location_room.organization_location.name
        )

        account_subscription_credit = AccountSubscriptionCredit(
            account_subscription=schedule_item_attendance.account_subscription,
            schedule_item_attendance=schedule_item_attendance,
            mutation_amount=1,
            mutation_type="SUB",
            description=description
        )
        account_subscription_credit.save()

    def subscription_class_permissions(self, account_subscription):

0 Source : recurrence.py
with BSD 3-Clause "New" or "Revised" License
from linuxsoftware

    def _getWhen(self, offset, numDays=1):
        retval = ""
        if self.freq == DAILY:
            retval = self.__getDailyWhen()

        elif self.freq == WEEKLY:
            retval = self.__getWeeklyWhen(offset)

        elif self.freq == MONTHLY:
            retval = self.__getMonthlyWhen(offset)

        elif self.freq == YEARLY:
            retval = self.__getYearlyWhen(offset)

        if numDays >= 2:
            retval += " "+_("for {n} days").format(n=numDays)
        if self.until:
            until = self.until + dt.timedelta(days=offset)
            retval += " "+_("(until {when})").format(when=dateShortFormat(until))
        return retval

    def __getDailyWhen(self):

0 Source : recurrence.py
with BSD 3-Clause "New" or "Revised" License
from linuxsoftware

    def __getWhenByMonthday(self, offset, of):
        daysOffset = ""
        d = self.bymonthday[0]
        if d == 1 and offset   <   0:
            # bump first day to previous month
            d = offset
            if self.freq != MONTHLY:
                months = [WRAPPED_MONTH_NAMES[m-1] for m in self.bymonth]
                of = " "+_("of {months}").format(months=hrJoin(months))

        elif d == -1 and offset > 0:
            # bump last day to next month
            d = offset
            if self.freq != MONTHLY:
                months = [WRAPPED_MONTH_NAMES[m+1] for m in self.bymonth]
                of = " "+_("of {months}").format(months=hrJoin(months))

        elif 0  <  d + offset  < = 28:
            # adjust within the month
            d += offset

        else:
            # too complicated don't adjust for any offset
            daysOffset = toDaysOffsetStr(offset)

        theOrdinal = toTheOrdinal(d, inTitleCase=False)
        if daysOffset:
            retval = _("{DaysOffset} {theOrdinal} day")  \
                     .format(DaysOffset=daysOffset, theOrdinal=theOrdinal)
        else:
            TheOrdinal = theOrdinal[0].upper() + theOrdinal[1:]
            retval = _("{TheOrdinal} day").format(TheOrdinal=TheOrdinal)
        retval += of
        return retval

    def __getWhenWithOffsetMonthdays(self, offset, of):

0 Source : idp.py
with GNU Lesser General Public License v3.0
from longguikeji

    def load(cls, tenant_uuid, app_id, force_refresh: bool = False) -> Server:
        """ Instantiate a IDP Server instance based on the config defined in the SAML_IDP_CONFIG settings.
            Throws an ImproperlyConfigured exception if it could not do so for any reason.
        """
        if cls._server_instance is None or force_refresh:
            conf = IdPConfig()
            md = cls.construct_metadata(  # pylint: disable=invalid-name
                tenant_uuid,
                app_id
            )
            try:
                conf.load(md)
                cls._server_instance = Server(config=conf)
            except Exception as err:
                raise ImproperlyConfigured(  # pylint: disable=raise-missing-from
                    _(
                        'Could not instantiate an IDP based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}'
                    ).format(
                        str(err)
                    )
                )
        return cls._server_instance

    @classmethod

0 Source : sp.py
with GNU Lesser General Public License v3.0
from longguikeji

    def load(cls, tenant_uuid, force_refresh: bool = False) -> Server:
        """ Instantiate a SP Server instance based on the config defined in the SAML_SP_CONFIG settings.
            Throws an ImproperlyConfigured exception if it could not do so for any reason.
        """
        if cls._server_instance is None or force_refresh:
            conf = SPConfig()
            md = cls.construct_metadata(  # pylint: disable=invalid-name
                tenant_uuid
            )
            try:
                conf.load(md)
                cls._server_instance = Server(config=conf)
            except Exception as err:
                raise ImproperlyConfigured(  # pylint: disable=raise-missing-from
                    _(
                        'Could not instantiate an SP based on the SAML_SP_CONFIG settings and configured ServiceProviders: {}'
                    ).format(
                        str(err)
                    )
                )
        return cls._server_instance

    @classmethod

0 Source : sync_projects.py
with GNU Affero General Public License v3.0
from manrs-tools

def sync_projects_to_db():
    print_debug("Synchronising projects")

    # Detect projects on the server
    server_projects = get_gns3_projects(session=session)

    # Sync projects
    projects = Project.objects.select_subclasses()
    for project in projects:
        try:
            for server_project in server_projects:
                if server_project['project_id'].lower() == str(project.gns3_id).lower():
                    break
            else:
                # Where did that one go?!?
                print_warning("- " + _("Project {project.name} disappeared from GNS3 server").format(project=project))
                # project.delete()
                continue

            # Open the project so its data becomes available in the API
            session.post(gns3_base_url + '/v2/projects/' + server_project['project_id'] + '/open')

            if server_project['name'] != project.name:
                print_message("- " + _("Project {old_name} renamed to {new_name}")
                              .format(old_name=project.name, new_name=server_project['name']))
                project.name = server_project['name']
                project.save()

            # Sync nodes
            server_nodes = get_gns3_nodes(server_project['project_id'], session=session)
            nodes = project.node_set.select_subclasses()
            for node in nodes:
                for server_node in server_nodes:
                    if server_node['node_id'].lower() == str(node.gns3_id).lower():
                        break
                else:
                    # Where did that one go?!?
                    print_warning("- " + _("Node {node.name} of project {project.name} disappeared from GNS3 server")
                                  .format(node=node, project=project))
                    # node.delete()
                    continue

                if server_node['name'] != node.name:
                    print_message("- " + _("Project {project.name} node {old} renamed to {new}")
                                  .format(project=project, old=node.name, new=server_node['name']))
                    node.name = server_node['name']
                    node.save()

                if server_node['properties']['mac_address'] != node.mac_address:
                    print_message("- " + _("Project {project.name} node {node.name} "
                                           "change MAC fix_address from {old} to {new}")
                                  .format(project=project, node=node, old=node.mac_address,
                                          new=server_node['properties']['mac_address']))
                    node.mac_address = server_node['properties']['mac_address']
                    node.save()

                if isinstance(node, ExerciseNode):
                    node.gns3_update_monitor_option(session=session)

            if isinstance(project, Exercise):
                running = len([node for node in server_nodes if node['status'] == 'started'])

                if running and project.deadline and project.deadline   <   timezone.now():
                    print_notice(_("Stopping exercise {}").format(project.name))
                    project.gns3_stop(session=session)

                if project.deadline and project.deadline  <  timezone.now() - timedelta(weeks=1):
                    print_notice(_("Deleting exercise {}").format(project.name))
                    project.delete()
                    continue

        except IntegrityError:
            print_error("  - " + _("Template is still referenced, leaving it for now"))


def run(run_once=False):

0 Source : sync_projects.py
with GNU Affero General Public License v3.0
from manrs-tools

def run(run_once=False):
    try:
        # Test reachability
        data = session.get(gns3_base_url + '/v2/version').json()
        print_notice(_("Connected to {hostname}:{port} (GNS v{version})").format(hostname=settings.GNS3['HOST'],
                                                                                 port=settings.GNS3['PORT'],
                                                                                 version=data['version']))

        # Run
        while True:
            sync_projects_to_db()

            if run_once:
                return

            time.sleep(10)

    except RequestException as e:
        print(_("Cannot connect to GNS3 server: {}".format(e)))

        if not run_once:
            # Don't exit too quickly, otherwise uwsgi loops too fast
            time.sleep(60)

    except Exception as e:
        print(_('Unexpected error: {}').format(e))

0 Source : serializers.py
with GNU General Public License v3.0
from observatorycontrolsystem

    def validate(self, data):
        is_staff = False
        only_schedulable = True
        request_context = self.context.get('request')
        if request_context:
            is_staff = request_context.user.is_staff
            only_schedulable = not (is_staff and ConfigDB.is_location_fully_set(data.get('location', {})))
        # check if the instrument specified is allowed
        # TODO: Check if ALL instruments are available at a resource defined by location
        if 'location' in data:
            # Check if the location is fully specified, and if not then use only schedulable instruments
            valid_instruments = configdb.get_instrument_type_codes(data.get('location', {}),
                                                              only_schedulable=only_schedulable)
            for configuration in data['configurations']:
                if configuration['instrument_type'] not in valid_instruments:
                    msg = _("Invalid instrument type '{}' at site={}, enc={}, tel={}. \n").format(
                        configuration['instrument_type'],
                        data.get('location', {}).get('site', 'Any'),
                        data.get('location', {}).get('enclosure', 'Any'),
                        data.get('location', {}).get('telescope', 'Any')
                    )
                    msg += _("Valid instruments include: ")
                    for inst_name in valid_instruments:
                        msg += inst_name + ', '
                    msg += '.'
                    if is_staff and not only_schedulable:
                        msg += '\nStaff users must fully specify location to schedule on non-SCHEDULABLE instruments'
                    raise serializers.ValidationError(msg)

        if 'acceptability_threshold' not in data:
            data['acceptability_threshold'] = max(
                [configdb.get_default_acceptability_threshold(configuration['instrument_type'])
                 for configuration in data['configurations']]
            )

        if 'extra_params' in data and 'mosaic_pattern' in data['extra_params']:
            pattern = data['extra_params']['mosaic_pattern']
            valid_patterns = list(settings.MOSAIC['valid_expansion_patterns']) + [settings.MOSAIC['custom_pattern_key']]
            if pattern not in valid_patterns:
                raise serializers.ValidationError(_(
                    f'Invalid mosaic pattern {pattern} set in the request extra_params, choose from {", ".join(valid_patterns)}'
                ))

        # check that the requests window has enough rise_set visible time to accomodate the requests duration
        if data.get('windows'):
            duration = get_total_request_duration(data)
            rise_set_intervals_by_site = get_filtered_rise_set_intervals_by_site(data, is_staff=is_staff)
            largest_interval = get_largest_interval(rise_set_intervals_by_site)
            for configuration in data['configurations']:
                if 'REPEAT' in configuration['type'].upper() and configuration.get('fill_window'):
                    max_configuration_duration = largest_interval.total_seconds() - duration + configuration.get('repeat_duration', 0) - 1
                    configuration['repeat_duration'] = max_configuration_duration
                    duration = get_total_request_duration(data)

                # delete the fill window attribute, it is only used for this validation
                try:
                    del configuration['fill_window']
                except KeyError:
                    pass
            if largest_interval.total_seconds()   <  = 0:
                raise serializers.ValidationError(
                    _(
                        'According to the constraints of the request, the target is never visible within the time '
                        'window. Check that the target is in the nighttime sky. Consider modifying the time '
                        'window or loosening the airmass or lunar separation constraints. If the target is '
                        'non sidereal, double check that the provided elements are correct.'
                    )
                )
            if largest_interval.total_seconds()  < = duration:
                raise serializers.ValidationError(
                    (
                        'According to the constraints of the request, the target is visible for a maximum of {0:.2f} '
                        'hours within the time window. This is less than the duration of your request {1:.2f} hours. '
                        'Consider expanding the time window or loosening the airmass or lunar separation constraints.'
                    ).format(
                        largest_interval.total_seconds() / 3600.0,
                        duration / 3600.0
                    )
                )
        return data


class CadenceRequestSerializer(RequestSerializer):

0 Source : manage_group.py
with GNU Affero General Public License v3.0
from openedx

    def handle(self, group_name, is_remove, permissions=None, **options):  # pylint: disable=arguments-differ

        if is_remove:
            self._handle_remove(group_name)
            return

        old_permissions = set()
        group, created = Group.objects.get_or_create(name=group_name)

        if created:
            try:
                # Needed for sqlite backend (i.e. in tests) because
                # name.max_length won't be enforced by the db.
                # See also http://www.sqlite.org/faq.html#q9
                group.full_clean()
            except ValidationError as exc:
                # give a more helpful error
                raise CommandError(
                    _(
                        'Invalid group name: "{group_name}". {messages}'
                    ).format(
                        group_name=group_name,
                        messages=exc.messages[0]
                    )
                ) from None
            self.stderr.write(_('Created new group: "{}"').format(group_name))
        else:
            self.stderr.write(_('Found existing group: "{}"').format(group_name))
            old_permissions = set(group.permissions.all())

        new_permissions = self._resolve_permissions(permissions or set())

        add_permissions = new_permissions - old_permissions
        remove_permissions = old_permissions - new_permissions

        self.stderr.write(
            _(
                'Adding {codenames} permissions to group "{group}"'
            ).format(
                codenames=[ap.name for ap in add_permissions],
                group=group.name
            )
        )
        self.stderr.write(
            _(
                'Removing {codenames} permissions from group "{group}"'
            ).format(
                codenames=[rp.codename for rp in remove_permissions],
                group=group.name
            )
        )

        group.permissions.set(new_permissions)

        group.save()

    def _resolve_permissions(self, permissions):

0 Source : manage_group.py
with GNU Affero General Public License v3.0
from openedx

    def _resolve_permissions(self, permissions):
        """
        Given a list of permission strings in the format 'app_label:model:codename', return a list
        of Permission model instances.
        """
        new_permissions = set()
        for permission in permissions:
            try:
                app_label, model_name, codename = permission.split(':')
            except ValueError:
                # give a more helpful error
                raise CommandError(_(
                    'Invalid permission option: "{}". Please specify permissions '
                    'using the format: app_label:model_name:permission_codename.'
                ).format(permission)) from None
            # this will raise a LookupError if it fails.
            try:
                model_class = apps.get_model(app_label, model_name)
            except LookupError as exc:
                raise CommandError(str(exc)) from None

            # Fetch content type for model, including proxy models.
            content_type = ContentType.objects.get_for_model(model_class, for_concrete_model=False)
            try:
                new_permission = Permission.objects.get(
                    content_type=content_type,
                    codename=codename,
                )
            except Permission.DoesNotExist:
                # give a more helpful error
                raise CommandError(
                    _(
                        'Invalid permission codename: "{codename}".  No such permission exists '
                        'for the model {module}.{model_name}.'
                    ).format(
                        codename=codename,
                        module=model_class.__module__,
                        model_name=model_class.__name__,
                    )
                ) from None
            new_permissions.add(new_permission)
        return new_permissions

0 Source : manage_user.py
with GNU Affero General Public License v3.0
from openedx

    def handle(  # pylint: disable=arguments-differ
        self, username, email, is_remove, is_staff, is_superuser, groups,
        unusable_password, initial_password_hash, *args, **options
    ):

        if is_remove:
            self._handle_remove(username, email)
            return

        old_groups, new_groups = set(), set()
        user, created = get_user_model().objects.get_or_create(
            username=username,
            defaults={'email': email}
        )

        if created:
            if initial_password_hash:
                if not (is_password_usable(initial_password_hash) and is_valid_django_hash(initial_password_hash)):
                    raise CommandError(f'The password hash provided for user {username} is invalid.')
                user.password = initial_password_hash
            else:
                # Set the password to a random, unknown, but usable password
                # allowing self-service password resetting.  Cases where unusable
                # passwords are required, should be explicit, and will be handled below.
                user.set_password(generate_password(length=25))
            self.stderr.write(_('Created new user: "{}"').format(user))
        else:
            # NOTE, we will not update the email address of an existing user.
            self.stderr.write(_('Found existing user: "{}"').format(user))
            self._check_email_match(user, email)
            old_groups = set(user.groups.all())

        self._maybe_update(user, 'is_staff', is_staff)
        self._maybe_update(user, 'is_superuser', is_superuser)

        # Set unusable password if specified
        if unusable_password and user.has_usable_password():
            self.stderr.write(_('Setting unusable password for user "{}"').format(user))
            user.set_unusable_password()

        # resolve the specified groups
        for group_name in groups or set():

            try:
                group = Group.objects.get(name=group_name)
                new_groups.add(group)
            except Group.DoesNotExist:
                # warn, but move on.
                self.stderr.write(_('Could not find a group named "{}" - skipping.').format(group_name))

        add_groups = new_groups - old_groups
        remove_groups = old_groups - new_groups

        self.stderr.write(
            _(
                'Adding user "{username}" to groups {group_names}'
            ).format(
                username=user.username,
                group_names=[g.name for g in add_groups]
            )
        )
        self.stderr.write(
            _(
                'Removing user "{username}" from groups {group_names}'
            ).format(
                username=user.username,
                group_names=[g.name for g in remove_groups]
            )
        )

        user.groups.set(new_groups)
        user._called_by_management_command = True  # pylint: disable=protected-access
        user.save()

0 Source : chcoll.py
with MIT License
from RxJellyBot

    def get(self, request, *args, **kwargs):
        # `kwargs` will be used as `nav_param` so extract chcoll_oid from `kwargs` instead of creating param.

        # `chcoll_oid` may be misformatted.
        # If so, `safe_cast` will yield `None` while the original parameter needs to be kept for the case of not found.
        chcoll_oid_str = kwargs.get("chcoll_oid", "")
        chcoll_oid = safe_cast(chcoll_oid_str, ObjectId)

        chcoll_data: Optional[ChannelCollectionModel] = ChannelCollectionManager.get_chcoll_oid(chcoll_oid)

        if not chcoll_data:
            return WebsiteErrorView.website_error(
                request, WebsiteError.CHANNEL_COLLECTION_NOT_FOUND, {"chcoll_oid": chcoll_oid_str}, nav_param=kwargs)

        msgdata_1d = MessageStatsDataProcessor.get_user_chcoll_messages(chcoll_data, hours_within=24)
        msgdata_7d = MessageStatsDataProcessor.get_user_chcoll_messages(chcoll_data, hours_within=168)

        return render_template(
            self.request, _("Channel Collection Info - {}").format(chcoll_oid), "info/chcoll/main.html",
            {
                "chcoll_data": chcoll_data,
                "chcoll_cch_data":
                    InfoProcessor.collate_child_channel_data(get_root_oid(request), chcoll_data.child_channel_oids),
                "user_message_data1d": msgdata_1d,
                "user_message_data7d": msgdata_7d
            },
            nav_param=kwargs)

0 Source : custom_import.py
with MIT License
from techlib

def custom_data_import_precheck(
    header, rows, expected_dimensions=('Institution', 'Source', 'Title', 'Metric')
) -> list:
    problems = []
    month_columns = []
    # check that we understand all the column names
    for i, col_name in enumerate(header):
        if col_name in expected_dimensions:
            pass
        else:
            month = col_name_to_month(col_name)
            if month is None:
                problems.append(_('Column name not understood: "{}"').format(col_name))
            else:
                month_columns.append(i)
    # check that there are numbers in the columns we expect them
    for i, row in enumerate(rows):
        for j in month_columns:
            cell = row[j]
            try:
                int(cell)
            except ValueError:
                problems.append(
                    _(
                        'Value cannot be converted into integer, row {row}, '
                        'column "{column}", value: "{value}"'
                    ).format(row=i + 1, column=header[j], value=cell)
                )
    return problems


DEFAULT_COLUMN_MAP = {

0 Source : custom_import.py
with MIT License
from techlib

def custom_data_to_records(
    records: [dict], column_map=None, extra_dims=None, initial_data=None
) -> [CounterRecord]:
    # prepare the keyword arguments
    if initial_data is None:
        initial_data = {}
    if column_map is None:
        column_map = DEFAULT_COLUMN_MAP
    if extra_dims is None:
        extra_dims = []
    # process the records
    result = []
    for record in records:
        implicit_dimensions = {}
        explicit_dimensions = {}
        monthly_values = {}
        for key, value in record.items():
            month = col_name_to_month(key)
            if month:
                monthly_values[month] = int(value)
            else:
                if key in column_map:
                    implicit_dimensions[column_map[key]] = value
                elif key in extra_dims:
                    explicit_dimensions[key] = value
                else:
                    raise KeyError(
                        _('We don\'t know how to interpret the column "{column}"').format(
                            column=key
                        )
                    )
        # we put initial data into the data we read - these are usually dimensions that are fixed
        # for the whole import and are not part of the data itself
        for key, value in initial_data.items():
            if key not in implicit_dimensions:
                implicit_dimensions[key] = value  # only update if the value is not present
        for month, value in monthly_values.items():
            result.append(
                CounterRecord(
                    value=value,
                    start=month,
                    dimension_data=explicit_dimensions,
                    **implicit_dimensions,
                )
            )
    return result


def histogram(iterable) -> Counter:

0 Source : dynamic_fields.py
with Apache License 2.0
from UniversitaDellaCalabria

    def __init__(self, *args, **data_kwargs):
        # Date DateField
        self.data = BaseDateField(*args, **data_kwargs)
        self.data.label = _("{} (Data)").format(data_kwargs.get('label'))
        self.data.name = "{}_dyn".format(format_field_name(self.data.label))
        self.data.parent = self

        # Hour SelectBox
        self.hour = CustomSelectBoxField(*args, **data_kwargs)
        self.hour.label = _("{} (Ore)").format(data_kwargs.get('label'))
        self.hour.name = "{}_dyn".format(format_field_name(self.hour.label))
        self.hour.choices = [(i,i) for i in range(24)]
        self.hour.initial = 0
        self.hour.parent = self

        # Minutes SelectBox
        self.minute = CustomSelectBoxField(*args, **data_kwargs)
        self.minute.label = _("{} (Minuti)").format(data_kwargs.get('label'))
        self.minute.name = "{}_dyn".format(format_field_name(self.minute.label))
        self.minute.choices = [(i,i) for i in range(60)]
        self.minute.initial = 0
        self.minute.parent = self

    def get_fields(self):

0 Source : dynamic_fields.py
with Apache License 2.0
from UniversitaDellaCalabria

    def __init__(self, *args, **data_kwargs):
        parent_label = data_kwargs.get('label')

        # Start date
        self.start = BaseDateField(*args, **data_kwargs)
        self.start.required = data_kwargs.get('required')
        self.start.label = _("{} (Data inizio)").format(parent_label)
        self.start.name = "{}_dyn".format(format_field_name(self.start.label))

        # Set child parent
        self.start.parent = self

        # End date
        self.end = BaseDateField(*args, **data_kwargs)
        self.end.required = data_kwargs.get('required')
        self.end.label = _("{} (Data fine)").format(parent_label)
        self.end.name = "{}_dyn".format(format_field_name(self.end.label))

        # Set child parent
        self.end.parent = self

    def get_fields(self):

0 Source : dynamic_fields.py
with Apache License 2.0
from UniversitaDellaCalabria

    def __init__(self, *args, **data_kwargs):
        parent_label = data_kwargs.get('label')

        # Procotol type (selectbox)
        self.tipo = CustomSelectBoxField(*args, **data_kwargs)
        self.tipo.required = data_kwargs.get('required')
        self.tipo.label = _("{} (Tipo numerazione)").format(parent_label)
        self.tipo.name = "{}_dyn".format(format_field_name(self.tipo.label))
        self.tipo.help_text = _("Scegli se protocollo/decreto/delibera, "
                                "al/alla quale la numerazione è riferita")
        self.tipo.choices += [(i[0].lower().replace(' ', '_'), i[1]) \
                             for i in CLASSIFICATION_LIST]
        self.tipo.parent = self

        # Protocol number (char field)
        self.numero = CustomCharField(*args, **data_kwargs)
        self.numero.required = data_kwargs.get('required')
        self.numero.label = _("{} (Numero Protocollo/Delibera/Decreto)").format(parent_label)
        self.numero.name = "{}_dyn".format(format_field_name(self.numero.label))
        self.numero.help_text = _("Indica il numero del "
                                  "protocollo/decreto/delibera")
        self.numero.parent = self

        # Protocol date (DateField)
        self.data = BaseDateField(*args, **data_kwargs)
        self.data.required = data_kwargs.get('required')
        self.data.label = _("{} (Data Protocollo/Delibera/Decreto)").format(parent_label)
        self.data.name = "{}_dyn".format(format_field_name(self.data.label))
        self.data.help_text = _("Indica la data del protocollo/delibera/decreto")
        self.data.parent = self

    def get_fields(self):

0 Source : decorators.py
with Apache License 2.0
from UniversitaDellaCalabria

def store_params_in_session(request):
    """ Entrypoint view for SSO. Gathers the parameters from the
        HTTP request and stores them in the session

        It do not return anything because request come as pointer
    """
    if request.method == 'POST':
        passed_data = request.POST
        binding = BINDING_HTTP_POST
    else:
        passed_data = request.GET
        binding = BINDING_HTTP_REDIRECT
    saml_request = passed_data.get('SAMLRequest')
    if saml_request:
        msg = "SAML request [\n{}]"
        logger.debug(msg.format(repr_saml(saml_request, b64=True)))
    else:  # pragma: no cover
        msg = _('not a valid SAMLRequest: {}').format(
            _('AuthnRequest is missing. Please Retry'))
        logger.info('SAML Request absent from {}'.format(request))
        return render(request, 'error.html',
                      {'exception_type': msg,
                       'exception_msg': _('Please renew your SAML Request'),
                       'extra_message': _not_valid_saml_msg},
                      status=403)

    request.saml_session['SAMLRequest'] = saml_request
    request.saml_session['Binding'] = binding
    request.saml_session['RelayState'] = passed_data.get('RelayState', '')


def store_params_in_session_func(func_to_decorate):

See More Examples