Example #1
0
def hints(hint):
    if hint <= 0:
        return 'this is probably not a flag', 404
    scores_dict = get_shelve('r')
    solvedit = [u for u, l in scores_dict.items() if hint in l]
    return render_template('%d.html' % hint,
                           username=cas.username,
                           solvedit=solvedit)
Example #2
0
File: app.py Project: bhaney/R1D2
def load_menu():
    db = shelve.get_shelve()
    fd = first_day_of_this_week()
    day = db.get('day', None)
    if day is None or day != fd:
        db['menu'] = r1.get_full_menu()
        db['day'] = fd
    return db['menu']
Example #3
0
def root():
    db = flask_shelve.get_shelve('c')
    lastupdated = 0 if not 'lastupdate' in db.keys() else int(db['lastupdate'])
    timedelta = calendar.timegm(time.gmtime()) - lastupdated
    print(timedelta)
    if (timedelta > 60 * 4):
        print("updating GDELT data")
        processGdeltData()
    return app.send_static_file('index.html')
def show_example():

    # #if request.method == 'GET':
    # Doc = read_document.Sample('/util/essay_samples/12Grade-informationExplanatory.txt', 'student', 'no')
    # return redirect(url_for('feedback', timestamp = Doc.timestamp))
    # #else:
    #  #   return redirect(url_for('intro'))
    db = get_shelve('c')
    Doc = db['example']
    return render_template('new_results.html', object=Doc)
Example #5
0
def score(username):
    scores_dict = get_shelve('r')
    completed = scores_dict[username] if username in scores_dict else set()
    score = calc_score(username, scores_dict)
    return render_template(
        "score.html",
        completed=map(str, completed),
        score=score,
        score_for=username,
        username=cas.username,
    )
Example #6
0
def md():
    db = flask_shelve.get_shelve('c', )

    camera_details = db[request.form['camera']]
    camera_details[
        'status'] = True if request.form['status'] == "True" else False
    db[request.form['camera']] = camera_details
    print(camera_details, request.form['camera'], request.form['status'],
          camera_details['status'], db[request.form['camera']])

    return 'OK'
Example #7
0
def index():
    scores_dict = get_shelve('r')
    hints = [x for x in sorted(flag_map.values()) if x > 0]
    board = sorted(
        ((n, ', '.join(map(str, fs)), "%.2f" % calc_score(n, scores_dict))
         for n, fs in scores_dict.items()),
        key=lambda x: float(x[2]),
        reverse=True)
    return render_template('index.html',
                           hints=hints,
                           board=board,
                           username=cas.username)
Example #8
0
def clear_old_shelve_objects():
    with app.test_request_context("/"):
        job = rq.get_current_job()
        job.meta["expired_keys"] = 0
        job.save_meta()

        shelve_db = flask_shelve.get_shelve("c")
        keys = shelve_db.keys()
        for i, key in enumerate(keys):
            _set_progress(job, i / len(keys))
            if learn_utils.is_last_view_expired(shelve_db, key):
                del shelve_db[key]
                job.meta["expired_keys"] += 1
                job.save_meta()
Example #9
0
File: app.py Project: funilrys/R1D2
def load_menu():
    """
    Get and return the full menu from the database.
    """

    database = shelve.get_shelve()
    first_day_of_the_week = first_day_of_this_week()
    current_day = database.get("day", None)

    if current_day is None or current_day != first_day_of_the_week:
        database["menu"] = get_full_menu()
        database["day"] = first_day_of_the_week

    return database["menu"]
Example #10
0
def record_view(username, page_name):
    with app.test_request_context("/"):
        job = rq.get_current_job()

        page_stats = learn_models.LearnPageStats.get_or_create(page_name)
        shelve_db = flask_shelve.get_shelve("c")
        shelve_key = f"{username}-{page_name}"

        if learn_utils.is_last_view_expired(shelve_db, shelve_key):
            page_stats.views += 1
            db.session.commit()

        # Update last seen time to now
        # It is INTENTIONAL that this updates even if we don't increment views
        learn_utils.update_shelve_expiration_time(shelve_db, shelve_key)
def save_to_db(datetime):
    if Doc.timestamp:
        key = Doc.timestamp
        db = get_shelve('c')
        db[Doc.time_stamp] = Doc

        #if "/shelve/" in request.path:
        #   status = """<span style="padding:15px; font-size:25px; vertical-align:top" title="save" class="glyphicon glyphicon-floppy-disk hidden-print"></span>"""
        #else:
        status = """<span style="vertical-align:top" title="saved" class="glyphicon glyphicon-floppy-saved hidden-print"></span>"""
        #if "shelve" in request.path:
        #    status = ' class=\"glyphicon glyphicon-floppy-disk hidden-print\" '
        #else:
        #    status = ' class=\"glyphicon glyphicon-floppy-saved hidden-print\" '
        return render_template('new_results.html', object=Doc, icon=status)
Example #12
0
def panelFeedData(panelName):
    print("getting panel thing")
    db = flask_shelve.get_shelve('c')

    data = None
    data = db[panelName]
    response = app.response_class(response=data,
                                  status=200,
                                  mimetype='application/json')
    return response

    if panelName == "toneHistogram":
        pass
    if panelName == "mapData":
        pass
    if panelName == "extremeTones":
        pass
    if panelName == "quadClassPiChart":
        pass
Example #13
0
def handle_flag_submit(flag=None):
    username = cas.username
    scores_dict = get_shelve('w')
    completed = scores_dict[username] if username in scores_dict else set()
    just_completed = None

    flag = bytes(flag.upper(), 'ascii')
    for actual_flag in flag_map:
        if flag == get_salted_hash(username, actual_flag):
            just_completed = flag_map[actual_flag]
            completed.add(just_completed)
            scores_dict[username] = completed
            print('{} completed {}'.format(username, flag_map[actual_flag]))

    return render_template(
        "completed.html",
        completed=map(str, completed) if completed else None,
        just_completed=just_completed,
        username=username,
        flag=flag)
def shelve():
    db = get_shelve('c')

    keys = list(db.keys())

    return render_template('keys.html', keys=keys)
Example #15
0
def processGdeltData():
    files = updateGdeltCSVs()
    print("downloaded new files")
    print("loading db")
    db = flask_shelve.get_shelve('c')
    print("loaded db")
    df = pd.read_table(files[0], header=None)

    toneList = (df[TONE_COLUMN] * 10).astype(int).sort_values()
    out = pd.cut(toneList, bins=60)
    counts = pd.value_counts(out)
    counts = counts.reindex(out.cat.categories)
    tones = []
    for interval in counts._index:
        tones.append([float(interval.left), int(counts[interval])])
    tones = json.dumps(tones)
    db['toneHistData'] = tones

    counts = df[QUADS_COLUMN].value_counts()
    print(counts)
    counts = [counts[i] if i in counts._index else 0 for i in range(1, 5)]
    print(counts)
    quads = []
    quads.append({
        'desc': 'e.g. agreement on policy',
        'name': 'Verbal Cooperation',
        'y': int(counts[0])
    })
    quads.append({
        'desc': 'e.g. a trade deal',
        'name': 'Material Cooperation',
        'y': int(counts[1])
    })
    quads.append({
        'desc': 'e.g. disagreement on policy',
        'name': 'Verbal Conflict',
        'y': int(counts[2])
    })
    quads.append({
        'desc': 'e.g. a research war',
        'name': 'Material Conflict',
        'y': int(counts[3])
    })
    db['quadPiData'] = json.dumps(quads)
    db['lastupdate'] = calendar.timegm(time.gmtime())

    urls = df.drop_duplicates(subset=60).sort_values(TONE_COLUMN)[60]
    listitems = []
    listitems.append("<b>Most Negative</b>")
    listitems.extend([
        "<a href=" + item + ">" + item + "</a>"
        for item in urls.iloc[0:10].tolist()
    ])
    listitems.append("<b>Most Positive</b>")
    listitems.extend([
        "<a href=" + item + ">" + item + "</a>"
        for item in urls.iloc[-11:-1].tolist()
    ])
    listitems.append("updated: " +
                     datetime.datetime.now().strftime("%m/%d %H:%M:%S"))
    db["toneListData"] = json.dumps(listitems)
Example #16
0
def index():
    db = flask_shelve.get_shelve('c')
    return json.dumps({'monkey': list(dict(db).values())})