Ejemplo n.º 1
0
def get_articles(num_of_objects):
    """
    Gets articles according to the number requested.
    :param num_of_objects: number of articles
    :return: articles
    """
    template = get_template("Files/template.html")
    resource = ""

    for i in range(1, num_of_objects + 1):

        temp_template = template

        # Get article with id i
        article = get_article(i)

        # Fill the template with the article's values.
        temp_template = temp_template.replace("Title", article["title"])
        temp_template = temp_template.replace("link", article["link"])
        temp_template = temp_template.replace(
            'img src=""', 'img src="{0}"'.format(article["img"]))
        temp_template = temp_template.replace("Content", article["content"])

        # Add the article to the final result.
        resource += temp_template + '\n'

    return resource
def queue_article_publication(article_id, version, run):
    if version is None or run is None:
        return {
                    'publication-status': 'error',
                    'id': article_id,
                    'version': str(version),
                    'run': run
                }
    queue_provider = QueueProvider()
    out_queue = queue_provider.get_queue(settings.workflow_starter_queue)
    article = get_article(article_id)
    article_versions = article.get('versions')
    result = {}

    if isinstance(article_versions, dict):
        version_data = article_versions.get(int(version))
        if isinstance(version_data, dict):
            version_properties = version_data.get('properties')
            if isinstance(version_properties, dict):
                # TODO : get publication status and check still valid
                # also see http://jira.elifesciences.org:8080/browse/ELPP-613
                status = 'queued'
                status_message = 'article queued'

                publication_data = version_properties.get('_publication-data')

                # This string is a base64 encoded message which allows initiation of the PostPerfectPublciation
                # workflow.

                # This class now needs constructs a workflow starter message which initiates the ApprovePerfectArticle
                # workflow. That workflow needs data to give drupal to publish the version <version> of article
                # <article_id> and also requires the data in this encoded string to initiate PostPerfectPublication upon
                #  successful publication so pass it article_id, version and the base 64 encoded string via the starter
                # mechanism

                follow_on_data = {
                    'article_id': article_id,
                    'version': version,
                    'run': run,
                    'publication_data': publication_data.get('value')
                }

                message = {
                    'workflow_name': 'ApproveArticlePublication',
                    'workflow_data': follow_on_data
                }

                m = Message()
                m.set_body(json.dumps(message))
                out_queue.write(m)

                result = {
                    'publication-status': status,
                    'id': article_id,
                    'version': str(version),
                    'run': run

                }

    return result
Ejemplo n.º 3
0
def queue_article_publication(article_id, version, run):
    if version is None or run is None:
        return {
            'publication-status': 'error',
            'id': article_id,
            'version': str(version),
            'run': run
        }
    queue_provider = QueueProvider()
    out_queue = queue_provider.get_queue(settings.workflow_starter_queue)
    article = get_article(article_id)
    article_versions = article.get('versions')
    result = {}

    if isinstance(article_versions, dict):
        version_data = article_versions.get(int(version))
        if isinstance(version_data, dict):
            version_properties = version_data.get('properties')
            if isinstance(version_properties, dict):
                # TODO : get publication status and check still valid
                # also see http://jira.elifesciences.org:8080/browse/ELPP-613
                status = 'queued'
                status_message = 'article queued'

                publication_data = version_properties.get('_publication-data')

                # This string is a base64 encoded message which allows initiation of the PostPerfectPublciation
                # workflow.

                # This class now needs constructs a workflow starter message which initiates the ApprovePerfectArticle
                # workflow. That workflow needs data to give drupal to publish the version <version> of article
                # <article_id> and also requires the data in this encoded string to initiate PostPerfectPublication upon
                #  successful publication so pass it article_id, version and the base 64 encoded string via the starter
                # mechanism

                follow_on_data = {
                    'article_id': article_id,
                    'version': version,
                    'run': run,
                    'publication_data': publication_data.get('value')
                }

                message = {
                    'workflow_name': 'ApproveArticlePublication',
                    'workflow_data': follow_on_data
                }

                m = Message()
                m.set_body(json.dumps(message))
                out_queue.write(m)

                result = {
                    'publication-status': status,
                    'id': article_id,
                    'version': str(version),
                    'run': run
                }

    return result
Ejemplo n.º 4
0
def article(url_code=None):
    article = articles.get_article(url_code)
    if not article:
        abort(404)
    return render_template(
        'article.html',
        article=article,
        debug=DEBUG
    )
Ejemplo n.º 5
0
def article(articleid):
    """
    Return article page
    """
    if articles.exist_article(db=DB, articleid=articleid,
                              invisible=True) and articleid.isdigit():
        article_data = dict(
            articles.get_article(db=DB,
                                 articleid=articleid,
                                 invisible=True,
                                 timeformat=CONFIG["system"]["time_format"],
                                 url=CONFIG["blog"]["url"]))
        return render_template("article.tmpl",
                               blog=CONFIG["blog"],
                               article=article_data,
                               is_article=True)
    abort(404)
Ejemplo n.º 6
0
def scrape(i, action='test'):
    def output(blocks):
        f = open('output.dat', 'w')
        for d in enumerate(map(strip_html, blocks)):
            print >> f, ("%03d: %s" % d).encode('utf-8')
        f.close()

    page = get_article(i)
    blocks = get_blocks(page)
    try:
        (l_bound, r_bound) = get_article_bounds(i, blocks)
    finally:
        pass
        #output(blocks)

    n = len(blocks)
    (xs, ys) = [normalize(range(n)), map(cost, blocks)]

    (cl_bound, cr_bound) = classify(zip(xs, ys))
    all_captured = (l_bound >= cl_bound and r_bound <= cr_bound)
    accuarcy = (((l_bound - cl_bound) + (cr_bound - r_bound)) * 1.0 /
                n) if all_captured else 1

    # for py.test
    if action == 'test':
        assert all_captured

    # R script for visual representation
    if action == 'plot':
        cs = map(lambda x: int(cl_bound <= x and x <= cr_bound), range(n))
        print plot_template % '\n'.join([
            'cs <- ' + to_vector(cs), 'xs <- ' + to_vector(xs),
            'ys <- ' + to_vector(map(lambda y: y * y, ys)),
            'l_bound <- %s/%s' % (l_bound, str(n)),
            'r_bound <- %s/%s' % (r_bound, str(n)),
            'msg <- "%s (%f)"' % ('OK' if all_captured else 'FAIL', accuarcy),
            'fn <- "./data_%d.png"' % i
        ])

    # an overview
    if action == 'stats':
        print '%2d : %s : %.04f' % (i, 'OK' if all_captured else 'FA',
                                    accuarcy)

    return accuarcy
Ejemplo n.º 7
0
def show_posted_page(article):
    raw_article = get_article(article)
    if raw_article['token'] != request.cookies.get('token'):
        return render_template('read_only_page.html',
                               token=raw_article['token'],
                               header=raw_article['header'],
                               signature=raw_article['signature'],
                               body=raw_article['body'])
    if request.method == 'POST':
        token = raw_article['token']
        header = request.form['header']
        signature = request.form['signature']
        body = request.form['body']
        article_save(header, signature, body, article, token)
        return redirect(url_for('show_posted_page', article=article))
    return render_template('page.html',
                           token=raw_article['token'],
                           header=raw_article['header'],
                           signature=raw_article['signature'],
                           body=raw_article['body'])
Ejemplo n.º 8
0
def get_detail_article_model(article_id):
    epoch = datetime.datetime.utcfromtimestamp(0)

    article = get_article(article_id)
    logging.debug("article data %s", str(article))

    model = {'id': article['article-identifier']}
    versions = article.get('versions')

    version_zero = versions.get(0)
    version_zero_properties = version_zero.get('properties')
    model['versions'] = {}
    for version in versions:
        if version > 0:
            logging.debug("version %s", str(version))

            version_data = versions.get(version)
            logging.debug("version_data %s", str(version_data))

            version_properties = version_data.get('properties')
            logging.debug("version_properties data %s", str(version_properties))

            merged_properties = version_zero_properties.copy()
            logging.debug("merged_properties data %s", str(merged_properties))

            merged_properties.update(version_properties)

            details = {'version-number': str(version)}

            corresponding_authors = merged_properties.get('corresponding-authors', None)
            if corresponding_authors is not None:
                details['corresponding-authors'] = corresponding_authors.get('value')
            doi = merged_properties.get('doi', None)
            if doi is not None:
                details['doi'] = doi.get('value')

            preview_base = settings.preview_base_url
            preview_path = merged_properties.get('path')
            if preview_path is not None and preview_base is not None:
                details['preview-link'] = preview_base + preview_path.get('value')
            publication_date = merged_properties.get('publication-date')
            if publication_date is not None:
                details['publication-date'] = publication_date.get('value')
            publication_status = merged_properties.get('publication-status')
            if publication_status is not None:
                details['publication-status'] = publication_status.get('value')
            status = merged_properties.get('status')
            if status is not None:
                details['status'] = status.get('value')
            title = merged_properties.get('title')
            if title is not None:
                details['title'] = title.get('value')
            authors = merged_properties.get('authors')
            if authors is not None:
                details['authors'] = authors.get('value')
            article_type = merged_properties.get('article-type')
            if article_type is not None:
                details['article-type'] = article_type.get('value')

            runs = {}
            version_runs = version_data.get('runs')
            for version_run in version_runs:
                run = {}

                run_data = version_runs.get(version_run)
                run_number = str(run_data.get('run-number'))
                run['run-number'] = run_number
                run['run-id'] = version_run
                run['version-number'] = str(version)
                run_events = run_data.get('events')
                events = []
                last_type = ""
                first = True
                for run_event in run_events:
                    if first:
                        run['first-event-timestamp'] = int((run_event.get('timestamp') - epoch).total_seconds())
                        first = False
                    event = {
                        "event-message": run_event.get('message'),
                        "event-status": run_event.get('status'),
                        "event-timestamp": int((run_event.get('timestamp') - epoch).total_seconds()),
                        "event-type": run_event.get('type')
                    }
                    if event['event-type'] == last_type:
                        events[-1] = event
                    else:
                        events.append(event)
                    last_type = event['event-type']
                run['events'] = events
                runs[run_number] = run


            model['versions'][str(version)] = {}
            model['versions'][str(version)]['details'] = details
            model['versions'][str(version)]['runs'] = runs

    return model
Ejemplo n.º 9
0
def get_detail_article_model(article_id):
    epoch = datetime.datetime.utcfromtimestamp(0)

    article = get_article(article_id)
    logging.debug("article data %s", str(article))

    model = {'id': article['article-identifier']}
    versions = article.get('versions')

    version_zero = versions.get(0)
    version_zero_properties = version_zero.get('properties')
    model['versions'] = {}
    for version in versions:
        if version > 0:
            logging.debug("version %s", str(version))

            version_data = versions.get(version)
            logging.debug("version_data %s", str(version_data))

            version_properties = version_data.get('properties')
            logging.debug("version_properties data %s",
                          str(version_properties))

            merged_properties = version_zero_properties.copy()
            logging.debug("merged_properties data %s", str(merged_properties))

            merged_properties.update(version_properties)

            details = {'version-number': str(version)}

            corresponding_authors = merged_properties.get(
                'corresponding-authors', None)
            if corresponding_authors is not None:
                details['corresponding-authors'] = corresponding_authors.get(
                    'value')
            doi = merged_properties.get('doi', None)
            if doi is not None:
                details['doi'] = doi.get('value')

            preview_base = settings.preview_base_url
            preview_path = merged_properties.get('path')
            if preview_path is not None and preview_base is not None:
                details['preview-link'] = preview_base + preview_path.get(
                    'value')
            publication_date = merged_properties.get('publication-date')
            if publication_date is not None:
                details['publication-date'] = publication_date.get('value')
            publication_status = merged_properties.get('publication-status')
            if publication_status is not None:
                details['publication-status'] = publication_status.get('value')
            status = merged_properties.get('status')
            if status is not None:
                details['status'] = status.get('value')
            title = merged_properties.get('title')
            if title is not None:
                details['title'] = title.get('value')
            authors = merged_properties.get('authors')
            if authors is not None:
                details['authors'] = authors.get('value')
            article_type = merged_properties.get('article-type')
            if article_type is not None:
                details['article-type'] = article_type.get('value')

            runs = {}
            version_runs = version_data.get('runs')
            for version_run in version_runs:
                run = {}

                run_data = version_runs.get(version_run)
                run_number = str(run_data.get('run-number'))
                run['run-number'] = run_number
                run['run-id'] = version_run
                run['version-number'] = str(version)
                run_events = run_data.get('events')
                events = []
                last_type = ""
                first = True
                for run_event in run_events:
                    if first:
                        run['first-event-timestamp'] = int(
                            (run_event.get('timestamp') -
                             epoch).total_seconds())
                        first = False
                    event = {
                        "event-message":
                        run_event.get('message'),
                        "event-status":
                        run_event.get('status'),
                        "event-timestamp":
                        int((run_event.get('timestamp') -
                             epoch).total_seconds()),
                        "event-type":
                        run_event.get('type')
                    }
                    if event['event-type'] == last_type:
                        events[-1] = event
                    else:
                        events.append(event)
                    last_type = event['event-type']
                run['events'] = events
                runs[run_number] = run

            model['versions'][str(version)] = {}
            model['versions'][str(version)]['details'] = details
            model['versions'][str(version)]['runs'] = runs

    return model
Ejemplo n.º 10
0
def article_page(topic_dir, article_filename, config):
    article_source = '{}/{}'.format(topic_dir, article_filename)
    topics = get_topics(config)
    article = get_article(config, article_source)

    return render_template("article.html", article=article, topics=topics)
Ejemplo n.º 11
0
from flask import Flask, render_template, url_for, send_file, flash, request
from facts import facts
from articles import get_article

app = Flask(__name__)

app.secret_key = "hello"
article_data = get_article()


@app.route('/')
def index():
    # if(request.method == 'POST'):
    #     # game_facts=facts()
    #     return flash("hello")
    # else:
    games = ['pong', 'space invaders']
    game_facts = facts()
    return render_template('index.html', data=[games, game_facts])


@app.route('/game/pong')
def pingpong():
    data = {
        'name':
        'Ping Pong',
        'desc':
        'Pong is a table tennis-themed arcade video game featuring simple two-dimensional graphics, manufactured by Atari and originally released in 1972.'
    }
    return render_template('game.html', data=data)