예제 #1
0
    def send_email(cls, email: List[str], subject: str, text: str,
                   html: str) -> Response:
        api_key = os.environ.get('MAILGUN_API_KEY', None)
        domain = os.environ.get('MAILGUN_DOMAIN', None)
        from_email = f'do-not-reply@{domain}'

        if api_key is None:
            raise MailGunException(gettext('mailgun_failed_load_api_key'))

        if domain is None:
            raise MailGunException(gettext('mailgun_failed_load_domain'))

        response = post(
            f'https://api.mailgun.net/v3/{domain}/messages',
            auth=('api', api_key),
            data={
                'from': f'{cls.FROM_TITLE} <{from_email}>',
                'to': email,
                'subject': subject,
                'text': text,
                'html': html,
            },
        )
        if response.status_code != 200:
            # print(response.status_code)
            # print(response.json())
            raise MailGunException('An error occurred while sending e-mail.')
        return response
예제 #2
0
    def check_calendar(self, hermes, intent_message):
        """Intent handler for checkCalendar"""

        calendar = None
        calendar_name = None
        timeref = None
        now = arrow.now()
        if intent_message.slots is not None:
            if intent_message.slots.Calendar:
                calendar_name = self._normalize_calendar_name(str(intent_message.slots.Calendar[0].slot_value.value.value))
                #calendar_name = str(intent_message.slots.Calendar[0].slot_value.value.value)
                self._progress("Checking calendar: {}".format(calendar_name))

            if intent_message.slots.Date:
                date_slot = intent_message.slots.Date[0]
                slot_value = date_slot.slot_value
                timeref = str(date_slot.raw_value)
                if isinstance(slot_value.value, InstantTimeValue):
                    start = arrow.get(slot_value.value.value, "YYYY-MM-DD HH:mm:ss ZZ")
                    if slot_value.value.grain == Grain.DAY:
                        end = start.ceil('day')
                    if slot_value.value.grain == Grain.WEEK:
                        # TODO: Figure out how to fix up start & end based on start of week
                        end = start.ceil('day')
                        end += timedelta(days=7)
                if isinstance(slot_value.value, TimeIntervalValue):
                    start = arrow.get(slot_value.value.from_date, "YYYY-MM-DD HH:mm:ss ZZ")
                    end = arrow.get(slot_value.value.to_date, "YYYY-MM-DD HH:mm:ss ZZ")

        # if timeref wasn't set, then we should jsut use today!
        if timeref is None:
            timeref = "today"
            start = now.floor('day')
            end = now.ceil('day')

        # Get calendar from calendar_name
        if calendar_name is not None:
            for cal in self.calendars:
                if cal['name'] == calendar_name:
                    calendar = cal
                    break;
            if calendar is None:
                self._progress("Didn\'t find a matching calendar: {}".format(calendar_name))
            # TODO: if calendar was not found, then snips didn't understand
            # the name of the calendar correctly; ask for clarification
            #if calendar is None:

        threading.Timer(interval=0.2, function=self._check_calendars, args=[hermes, intent_message.site_id, calendar, start, end, timeref]).start()
        if calendar is None:
            hermes.publish_end_session(intent_message.session_id, gettext("PLEASE_WAIT_PLURAL"))
        else:
            hermes.publish_end_session(intent_message.session_id, gettext("PLEASE_WAIT").format(calendar=calendar['name']))
예제 #3
0
def ActivateTranslation(session, config, language, localedir=None):
    global ACTIVE_TRANSLATION, RECENTLY_TRANSLATED

    if not language:
        language = os.getenv('LANG', None)

    if not localedir:
        import mailpile.config.paths
        localedir = mailpile.config.paths.DEFAULT_LOCALE_DIRECTORY()

    trans = None
    if (not language) or language[:5].lower() in ('en', 'en_us', 'c'):
        trans = NullTranslations()
    elif language:
        try:
            trans = translation("mailpile",
                                localedir, [language],
                                codeset="utf-8")
        except IOError:
            if session:
                session.ui.debug('Failed to load language %s' % language)

    if not trans:
        trans = translation("mailpile",
                            localedir,
                            codeset='utf-8',
                            fallback=True)

        if session:
            session.ui.debug('Failed to configure i18n (%s). '
                             'Using fallback.' % language)

    if trans:
        with RECENTLY_TRANSLATED_LOCK:
            RECENTLY_TRANSLATED = []

        ACTIVE_TRANSLATION = trans
        trans.org_gettext = trans.gettext
        trans.org_ngettext = trans.ngettext
        trans.gettext = lambda t, g: gettext(g)
        trans.ngettext = lambda t, s1, s2, n: ngettext(s1, s2, n)
        trans.set_output_charset("utf-8")

        if hasattr(config, 'jinja_env'):
            config.jinja_env.install_gettext_translations(trans, newstyle=True)

        if session and language and not isinstance(trans, NullTranslations):
            session.ui.debug(gettext('Loaded language %s') % language)

    return trans
예제 #4
0
    def action_mail1(self, ids):
        try:
            # if more than one row is selected, show error and don't mail anything..
            totalcount = User.query.filter(User.id.in_(ids)).count()
            print 'totalcount= ', totalcount
            if totalcount > 1:
                flash('Error!  Only select one row to email to the group!'  )
                return
            
            # Mail the one record.
            query = User.query.filter(User.id.in_(ids))
            count = 0
            for user in query.all():
                msg = Message('test-sendmail1-9-f-20160314', sender=creds.cred['mailu'], recipients=['*****@*****.**'])
                msg.body = """
                From: %s <%s>
                user name: %s 
                """ % ('dave', creds.cred['mailu'], user.last_name)
                mail.send(msg)
                #return ('<br><br><hr> Mail send processed. Press your browser BACK button.<hr>')
                count += 1

            flash('Mail was successfully sent.  '  )
        
        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(gettext('Failed . %(error)s', error=str(ex)), 'error')        
예제 #5
0
    def action_mail1(self, ids):
        try:
            # if more than one row is selected, show error and don't mail anything..
            totalcount = User.query.filter(User.id.in_(ids)).count()
            print 'totalcount= ', totalcount
            if totalcount > 1:
                flash('Error!  Only select one row to email to the group!'  )
                return
            
            # Mail the one record.
            query = User.query.filter(User.id.in_(ids))
            count = 0
            for user in query.all():
                msg = Message('test-sendmail1-9-f-20160314', sender=creds.cred['mailu'], recipients=['*****@*****.**'])
                msg.body = """
                From: %s <%s>
                user name: %s 
                """ % ('dave', creds.cred['mailu'], user.last_name)
                msg.html = '''
                From: %s <%s>
                <table cellpadding="5" cellspacing="0" border="1"   bgcolor="#DAFFDA">
                <tr ><td>last name: </td><td> %s </td></tr>
                </table>
                '''  %('dave', creds.cred['mailu'], user.last_name)
                mail.send(msg)
                #return ('<br><br><hr> Mail send processed. Press your browser BACK button.<hr>')
                count += 1

            flash('Mail was successfully sent.  '  )
        
        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(gettext('Failed . %(error)s', error=str(ex)), 'error')        
예제 #6
0
def ActivateTranslation(session, config, language):
    global ACTIVE_TRANSLATION, RECENTLY_TRANSLATED

    trans = None
    if language:
        try:
            trans = translation("mailpile", config.getLocaleDirectory(),
                                [language], codeset="utf-8")
        except IOError:
            if session and language[:2] != 'en':
                session.ui.debug('Failed to load language %s' % language)

    if not trans:
        trans = translation("mailpile", config.getLocaleDirectory(),
                            codeset='utf-8', fallback=True)

        if (session and language[:2] != 'en'
                and isinstance(trans, NullTranslations)):
            session.ui.debug('Failed to configure i18n. '
                             'Using fallback.')

    if trans:
        with RECENTLY_TRANSLATED_LOCK:
            RECENTLY_TRANSLATED = []
        ACTIVE_TRANSLATION = trans
        trans.set_output_charset("utf-8")

        if hasattr(config, 'jinja_env'):
            config.jinja_env.install_gettext_translations(trans,
                                                          newstyle=True)

        if session and language and not isinstance(trans, NullTranslations):
            session.ui.debug(gettext('Loaded language %s') % language)

    return trans
예제 #7
0
파일: i18n.py 프로젝트: mailpile/Mailpile
def ActivateTranslation(session, config, language, localedir=None):
    global ACTIVE_TRANSLATION, RECENTLY_TRANSLATED

    if not language:
        language = os.getenv('LANG', None)

    if not localedir:
        import mailpile.config.paths
        localedir = mailpile.config.paths.DEFAULT_LOCALE_DIRECTORY()

    trans = None
    if language:
        try:
            trans = translation("mailpile", localedir,
                                [language], codeset="utf-8")
        except IOError:
            if session and language[:2] not in ('en', 'C'):
                session.ui.debug('Failed to load language %s' % language)

    if not trans:
        trans = translation("mailpile", localedir,
                            codeset='utf-8', fallback=True)

        if (session and language and language[:2] not in ('en', 'C', '')
                and isinstance(trans, NullTranslations)):
            session.ui.debug('Failed to configure i18n (%s). '
                             'Using fallback.' % language)

    if trans:
        with RECENTLY_TRANSLATED_LOCK:
            RECENTLY_TRANSLATED = []

        ACTIVE_TRANSLATION = trans
        trans.org_gettext = trans.gettext
        trans.org_ngettext = trans.ngettext
        trans.gettext = lambda t, g: gettext(g)
        trans.ngettext = lambda t, s1, s2, n: ngettext(s1, s2, n)
        trans.set_output_charset("utf-8")

        if hasattr(config, 'jinja_env'):
            config.jinja_env.install_gettext_translations(trans,
                                                          newstyle=True)

        if session and language and not isinstance(trans, NullTranslations):
            session.ui.debug(gettext('Loaded language %s') % language)

    return trans
예제 #8
0
def add_to_list(hermes, intent_message):
    """Adds the given item and quantity to the given list"""
    if hermes.injection_lock:
        sentence = gettext("STR_UPDATING_WAIT_ADD")
        hermes.publish_end_session(intent_message.session_id, sentence)
        return

    quantity = 1
    what = None
    which_list = None
    if intent_message.slots is not None:
        try:
            what = intent_message.slots.what[0].raw_value
        except (TypeError, LookupError, ValueError):
            pass
        try:
            which_list = intent_message.slots.list[0].slot_value.value.value
        except (TypeError, LookupError, ValueError):
            pass
        try:
            quantity = int(float(intent_message.slots.quantity[0].slot_value.value.value))
        except (TypeError, LookupError, ValueError):
            pass

    # Set whichList to defaultlist if it's None or matches
    # gettext("STR_DEFAULT_LIST") The API would use the same list if we
    # passed None, but the code below would fail when giving the
    # response.
    if (which_list is None) or \
       (which_list.casefold() == gettext("STR_DEFAULT_LIST").casefold()):
        which_list = hermes.skill_config['secret']['defaultlist']

    if what is None:
        sentence = gettext("STR_ADD_MISSING_WHAT").format(l=which_list)
        hermes.publish_end_session(intent_message.session_id, sentence)
        return

    client = our_groceries_client.OurGroceriesClient()
    client.authenticate(hermes.skill_config['secret']['username'],
                        hermes.skill_config['secret']['password'],
                        hermes.skill_config['secret']['defaultlist'])
    client.add_to_list(what, quantity, which_list)

    # Respond that we added it to the list
    sentence = gettext("STR_ADD_SUCCESS_DETAILS") \
        .format(q=quantity, w=what, l=which_list)
    hermes.publish_end_session(intent_message.session_id, sentence)
예제 #9
0
파일: i18n.py 프로젝트: srmtlab/socialtag
def lazy_gettext(message):
    """
    Lazily evaluated version of ``gettext()``.

    This function uses the appropriate Gettext API object based on the value of
    ``bottle.request.gettext`` set by the plugin. It will fail with
    ``AttributeError`` exception if the plugin is not installed.
    """
    gettext = request.gettext.gettext
    return to_unicode(gettext(message))
예제 #10
0
    def translate(self, string, arguments=None):
        if PY3:
            gettext = self.lang.gettext
        else:
            gettext = self.lang.ugettext

        translated = gettext(string)
        if arguments is not None:
            translated = translated % arguments

        return translated
    def translate(self, string, arguments=None):
        if PY3:
            gettext = self.lang.gettext
        else:
            gettext = self.lang.ugettext

        translated = gettext(string)
        if arguments is not None:
            translated = translated % arguments

        return translated
예제 #12
0
파일: i18n.py 프로젝트: mojoaxel/librarian
def lazy_gettext(message):
    """
    Lazily evaluated version of ``gettext()``.

    This function uses the appropriate Gettext API object based on the value of
    ``bottle.request.gettext`` set by the plugin. It will fail with
    ``AttributeError`` exception if the plugin is not installed.

    :param message:     translatable message
    :returns:           lazy proxy object
    """
    gettext = request.gettext.gettext
    return gettext(message)
예제 #13
0
파일: i18n.py 프로젝트: mojoaxel/librarian
def lazy_gettext(message):
    """
    Lazily evaluated version of ``gettext()``.

    This function uses the appropriate Gettext API object based on the value of
    ``bottle.request.gettext`` set by the plugin. It will fail with
    ``AttributeError`` exception if the plugin is not installed.

    :param message:     translatable message
    :returns:           lazy proxy object
    """
    gettext = request.gettext.gettext
    return gettext(message)
예제 #14
0
    def handle(self, *args, **options):
        """
        コマンド実行時のハンドラ。
        引数に応じて各サービスを実行する
        """
        execute_batch = None

        for index, parameter in enumerate(options['parameter']):
            if index == 0:
                execute_batch = parameter

        logging.info(gettext("I900"), execute_batch)

        try:
            if execute_batch == 'create_employees':
                EmployeesService.create_employees()
            elif execute_batch == 'create_departments':
                EmployeesService.create_departments()
            elif execute_batch == 'update_employees':
                EmployeesService.update_employees()
            elif execute_batch == 'select_employees':
                EmployeesService.select_employees()
            elif execute_batch == 'truncate_employees':
                EmployeesService.truncate_employees()
            elif execute_batch == 'create_scrapy_html':
                ScrapyService.create_scrapy_html()
            elif execute_batch == 'parse_scrapy_html':
                ScrapyService.parse_scrapy_html()
            else:
                logging.info(gettext("E902"), execute_batch)
        except ProgrammingError as e:
            logging.exception(gettext("E903"), e)
        except Exception as e:
            logging.exception(gettext("E990"), e)

        logging.info(gettext("I901"), execute_batch)
예제 #15
0
    def clean(self, value):

        value = super(forms.ChoiceField, self).clean(value)
        if value in (None, ''):
            value = u''
        value = forms.util.smart_str(value)
        if value == u'':
            return value
        valid_values = []
        for group_label, group in self.choices:
            valid_values += [str(k) for k, v in group]
        if value not in valid_values:
            raise ValidationError(
                gettext(
                    u'Select a valid choice. That choice is not one of the available choices.'
                ))
        return value
예제 #16
0
    def action_mail1(self, ids):
        try:
            # if more than one row is selected, show error and don't mail anything..
            totalcount = User.query.filter(User.id.in_(ids)).count()
            print "totalcount= ", totalcount
            if totalcount > 1:
                flash("Error!  Only select one row to email to the group!")
                return

            # Mail the one record.
            query = User.query.filter(User.id.in_(ids))
            count = 0
            for user in query.all():
                msg = Message(
                    "test-sendmail1-9-f-20160314", sender=creds.cred["mailu"], recipients=["*****@*****.**"]
                )
                msg.body = """
                From: %s <%s>
                user name: %s 
                """ % (
                    "dave",
                    creds.cred["mailu"],
                    user.last_name,
                )
                msg.html = """
                From: %s <%s>
                <table cellpadding="5" cellspacing="0" border="1"   bgcolor="#DAFFDA">
                <tr ><td>last name: </td><td> %s </td></tr>
                </table>
                """ % (
                    "dave",
                    creds.cred["mailu"],
                    user.last_name,
                )
                mail.send(msg)
                # return ('<br><br><hr> Mail send processed. Press your browser BACK button.<hr>')
                count += 1

            flash("Mail was successfully sent.  ")

        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(gettext("Failed . %(error)s", error=str(ex)), "error")
예제 #17
0
    def action_approve(self, ids):
        try:
            query = User.query.filter(User.id.in_(ids))

            count = 0
            for user in query.all():
                #import pdb;  pdb.set_trace()
                user.active = 1
                user.confirmed_at = datetime.datetime.fromtimestamp(time.time())
                db.session.commit()
                count += 1

            flash('User was successfully approved.'  )
        
        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(gettext('Failed to approve users. %(error)s', error=str(ex)), 'error')        
예제 #18
0
def gtk_builder_translation_hack(builder):
    """Hack to allow translating the UI on Windows.

    :param Gtk.Builder builder: The builder to hack...
    """
    translatable_properties = [
        "label",
        "text",
        "title",
        "tooltip-text",
    ]
    for widget in builder.get_objects():
        widget_properties = [prop.name for prop in widget.list_properties()]
        for translatable_property in translatable_properties:
            if translatable_property not in widget_properties:
                continue
            text = widget.get_property(translatable_property)
            if not text:
                continue
            widget.set_property(translatable_property, gettext(text))
예제 #19
0
    def action_approve(self, ids):
        try:
            query = User.query.filter(User.id.in_(ids))

            count = 0
            for user in query.all():
                #import pdb;  pdb.set_trace()
                user.active = 1
                user.confirmed_at = datetime.datetime.fromtimestamp(
                    time.time())
                db.session.commit()
                count += 1

            flash('User was successfully approved.')

        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(gettext('Failed to approve users. %(error)s', error=str(ex)),
                  'error')
예제 #20
0
    def action_mail1(self, ids):
        try:
            # if more than one row is selected, show error and don't mail anything..
            totalcount = User.query.filter(User.id.in_(ids)).count()
            print 'totalcount= ', totalcount
            if totalcount > 1:
                flash('Error!  Only select one row to email to the group!'  )
                return
            
            # Mail the one record.
            query = User.query.filter(User.id.in_(ids))
            count = 0
            for user in query.all():
                mail2()
                count += 1

            flash('Mail was successfully sent.  '  )
        
        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(gettext('Failed . %(error)s', error=str(ex)), 'error')        
예제 #21
0
    def _check_calendars(self, hermes, site_id, calendar, start, end, timeref):
        # At this point, we know which calendar the user wants, or if the
        # user wants all calendars, so get the events!
        if calendar is not None:
            self._progress('Checking single calendar')
            event_list = self._get_events(calendar, start, end)
        else:
            self._progress('Checking all calendars')
            event_list = []
            for calendar in self.calendars:
                event_list.extend(self._get_events(calendar, start, end))

        # Build our response string...
        events = ''
        if len(event_list) != 0:
            date_format = gettext("FORMAT_DATE_TIME_12")
            if self.config['secret']['Hour'] == 24:
                date_format = gettext("FORMAT_DATE_TIME_24")
            now = arrow.now()
            for event in event_list:
                start_time = arrow.get(event['start'])
                end_time = arrow.get(event['end'])
                td = end_time - start_time
                if td.days == 1 and td.seconds == 0:
                    event_text = gettext("STR_EVENT_ALL_DAY") \
                        .format(subject=event['title'], day=start_time.strftime('%A'))
                    events += event_text
                else:
                    td = start_time - now
                    if td.days == 0 and td.seconds <= 7200:
                        start = start_time.humanize(granularity='minute')
                    else:
                        start = start_time.strftime(date_format)
                    event_text = gettext("STR_EVENT") \
                        .format(start=start, end=end_time.strftime(date_format), subject=event['title'])
                    events += event_text

            sentence = gettext("STR_EVENTS") \
                .format(timeref=timeref, events=events)
        else:
            sentence = gettext("STR_NO_EVENTS").format(timeref=timeref)

        self._progress(sentence)
        hermes.publish_start_session_notification(site_id, sentence, None)
예제 #22
0
파일: common.py 프로젝트: cuissai/fun-apps
# we use mysql to store mutualize session persistance between Django instances
SESSION_ENGINE = 'django.contrib.sessions.backends.db'

WIKI_ENABLED = True

TIME_ZONE = 'Europe/Paris'

# i18n
USE_I18N = True
gettext = lambda s: s

LANGUAGE_CODE = 'fr'
# These are the languages we allow on FUN platform
# DarkLanguageConfig.released_languages must use the same codes (comma separated)
LANGUAGES = (
    ('fr', gettext('French')),
    ('en', gettext('English')),
    ('de-de', gettext('German')), # codes have to match edX's ones (lms.envs.common.LANGUAGES)
)
# EdX rely on this code to display current language to user, when not yet set in preferences
# This is probably a bug because user with an english browser, will have the english i18n
# still, when not set, the preference page will show 'fr' as default language.
# (student.views.dashboard use settings.LANGUAGE instead of request.LANGUAGE)

PIPELINE = True  # use djangopipeline aggregated css and js file (in production)
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = "/edx/var/edxapp/uploads"

STATIC_ROOT = "/edx/var/edxapp/staticfiles"
예제 #23
0
파일: i18n.py 프로젝트: Theer108/invenio
 def unicode_gettext_wrapper(text, **kwargs):
     from invenio.base.helpers import unicodifier
     from invenio.utils.text import wash_for_utf8
     return wash_for_utf8(
         gettext(unicodifier(text), **unicodifier(kwargs)))
예제 #24
0
 def unicode_gettext_wrapper(text, **kwargs):
     from invenio.base.helpers import unicodifier
     from invenio.utils.text import wash_for_utf8
     return wash_for_utf8(gettext(unicodifier(text),
                                  **unicodifier(kwargs)))
예제 #25
0
 def get_type_name(self, gettext):
     return gettext("file upload")
예제 #26
0
 def get_type_name(self, gettext):
     return gettext("multiple choice")
예제 #27
0
 def get_type_name(self, gettext):
     return gettext("match")
예제 #28
0
 def clean_email(self):
     email = self.cleaned_data['email']
     if not User.objects.filter(email__iexact=email, is_active=True).exists():
         msg = gettext("There is no user registered with the specified E-Mail address.")
         self.add_error('email', msg)
     return email
예제 #29
0
 def _get_events(self, calendar, start, end):
     date_format = gettext("FORMAT_DATE_TIME_24")
     self._progress("Getting events for calendar: {} start: {} end: {}".format(calendar['name'], start.strftime(date_format), end.strftime(date_format)))
     response = self.api.calendars.events(calendar['entity_id'], start, end)
     return response.body
예제 #30
0
 def get_type_name(cls, gettext):
     return gettext("code")
예제 #31
0
파일: translators.py 프로젝트: CZ-NIC/foris
 def __str__(self):
     return gettext(self.text)
예제 #32
0
 def get_type_name(cls, gettext):
     return gettext("single-line code")
예제 #33
0
 def get_type_name(self, gettext):
     return gettext("multiple choice")
예제 #34
0
 def translate(message, plural_message=None, count=None):
     if plural_message is not None:
         assert count is not None
         return ngettext(message, plural_message, count)
     else:
         return gettext(message)
예제 #35
0
 def get_type_name(cls, gettext):
     return gettext("code")
예제 #36
0
 def get_type_name(self, gettext):
     return gettext("file upload")
예제 #37
0
def check_list(hermes, intent_message):
    """Checks the given list for an item and speaks if it's there"""
    if hermes.injection_lock:
        sentence = gettext("STR_UPDATING_WAIT_ADD")
        hermes.publish_end_session(intent_message.session_id, sentence)
        return
        
    quantity = '1'
    what = None
    which_list = None
    sentence = None
    if intent_message.slots is not None:
        try:
            what = intent_message.slots.what[0].raw_value
        except (TypeError, LookupError, ValueError):
            pass
        try:
            which_list = intent_message.slots.list[0].slot_value.value.value
        except (TypeError, LookupError, ValueError):
            pass

    # Set whichList to defaultlist if it's None or matches
    # gettext("STR_DEFAULT_LIST") The API would use the same list if we
    # passed None, but the code below would fail when giving the
    # response.
    if (which_list is None) or \
       (which_list.casefold() == gettext("STR_DEFAULT_LIST").casefold()):
        which_list = hermes.skill_config['secret']['defaultlist']

    if what is None:
        sentence = gettext("STR_CHECK_MISSING_WHAT").format(l=which_list)
        hermes.publish_end_session(intent_message.session_id, sentence)
        return

    client = our_groceries_client.OurGroceriesClient()
    client.authenticate(hermes.skill_config['secret']['username'],
                        hermes.skill_config['secret']['password'],
                        hermes.skill_config['secret']['defaultlist'])
    items = client._get_list_data(which_list)
    for item in items:
        crossed_off = item.get('crossedOff', False)
        # Note our two primary regular expressions are commented out
        # below and combined into regex.  The uncommented regex line
        # below this is just building the expression all at once.
        #regex1 = r"^" + re.escape(what) + r" *$"
        #regex2 = r"^" + re.escape(what) + r"\ \((\d+)\)$"
        #regex = r"(" + regex1 + r")|(" + regex2 + r")"
        regex = r'(^' + re.escape(what) + r' *$)|(^' + re.escape(what) + r'\ \((\d+)\)$)'
        res = re.search(regex, item['value'], re.IGNORECASE)
        # Note the following two conditions are not combined because we
        # want to break the loop even if the item is crossed off.  If
        # it's crossed off, we don't need to keep looking for a match --
        # you can't have the same item on the list with different case.
        # Perhaps with different spelling, but we're not doing sounds
        # like checking here. :(
        if res is not None:
            if not crossed_off:
                quantity = res.group(3)
                if quantity is None:
                    quantity = '1'
                sentence = gettext("STR_CHECK_SUCCESS_DETAILS") \
                    .format(q=quantity, w=what, l=which_list)
            break
    if sentence is None:
        sentence = gettext("STR_CHECK_NOT_FOUND").format(w=what, l=which_list)

    # Respond that we added it to the list
    hermes.publish_end_session(intent_message.session_id, sentence)
예제 #38
0
 def get_type_name(self, gettext):
     return gettext("match")
예제 #39
0
 def _init_enum_area_opts(self, gettext):
   _list = (('--banner', '--current-user', '--current-db', '--hostname', '--is-dba'),
            ('--users', '--passwords', '--privileges', '--roles', '--dbs'),
            ('--tables', '--columns', '--schema', '--count', '--comments'))
   self._enum_area_opts_ckbtns = [[cb(gettext(j)) for j in i] for i in _list]
예제 #40
0
 def get_type_name(cls, gettext):
     return gettext("single-line code")
예제 #41
0
def _(msg):
    if initialized:
        gettext = builtins.__dict__.get('_', None)
        if gettext is not None:
            return gettext(msg)
    return msg
예제 #42
0
파일: i18n.py 프로젝트: kyonetca/librarian
def lazy_gettext(message):
    gettext = request.gettext.gettext
    return gettext(message)
예제 #43
0
파일: translators.py 프로젝트: CZ-NIC/foris
 def __str__(self):
     return gettext(self.text)