コード例 #1
0
ファイル: util.py プロジェクト: clld/glottolog3
def format_iso_retirement(req, lang):
    ir = lang.iso_retirement
    _md, comment = [], ''
    if ir.description:
        comment = HTML.div(
            HTML.p(HTML.strong("Excerpt from change request document:")),
            HTML.blockquote(md(req, ir.description, small=True)))

    if ir.change_request:
        _md.append((
            'Change request:',
            link(
                req,
                Refprovider.get('iso6393:{0}'.format(ir.change_request)).ref,
                label=ir.change_request)))
    _md.append(('ISO 639-3:', ir.id))
    _md.append(('Name:', ir.name))
    if ir.reason:
        _md.append(('Reason:', ir.reason))
    _md.append(('Effective:', ir.effective))

    return infobox(
        HTML.p(
            HTML.strong("Retired in ISO 639-3: "),
            linkify_iso_codes(req, ir.remedy, class_='iso639-3')),
        HTML.ul(*[HTML.li(HTML.strong(dt), Markup(' '), dd) for dt, dd in _md], **{'class': 'inline'}),
        comment)
コード例 #2
0
def format_iso_retirement(req, lang):
    ir = lang.jsondata['iso_retirement']
    _md, comment = [], ''
    if ir['comment']:
        comment = HTML.div(
            HTML.p(HTML.strong("Excerpt from change request document:")),
            HTML.blockquote(md(req, ir['comment'], small=True)))

    if ir['change_request']:
        _md.append(('Change request:',
                    link(req,
                         Refprovider.get('iso6393:{0}'.format(
                             ir['change_request'])).ref,
                         label=ir['change_request'])))
    _md.append(('ISO 639-3:', ir['code']))
    _md.append(('Name:', ir['name']))
    if ir['reason']:
        _md.append(('Reason:', ir['reason']))
    _md.append(('Effective:', ir['effective']))

    return infobox(
        HTML.p(HTML.strong("Retired in ISO 639-3: "),
               linkify_iso_codes(req, ir['remedy'], class_='iso639-3')),
        HTML.ul(
            *[
                HTML.li(HTML.strong(dt), Markup(' '), dd)
                for dt, dd in _md
            ], **{'class': 'inline'}), comment)
コード例 #3
0
ファイル: helpers.py プロジェクト: FieldDB/clld
def text2html(text, mode='br', sep='\n\n'):
    """
    >>> assert 'div' in unicode(text2html('chunk', mode='p'))
    """
    if mode == 'p':
        return HTML.div(*[HTML.p(literal(newline2br(line))) for line in text.split(sep)])
    return HTML.p(literal(newline2br(text)))
コード例 #4
0
ファイル: helpers.py プロジェクト: cevmartinez/clld
def text2html(text, mode="br", sep="\n\n"):
    """Turn plain text into simple HTML.

    >>> assert 'div' in text_type(text2html('chunk', mode='p'))
    """
    if mode == "p":
        return HTML.div(*[HTML.p(literal(newline2br(line))) for line in text.split(sep)])
    return HTML.p(literal(newline2br(text)))
コード例 #5
0
def text2html(text, mode='br', sep='\n\n'):
    """
    >>> assert 'div' in unicode(text2html('chunk', mode='p'))
    """
    if mode == 'p':
        return HTML.div(
            *[HTML.p(literal(newline2br(line))) for line in text.split(sep)])
    return HTML.p(literal(newline2br(text)))
コード例 #6
0
def format_comment(req, comment):
    """
    We collect source ids found in comment, retrieve the corresponding source objects from
    the database in a single query and then replace the ids with formatted source links.
    """
    parts = []
    sources = {}
    pos = 0
    comment = comment.replace('~', ' ')
    for match in REF_PATTERN.finditer(comment):
        preceding = comment[pos:match.start()]
        parts.append(preceding)
        add_braces = \
            (preceding.strip().split() or ['aaa'])[-1] not in ['in', 'of', 'per', 'by']
        if add_braces:
            parts.append('(')
        parts.append(match.group('id'))
        sources[match.group('id')] = None
        if add_braces:
            parts.append(')')
        pos = match.end()
    parts.append(comment[pos:])

    for source in DBSession.query(Source).filter(Source.id.in_(sources.keys())):
        sources[source.id] = source

    return HTML.p(*[link(req, sources[p]) if p in sources else p for p in parts] )
コード例 #7
0
def collapsed(id_, content, button_content=None):
    return HTML.div(
        HTML.p(
            HTML.a(
                button_content or icon('plus-sign'), **{
                    'class': 'btn',
                    'data-toggle': 'collapse',
                    'data-target': '#%s' % id_
                })), HTML.div(content, id=id_, class_='collapse'))
コード例 #8
0
ファイル: helpers.py プロジェクト: cevmartinez/clld
def collapsed(id_, content, button_content=None):
    return HTML.div(
        HTML.p(
            HTML.a(
                button_content or icon("plus-sign"),
                **{"class": "btn", "data-toggle": "collapse", "data-target": "#%s" % id_}
            )
        ),
        HTML.div(content, id=id_, class_="collapse"),
    )
コード例 #9
0
ファイル: util.py プロジェクト: clld/wold2
def hb_score(name, description, domain):
    return HTML.div(
        HTML.p("""This gives the average {name} of all words corresponding to
this meaning. The following {name}s are assigned to
words depending on {description}:""".format(**locals())),
        HTML.table(
            HTML.thead(HTML.tr(
                HTML.th(' '), HTML.th('score'))),
            HTML.tbody(
                *[HTML.tr(HTML.td(label), HTML.td(score)) for label, score in domain])))
コード例 #10
0
ファイル: util.py プロジェクト: elreynol/wold2
def hb_score(name, description, domain):
    return HTML.div(
        HTML.p("""This gives the average {name} of all words corresponding to
this meaning. The following {name}s are assigned to
words depending on {description}:""".format(**locals())),
        HTML.table(
            HTML.thead(HTML.tr(
                HTML.th(' '), HTML.th('score'))),
            HTML.tbody(
                *[HTML.tr(HTML.td(label), HTML.td(score)) for label, score in domain])))
コード例 #11
0
ファイル: helpers.py プロジェクト: Woseseltops/clld
def alt_representations(req, rsc, doc_position='right', exclude=None):
    exclude = exclude or []
    exclude.extend(['html', 'snippet.html'])
    adapters = [
        a
        for n, a in req.registry.getAdapters([rsc], interfaces.IRepresentation)
        if a.extension not in set(exclude)
    ]
    doc = []
    for adapter in adapters:
        if adapter.__doc__:
            doc.append(HTML.dt(adapter.name or adapter.extension))
            doc.append(HTML.dd(adapter.__doc__))
    doc = HTML.div(
        HTML.p(
            """You may download alternative representations of the data on
"%s" by clicking the button """ % rsc.name, icon('download-alt')),
        HTML.dl(*doc))
    return HTML.div(
        HTML.div(
            button(
                icon('info-sign', inverted=True), **{
                    'class': ['btn-info'],
                    'id': 'rsc-dl',
                    'data-content': unicode(doc)
                }),
            HTML.a(
                icon('download-alt'), HTML.span(class_="caret"), **{
                    'class_': "btn dropdown-toggle",
                    'data-toggle': "dropdown",
                    'href': "#",
                    'id': "dt-dl-opener",
                }),
            HTML.ul(
                *[
                    HTML.li(
                        HTML.
                        a(a.name or a.extension,
                          href="#",
                          onclick="document.location.href = '%s'; return false;"
                          % req.resource_url(rsc, ext=a.extension),
                          id='dt-dl-%s' % a.extension)) for a in adapters
                ], **dict(class_="dropdown-menu")),
            class_='btn-group'),
        HTML.script(
            literal("""\
    $(document).ready(function() {
        $('#rsc-dl').clickover({
            html: true,
            title: 'Alternative representations',
            placement: '%s',
            trigger: 'click'
        });
    });""" % doc_position)))
コード例 #12
0
ファイル: base.py プロジェクト: clld/clld
 def doc(self):
     items = []
     for col in self.ctx.cols:
         dsc = col.js_args.get('sDescription')
         if dsc:
             items.extend([HTML.dt(col.js_args['sTitle']), HTML.dd(dsc)])
     return HTML.dl(
         HTML.p(
             'Columns containing numeric data may be filtered giving upper or lower '
             'bounds in the form "<5" or ranges in the form "-2..20".'),
         self.ctx.options.get('sDescription', ''),
         *items)
コード例 #13
0
ファイル: helpers.py プロジェクト: FieldDB/clld
def alt_representations(req, rsc, doc_position='right', exclude=None):
    exclude = exclude or []
    exclude.extend(['html', 'snippet.html'])
    adapters = [a for n, a in req.registry.getAdapters([rsc], interfaces.IRepresentation)
                if a.extension not in set(exclude)]
    doc = []
    for adapter in adapters:
        if adapter.__doc__:
            doc.append(HTML.dt(adapter.name or adapter.extension))
            doc.append(HTML.dd(adapter.__doc__))
    doc = HTML.div(
        HTML.p(
            """You may download alternative representations of the data on
"%s" by clicking the button """ % rsc.name,
            icon('download-alt')),
        HTML.dl(*doc))
    return HTML.div(HTML.div(
        button(
            icon('info-sign', inverted=True),
            **{'class': ['btn-info'],
               'id': 'rsc-dl',
               'data-content': unicode(doc)}),
        HTML.a(
            icon('download-alt'),
            HTML.span(class_="caret"),
            **{
                'class_': "btn dropdown-toggle",
                'data-toggle': "dropdown",
                'href': "#",
                'id': "dt-dl-opener",
            }
        ),
        HTML.ul(
            *[HTML.li(HTML.a(
                a.name or a.extension,
                href="#",
                onclick="document.location.href = '%s'; return false;"
                        % req.resource_url(rsc, ext=a.extension),
                id='dt-dl-%s' % a.extension))
              for a in adapters],
            **dict(class_="dropdown-menu")),
        class_='btn-group'),
        HTML.script(literal("""\
    $(document).ready(function() {
        $('#rsc-dl').clickover({
            html: true,
            title: 'Alternative representations',
            placement: '%s',
            trigger: 'click'
        });
    });""" % doc_position)))
コード例 #14
0
def format_classificationcomment(req, comment):
    parts = []
    pos = 0
    for match in REF_PATTERN.finditer(comment):
        preceding = comment[pos:match.start()]
        parts.append(preceding)
        preceding_words = preceding.strip().split()
        if preceding_words and preceding_words[-1] not in [
                'in', 'of', 'per', 'by'
        ]:
            parts.append('(')
        parts.append(link(req, Source.get(match.group('id'))))
        if preceding_words and preceding_words[-1] not in [
                'in', 'of', 'per', 'by'
        ]:
            parts.append(')')
        pos = match.end()
    parts.append(comment[pos:])
    return HTML.p(*parts)
コード例 #15
0
ファイル: downloadwidget.py プロジェクト: cevmartinez/clld
    def render(self, no_js=False):
        adapters = [
            a for n, a in self.req.registry.getAdapters([self.obj],
                                                        self.interface)
            if a.extension not in set(self.options['exclude'])
        ]
        adoc = []
        for adapter in adapters:
            if adapter.__doc__:
                adoc.append(HTML.dt(adapter.name or adapter.extension))
                adoc.append(HTML.dd(adapter.__doc__))
        doc = HTML.div(
            HTML.p(
                """You may download alternative representations of the data on
"%s" by clicking the button """ % self.ctx,
                HTML.i(class_='icon-download-alt')), self.doc(),
            HTML.dl(*adoc))
        res = HTML.div(
            HTML.button(HTML.i(class_='icon-info-sign icon-white'),
                        class_='btn btn-info %s' % self._opener_class,
                        **{
                            'data-content': text_type(doc),
                            'type': 'button'
                        }),
            HTML.a(
                HTML.i(class_='icon-download-alt'), HTML.span(class_="caret"),
                **{
                    'class_': "btn dropdown-toggle",
                    'data-toggle': "dropdown",
                    'href': "#",
                    'id': self._id_prefix + "opener"
                }),
            HTML.ul(*[HTML.li(self.dl_link(adapter)) for adapter in adapters],
                    **dict(class_="dropdown-menu")),
            class_='btn-group right')
        if no_js:
            return res
        return HTML.div(res, self.js())
コード例 #16
0
ファイル: downloadwidget.py プロジェクト: clld/clld
    def render(self, no_js=False):
        adapters = [a for n, a in
                    self.req.registry.getAdapters([self.obj], self.interface)
                    if a.extension not in set(self.options['exclude'])]
        adapters = sorted(adapters, key=lambda x: x.extension)
        adoc = []
        for adapter in adapters:
            if adapter.__doc__:
                adoc.append(HTML.dt(adapter.name or adapter.extension))
                adoc.append(HTML.dd(adapter.__doc__))
        doc = HTML.div(
            HTML.p(
                """You may download alternative representations of the data on
"%s" by clicking the button """ % self.ctx,
                HTML.i(class_='icon-download-alt')),
            self.doc(),
            HTML.dl(*adoc))
        res = HTML.div(
            HTML.button(
                HTML.i(class_='icon-info-sign icon-white'),
                class_='btn btn-info %s' % self._opener_class,
                **{'data-content': text_type(doc), 'type': 'button'}),
            HTML.a(
                HTML.i(class_='icon-download-alt'),
                HTML.span(class_="caret"),
                **{
                    'class_': "btn dropdown-toggle",
                    'data-toggle': "dropdown",
                    'href': "#",
                    'id': self._id_prefix + "opener"}),
            HTML.ul(
                *[HTML.li(self.dl_link(adapter)) for adapter in adapters],
                **dict(class_="dropdown-menu")),
            class_='btn-group right')
        if no_js:
            return res
        return HTML.div(res, self.js())
コード例 #17
0
ファイル: helpers.py プロジェクト: cevmartinez/clld
def rendered_sentence(sentence, abbrs=None, fmt="long"):
    """Format a sentence as HTML."""
    if sentence.xhtml:
        return HTML.div(HTML.div(Markup(sentence.xhtml), class_="body"), class_="sentence")

    if abbrs is None:
        q = DBSession.query(models.GlossAbbreviation).filter(
            or_(
                models.GlossAbbreviation.language_pk == sentence.language_pk,
                models.GlossAbbreviation.language_pk == None,
            )
        )
        abbrs = dict((g.id, g.name) for g in q)

    def gloss_with_tooltip(gloss):
        person_map = {"1": "first person", "2": "second person", "3": "third person"}

        res = []
        end = 0
        for match in GLOSS_ABBR_PATTERN.finditer(gloss):
            if match.start() > end:
                res.append(gloss[end : match.start()])

            abbr = match.group("abbr")
            if abbr in abbrs:
                explanation = abbrs[abbr]
                if match.group("personprefix"):
                    explanation = "%s %s" % (person_map[match.group("personprefix")], explanation)

                if match.group("personsuffix"):
                    explanation = "%s %s" % (explanation, person_map[match.group("personsuffix")])

                res.append(
                    HTML.span(
                        HTML.span(gloss[match.start() : match.end()].lower(), class_="sc"),
                        **{"data-hint": explanation, "class": "hint--bottom"}
                    )
                )
            else:
                res.append(abbr)

            end = match.end()

        res.append(gloss[end:])
        return filter(None, res)

    def alt_translation(sentence):
        res = ""
        if sentence.jsondata.get("alt_translation"):
            text = sentence.jsondata["alt_translation"]
            name = ""
            if ALT_TRANSLATION_LANGUAGE_PATTERN.match(text):
                name, text = [t.strip() for t in text.split(":", 1)]
                name = HTML.span(name + ": ")
            res = HTML.div(name, HTML.span(text, class_="translation"))
        return res

    units = []
    if sentence.analyzed and sentence.gloss:
        analyzed = sentence.analyzed
        glossed = sentence.gloss
        for morpheme, gloss in zip(analyzed.split("\t"), glossed.split("\t")):
            units.append(
                HTML.div(
                    HTML.div(morpheme, class_="morpheme"),
                    HTML.div(*gloss_with_tooltip(gloss), **{"class": "gloss"}),
                    class_="gloss-unit",
                )
            )

    return HTML.p(
        HTML.div(
            HTML.div(
                HTML.div(sentence.original_script, class_="original-script") if sentence.original_script else "",
                HTML.div(literal(sentence.markup_text or sentence.name), class_="object-language"),
                HTML.div(*units, **{"class": "gloss-box"}) if units else "",
                HTML.div(sentence.description, class_="translation") if sentence.description else "",
                alt_translation(sentence),
                class_="body",
            ),
            class_="sentence",
        ),
        class_="sentence",
    )
コード例 #18
0
ファイル: helpers.py プロジェクト: clld/clld
def collapsed(id_, content, button_content=None):
    return HTML.div(
        HTML.p(HTML.a(
            button_content or icon('plus-sign'),
            **{'class': 'btn', 'data-toggle': 'collapse', 'data-target': '#%s' % id_})),
        HTML.div(content, id=id_, class_='collapse'))
コード例 #19
0
ファイル: helpers.py プロジェクト: clld/clld
def text2html(text, mode='br', sep='\n\n'):
    """Turn plain text into simple HTML."""
    if mode == 'p':
        return HTML.div(*[HTML.p(literal(newline2br(line))) for line in text.split(sep)])
    return HTML.p(literal(newline2br(text)))
コード例 #20
0
def rendered_sentence(sentence, abbrs=None, fmt='long'):
    """Format a sentence as HTML."""
    if sentence.xhtml:
        return HTML.div(
            HTML.div(Markup(sentence.xhtml), class_='body'), class_="sentence")

    if abbrs is None:
        q = DBSession.query(models.GlossAbbreviation).filter(
            or_(models.GlossAbbreviation.language_pk == sentence.language_pk,
                models.GlossAbbreviation.language_pk == None)
        )
        abbrs = dict((g.id, g.name) for g in q)

    def gloss_with_tooltip(gloss):
        person_map = {
            '1': 'first person',
            '2': 'second person',
            '3': 'third person',
        }

        res = []
        end = 0
        for match in GLOSS_ABBR_PATTERN.finditer(gloss):
            if match.start() > end:
                res.append(gloss[end:match.start()])

            abbr = match.group('abbr')
            if abbr in abbrs:
                explanation = abbrs[abbr]
                if match.group('personprefix'):
                    explanation = '%s %s' % (
                        person_map[match.group('personprefix')], explanation)

                if match.group('personsuffix'):
                    explanation = '%s %s' % (
                        explanation, person_map[match.group('personsuffix')])

                res.append(HTML.span(
                    HTML.span(gloss[match.start():match.end()].lower(), class_='sc'),
                    **{'data-hint': explanation, 'class': 'hint--bottom'}))
            else:
                res.append(abbr)

            end = match.end()

        res.append(gloss[end:])
        return filter(None, res)

    def alt_translation(sentence):
        res = ''
        if sentence.jsondata.get('alt_translation'):
            text = sentence.jsondata['alt_translation']
            name = ''
            if ALT_TRANSLATION_LANGUAGE_PATTERN.match(text):
                name, text = [t.strip() for t in text.split(':', 1)]
                name = HTML.span(name + ': ')
            res = HTML.div(name, HTML.span(text, class_='translation'))
        return res

    units = []
    if sentence.analyzed and sentence.gloss:
        analyzed = sentence.analyzed
        glossed = sentence.gloss
        for morpheme, gloss in zip(analyzed.split('\t'), glossed.split('\t')):
            units.append(HTML.div(
                HTML.div(morpheme, class_='morpheme'),
                HTML.div(*gloss_with_tooltip(gloss), **{'class': 'gloss'}),
                class_='gloss-unit'))

    return HTML.p(
        HTML.div(
            HTML.div(
                HTML.div(sentence.original_script, class_='original-script')
                if sentence.original_script else '',
                HTML.div(literal(sentence.markup_text or sentence.name),
                         class_='object-language'),
                HTML.div(*units, **{'class': 'gloss-box'}) if units else '',
                HTML.div(sentence.description, class_='translation')
                if sentence.description else '',
                alt_translation(sentence),
                class_='body',
            ),
            class_="sentence",
        ),
        class_="sentence",
    )
コード例 #21
0
def rendered_sentence(sentence, abbrs=None, fmt='long'):
    if sentence.xhtml:
        return HTML.div(HTML.div(Markup(sentence.xhtml), class_='body'),
                        class_="sentence")

    if abbrs is None:
        q = DBSession.query(models.GlossAbbreviation).filter(
            or_(models.GlossAbbreviation.language_pk == sentence.language_pk,
                models.GlossAbbreviation.language_pk == None))
        abbrs = dict((g.id, g.name) for g in q)

    def gloss_with_tooltip(gloss):
        person_map = {
            '1': 'first person',
            '2': 'second person',
            '3': 'third person',
        }

        res = []
        end = 0
        for match in GLOSS_ABBR_PATTERN.finditer(gloss):
            if match.start() > end:
                res.append(literal(gloss[end:match.start()]))

            abbr = match.group('abbr')
            if abbr in abbrs:
                explanation = abbrs[abbr]
                if match.group('personprefix'):
                    explanation = '%s %s' % (
                        person_map[match.group('personprefix')], explanation)

                if match.group('personsuffix'):
                    explanation = '%s %s' % (
                        explanation, person_map[match.group('personsuffix')])

                res.append(
                    HTML.span(
                        HTML.span(gloss[match.start():match.end()].lower(),
                                  class_='sc'), **{
                                      'data-hint': explanation,
                                      'class': 'hint--bottom'
                                  }))
            else:
                res.append(abbr)

            end = match.end()

        res.append(literal(gloss[end:]))
        return filter(None, res)

    units = []
    if sentence.analyzed and sentence.gloss:
        analyzed = sentence.analyzed
        glossed = sentence.gloss
        for morpheme, gloss in zip(analyzed.split('\t'), glossed.split('\t')):
            units.append(
                HTML.div(HTML.div(literal(morpheme), class_='morpheme'),
                         HTML.div(*gloss_with_tooltip(gloss),
                                  **{'class': 'gloss'}),
                         class_='gloss-unit'))

    return HTML.p(
        HTML.div(
            HTML.div(
                HTML.div(literal(sentence.markup_text or sentence.name),
                         class_='object-language'),
                HTML.div(*units, **{'class': 'gloss-box'}) if units else '',
                HTML.div(sentence.description, class_='translation')
                if sentence.description else '',
                HTML.div(sentence.original_script, class_='original_script')
                if sentence.original_script else '',
                #HTML.small(literal(sentence.comment)) if sentence.comment and fmt == 'long' else '',
                class_='body',
            ),
            class_="sentence",
        ),
        class_="sentence",
    )
コード例 #22
0
def text2html(text, mode='br', sep='\n\n'):
    """Turn plain text into simple HTML."""
    if mode == 'p':
        return HTML.div(*[HTML.p(literal(newline2br(line))) for line in text.split(sep)])
    return HTML.p(literal(newline2br(text)))
コード例 #23
0
ファイル: datatables.py プロジェクト: clld/dictionaria
 def format(self, item):
     return HTML.p(item.datadict().get(self.name, ''))
コード例 #24
0
ファイル: datatables.py プロジェクト: clld/parabank
 def format(self, item):
     return HTML.p(
         *[link(self.dt.req, language, style_="padding-left:10px") + ","
           for language in item.languages],
         class_="unstyled")