Beispiel #1
0
def qa_openness_stars_dataset_html(dataset):
    qa = dataset.get('qa')
    if not qa:
        return tk.literal('<!-- No qa info for this dataset -->')
    extra_vars = copy.deepcopy(qa)
    return tk.literal(
        tk.render('qa/openness_stars_brief.html', extra_vars=extra_vars))
Beispiel #2
0
def qa_openness_stars_resource_html(resource):
    qa = resource.get('qa')
    if not qa:
        return tk.literal('<!-- No qa info for this resource -->')
    if not isinstance(qa, dict):
        return tk.literal('<!-- QA info was of the wrong type -->')

    # Take a copy of the qa dict, because weirdly the renderer appears to add
    # keys to it like _ and app_globals. This is bad because when it comes to
    # render the debug in the footer those extra keys take about 30s to render,
    # for some reason.
    extra_vars = copy.deepcopy(qa)
    if "openness_score_reason" in extra_vars:
        if not extra_vars["openness_score_reason_args"] is None:
            messages = list()
            for template, args in zip(
                    extra_vars["openness_score_reason"].split("||"),
                    json.loads(extra_vars["openness_score_reason_args"])):
                try:
                    messages.append(tk._(template) % tuple(args))
                except TypeError:
                    messages.append(tk._(template))

            extra_vars["openness_score_reason"] = " ".join(messages)
        else:
            extra_vars["openness_score_reason"] = tk._(
                extra_vars["openness_score_reason"])
    return tk.literal(
        tk.render('qa/openness_stars.html', extra_vars=extra_vars))
Beispiel #3
0
def qa_openness_stars_dataset_html(dataset):
    qa = dataset.get('qa')
    if not qa:
        return tk.literal('<!-- No qa info for this dataset -->')
    extra_vars = copy.deepcopy(qa)
    return tk.literal(
        tk.render('qa/openness_stars_brief.html',
                  extra_vars=extra_vars))
Beispiel #4
0
def archiver_is_resource_broken_html(resource):
    archival = resource.get('archiver')
    if not archival:
        return tk.literal('<!-- No archival info for this resource -->')
    extra_vars = {'resource': resource}
    extra_vars.update(archival)
    return tk.literal(
        tk.render('archiver/is_resource_broken.html', extra_vars=extra_vars))
Beispiel #5
0
def archiver_is_resource_broken_html(resource):
    archival = resource.get('archiver')
    if not archival:
        return tk.literal('<!-- No archival info for this resource -->')
    extra_vars = {'resource': resource}
    extra_vars.update(archival)
    return tk.literal(
        tk.render('archiver/is_resource_broken.html',
                  extra_vars=extra_vars))
Beispiel #6
0
def qa_openness_stars_dataset_html(dataset):
    qa = dataset.get('qa')
    if not qa:
        return tk.literal('<!-- No qa info for this dataset -->')
    if not isinstance(qa, dict):
        return tk.literal('<!-- QA info was of the wrong type -->')
    extra_vars = copy.deepcopy(qa)
    return tk.literal(
        tk.render('qa/openness_stars_brief.html', extra_vars=extra_vars))
Beispiel #7
0
def qa_openness_stars_dataset_html(dataset):
    qa = dataset.get('qa')
    if not qa:
        return tk.literal('<!-- No qa info for this dataset -->')
    if not isinstance(qa, dict):
        return tk.literal('<!-- QA info was of the wrong type -->')
    extra_vars = copy.deepcopy(qa)
    return tk.literal(
        tk.render('qa/openness_stars_brief.html',
                  extra_vars=extra_vars))
Beispiel #8
0
def qa_openness_stars_resource_html(resource):
    qa = resource.get('qa')
    if not qa:
        return tk.literal('<!-- No qa info for this resource -->')
    # Take a copy of the qa dict, because weirdly the renderer appears to add
    # keys to it like _ and app_globals. This is bad because when it comes to
    # render the debug in the footer those extra keys take about 30s to render,
    # for some reason.
    extra_vars = copy.deepcopy(qa)
    return tk.literal(
        tk.render('qa/openness_stars.html', extra_vars=extra_vars))
Beispiel #9
0
def qa_openness_stars_resource_html(resource):
    qa = resource.get('qa')
    if not qa:
        return tk.literal('<!-- No qa info for this resource -->')
    # Take a copy of the qa dict, because weirdly the renderer appears to add
    # keys to it like _ and app_globals. This is bad because when it comes to
    # render the debug in the footer those extra keys take about 30s to render,
    # for some reason.
    extra_vars = copy.deepcopy(qa)
    return tk.literal(
        tk.render('qa/openness_stars.html',
                  extra_vars=extra_vars))
def render_mini_stars(stars):
    '''Returns HTML to show a number of stars out of five, with a reason and
    date, plus a tooltip describing the levels.'''

    if stars==0:
        stars_html = 5 * '&#9734'
    else:
        stars_html = (int(stars) or 0) * '&#9733'
        stars_html += (5-int(stars)) * '&#9734'

    reason = get_caption(int(stars))
    tooltip = t.literal('<div class="star-rating-reason">%s</div>' % escape(reason)) if reason else ''

    return t.literal('<span class="star-rating"><span class="tooltip">%s</span>%s</span>' % (tooltip, stars_html))
def ogdch_localize_activity_item(msg):
    """localizing activity messages: this function gets an html message and
    replaces the language dict in there with the localized value
    """
    try:
        parser = HTMLParser()
        unescaped_msg = parser.unescape(msg)
        language_dict = re.search(REGEX_LANGUAGE_DICT, unescaped_msg).group(0)
        localized_language_dict = get_localized_value_for_display(language_dict)  # noqa
        localized_msg = unescaped_msg.replace(language_dict, localized_language_dict)  # noqa
        return tk.literal(localized_msg)
    except Exception as e:
        log.error("Error {} occured while localizing an activity message".format(e, msg))  # noqa
    return tk.literal(msg)
def get_image_for_group(group_name, return_path=False):
    '''
    Render an inline svg snippet for the named group (topic). These groups
    correlate with those created by the `create_topics` command.
    '''
    jinja_env = toolkit.config['pylons.app_globals'].jinja_env
    groups = {
        'education': 'icons/book.svg',
        'environment': 'icons/leaf.svg',
        'health': 'icons/heart.svg',
        'housing': 'icons/keys.svg',
        'immigration': 'icons/passport.svg',
        'transportation': 'icons/bus.svg'
    }

    # Fetch svg template if there is one, otherwise return empty string.
    try:
        path = groups[group_name]
        if return_path:
            return path
        svg = jinja_env.get_template(path)
    except KeyError:
        # TODO: provide default icon
        return ''

    img = toolkit.literal("<span class='image %s'>" % group_name +
                          svg.render() + "</span>")
    return img
Beispiel #13
0
def ogdch_localize_activity_item(msg):
    """localizing activity messages: this function gets an html message and
    replaces the language dict in there with the localized value
    """
    parser = HTMLParser()
    unescaped_msg = parser.unescape(msg)

    language_dict_result = re.search(REGEX_LANGUAGE_DICT, unescaped_msg)
    if not language_dict_result:
        return tk.literal(msg)

    language_dict = language_dict_result.group(0)
    localized_language_dict = get_localized_value_for_display(language_dict)
    localized_msg = unescaped_msg.replace(language_dict,
                                          localized_language_dict)
    return tk.literal(localized_msg)
def to_c14n_markup(markup, with_comments=True, pretty=False):
    if not isinstance(markup, basestring):
        markup = unicode(markup)
    el = etree.fromstring(markup)
    markup = etree.tostring(
        el, method='c14n', with_comments=with_comments, pretty_print=pretty)
    return toolkit.literal(markup.decode('utf-8'))
def mini_stars_facet(num_stars):
    '''
    Returns HTML for a numbers of mini-stars with a caption describing the meaning.
    '''
    mini_stars = num_stars * '&#9733'
    mini_stars += '&#9734' * (5-num_stars)
    caption = get_caption[int(num_stars)]
    return t.literal('%s&nbsp; %s' % (mini_stars, caption))
Beispiel #16
0
def get_qa_openness(dataset):
    qa = dataset.get('qa')
    if not qa or not isinstance(qa, dict):
        extra_vars = {'openness_score': None}
    else:
        extra_vars = copy.deepcopy(qa)
    return toolkit.literal(
        toolkit.render('qa/openness_stars_brief.html', extra_vars=extra_vars))
def render_stars(stars, reason, last_updated):
    '''Returns HTML to show a number of stars out of five, with a reason and
    date, plus a tooltip describing the levels.'''

    if stars==0:
        stars_html = 5 * '<i class="icon-star-empty"></i>'
    else:
        stars_html = (stars or 0) * '<i class="icon-star"></i>'
        stars_html += (5-stars) * '<i class="icon-star-empty"></i>'

    tooltip = t.literal('<div class="star-rating-reason"><b>' + _('Reason') + ': </b>%s</div>' % escape(_(reason))) if reason else ''
    for i in range(5,0,-1):
        classname = 'fail' if (i > (stars or 0)) else ''
        tooltip += t.literal('<div class="star-rating-entry %s">%s</div>' % (classname, mini_stars_and_caption(i)))

    if last_updated:
        datestamp = render_datestamp(last_updated)
        tooltip += t.literal('<div class="star-rating-last-updated"><b>' + _('Score updated') + ': </b>%s</div>' % datestamp)


    tooltipo = t.literal(_('Reason') + ': %s' % _(reason)) if reason else ''

    for i in range(5,0,-1):
        tooltipo += t.literal("&#xa;%s" % mini_stars_and_caption(i))

    if last_updated:
        datestamp = render_datestamp(last_updated)
        tooltipo += t.literal(_('Score updated') + ' %s' % datestamp)

    return t.literal(_('Openness Rating') + ': <span class="star-rating"><span class="tooltip" style="display:none">%s</span>'
                                            '<a href="http://lab.linkeddata.deri.ie/2010/star-scheme-by-example/" target="_blank">%s</a>'
                                            '</span>' % (tooltip, stars_html))
Beispiel #18
0
def to_c14n_markup(markup, with_comments=True, pretty=False):
    if not isinstance(markup, basestring):
        markup = unicode(markup)
    el = etree.fromstring(markup)
    markup = etree.tostring(el,
                            method='c14n',
                            with_comments=with_comments,
                            pretty_print=pretty)
    return toolkit.literal(markup.decode('utf-8'))
Beispiel #19
0
    def column_select(columns):

        html = u''

        html += u'<select>'
        for col in columns:
            html += u'<option>'
        html += u'</select>'

        return toolkit.literal(html)
    def get_fields_markup(self):
        if request.method == 'POST':
            d = dict(request.params.items())
            response.headers['Content-Type'] = 'application/json' 
            return json.dumps(d)

        x = fixtures.foo1
        S = x.get_schema()
        test_fields = {
            'url': { 'title': u'Website URL' },
            'rating': { 'title': u'Foo Rating' },
            'grade': { 'title': u'Foo Grade' },
            'contacts': { 'title': u'Contacts', },
            'title': {
                'required': True,
                'classes': [ 'control-medium' ],
                'title': u'Title',
                'description': u'Blah blah',
                'placeholder': u'Enter a title',
                'attrs': { 'data-foo': 'baz', 'data-boo': 'faz', 'autocomplete': 'off' }
            },
            'temporal_extent': { 'title': u'Temporal Extent', },
            'reviewed': { 'title': u'Reviewed', },
            'description': { 'description': u'Add a detailed description', },
            'thematic_category': {},
            'tags': {},
            'created': { 'title': u'Created At', 'placeholder': datetime.datetime.now() },
            'wakeup_time': { 'title': u'Wakeup At',},
            'password': {},
        }
        c.form_sections = []
        for k, data in test_fields.items():
            f = x.get_field(k)
            c.form_sections.append({
                'heading': toolkit.literal('<h3>Field <code>%s</code></h3>' %(k)),
                'body': \
                    markup_for_field('edit', f, name_prefix='foo1', data=data) + \
                    toolkit.literal('<hr/>') + \
                    markup_for_field('read:bar', f, name_prefix='foo1', data=data)
            })
        #raise Exception('Break')
        c.form_class = 'form-horizontal' # 'form-horizontal'
        return render('tests/accordion-form.html')
Beispiel #21
0
def qa_openness_stars_dataset_html(dataset):
    qa = dataset.get('qa')
    if not qa:
        return tk.literal('<!-- No qa info for this dataset -->')
    if not isinstance(qa, dict):
        return tk.literal('<!-- QA info was of the wrong type -->')
    extra_vars = copy.deepcopy(qa)
    if "openness_score_reason" in extra_vars:
        if not extra_vars["openness_score_reason_args"] is None:
            messages = list()
            for template, args in zip(
                    extra_vars["openness_score_reason"].split("||"),
                    json.loads(extra_vars["openness_score_reason_args"])):
                try:
                    messages.append(tk._(template) % tuple(args))
                except TypeError:
                    messages.append(tk._(template))

            extra_vars["openness_score_reason"] = " ".join(messages)
        else:
            extra_vars["openness_score_reason"] = tk._(
                extra_vars["openness_score_reason"])
    return tk.literal(
        tk.render('qa/openness_stars_brief.html', extra_vars=extra_vars))
def mini_stars_and_caption(num_stars):
    '''
    Returns HTML for a numbers of mini-stars with a caption describing the meaning.
    '''
    mini_stars = num_stars * '&#9733'
    mini_stars += '&#9734' * (5-num_stars)
    caption = [
        _('Unavailable or not openly licensed'),
        _('Unstructured data (e.g. PDF)'),
        _('Structured data but proprietry format (e.g. Excel)'),
        _('Structured data in open format (e.g. CSV)'),
        _('Linkable data - served at URIs (e.g. RDF)'),
        _('Linked data - data URIs and linked to other data (e.g. RDF)')
    ]
    #log.debug(caption[num_stars])
    return t.literal('%s&nbsp; %s' % (mini_stars, caption[num_stars]))
Beispiel #23
0
    def package_matrix(packages, core_fields):

        html = u''

        html += u'<table class="table table-bordered table-condensed packages">' + u"\n"

        table_rows = []
        table_heads = {}
        for pkg_dict in packages:
            dic = {}
            for key, value in pkg_dict.iteritems():
                if key == 'tags':
                    tags = []
                    for tag_dict in pkg_dict['tags']:
                        tags += [tag_dict['name']]
                    dic['tags'] = tags
                    table_heads['tags'] = ""
                elif key == 'groups':
                    groups = []
                    #for group_dict in pkg_dict['groups']:
                    #    groups += [group_dict['id']]
                    #dic['groups'] = groups
                    dic['groups'] = pkg_dict['groups']
                    table_heads['groups'] = ""
                elif key == 'extras':
                    for extra_dict in pkg_dict['extras']:
                        if not extra_dict['key'] in dic.keys():
                            dic[extra_dict['key']] = extra_dict['value']
                            table_heads[extra_dict['key']] = ""
                elif key in core_fields and key not in dic.keys():
                    dic[key] = value
                    table_heads[key] = ""
            table_rows.append(dic)
        if 'title' in table_heads:
            del table_heads['title']
        if 'id' in table_heads:
            del table_heads['id']
        table_heads_sorted = sorted(table_heads.iterkeys())

        html += u'<thead>' + u"\n"
        html += u'<tr>' + u"\n"
        html += u'<th class="edit narrowTh" style="width: 15px;"><input type="checkbox" name="checkall" value="checkall" class="checkall"/></th>' + u"\n"
        html += u'<th class="title wideTh" style="max-width: 250px;">Title</th>' + u"\n"
        for key in table_heads_sorted:
            html += u'<th class="' + unicode(key) + u' wideTh">' + unicode(
                _(key)) + u'</th>' + u"\n"
        html += u'<th class="single_edit narrowTh" style="width: 35px;">Edit</th>' + u"\n"
        html += u'</tr>' + u"\n"
        html += u'</thead>' + u"\n"
        html += u'<tbody>'

        for row in table_rows:

            html += u'<tr>'

            html += u'<td><input type="checkbox" name="package_select" class="package_select" value="' + unicode(
                row['id']) + u'" /></td>'
            html += u'<td class="title ' + row['id'] + '">'
            html += unicode(
                h.link_to(
                    row['title'] or row['name'],
                    h.url_for(controller='package',
                              action='read',
                              id=row['name'])))
            html += u'</td>'
            for key in table_heads_sorted:

                if key in row:

                    import json

                    try:
                        row_key = json.loads(row[key])
                    except (ValueError, TypeError):
                        row_key = row[key]
                    if key == "notes":
                        val = h.markdown_extract(row_key)
                    if key == "groups":
                        group_ids = []
                        group_names = []
                        for group_dict in row[key]:
                            group_ids += [group_dict['id']]
                            group_names += [
                                h.group_name_to_title(group_dict['name'])
                            ]
                        row_key = ", ".join(group_ids)
                        val = ", ".join(group_names)
                    elif isinstance(row_key, list):
                        val = ", ".join(row_key)
                    else:
                        val = row_key

                    full_val = row_key

                    html += u'<td class="' + unicode(key) + u' ' + unicode(
                        row['id']
                    ) + u'" title="' + unicode(
                        full_val
                    ) + u'" style="max-height: 100px; display: block; overflow-y: auto;">'
                    html += unicode(val)
                    html += u'</td>'
                else:
                    html += u'<td class="' + unicode(key) + u' ' + unicode(
                        row['id']
                    ) + u'" style="max-height: 100px; display: block; overflow-y: scroll;"></td>'
            html += u'<td class="single_edit">' + unicode(
                h.subnav_link(h.icon('package_edit'),
                              controller='package',
                              action='edit',
                              id=row['name'])) + u'</td>'
            html += u'</tr>'
        html += u'</tbody>'
        html += u'</table>'

        return toolkit.literal(html)
Beispiel #24
0
 def get_item_template_vars(self, index=None):
     return {
         'title': toolkit.literal('%s <code>#%s</code>' % (
             self.field.value_type.title, 
             str(index + 1) if isinstance(index, int) else '{{index1}}')),
     }
 def get_objects_markup(self):
     markup = ''
     c.form_sections = []
     
     # 1. A Point object
     obj = fixtures.pt1
     assert isinstance(obj, types.Point)
     data = {
         'required': False,
         'classes': [],
         'input_classes': [ 'input-small' ],
         'title': u'Point A',
     }
     c.form_sections.append({
         'heading': toolkit.literal('<h3>Object <code>Point</code></h3>'),
         'body': \
             markup_for_object('edit:baz', obj, name_prefix='pt1', data=data) + \
             toolkit.literal('<hr/>') + \
             markup_for_object('read:boz', obj, name_prefix='pt1', data={'title': u'Point B'})
     })
     
     # 2.1 A TemporalExtent object
     obj = fixtures.dt1
     assert isinstance(obj, types.TemporalExtent)
     c.form_sections.append({
         'heading': toolkit.literal('<h3>Object <code>TemporalExtent</code></h3>'),
         'body': markup_for_object('edit:faz.baz', obj, name_prefix='dt1', data={'title': u'Extent A'}) +
             toolkit.literal('<hr/>') +
             markup_for_object('read', obj, name_prefix='dt1', data={ 'title': u'Extent B' })
     })
     
     # 2.2 A TemporalExtent object (with errors)
     obj = types.TemporalExtent(
         start=datetime.date(2014, 1, 1), end=datetime.date(2013, 1, 1))
     errs = obj.validate()
     errs = obj.dictize_errors(errs)
     assert isinstance(obj, types.TemporalExtent)
     c.form_sections.append({
         'heading': toolkit.literal('<h3>Object <code>TemporalExtent</code></h3>'),
         'body': \
             markup_for_object('edit:faz.baz', obj, 
                 errors=errs, name_prefix='dt1', data={'title': u'Extent A'}) + \
             toolkit.literal('<hr/>') + \
             markup_for_object('read', obj, 
                 errors=errs, name_prefix='dt1', data={ 'title': u'Extent B' })
     })
    
     # 3. A PostalAddress object
     obj = types.PostalAddress(address=u'22 Acacia Avenue', postalcode=u'12345')
     c.form_sections.append({
         'heading': toolkit.literal('<h3>Object <code>PostalAddress</code></h3>'),
         'body': \
             markup_for_object('edit:comfortable', obj, 
                 name_prefix='contact_info', data={'title': u'Address A'}) + \
             toolkit.literal('<hr/>') + \
             markup_for_object('read', obj, 
                 name_prefix='contact_info', data={'title': u'Address B'})
     })
     
     # Render
     c.form_class = 'form-horizontal'
     return render('tests/accordion-form.html')
Beispiel #26
0
    def get_objects_markup(self):
        markup = ''
        c.form_sections = []

        # 1. A Point object
        obj = fixtures.pt1
        assert isinstance(obj, types.Point)
        data = {
            'required': False,
            'classes': [],
            'input_classes': ['input-small'],
            'title': u'Point A',
        }
        c.form_sections.append({
            'heading': toolkit.literal('<h3>Object <code>Point</code></h3>'),
            'body': \
                markup_for_object('edit:baz', obj, name_prefix='pt1', data=data) + \
                toolkit.literal('<hr/>') + \
                markup_for_object('read:boz', obj, name_prefix='pt1', data={'title': u'Point B'})
        })

        # 2.1 A TemporalExtent object
        obj = fixtures.dt1
        assert isinstance(obj, types.TemporalExtent)
        c.form_sections.append({
            'heading':
            toolkit.literal('<h3>Object <code>TemporalExtent</code></h3>'),
            'body':
            markup_for_object('edit:faz.baz',
                              obj,
                              name_prefix='dt1',
                              data={'title': u'Extent A'}) +
            toolkit.literal('<hr/>') + markup_for_object(
                'read', obj, name_prefix='dt1', data={'title': u'Extent B'})
        })

        # 2.2 A TemporalExtent object (with errors)
        obj = types.TemporalExtent(start=datetime.date(2014, 1, 1),
                                   end=datetime.date(2013, 1, 1))
        errs = obj.validate()
        errs = obj.dictize_errors(errs)
        assert isinstance(obj, types.TemporalExtent)
        c.form_sections.append({
            'heading': toolkit.literal('<h3>Object <code>TemporalExtent</code></h3>'),
            'body': \
                markup_for_object('edit:faz.baz', obj,
                    errors=errs, name_prefix='dt1', data={'title': u'Extent A'}) + \
                toolkit.literal('<hr/>') + \
                markup_for_object('read', obj,
                    errors=errs, name_prefix='dt1', data={ 'title': u'Extent B' })
        })

        # 3. A PostalAddress object
        obj = types.PostalAddress(address=u'22 Acacia Avenue',
                                  postalcode=u'12345')
        c.form_sections.append({
            'heading': toolkit.literal('<h3>Object <code>PostalAddress</code></h3>'),
            'body': \
                markup_for_object('edit:comfortable', obj,
                    name_prefix='contact_info', data={'title': u'Address A'}) + \
                toolkit.literal('<hr/>') + \
                markup_for_object('read', obj,
                    name_prefix='contact_info', data={'title': u'Address B'})
        })

        # Render
        c.form_class = 'form-horizontal'
        return render('tests/accordion-form.html')
Beispiel #27
0
    def get_fields_markup(self):
        if request.method == 'POST':
            d = dict(request.params.items())
            response.headers['Content-Type'] = 'application/json'
            return json.dumps(d)

        x = fixtures.foo1
        S = x.get_schema()
        test_fields = {
            'url': {
                'title': u'Website URL'
            },
            'rating': {
                'title': u'Foo Rating'
            },
            'grade': {
                'title': u'Foo Grade'
            },
            'contacts': {
                'title': u'Contacts',
            },
            'title': {
                'required': True,
                'classes': ['control-medium'],
                'title': u'Title',
                'description': u'Blah blah',
                'placeholder': u'Enter a title',
                'attrs': {
                    'data-foo': 'baz',
                    'data-boo': 'faz',
                    'autocomplete': 'off'
                }
            },
            'temporal_extent': {
                'title': u'Temporal Extent',
            },
            'reviewed': {
                'title': u'Reviewed',
            },
            'description': {
                'description': u'Add a detailed description',
            },
            'thematic_category': {},
            'tags': {},
            'created': {
                'title': u'Created At',
                'placeholder': datetime.datetime.now()
            },
            'wakeup_time': {
                'title': u'Wakeup At',
            },
            'password': {},
        }
        c.form_sections = []
        for k, data in test_fields.items():
            f = x.get_field(k)
            c.form_sections.append({
                'heading': toolkit.literal('<h3>Field <code>%s</code></h3>' %(k)),
                'body': \
                    markup_for_field('edit', f, name_prefix='foo1', data=data) + \
                    toolkit.literal('<hr/>') + \
                    markup_for_field('read:bar', f, name_prefix='foo1', data=data)
            })
        #raise Exception('Break')
        c.form_class = 'form-horizontal'  # 'form-horizontal'
        return render('tests/accordion-form.html')